From 2bd6e19519dcb6ea48621a23bbb1f986f00237e7 Mon Sep 17 00:00:00 2001 From: GloamXun Date: Sat, 21 Nov 2026 13:58:26 +0800 Subject: [PATCH] Render native XeTeX PNG, JPEG and BMP graphics --- Cargo.lock | 1 + crates/texrra-tex-core/Cargo.toml | 1 + .../texrra-tex-core/src/execution/device.rs | 24 +- .../src/execution/diagnostics.rs | 8 +- .../texrra-tex-core/src/execution/engine.rs | 1 + .../src/execution/engine/device.rs | 6 +- .../src/execution/engine/page.rs | 22 +- .../src/execution/engine/pdf_image.rs | 115 +++++--- .../src/execution/engine/specials.rs | 12 +- .../src/execution/format_image.rs | 2 +- crates/texrra-tex-core/src/execution/job.rs | 2 + crates/texrra-tex-core/src/execution/state.rs | 2 + crates/texrra-tex-core/src/pdf.rs | 20 +- crates/texrra-tex-core/src/pdf_device.rs | 1 + .../src/pdf_device/xdv_image.rs | 254 ++++++++++++++++++ crates/texrra-tex-core/src/pdf_image.rs | 230 +++++++++++++--- crates/texrra-tex-core/src/pdf_image/bmp.rs | 41 +++ crates/texrra-tex-core/src/pdf_image/icc.rs | 24 ++ crates/texrra-tex-core/src/pdf_image/jpeg.rs | 97 ++++++- crates/texrra-tex-core/src/pdf_image/png.rs | 35 ++- .../tests/execution_xetex_profile.rs | 10 +- docs/P2_M1_PROGRESS.md | 33 +++ 22 files changed, 821 insertions(+), 120 deletions(-) create mode 100644 crates/texrra-tex-core/src/pdf_device/xdv_image.rs create mode 100644 crates/texrra-tex-core/src/pdf_image/bmp.rs create mode 100644 crates/texrra-tex-core/src/pdf_image/icc.rs diff --git a/Cargo.lock b/Cargo.lock index a60b0a2..11ae76e 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1479,6 +1479,7 @@ version = "0.1.0" dependencies = [ "flate2", "hyphenate", + "image 0.23.14", "libc", "lopdf", "md5", diff --git a/crates/texrra-tex-core/Cargo.toml b/crates/texrra-tex-core/Cargo.toml index cc245ad..0fe2a48 100644 --- a/crates/texrra-tex-core/Cargo.toml +++ b/crates/texrra-tex-core/Cargo.toml @@ -7,6 +7,7 @@ description = "Experimental incremental TeX-compatible typesetting core (route D [dependencies] flate2 = "1.1" +image = { version = "0.23.12", default-features = false, features = ["bmp"] } lopdf = "0.26" md5 = "0.8" png = "0.18.1" diff --git a/crates/texrra-tex-core/src/execution/device.rs b/crates/texrra-tex-core/src/execution/device.rs index 440b028..424a4c3 100644 --- a/crates/texrra-tex-core/src/execution/device.rs +++ b/crates/texrra-tex-core/src/execution/device.rs @@ -40,6 +40,8 @@ pub struct NativeShipout { pub(super) pdf_color_steps: Vec>>, #[serde(default, skip_serializing_if = "Vec::is_empty")] pub(super) pdf_graphics_steps: Vec>, + #[serde(default, skip_serializing_if = "BTreeMap::is_empty")] + pub(super) pdf_special_images: BTreeMap, TokenOrigin)>, #[serde(default, skip_serializing_if = "Vec::is_empty")] pub specials: Vec, #[serde(default, skip_serializing_if = "Option::is_none")] @@ -91,7 +93,7 @@ impl NativeShipout { .map(DisplayItem::PdfColor), ); let mut color_steps = self.pdf_color_steps.iter(); - let mut graphics_steps = self.pdf_graphics_steps.iter(); + let mut graphics_steps = self.pdf_graphics_steps.iter().enumerate(); let mut invalid_geometry = false; let mut missing_color_step = false; let mut missing_graphics_step = false; @@ -128,12 +130,28 @@ impl NativeShipout { } boxes::GeometryItem::PdfGraphics { x, y } => { match graphics_steps.next() { - Some(Some(operation)) => page.items.push(DisplayItem::PdfGraphics { + Some((_, Some(operation))) => page.items.push(DisplayItem::PdfGraphics { x: self.device.horizontal_origin + x, y: self.device.vertical_origin + self.box_node.height + y, operation: operation.clone(), }), - Some(None) => {} + Some((step, None)) => { + if let Some((image, origin)) = self.pdf_special_images.get(&step) { + let [left, bottom] = image.xdv.as_ref().unwrap().layout_offset; + page.sources.insert( + page.items.len(), + crate::provenance::PaintSource::token(*origin), + ); + page.items.push(DisplayItem::PdfImage { + x: self.device.horizontal_origin + x + left, + y: self.device.vertical_origin + self.box_node.height + y + - image.height - bottom, + width: image.width, + height: image.height, + image: image.clone(), + }); + } + } None => missing_graphics_step = true, } return; diff --git a/crates/texrra-tex-core/src/execution/diagnostics.rs b/crates/texrra-tex-core/src/execution/diagnostics.rs index c5f49d3..e0c78f0 100644 --- a/crates/texrra-tex-core/src/execution/diagnostics.rs +++ b/crates/texrra-tex-core/src/execution/diagnostics.rs @@ -624,7 +624,11 @@ impl Printer<'_> { } OutputOperation::PdfImage { image, .. } => { if image.xdv.is_some() { - self.command("XeTeXpdffile"); + self.command(if image.image.raster_frame().is_some() { + "XeTeXpicfile" + } else { + "XeTeXpdffile" + }); self.literal(&format!( " \"{}\"", image.image.version.path.display() @@ -667,7 +671,7 @@ impl Printer<'_> { self.tokens(tokens)?; } OutputOperation::PdfSavePosition => self.command("pdfsavepos"), - OutputOperation::Special { shipout, tokens } => { + OutputOperation::Special { shipout, tokens, .. } => { self.command("special"); if *shipout { self.literal(" shipout"); diff --git a/crates/texrra-tex-core/src/execution/engine.rs b/crates/texrra-tex-core/src/execution/engine.rs index be617aa..b5934c9 100644 --- a/crates/texrra-tex-core/src/execution/engine.rs +++ b/crates/texrra-tex-core/src/execution/engine.rs @@ -3153,6 +3153,7 @@ impl Executor { Primitive::XeTeXversion => "XeTeXversion".into(), Primitive::XeTeXrevision => "XeTeXrevision".into(), Primitive::XeTeXpdffile => "XeTeXpdffile".into(), + Primitive::XeTeXpicfile => "XeTeXpicfile".into(), Primitive::XeTeXpdfpagecount => "XeTeXpdfpagecount".into(), Primitive::Etexversion => "eTeXversion".into(), Primitive::Etexrevision => "eTeXrevision".into(), diff --git a/crates/texrra-tex-core/src/execution/engine/device.rs b/crates/texrra-tex-core/src/execution/engine/device.rs index d59fcf9..82e5808 100644 --- a/crates/texrra-tex-core/src/execution/engine/device.rs +++ b/crates/texrra-tex-core/src/execution/engine/device.rs @@ -26,7 +26,7 @@ impl Executor { span: token.span, })?; } - Special => self.scan_special(token.span, files)?, + Special => self.scan_special(token, files)?, Pdfsave | Pdfsetmatrix | Pdfrestore | Pdfliteral => { self.scan_pdf_graphics(primitive, token.span, files)? } @@ -48,7 +48,9 @@ impl Executor { Pdfinfo => self.scan_pdf_info(files)?, Pdfximage => self.scan_pdf_image(token, false, files)?, Pdfrefximage => self.reference_pdf_image(token, files)?, - XeTeXpdffile => self.scan_xdv_pdf_image(token, files)?, + XeTeXpdffile | XeTeXpicfile => { + self.scan_xdv_image(token, primitive == XeTeXpdffile, files)? + } _ => return Ok(false), } Ok(true) diff --git a/crates/texrra-tex-core/src/execution/engine/page.rs b/crates/texrra-tex-core/src/execution/engine/page.rs index fce2d34..dbc5966 100644 --- a/crates/texrra-tex-core/src/execution/engine/page.rs +++ b/crates/texrra-tex-core/src/execution/engine/page.rs @@ -343,6 +343,7 @@ impl Executor { pdf_color_start, pdf_color_steps: Vec::new(), pdf_graphics_steps: Vec::new(), + pdf_special_images: Default::default(), specials: Vec::new(), pdf_text_spaces: None, pdf_resource_entries, @@ -432,12 +433,29 @@ impl Executor { return self.fail("cannot ship a PDF color operation to DVI"); } shipout.pdf_color_steps.push(self.ship_pdf_color(*stack, action, output.span, files)?); - } else if matches!(output.operation, OutputOperation::Special { .. }) { + } else if let OutputOperation::Special { origin, .. } = &output.operation { let special = self.resolve_special( output, position.expect("special needs a shipout position"), files, )?; let graphics = if let Some(pdf) = &device.pdf { - self.render_special(&special, pdf.driver, files)? + if pdf.driver == crate::pdf_device::PdfDriver::Xdv + && let Some(image) = crate::pdf_device::xdv_image::ImageSpecial::parse( + &special.bytes, device.magnification, + ).map_err(|error| self.error(error, special.span))? + { + if let Some(image) = self.ship_xdv_raster_special(image, special.span, files)? { + shipout.pdf_special_images.insert( + shipout.pdf_graphics_steps.len(), + (image, origin.unwrap_or(TokenOrigin { + span: special.span, + invocation: None, + })), + ); + } + None + } else { + self.render_special(&special, pdf.driver, files)? + } } else { None }; diff --git a/crates/texrra-tex-core/src/execution/engine/pdf_image.rs b/crates/texrra-tex-core/src/execution/engine/pdf_image.rs index d2bb88d..d02f515 100644 --- a/crates/texrra-tex-core/src/execution/engine/pdf_image.rs +++ b/crates/texrra-tex-core/src/execution/engine/pdf_image.rs @@ -166,44 +166,47 @@ impl Executor { Ok((name, from)) } - pub(super) fn scan_xdv_pdf_image( + pub(super) fn scan_xdv_image( &mut self, token: &Token, + pdf: bool, files: &mut impl SourceProvider, ) -> Result<(), Error> { if self.native_page.is_none() { - return self.fail("XeTeX PDF image requires a native page job"); + return self.fail("XeTeX image requires a native page job"); } if !self.math.is_empty() { - return self.fail("XeTeX PDF image is illegal in math mode"); + return self.fail("XeTeX image is illegal in math mode"); } let (name, from) = self.xdv_image_filename(token, files)?; - let page = if self.keyword("page", files)? { - self.integer(files)? - } else { - 0 - }; - let mut box_type = PageBox::Crop; - for (keyword, kind) in [ - ("crop", PageBox::Crop), - ("media", PageBox::Media), - ("bleed", PageBox::Bleed), - ("trim", PageBox::Trim), - ("art", PageBox::Art), - ] { - if self.keyword(keyword, files)? { - box_type = kind; - break; + let (image, source_origin, page) = if pdf { + let page = if self.keyword("page", files)? { + self.integer(files)? + } else { + 0 + }; + let mut box_type = PageBox::Crop; + for (keyword, kind) in [ + ("crop", PageBox::Crop), + ("media", PageBox::Media), + ("bleed", PageBox::Bleed), + ("trim", PageBox::Trim), + ("art", PageBox::Art), + ] { + if self.keyword(keyword, files)? { + box_type = kind; + break; + } } - } - - let resource = files - .resource(ResourceKind::Tex, &name, &from) - .map_err(|message| { - self.error(format!("cannot find PDF image {name}: {message}"), token.span) - })?; - let (image, source_origin) = PdfImage::read_xdv(resource, page, box_type) - .map_err(|message| self.error(message, token.span))?; + let resource = files + .resource(ResourceKind::Tex, &name, &from) + .map_err(|message| self.error(message, token.span))?; + let (image, source_origin) = PdfImage::read_xdv(resource, page, box_type) + .map_err(|message| self.error(message, token.span))?; + (Arc::new(image), source_origin, page) + } else { + (self.xdv_raster_source(&name, &from, token.span, files)?, [0.0; 2], 0) + }; let mut placement = XdvImagePlacement::new(&image, source_origin); loop { if self.keyword("scaled", files)? { @@ -241,6 +244,30 @@ impl Executor { self.defer_image(image, token) } + fn xdv_raster_source( + &self, + name: &str, + from: &str, + span: Span, + files: &mut impl SourceProvider, + ) -> Result, Error> { + let resource = files + .resource(ResourceKind::Tex, name, from) + .map_err(|message| self.error(message, span))?; + // A layout measurement and later shipout share the decoded pixels + // only if the resource provider returns the same version. + if let Some(registered) = self.pdf_images.iter().rev().find(|registered| { + registered.image.xdv.is_some() + && registered.image.image.raster_frame().is_some() + && registered.image.image.version == resource.version + }) { + return Ok(registered.image.image.clone()); + } + PdfImage::read_xdv_raster(resource) + .map(Arc::new) + .map_err(|message| self.error(message, span)) + } + fn xdv_image_size( &mut self, placement: &mut XdvImagePlacement, @@ -249,12 +276,36 @@ impl Executor { ) -> Result<(), Error> { let size = self.dimension(false, false, files)?.amount; if size <= 0 { - return self.fail("XeTeX PDF image size must be positive"); + return self.fail("XeTeX image size must be positive"); } placement.request_size(axis, size); Ok(()) } + pub(super) fn ship_xdv_raster_special( + &mut self, + special: crate::pdf_device::xdv_image::ImageSpecial, + span: Span, + files: &mut impl SourceProvider, + ) -> Result>, Error> { + let from = self.source_name(span); + self.reads.insert(Dependency::FileLookup { + name: special.file.clone(), + from: from.clone(), + }); + let resource = self.xdv_raster_source(&special.file, &from, span, files)?; + let image = special.place(self.pdf_images.len() + 1, resource) + .map_err(|error| self.error(error, span))?; + let image = Arc::new(image); + self.pdf_images.push(RegisteredImage { + image: image.clone(), + attributes: None, + }); + let hidden = special.hidden; + self.emit_pdf_image_object(image.clone(), special.attributes); + Ok((!hidden).then_some(image)) + } + // A PDF image object is emitted once, when used at shipout or immediately. // Expansion took place during registration, but escapechar and catcodes // belong to the token printer at the time of writing the object. @@ -287,6 +338,11 @@ impl Executor { } else { text.into_bytes() }; + self.emit_pdf_image_object(image, attributes); + Ok(()) + } + + fn emit_pdf_image_object(&mut self, image: Arc, attributes: Vec) { let compression = self .read_parameter(Parameter::Pdfcompresslevel) .width() @@ -296,7 +352,6 @@ impl Executor { attributes, compression, })); - Ok(()) } pub(super) fn reference_pdf_image( diff --git a/crates/texrra-tex-core/src/execution/engine/specials.rs b/crates/texrra-tex-core/src/execution/engine/specials.rs index 936c50f..aac7a35 100644 --- a/crates/texrra-tex-core/src/execution/engine/specials.rs +++ b/crates/texrra-tex-core/src/execution/engine/specials.rs @@ -5,7 +5,7 @@ use crate::pdf_device::{PdfDriver, PdfGraphics, PdfLiteralMode, PdfMatrix}; impl Executor { pub(super) fn scan_special( &mut self, - span: Span, + token: &Token, files: &mut impl SourceProvider, ) -> Result<(), Error> { let shipout = self.keyword("shipout", files)?; @@ -15,8 +15,12 @@ impl Executor { self.scan_expanded_group(files)? }; self.defer_output(OutputNode { - operation: OutputOperation::Special { shipout, tokens }, - span, + operation: OutputOperation::Special { + shipout, + tokens, + origin: Some(token.into()), + }, + span: token.span, }) } @@ -28,7 +32,7 @@ impl Executor { ) -> Result { self.current = node.span; self.tick()?; - let OutputOperation::Special { shipout, tokens } = &node.operation else { + let OutputOperation::Special { shipout, tokens, .. } = &node.operation else { unreachable!() }; let expanded; diff --git a/crates/texrra-tex-core/src/execution/format_image.rs b/crates/texrra-tex-core/src/execution/format_image.rs index 5dbe64a..335c8a3 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 = 63; +const SCHEMA: u32 = 64; const COMPATIBLE_SCHEMAS: [u32; 31] = [ 27, 28, 31, 32, 33, 34, 35, 36, 37, 38, 39, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, SCHEMA, ]; diff --git a/crates/texrra-tex-core/src/execution/job.rs b/crates/texrra-tex-core/src/execution/job.rs index d1f41cf..071ead1 100644 --- a/crates/texrra-tex-core/src/execution/job.rs +++ b/crates/texrra-tex-core/src/execution/job.rs @@ -256,6 +256,8 @@ pub enum OutputOperation { Special { shipout: bool, tokens: Vec, + #[serde(default, skip_serializing_if = "Option::is_none")] + origin: Option, }, } diff --git a/crates/texrra-tex-core/src/execution/state.rs b/crates/texrra-tex-core/src/execution/state.rs index 506c01a..22e91a2 100644 --- a/crates/texrra-tex-core/src/execution/state.rs +++ b/crates/texrra-tex-core/src/execution/state.rs @@ -365,6 +365,7 @@ pub enum Primitive { XeTeXrevision, XeTeXpdffile, XeTeXpdfpagecount, + XeTeXpicfile, } impl Primitive { @@ -1637,6 +1638,7 @@ impl State { ("XeTeXversion", Primitive::XeTeXversion), ("XeTeXrevision", Primitive::XeTeXrevision), ("XeTeXpdffile", Primitive::XeTeXpdffile), + ("XeTeXpicfile", Primitive::XeTeXpicfile), ("XeTeXpdfpagecount", Primitive::XeTeXpdfpagecount), ] { self.update_profile_command(name, Meaning::Primitive(primitive), enabled); diff --git a/crates/texrra-tex-core/src/pdf.rs b/crates/texrra-tex-core/src/pdf.rs index 1c4c788..b4939f7 100755 --- a/crates/texrra-tex-core/src/pdf.rs +++ b/crates/texrra-tex-core/src/pdf.rs @@ -1027,15 +1027,21 @@ fn page_content( // The XDV driver rounds the image translation relative // to its page origin, with three decimals by default. let round = |value: f64| (value * 1000.0).round() / 1000.0; - let x = round(list.units.bp(*x) + tx - origin_x) + round(origin_x) + let [left, bottom] = placement.layout_offset; + let x = round(list.units.bp(*x - left) + tx - origin_x) + round(origin_x) - list.units.bp(h); - let y = round(list.units.bp(height - *y - *image_height) + ty - origin_y) - + round(origin_y) - list.units.bp(v); + let y = round( + list.units.bp(height - *y - *image_height - bottom) + ty - origin_y, + ) + round(origin_y) - list.units.bp(v); let [a, b, c, d, x, y] = [a, b, c, d, x, y].map(crate::pdf_image::real); - content.push_str(&format!( - "q {a} {b} {c} {d} {x} {y} cm /PI{} Do Q\n", - image.id - )); + content.push_str(&format!("q {a} {b} {c} {d} {x} {y} cm ")); + if let Some(clip) = placement.clip() { + let [x, y, w, h] = clip.map(|value| { + crate::pdf_image::real((value * 1000.0).round() / 1000.0) + }); + content.push_str(&format!("{x} {y} {w} {h} re W n ")); + } + content.push_str(&format!("/PI{} Do Q\n", image.id)); continue; } let [sx, sy] = if image.image.raster_frame().is_some() diff --git a/crates/texrra-tex-core/src/pdf_device.rs b/crates/texrra-tex-core/src/pdf_device.rs index 2fa01a9..05a31e1 100644 --- a/crates/texrra-tex-core/src/pdf_device.rs +++ b/crates/texrra-tex-core/src/pdf_device.rs @@ -97,6 +97,7 @@ pub fn print_sp(value: i64, digits: u8) -> String { } } mod color; +pub(crate) mod xdv_image; mod graphics; pub(crate) use color::{ColorResult, PdfColorStacks}; pub use color::{PdfColorProgram, PdfColorStackAction}; diff --git a/crates/texrra-tex-core/src/pdf_device/xdv_image.rs b/crates/texrra-tex-core/src/pdf_device/xdv_image.rs new file mode 100644 index 0000000..0955030 --- /dev/null +++ b/crates/texrra-tex-core/src/pdf_device/xdv_image.rs @@ -0,0 +1,254 @@ +//! The xdvipdfmx raster image device special. +use super::Affine; +use crate::pdf_image::{PdfImage, PdfImageUse, real}; +use lopdf::{Object, content::Content}; +use std::{iter::Peekable, str::SplitAsciiWhitespace, sync::Arc}; + +pub(crate) struct ImageSpecial { + pub file: String, + pub attributes: Vec, + pub hidden: bool, + bbox: Option<[f64; 4]>, + dimensions: [Option; 3], + transform: Affine, + clip: bool, +} + +impl ImageSpecial { + pub(crate) fn parse(data: &[u8], magnification: i32) -> Result, String> { + let Some(body) = data.trim_ascii_start().strip_prefix(b"pdf:") else { + return Ok(None); + }; + let body = body.trim_ascii_start(); + let name_end = body + .iter() + .position(|byte| byte.is_ascii_whitespace() || matches!(byte, b'(' | b'<')) + .unwrap_or(body.len()); + if !matches!(&body[..name_end], b"image" | b"img") { + return Ok(None); + } + let body = &body[name_end..]; + let file_pos = body + .iter() + .position(|byte| matches!(byte, b'(' | b'<')) + .ok_or("missing XDV image filename string")?; + let parameters = + std::str::from_utf8(&body[..file_pos]).map_err(|error| error.to_string())?; + let mut words = parameters.split_ascii_whitespace().peekable(); + let mut bbox = None; + let mut dimensions = [None; 3]; + let mut clip = true; + let mut hidden = false; + let mut scales = [None; 2]; + let mut overall_scale = None; + let mut rotation = 0.0; + let mut matrix = None; + while let Some(parameter) = words.next() { + match parameter { + "bbox" => { + bbox = Some([ + number(words.next())?, + number(words.next())?, + number(words.next())?, + number(words.next())?, + ]); + } + "width" => dimensions[0] = Some(length(&mut words, magnification)?), + "height" => dimensions[1] = Some(length(&mut words, magnification)?), + "depth" => dimensions[2] = Some(length(&mut words, magnification)?), + "scale" => overall_scale = Some(number(words.next())?), + "xscale" => scales[0] = Some(number(words.next())?), + "yscale" => scales[1] = Some(number(words.next())?), + "rotate" => rotation = number(words.next())?, + "matrix" => { + matrix = Some(Affine([ + number(words.next())?, + number(words.next())?, + number(words.next())?, + number(words.next())?, + number(words.next())?, + number(words.next())?, + ])); + } + "clip" => clip = number(words.next())? != 0.0, + "hide" => hidden = true, + "page" if matches!(number(words.next())?, 0.0 | 1.0) => {} + _ => return Err(format!("unsupported XDV raster image option {parameter}")), + } + } + if overall_scale.is_some() && scales.iter().any(Option::is_some) { + return Err("XDV image scale conflicts with an axis scale".into()); + } + if dimensions[0].is_some() && scales[0].is_some() { + scales[0] = None; + } else if (dimensions[1].is_some() || dimensions[2].is_some()) && scales[1].is_some() { + scales[1] = None; + } + let [sx, sy] = scales.map(|value| value.or(overall_scale).unwrap_or(1.0)); + let (sin, cos) = rotation.to_radians().sin_cos(); + let transform = + matrix.unwrap_or(Affine([cos * sx, sin * sx, -sin * sy, cos * sy, 0.0, 0.0])); + + // The suffix shares the PDF string and dictionary grammar. Decode + // the objects with the same parser used for native page resources. + let mut pdf_objects = body[file_pos..].to_vec(); + pdf_objects.extend_from_slice(b"\nq"); + let parsed = Content::decode(&pdf_objects).map_err(|error| error.to_string())?; + let [operation] = parsed.operations.as_slice() else { + return Err("invalid PDF objects in XDV image special".into()); + }; + let (file, dictionary) = match operation.operands.as_slice() { + [Object::String(file, _)] if operation.operator == "q" => (file, None), + [Object::String(file, _), Object::Dictionary(dict)] if operation.operator == "q" => { + (file, Some(dict)) + } + _ => { + return Err("expected filename and optional XDV image attribute dictionary".into()); + } + }; + let file = String::from_utf8(file.clone()).map_err(|error| error.to_string())?; + let mut attributes = Vec::new(); + if let Some(dictionary) = dictionary { + for (key, value) in dictionary.iter() { + match (key.as_slice(), value) { + (b"Decode", Object::Array(values)) => { + if values.is_empty() || values.len() % 2 != 0 { + return Err("XDV image Decode array requires pairs".into()); + } + attributes.extend_from_slice(b"/Decode ["); + for value in values { + let number = match value { + Object::Integer(value) => *value as f64, + Object::Real(value) if value.is_finite() => *value, + _ => { + return Err( + "XDV image Decode array requires finite numbers".into() + ); + } + }; + attributes.extend_from_slice(real(number).as_bytes()); + attributes.push(b' '); + } + attributes.extend_from_slice(b"] "); + } + (b"Interpolate", Object::Boolean(value)) => { + attributes.extend_from_slice(if *value { + b"/Interpolate true " + } else { + b"/Interpolate false " + }); + } + _ => { + return Err(format!( + "unsupported XDV image attribute {}", + String::from_utf8_lossy(key) + )); + } + } + } + } + Ok(Some(Self { + file, + attributes, + hidden, + bbox, + dimensions, + transform, + clip, + })) + } + + pub(crate) fn place(&self, id: usize, image: Arc) -> Result { + let [natural_w, natural_h] = image.extent(); + let ([pixels_w, pixels_h], _) = image + .raster_frame() + .ok_or("XDV special needs a raster image")?; + let [left, bottom, right, top] = self.bbox.unwrap_or([0.0, 0.0, natural_w, natural_h]); + let [box_w, box_h] = [right - left, top - bottom]; + if box_w <= 0.0 || box_h <= 0.0 { + return Err("XDV image bounding box must have positive dimensions".into()); + } + let [requested_w, requested_h, depth] = self.dimensions; + let requested_h = requested_h.or(depth.map(|_| 0.0)); + let depth = depth.unwrap_or(0.0); + let [xscale, yscale] = [natural_w / box_w, natural_h / box_h]; + let pixel_aspect = pixels_w as f64 / pixels_h as f64; + let (width, height, depth) = match (requested_w, requested_h) { + (Some(w), Some(h)) => (w * xscale, (h + depth) * yscale, depth * yscale), + (Some(w), None) => (w * xscale, w * xscale / pixel_aspect, 0.0), + (None, Some(h)) => ( + (h + depth) * yscale * pixel_aspect, + (h + depth) * yscale, + depth * yscale, + ), + (None, None) => (box_w, box_h, 0.0), + }; + let sizing = Affine([ + width, + 0.0, + 0.0, + height, + -left * width / natural_w, + -bottom * height / natural_h - depth, + ]); + let clip = (self.clip && self.bbox.is_some()).then_some([ + left / natural_w, + bottom / natural_h, + box_w / natural_w, + box_h / natural_h, + ]); + PdfImageUse::new_xdv_raster_special(id, image, self.transform.concatenate(sizing), clip) + } +} + +fn number(word: Option<&str>) -> Result { + word.and_then(|word| word.parse::().ok()) + .filter(|value| value.is_finite()) + .ok_or("invalid XDV image number") +} + +fn length( + words: &mut Peekable>, + magnification: i32, +) -> Result { + let word = words.next().ok_or("missing XDV image length")?; + let split = word + .bytes() + .position(|byte| byte.is_ascii_alphabetic()) + .unwrap_or(word.len()); + let (value, mut unit) = word.split_at(split); + let value = number(Some(value))?; + if unit.is_empty() && words.peek().is_some_and(|word| is_unit(word)) { + unit = words.next().unwrap(); + } + let mut factor = 1.0; + if let Some(rest) = unit.strip_prefix("true") { + unit = if rest.is_empty() { + words.next().ok_or("missing XDV image unit")? + } else { + rest + }; + factor *= 1000.0 / f64::from(magnification); + } + factor *= match unit { + "pt" => 800.0 / 803.0, + "in" => 72.0, + "cm" => 72.0 / 2.54, + "mm" => 72.0 / 25.4, + "" | "bp" => 1.0, + "pc" => 12.0 * 800.0 / 803.0, + "dd" => 1238.0 / 1157.0 * 800.0 / 803.0, + "cc" => 12.0 * 1238.0 / 1157.0 * 800.0 / 803.0, + "sp" => 800.0 / 803.0 / 65536.0, + _ => return Err("invalid XDV image length unit"), + }; + Ok(value * factor) +} + +fn is_unit(word: &str) -> bool { + word == "true" + || matches!( + word.strip_prefix("true").unwrap_or(word), + "pt" | "in" | "cm" | "mm" | "bp" | "pc" | "dd" | "cc" | "sp" + ) +} diff --git a/crates/texrra-tex-core/src/pdf_image.rs b/crates/texrra-tex-core/src/pdf_image.rs index 7fc593f..e8b7c3f 100644 --- a/crates/texrra-tex-core/src/pdf_image.rs +++ b/crates/texrra-tex-core/src/pdf_image.rs @@ -1,5 +1,7 @@ //! Native image XObjects and the resource objects reachable from their content. +mod bmp; mod jpeg; +mod icc; mod png; use crate::{ pdf_device::Affine, @@ -58,12 +60,20 @@ pub struct PdfImageUse { pub(crate) struct XdvPdfPlacement { pub(crate) page_request: i32, matrix: [u64; 6], + #[serde(default, skip_serializing_if = "Option::is_none")] + clip: Option<[u64; 4]>, + #[serde(default)] + pub(crate) layout_offset: [i64; 2], } impl XdvPdfPlacement { pub(crate) fn paint_matrix(&self) -> [f64; 6] { self.matrix.map(f64::from_bits) } + + pub(crate) fn clip(&self) -> Option<[f64; 4]> { + self.clip.map(|rect| rect.map(f64::from_bits)) + } } #[derive(Clone, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)] @@ -116,7 +126,7 @@ impl PdfImageUse { pub(crate) fn new_xdv( id: usize, - image: PdfImage, + image: Arc, placement: XdvImagePlacement, page_request: i32, ) -> Result { @@ -146,15 +156,68 @@ impl PdfImageUse { .parse() .expect("printed 16.16 value") }); + let matrix = if image.raster_frame().is_some() { + let [width, height] = image.extent(); + Affine(matrix) + .concatenate(Affine([width, 0.0, 0.0, height, 0.0, 0.0])) + .0 + .map(|value| (value * 100_000.0).round() / 100_000.0) + } else { + matrix + }; Ok(Self { id, - image: Arc::new(image), + image, width, height, depth: 0, xdv: Some(XdvPdfPlacement { page_request, matrix: matrix.map(f64::to_bits), + clip: None, + layout_offset: [0, 0], + }), + }) + } + + pub(crate) fn new_xdv_raster_special( + id: usize, + image: Arc, + matrix: Affine, + clip: Option<[f64; 4]>, + ) -> Result { + if matrix.0.iter().any(|value| !value.is_finite()) + || clip.is_some_and(|rect| rect.iter().any(|value| !value.is_finite())) + { + return Err("XDV raster image transform exceeds capacity".into()); + } + let [x, y, w, h] = clip.unwrap_or([0.0, 0.0, 1.0, 1.0]); + let [x0, y0, x1, y1] = [x, y, x + w, y + h].map(|value| value.clamp(0.0, 1.0)); + let [left, bottom] = matrix.point(x0, y0); + let bounds = [(x0, y1), (x1, y0), (x1, y1)].iter().fold( + [left, bottom, left, bottom], + |[left, bottom, right, top], &(x, y)| { + let [x, y] = matrix.point(x, y); + [left.min(x), bottom.min(y), right.max(x), top.max(y)] + }, + ); + let [left, bottom, right, top] = + bounds.map(|value| (value * 803.0 / 800.0 * 65536.0).round()); + if [left, bottom, right, top].iter().any(|value| value.abs() > 1_073_741_823.0) { + return Err("XDV raster image bounds exceed capacity".into()); + } + let matrix = matrix.0.map(|value| (value * 100_000.0).round() / 100_000.0); + Ok(Self { + id, + image, + width: (right - left) as i64, + height: (top - bottom) as i64, + depth: 0, + xdv: Some(XdvPdfPlacement { + page_request: 0, + matrix: matrix.map(f64::to_bits), + clip: clip.map(|rect| rect.map(f64::to_bits)), + layout_offset: [left as i64, bottom as i64], }), }) } @@ -250,7 +313,9 @@ enum Part { precision: u8, bytes: Vec, }, - Png(png::PngImage), + Png(png::SampledImage), + Bmp(png::SampledImage), + XdvCmykDecode, } pub(crate) fn real(value: f64) -> String { @@ -281,13 +346,6 @@ impl PdfImage { if header.progressive && pdf_version.0 == 1 && pdf_version.1 <= 2 { return Err("cannot use progressive DCT with PDF-1.2".into()); } - let [width, height] = header.size; - let color = match header.components { - 1 => "/DeviceGray", - 3 => "/DeviceRGB", - 4 => "/DeviceCMYK /Decode [1 0 1 0 1 0 1 0]", - _ => unreachable!("JPEG component count was checked"), - }; let mut density = header.density; let warning = if density.iter().any(|&dpi| dpi > 65_535) { Some("too large image resolution ignored") @@ -306,31 +364,115 @@ impl PdfImage { let denominator = 100 * i64::from(density[axis]); (numerator + denominator / 2) / denominator }); - let dictionary = format!( - "/Type /XObject /Subtype /Image /Width {width} /Height {height} \ - /ColorSpace {color} /BitsPerComponent {} /Filter /DCTDecode /Length {} >>\nstream\n", + Ok((Self::jpeg_xobject(resource, header, natural, [1.0; 2], false), warning)) + } + + fn jpeg_xobject( + resource: LoadedResource, + header: jpeg::Header, + natural: [i64; 2], + extent: [f64; 2], + xdv: bool, + ) -> Self { + let [width, height] = header.size; + let color = match header.components { + 1 => "/DeviceGray", + 3 => "/DeviceRGB", + 4 => "/DeviceCMYK", + _ => unreachable!("JPEG component count was checked"), + }; + let profile = header.icc.as_ref() + .filter(|_| xdv) + .and_then(|bytes| icc::intent(bytes, header.components).map(|intent| (bytes, intent))); + let mut parts = vec![Part::Bytes( + format!("/Type /XObject /Subtype /Image /Width {width} /Height {height}").into_bytes(), + )]; + if let Some((_, intent)) = profile { + parts.push(Part::Bytes(format!(" /Intent /{intent} /ColorSpace [/ICCBased ").into_bytes())); + parts.push(Part::Ref(1)); + parts.push(Part::Bytes(b"]".to_vec())); + } else { + parts.push(Part::Bytes(format!(" /ColorSpace {color}").into_bytes())); + } + if header.components == 4 { + if xdv && header.adobe { + parts.push(Part::XdvCmykDecode); + } else if !xdv { + parts.push(Part::Bytes(b" /Decode [1 0 1 0 1 0 1 0]".to_vec())); + } + } + parts.push(Part::Bytes(format!( + " /BitsPerComponent {} /Filter /DCTDecode /Length {} >>\nstream\n", header.precision, resource.data.len() + ).into_bytes())); + parts.push(Part::Jpeg { + size: header.size, + precision: header.precision, + bytes: resource.data, + }); + parts.push(Part::Bytes(b"\nendstream".to_vec())); + let mut objects = vec![parts]; + if let Some((bytes, _)) = profile { + objects.push(vec![Part::Bytes(crate::pdf::objects::stream( + &format!("/N {} /Alternate {color}", header.components), + bytes, + 6, + ))]); + } + Self { + version: resource.version, + page: 1, + page_count: 1, + natural, + extent: extent.map(f64::to_bits), + objects, + } + } + + pub(crate) fn read_xdv_raster(resource: LoadedResource) -> Result { + let invalid = |error: &str| format!( + "could not parse XDV raster {}: {error}", + resource.version.path.display() ); - Ok(( - Self { - version: resource.version, - page: 1, - page_count: 1, - natural, - extent: [1.0_f64.to_bits(); 2], - objects: vec![vec![ - Part::Bytes(dictionary.into_bytes()), - Part::Jpeg { - size: header.size, - precision: header.precision, - bytes: resource.data, - }, - Part::Bytes(b"\nendstream".to_vec()), - ]], - }, - warning, - )) + let extent = |size: [u32; 2], density: [f64; 2]| -> Result<[f64; 2], String> { + let bp = std::array::from_fn(|axis| f64::from(size[axis]) * 72.0 / density[axis]); + if bp.iter().any(|&value| !value.is_finite() || value <= 0.0) { + return Err(invalid("invalid dimensions or density")); + } + Ok(bp) + }; + let natural = + |bp: [f64; 2]| bp.map(|value| (value * 803.0 / 800.0 * 65536.0).round() as i64); + if resource.data.starts_with(jpeg::SIGNATURE) { + let header = jpeg::read(&resource.data).map_err(invalid)?; + let bp = extent(header.size.map(u32::from), header.xdv_density)?; + return Ok(Self::jpeg_xobject(resource, header, natural(bp), bp, true)); + } + let (part, bp) = if Self::is_png(&resource) { + let (image, physical) = png::decode(&resource.data).map_err(|error| invalid(&error))?; + let density = physical.map_or([72.0; 2], |physical| { + [physical.xppu, physical.yppu].map(|ppm| { + if ppm == 0 { 72.0 } else { f64::from(ppm) * 0.0254 } + }) + }); + let bp = extent(image.size, density)?; + (Part::Png(image), bp) + } else if resource.data.starts_with(bmp::SIGNATURE) { + let (image, density) = bmp::decode(&resource.data).map_err(|error| invalid(&error))?; + let bp = extent(image.size, density)?; + (Part::Bmp(image), bp) + } else { + return Err(invalid("expected PNG, JPEG, or BMP")); + }; + Ok(Self { + version: resource.version, + page: 1, + page_count: 1, + natural: natural(bp), + extent: bp.map(f64::to_bits), + objects: vec![vec![part]], + }) } pub(crate) fn is_png(resource: &LoadedResource) -> bool { @@ -349,20 +491,22 @@ impl PdfImage { Part::Jpeg { size, precision, .. } => Some((size.map(i64::from), *precision)), - Part::Png(png) => Some((png.size.map(i64::from), png.source_depth)), + Part::Png(samples) | Part::Bmp(samples) => { + Some((samples.size.map(i64::from), samples.source_depth)) + } _ => None, }) } - fn png(&self) -> Option<&png::PngImage> { + fn sampled_image(&self) -> Option<&png::SampledImage> { match self.objects.first()?.as_slice() { - [Part::Png(png)] => Some(png), + [Part::Png(samples) | Part::Bmp(samples)] => Some(samples), _ => None, } } pub(crate) fn png_transparency(&self, pdf_version: (i32, i32)) -> bool { - self.png().is_some_and(|png| png.has_alpha(pdf_version)) + self.sampled_image().is_some_and(|samples| samples.has_alpha(pdf_version)) } pub(crate) fn read( @@ -557,8 +701,8 @@ impl PdfImage { compression: u8, pdf_version: (i32, i32), ) -> usize { - if let Some(png) = self.png() { - return png.append(pdf, attributes, compression, pdf_version); + if let Some(samples) = self.sampled_image() { + return samples.append(pdf, attributes, compression, pdf_version); } let base = pdf.len() + 1; pdf.extend(self.objects.iter().enumerate().map(|(index, parts)| { @@ -574,7 +718,15 @@ impl PdfImage { match part { Part::Bytes(bytes) | Part::Jpeg { bytes, .. } => body.extend_from_slice(bytes), Part::Ref(id) => write!(body, "{} 0 R", base + id).unwrap(), - Part::Png(_) => unreachable!("PNG owns its image objects"), + Part::Png(_) | Part::Bmp(_) => unreachable!("sampled image owns its objects"), + Part::XdvCmykDecode => { + if !attributes + .split(|byte| byte.is_ascii_whitespace()) + .any(|part| part == b"/Decode") + { + body.extend_from_slice(b" /Decode [1 0 1 0 1 0 1 0]"); + } + } } } body diff --git a/crates/texrra-tex-core/src/pdf_image/bmp.rs b/crates/texrra-tex-core/src/pdf_image/bmp.rs new file mode 100644 index 0000000..7c36235 --- /dev/null +++ b/crates/texrra-tex-core/src/pdf_image/bmp.rs @@ -0,0 +1,41 @@ +//! BMP raster decoding and the density recorded by the DIB header. +use image::{ColorType, ImageDecoder, codecs::bmp::BmpDecoder}; +use std::io::Cursor; + +use super::png::SampledImage; + +pub(super) const SIGNATURE: &[u8] = b"BM"; + +pub(super) fn decode(bytes: &[u8]) -> Result<(SampledImage, [f64; 2]), String> { + let dib = bytes.get(14..).ok_or("truncated BMP file header")?; + let long = |at: usize| -> Result { + let word = dib.get(at..at + 4).ok_or("truncated BMP DIB header")?; + Ok(u32::from_le_bytes(word.try_into().unwrap())) + }; + let density = match long(0)? { + 12 => [72.0; 2], + 40 | 52 | 56 | 108 | 124 => { + let ppm = [long(24)? as i32, long(28)? as i32]; + if ppm.iter().all(|&value| value > 0) { + ppm.map(|value| f64::from(value) * 0.0254) + } else { + [72.0; 2] + } + } + _ => return Err("unsupported BMP DIB header".into()), + }; + let decoder = BmpDecoder::new(Cursor::new(bytes)).map_err(|error| error.to_string())?; + if decoder.color_type() != ColorType::Rgb8 { + return Err("unsupported BMP color layout for XDV".into()); + } + let (width, height) = decoder.dimensions(); + let capacity = decoder.total_bytes(); + if capacity > 256 * 1024 * 1024 { + return Err("decoded BMP exceeds native image capacity".into()); + } + let mut samples = vec![0; capacity as usize]; + decoder + .read_image(&mut samples) + .map_err(|error| error.to_string())?; + Ok((SampledImage::rgb8([width, height], samples), density)) +} diff --git a/crates/texrra-tex-core/src/pdf_image/icc.rs b/crates/texrra-tex-core/src/pdf_image/icc.rs new file mode 100644 index 0000000..9fdc030 --- /dev/null +++ b/crates/texrra-tex-core/src/pdf_image/icc.rs @@ -0,0 +1,24 @@ +//! ICC profile metadata needed by PDF image color spaces. + +pub(super) fn intent(profile: &[u8], components: u8) -> Option<&'static str> { + let header = profile.get(..128)?; + let size = u32::from_be_bytes(header[..4].try_into().unwrap()) as usize; + let signature: &[u8] = match components { + 1 => b"GRAY", + 3 => b"RGB ", + 4 => b"CMYK", + _ => return None, + }; + if size != profile.len() || &header[16..20] != signature || &header[36..40] != b"acsp" { + return None; + } + let intent = u32::from_be_bytes(header[64..68].try_into().unwrap()); + [ + "Perceptual", + "RelativeColorimetric", + "Saturation", + "AbsoluteColorimetric", + ] + .get(intent as usize) + .copied() +} diff --git a/crates/texrra-tex-core/src/pdf_image/jpeg.rs b/crates/texrra-tex-core/src/pdf_image/jpeg.rs index e4c9ae8..206a338 100644 --- a/crates/texrra-tex-core/src/pdf_image/jpeg.rs +++ b/crates/texrra-tex-core/src/pdf_image/jpeg.rs @@ -1,4 +1,5 @@ -//! JPEG frame and density metadata. The encoded image stays in its original stream. +//! JPEG frame, density and color-profile metadata. +use std::collections::BTreeMap; pub(super) const SIGNATURE: &[u8] = b"\xff\xd8"; @@ -7,7 +8,10 @@ pub(super) struct Header { pub precision: u8, pub components: u8, pub density: [u32; 2], + pub xdv_density: [f64; 2], pub progressive: bool, + pub icc: Option>, + pub adobe: bool, } pub(super) fn read(bytes: &[u8]) -> Result { @@ -15,7 +19,10 @@ pub(super) fn read(bytes: &[u8]) -> Result { .strip_prefix(SIGNATURE) .ok_or("missing JPEG signature")?; let mut density = [0, 0]; + let mut xdv_density = [0.0; 2]; let mut first = true; + let mut profile_chunks = BTreeMap::new(); + let mut adobe = false; let truncated = "premature end of JPEG header"; loop { rest = rest.strip_prefix(&[0xff]).ok_or("expected JPEG marker")?; @@ -61,42 +68,87 @@ pub(super) fn read(bytes: &[u8]) -> Result { precision, components, density, + xdv_density: if xdv_density == [0.0; 2] { + [72.0; 2] + } else { + xdv_density + }, progressive: marker == 0xc2, + icc: assemble_profile(&profile_chunks), + adobe, }); } 0xc5..=0xc7 | 0xc9..=0xcb | 0xcd..=0xcf => { return Err("unsupported JPEG compression"); } - 0xe0 if first => { + 0xe0 => { if let Some(&[_, _, unit, x0, x1, y0, y1, ..]) = segment.strip_prefix(b"JFIF\0") { let x = u32::from(u16::from_be_bytes([x0, x1])); let y = u32::from(u16::from_be_bytes([y0, y1])); - density = match unit { - 1 => [x, y], - 2 => [x * 254 / 100, y * 254 / 100], - _ => [0, 0], + xdv_density = match unit { + 1 => [f64::from(x), f64::from(y)], + 2 => [f64::from(x) * 2.54, f64::from(y) * 2.54], + _ => [72.0; 2], }; - if density.contains(&0) { - density = [density[0].max(density[1]); 2]; + if first { + density = match unit { + 1 => [x, y], + 2 => [x * 254 / 100, y * 254 / 100], + _ => [0, 0], + }; + if density.contains(&0) { + density = [density[0].max(density[1]); 2]; + } } } } - 0xe1 if first => { + 0xe1 => { if let Some(tiff) = segment.strip_prefix(b"Exif\0") { let start = tiff .iter() .position(|&byte| byte != 0) .unwrap_or(tiff.len()); - density = exif_density(&tiff[start..]).unwrap_or([0, 0]); + if let Some((legacy, exact)) = exif_density(&tiff[start..]) { + if first { + density = legacy; + } + if xdv_density.iter().all(|dpi| *dpi < 0.1) { + xdv_density = exact; + } + } } } + 0xe2 => { + if let Some(&[index, count, ref bytes @ ..]) = + segment.strip_prefix(b"ICC_PROFILE\0") + { + profile_chunks.insert(index, (count, bytes)); + } + } + 0xee if segment.starts_with(b"Adobe") => adobe = true, _ => {} } first = false; } } -fn exif_density(tiff: &[u8]) -> Option<[u32; 2]> { +fn assemble_profile(chunks: &BTreeMap) -> Option> { + let &(total, _) = chunks.get(&1)?; + if usize::from(total) != chunks.len() { + return None; + } + let mut profile = Vec::new(); + for index in 1..=total { + let &(count, data) = chunks.get(&index)?; + if count != total { + return None; + } + profile.extend_from_slice(data); + } + Some(profile) +} + +fn exif_density(tiff: &[u8]) -> Option<([u32; 2], [f64; 2])> { let little = match tiff.get(..2)? { b"II" => true, b"MM" => false, @@ -127,6 +179,7 @@ fn exif_density(tiff: &[u8]) -> Option<[u32; 2]> { let end = start.checked_add(12 * entries)?; tiff.get(start..end)?; let mut density = [72, 72]; + let mut exact = [72.0; 2]; let mut cm = false; for at in (start..end).step_by(12) { match (short(at)?, short(at + 2)?, long(at + 4)?) { @@ -135,7 +188,9 @@ fn exif_density(tiff: &[u8]) -> Option<[u32; 2]> { let numerator = long(offset)?; let denominator = long(offset.checked_add(4)?)?; if denominator != 0 { - density[usize::from(tag == 283)] = numerator / denominator; + let axis = usize::from(tag == 283); + density[axis] = numerator / denominator; + exact[axis] = f64::from(numerator) / f64::from(denominator); } } (296, 3, 1) => cm = short(at + 8)? == 3, @@ -145,6 +200,22 @@ fn exif_density(tiff: &[u8]) -> Option<[u32; 2]> { if cm { density = density.map(|value| u32::try_from(u64::from(value) * 254 / 100).unwrap_or(u32::MAX)); + exact = exact.map(|dpi| dpi * 2.54); + } + Some((density, exact)) +} + +#[cfg(test)] +mod tests { + use super::read; + + #[test] + fn jfif_keeps_fractional_xdv_density_and_legacy_integer_density() { + let mut jpeg = b"\xff\xd8\xff\xe0\x00\x10JFIF\0\x01\x02\x02\x00\x30\x00\x39\0\0".to_vec(); + jpeg.extend_from_slice(b"\xff\xc0\x00\x0b\x08\x00\x64\x00\xb4\x01\x01\x11\x00"); + let header = read(&jpeg).unwrap(); + assert_eq!(header.size, [180, 100]); + assert_eq!(header.density, [121, 144]); + assert_eq!(header.xdv_density, [48.0 * 2.54, 57.0 * 2.54]); } - Some(density) } diff --git a/crates/texrra-tex-core/src/pdf_image/png.rs b/crates/texrra-tex-core/src/pdf_image/png.rs index c258446..2e32f2c 100644 --- a/crates/texrra-tex-core/src/pdf_image/png.rs +++ b/crates/texrra-tex-core/src/pdf_image/png.rs @@ -1,7 +1,7 @@ //! Decode PNG samples for native PDF image XObjects. use super::{Part, PdfImage}; use crate::{pdf::objects, resources::LoadedResource}; -use ::png::{ColorType, Decoder, Transformations, Unit}; +use ::png::{ColorType, Decoder, PixelDimensions, Transformations, Unit}; use serde::{Deserialize, Serialize}; use std::{fmt::Write, io::Cursor}; @@ -15,7 +15,7 @@ enum ColorSpace { } #[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)] -pub(super) struct PngImage { +pub(super) struct SampledImage { pub(super) size: [u32; 2], pub(super) source_depth: u8, depth: u8, @@ -24,7 +24,7 @@ pub(super) struct PngImage { alpha: Vec, } -fn decode(bytes: &[u8]) -> Result<(PngImage, [u32; 2]), String> { +pub(super) fn decode(bytes: &[u8]) -> Result<(SampledImage, Option), String> { let read_info = |transforms| { let mut decoder = Decoder::new(Cursor::new(bytes)); decoder.set_transformations(transforms); @@ -39,12 +39,9 @@ fn decode(bytes: &[u8]) -> Result<(PngImage, [u32; 2]), String> { reader = read_info(Transformations::EXPAND)?; } let info = reader.info(); - let density = info + let physical = info .pixel_dims - .filter(|physical| physical.unit == Unit::Meter) - .map_or([0, 0], |physical| { - [physical.xppu, physical.yppu].map(|px| ((u64::from(px) * 254 + 5_000) / 10_000) as u32) - }); + .filter(|physical| physical.unit == Unit::Meter); let palette = info.palette.clone(); let capacity = reader .output_buffer_size() @@ -90,7 +87,7 @@ fn decode(bytes: &[u8]) -> Result<(PngImage, [u32; 2]), String> { buf.truncate(alpha.len() * color_bytes); } Ok(( - PngImage { + SampledImage { size: [width, height], source_depth, depth, @@ -98,7 +95,7 @@ fn decode(bytes: &[u8]) -> Result<(PngImage, [u32; 2]), String> { samples: buf, alpha, }, - density, + physical, )) } @@ -106,12 +103,15 @@ pub(super) fn read( resource: LoadedResource, fallback_resolution: i32, ) -> Result<(PdfImage, Option<&'static str>), String> { - let (image, mut density) = decode(&resource.data).map_err(|error| { + let (image, physical) = decode(&resource.data).map_err(|error| { format!( "could not parse PNG image {}: {error}", resource.version.path.display() ) })?; + let mut density = physical.map_or([0, 0], |physical| { + [physical.xppu, physical.yppu].map(|px| ((u64::from(px) * 254 + 5_000) / 10_000) as u32) + }); let warning = if density.iter().any(|&dpi| dpi > 65_535) { Some("too large image resolution ignored") } else if density != [0, 0] && density.contains(&0) { @@ -141,7 +141,18 @@ pub(super) fn read( )) } -impl PngImage { +impl SampledImage { + pub(super) fn rgb8(size: [u32; 2], samples: Vec) -> Self { + Self { + size, + source_depth: 8, + depth: 8, + color: ColorSpace::Rgb, + samples, + alpha: Vec::new(), + } + } + pub(super) fn has_alpha(&self, pdf_version: (i32, i32)) -> bool { pdf_version >= (1, 4) && !self.alpha.is_empty() } diff --git a/crates/texrra-tex-core/tests/execution_xetex_profile.rs b/crates/texrra-tex-core/tests/execution_xetex_profile.rs index 6a1e533..03686c3 100644 --- a/crates/texrra-tex-core/tests/execution_xetex_profile.rs +++ b/crates/texrra-tex-core/tests/execution_xetex_profile.rs @@ -41,7 +41,7 @@ fn xetex_primitives_follow_each_profiles_language_and_device() { \message{\meaning\XeTeXversion/\meaning\XeTeXrevision/\meaning\pdfoutput} \message{\meaning\strcmp/\meaning\pdfstrcmp/\meaning\pdfsavepos} \message{\meaning\pdftexversion/\meaning\Uchar/\meaning\pdfpagesattr} - \message{\meaning\XeTeXpdffile/\meaning\XeTeXpdfpagecount} + \message{\meaning\XeTeXpdffile/\meaning\XeTeXpdfpagecount/\meaning\XeTeXpicfile} \end"; for (profile, etex, expected) in [ ( @@ -51,7 +51,7 @@ fn xetex_primitives_follow_each_profiles_language_and_device() { r"\XeTeXversion/\XeTeXrevision/undefined", r"\strcmp/undefined/\pdfsavepos", r"undefined/\Uchar/undefined", - r"\XeTeXpdffile/\XeTeXpdfpagecount", + r"\XeTeXpdffile/\XeTeXpdfpagecount/\XeTeXpicfile", ], ), ( @@ -61,7 +61,7 @@ fn xetex_primitives_follow_each_profiles_language_and_device() { "undefined/undefined/undefined", r"\strcmp/undefined/\pdfsavepos", r"undefined/\Uchar/undefined", - "undefined/undefined", + "undefined/undefined/undefined", ], ), ( @@ -71,7 +71,7 @@ fn xetex_primitives_follow_each_profiles_language_and_device() { r"undefined/undefined/\pdfoutput", r"undefined/\pdfstrcmp/\pdfsavepos", r"undefined/\Uchar/\pdfpagesattr", - "undefined/undefined", + "undefined/undefined/undefined", ], ), ( @@ -81,7 +81,7 @@ fn xetex_primitives_follow_each_profiles_language_and_device() { r"undefined/undefined/\pdfoutput", r"undefined/\pdfstrcmp/\pdfsavepos", r"\pdftexversion/undefined/\pdfpagesattr", - "undefined/undefined", + "undefined/undefined/undefined", ], ), ] { diff --git a/docs/P2_M1_PROGRESS.md b/docs/P2_M1_PROGRESS.md index a876855..2babc6c 100644 --- a/docs/P2_M1_PROGRESS.md +++ b/docs/P2_M1_PROGRESS.md @@ -2175,6 +2175,39 @@ PDF,恢复实际 PFB 并反转斜切时复用 1277 步,只替换第二页。 全量编译一致。incremental-receipt.json 的 SHA-256 为 bbc0991b0316e6d76aa58649ec873525f5544ab530d93fe491fc6e16bd00a27d。 +### XeTeX 位图原语和出页设备 + +\XeTeXpicfile 接入扩展原语表。PNG 读取 pHYs,JPEG 读取 JFIF +与 Exif,BMP 读取实际 DIB 头和样本。密度使用原始精度,盒节点 +沿用 XeTeX 的单精度角点、宽高调整及旋转。BMP 无有效密度时 +采用 xdvipdfmx 的 72 DPI 默认值。参考原语在这一输入上的溢出 +诊断保留于 reference/no-density.console.log。 + +原样 xetex.def 使用原语测量,再以真实 pdf:image 特殊指令 +出页。引擎按设备协议解释文件名、裁剪框、尺寸、变换与图像 +属性,在实际出页读取资源并记录原样路径及指纹。PNG 保留透明 +样本,JPEG 直接嵌入原始 DCT 数据和有效 ICC 配置,BMP 复用 +现有 Rust 解码器。同一资源版本的测量与出页共享已解码样本。 + +原样 xelatex.ini 生成 schema64。单独原语、原样 graphicx 的六处 +位图放置和前一阶段的 PDF 放置共三个作业。盒尺寸和 144 DPI +像素逐项一致,两份 LaTeX 作业的 .aux 一致。回执与资源清单位于 +target/p3-xetex-raster/receipt.json。23 项定向回归通过。三页项目在 +出页阶段读取实际 PNG,文件损坏时保留上一版 PDF。恢复更新后 +复用 1238 步,只更新第 2 页。PDF、SVG 与来源映射和同一修订的 +独立全量一致。证据见 target/p3-xetex-raster/revisions/receipt.json。 + +[XeTeX 的位图读取](https://github.com/TeX-Live/texlive-source/blob/trunk/texk/web2c/xetexdir/XeTeX_pic.c#L86-L143) +[xdvipdfmx 的图像尺寸和裁剪](https://github.com/TeX-Live/texlive-source/blob/trunk/texk/dvipdfm-x/pdfximage.c#L879-L1048) +[LaTeX 的 XeTeX 图形驱动](https://github.com/latex3/graphics-def/blob/main/xetex.def) + +同一 schema64 推进至原样 unicode-math-xetex.sty 第 3253 行。 +XeTeX 参考已用真实 Latin Modern Math 出页。当前首处差异为 +^^^^2032 被输入扫描拆成 U+001E。原样输入、从 CTAN TeX Live +取得的包与字体、参考 PDF 和失败日志保存在 +target/p3-xetex-raster/math-next。接续 XeTeX 的扩展 ^^ 字符 +转换,再按真实包的实际执行推进 OpenType MATH。 + ### XeTeX PDF 图形节点与设备变换 原样 xelatex.ini 生成并重载 schema63。扩展模式下