Import PNG images in the native PDF device

This commit is contained in:
gloamxun committed 2026-11-21 04:13:18 +08:00
1 parent 297431a547
commit 555a029505
13 files changed
+467 -35

No files matched your search

Generated
+1
View File
@@ -1433,6 +1433,7 @@ dependencies = [
"hyphenate",
"libc",
"lopdf",
"png 0.18.1",
"rusttype",
"serde",
"serde_json",
+1
View File
@@ -8,6 +8,7 @@ description = "Experimental incremental TeX-compatible typesetting core (route D
[dependencies]
flate2 = "1.1"
lopdf = "0.26"
png = "0.18.1"
rusttype = "0.8.3"
serde = { version = "1.0", features = ["derive", "rc"] }
serde_json = "1.0"
@@ -19,7 +19,7 @@ impl Executor {
(Primitive::Pdflastximagecolordepth, Some(image)) => image
.image
.image
.jpeg_frame()
.raster_frame()
.map_or(0, |(_, precision)| i32::from(precision)),
_ => 0,
}
@@ -99,14 +99,19 @@ impl Executor {
token.span,
)
})?;
let image = if PdfImage::is_jpeg(&source) {
let png = PdfImage::is_png(&source);
let image = if png || PdfImage::is_jpeg(&source) {
let resolution = self.read_parameter(Parameter::Pdfimageresolution).width();
let version = (
self.read_parameter(Parameter::Pdfmajorversion).width(),
self.read_parameter(Parameter::Pdfminorversion).width(),
);
let (image, warning) = PdfImage::read_jpeg(source, resolution, version)
.map_err(|error| self.error(error, token.span))?;
let decoded = if png {
PdfImage::read_png(source, resolution)
} else {
PdfImage::read_jpeg(source, resolution, version)
};
let (image, warning) = decoded.map_err(|error| self.error(error, token.span))?;
if let Some(warning) = warning {
files
.observe_diagnostic(
@@ -157,8 +162,15 @@ impl Executor {
} else {
text.into_bytes()
};
self.events
.push(Event::PdfImageObject(PdfImageObject { image, attributes }));
let compression = self
.read_parameter(Parameter::Pdfcompresslevel)
.width()
.clamp(0, 9) as u8;
self.events.push(Event::PdfImageObject(PdfImageObject {
image,
attributes,
compression,
}));
Ok(())
}
+33 -11
View File
@@ -22,7 +22,7 @@ use crate::type1::Type1Font;
#[path = "pdf_text.rs"]
mod native_text;
#[path = "pdf_objects.rs"]
mod objects;
pub(crate) mod objects;
#[path = "pdf_pk.rs"]
mod pk_fonts;
@@ -983,7 +983,7 @@ fn page_content(
height: image_height,
image,
} => {
let [sx, sy] = if image.image.jpeg_frame().is_some()
let [sx, sy] = if image.image.raster_frame().is_some()
&& list.units == crate::render::DisplayUnits::TeX
{
[
@@ -2183,15 +2183,21 @@ fn write_pdf(
let mut page_ids: Vec<usize> = Vec::new();
let mut destinations = BTreeMap::new();
let mut numbers = BTreeMap::new();
let pdf_version = pages
.first()
.and_then(|page| page.pdf.as_ref())
.map_or((1, 4), |pdf| (pdf.file.major, i32::from(pdf.file.minor)));
let mut form_ids = BTreeMap::new();
for list in pages {
for item in &list.items {
if let DisplayItem::PdfImageObject(object) = item {
form_ids.entry(object.image.id).or_insert_with(|| {
object
.image
.image
.append_to(&mut objects, &object.attributes)
object.image.image.append_to(
&mut objects,
&object.attributes,
object.compression,
pdf_version,
)
});
}
}
@@ -2199,13 +2205,29 @@ fn write_pdf(
for list in pages {
for item in &list.items {
if let DisplayItem::PdfImage { image, .. } = item {
form_ids
.entry(image.id)
.or_insert_with(|| image.image.append_to(&mut objects, &[]));
form_ids.entry(image.id).or_insert_with(|| {
let compression = list.pdf.as_ref().map_or(0, |pdf| pdf.stream_compression);
image.image.append_to(&mut objects, &[], compression, pdf_version)
});
}
}
}
let mut png_group = None;
for (page_index, list) in pages.iter().enumerate() {
let png_group_ref = if !list.pdf_resources.has_page_group
&& list.items.iter().any(|item| {
matches!(item, DisplayItem::PdfImage { image, .. }
if image.image.png_transparency(pdf_version))
})
{
let id = *png_group.get_or_insert_with(|| {
objects.push(b"<< /Type /Group /S /Transparency /CS /DeviceRGB /I true >>".to_vec());
objects.len()
});
format!(" /Group {id} 0 R")
} else {
String::new()
};
let width = if final_compression.is_some() {
list.width
} else {
@@ -2343,9 +2365,9 @@ fn write_pdf(
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());
page.extend_from_slice(format!(" /Parent 2 0 R{annots}{png_group_ref} >>").as_bytes());
} else {
page.extend_from_slice(format!("{annots} /Contents {content_id} 0 R >>").as_bytes());
page.extend_from_slice(format!("{annots} /Contents {content_id} 0 R{png_group_ref} >>").as_bytes());
}
if let Some(id) = reserved_page {
objects[id - 1] = page;
@@ -77,7 +77,8 @@ pub(crate) fn resolve(
// 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");
resource.has_page_group = local.has(b"Group");
resource.needs_pdf_for_preview |= resource.overrides_paint || resource.has_page_group;
let supplied_media = supplies_media_box(&resource.attributes);
let media_value = if supplied_media {
@@ -327,6 +327,7 @@ pub struct PageResources {
pub(crate) attributes: Arc<[u8]>,
pub(crate) viewport: Option<super::page_attributes::Viewport>,
pub(crate) overrides_paint: bool,
pub(crate) has_page_group: bool,
pub(crate) opacity: BTreeMap<Vec<u8>, Transparency>,
pub(crate) needs_pdf_for_preview: bool,
}
+52 -12
View File
@@ -1,5 +1,6 @@
//! Native image XObjects and the resource objects reachable from their content.
mod jpeg;
mod png;
use crate::resources::{LoadedResource, ResourceVersion};
use lopdf::{Dictionary, Document, Object, ObjectId};
use std::{
@@ -52,6 +53,8 @@ pub struct PdfImageUse {
pub struct PdfImageObject {
pub image: Arc<PdfImageUse>,
pub attributes: Vec<u8>,
#[serde(default)]
pub compression: u8,
}
impl PdfImageUse {
@@ -61,21 +64,24 @@ impl PdfImageUse {
requested: [Option<i32>; 3],
) -> Result<Self, String> {
let [w, h] = image.natural;
let jpeg = image.jpeg_frame().map(|(size, _)| size.map(i64::from));
let [aspect_width, aspect_height] = jpeg.unwrap_or([w, h]);
let raster = image.raster_frame().map(|(size, _)| size);
let [aspect_width, aspect_height] = raster.unwrap_or([w, h]);
let [width, height, depth] = requested.map(|value| value.map(i64::from));
let ratio = |value: i64, numerator: i64, denominator: i64| {
let product = value * numerator;
product.signum() * ((product.abs() + denominator / 2) / denominator)
let ratio = |value: i64, numerator: i64, denominator: i64| -> Result<i64, String> {
let product = i128::from(value) * i128::from(numerator);
let denominator = i128::from(denominator);
let rounded = product.signum() * ((product.abs() + denominator / 2) / denominator);
i64::try_from(rounded)
.map_err(|_| "native PDF image dimension capacity exceeded".into())
};
let depth = depth.unwrap_or(0);
let (width, height) = match (width, height) {
(None, None) if jpeg.is_some() && requested[2].is_some() => {
(ratio(h, aspect_width, aspect_height), h - depth)
(None, None) if raster.is_some() && requested[2].is_some() => {
(ratio(h, aspect_width, aspect_height)?, h - depth)
}
(None, None) => (w, h - depth),
(Some(width), None) => (width, ratio(width, aspect_height, aspect_width) - depth),
(None, Some(height)) => (ratio(height + depth, aspect_width, aspect_height), height),
(Some(width), None) => (width, ratio(width, aspect_height, aspect_width)? - depth),
(None, Some(height)) => (ratio(height + depth, aspect_width, aspect_height)?, height),
(Some(width), Some(height)) => (width, height),
};
if [width, height, depth].iter().any(|v| v.abs() > 1073741823) {
@@ -104,6 +110,7 @@ enum Part {
precision: u8,
bytes: Vec<u8>,
},
Png(png::PngImage),
}
pub(crate) fn real(value: f64) -> String {
@@ -186,15 +193,38 @@ impl PdfImage {
))
}
pub(crate) fn jpeg_frame(&self) -> Option<([u16; 2], u8)> {
pub(crate) fn is_png(resource: &LoadedResource) -> bool {
resource.data.starts_with(png::SIGNATURE)
}
pub(crate) fn read_png(
resource: LoadedResource,
fallback_resolution: i32,
) -> Result<(Self, Option<&'static str>), String> {
png::read(resource, fallback_resolution)
}
pub(crate) fn raster_frame(&self) -> Option<([i64; 2], u8)> {
self.objects.first()?.iter().find_map(|part| match part {
Part::Jpeg {
size, precision, ..
} => Some((*size, *precision)),
} => Some((size.map(i64::from), *precision)),
Part::Png(png) => Some((png.size.map(i64::from), png.source_depth)),
_ => None,
})
}
fn png(&self) -> Option<&png::PngImage> {
match self.objects.first()?.as_slice() {
[Part::Png(png)] => Some(png),
_ => None,
}
}
pub(crate) fn png_transparency(&self, pdf_version: (i32, i32)) -> bool {
self.png().is_some_and(|png| png.has_alpha(pdf_version))
}
pub(crate) fn read(
resource: LoadedResource,
page: usize,
@@ -324,7 +354,16 @@ impl PdfImage {
self.extent.map(f64::from_bits)
}
pub(crate) fn append_to(&self, pdf: &mut Vec<Vec<u8>>, attributes: &[u8]) -> usize {
pub(crate) fn append_to(
&self,
pdf: &mut Vec<Vec<u8>>,
attributes: &[u8],
compression: u8,
pdf_version: (i32, i32),
) -> usize {
if let Some(png) = self.png() {
return png.append(pdf, attributes, compression, pdf_version);
}
let base = pdf.len() + 1;
pdf.extend(self.objects.iter().enumerate().map(|(index, parts)| {
let mut body = Vec::new();
@@ -339,6 +378,7 @@ 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"),
}
}
body
+204
View File
@@ -0,0 +1,204 @@
//! 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 serde::{Deserialize, Serialize};
use std::{fmt::Write, io::Cursor};
pub(super) const SIGNATURE: &[u8] = b"\x89PNG\r\n\x1a\n";
#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
enum ColorSpace {
Gray,
Rgb,
Indexed(Vec<u8>),
}
#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub(super) struct PngImage {
pub(super) size: [u32; 2],
pub(super) source_depth: u8,
depth: u8,
color: ColorSpace,
samples: Vec<u8>,
alpha: Vec<u8>,
}
fn decode(bytes: &[u8]) -> Result<(PngImage, [u32; 2]), String> {
let read_info = |transforms| {
let mut decoder = Decoder::new(Cursor::new(bytes));
decoder.set_transformations(transforms);
decoder.set_ignore_text_chunk(true);
decoder.read_info().map_err(|error| error.to_string())
};
let mut reader = read_info(Transformations::IDENTITY)?;
let [width, height] = [reader.info().width, reader.info().height];
let source_depth = reader.info().bit_depth as u8;
// Preserve packed grayscale and palettes unless tRNS needs an alpha channel.
if reader.info().trns.is_some() {
reader = read_info(Transformations::EXPAND)?;
}
let info = reader.info();
let density = 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)
});
let palette = info.palette.clone();
let capacity = reader
.output_buffer_size()
.ok_or("PNG dimensions exceed decoder capacity")?;
// The decoder limits its own scratch allocations. Its caller-provided
// output buffer also needs a bound before allocating decompressed pixels.
if capacity > 256 * 1024 * 1024 {
return Err("decoded PNG exceeds native image capacity".into());
}
let mut buf = vec![0; capacity];
let info = reader
.next_frame(&mut buf)
.map_err(|error| error.to_string())?;
if [info.width, info.height] != [width, height] {
return Err("PNG default frame dimensions differ from IHDR".into());
}
buf.truncate(info.buffer_size());
reader.finish().map_err(|error| error.to_string())?;
let color = match info.color_type {
ColorType::Grayscale | ColorType::GrayscaleAlpha => ColorSpace::Gray,
ColorType::Rgb | ColorType::Rgba => ColorSpace::Rgb,
ColorType::Indexed => {
let table = palette.ok_or("indexed PNG has no palette")?;
if !(3..=768).contains(&table.len()) || table.len() % 3 != 0 {
return Err("invalid indexed PNG palette".into());
}
ColorSpace::Indexed(table.into_owned())
}
};
let depth = info.bit_depth as u8;
let mut alpha = Vec::new();
if matches!(info.color_type, ColorType::GrayscaleAlpha | ColorType::Rgba) {
let sample = usize::from(depth / 8);
let stride = sample * info.color_type.samples();
let color_bytes = stride - sample;
alpha.reserve(buf.len() / stride);
for offset in (0..buf.len()).step_by(stride) {
let start = offset / stride * color_bytes;
// PDF's soft mask uses the high byte even for 16-bit PNG color.
alpha.push(buf[offset + color_bytes]);
buf.copy_within(offset..offset + color_bytes, start);
}
buf.truncate(alpha.len() * color_bytes);
}
Ok((
PngImage {
size: [width, height],
source_depth,
depth,
color,
samples: buf,
alpha,
},
density,
))
}
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| {
format!(
"could not parse PNG image {}: {error}",
resource.version.path.display()
)
})?;
let warning = if density.iter().any(|&dpi| dpi > 65_535) {
Some("too large image resolution ignored")
} else if density != [0, 0] && density.contains(&0) {
Some("too small image resolution ignored")
} else {
None
};
if warning.is_some() || density == [0, 0] {
let resolution = fallback_resolution.clamp(0, 65_535) as u32;
density = [if resolution == 0 { 72 } else { resolution }; 2];
}
let natural = std::array::from_fn(|axis| {
let numerator = 473_628_672_i64 * i64::from(image.size[axis]);
let denominator = 100 * i64::from(density[axis]);
(numerator + denominator / 2) / denominator
});
Ok((
PdfImage {
version: resource.version,
page: 1,
page_count: 1,
natural,
extent: [1.0_f64.to_bits(); 2],
objects: vec![vec![Part::Png(image)]],
},
warning,
))
}
impl PngImage {
pub(super) fn has_alpha(&self, pdf_version: (i32, i32)) -> bool {
pdf_version >= (1, 4) && !self.alpha.is_empty()
}
pub(super) fn append(
&self,
pdf: &mut Vec<Vec<u8>>,
attributes: &[u8],
compression: u8,
pdf_version: (i32, i32),
) -> usize {
let id = pdf.len() + 1;
let [width, height] = self.size;
let mut color = match &self.color {
ColorSpace::Gray => "/DeviceGray".to_owned(),
ColorSpace::Rgb => "/DeviceRGB".to_owned(),
ColorSpace::Indexed(table) => {
let mut color = format!("[/Indexed /DeviceRGB {} <", table.len() / 3 - 1);
for byte in table {
write!(color, "{byte:02X}").expect("writing to a string");
}
color.push_str(">]");
color
}
};
let has_alpha = self.has_alpha(pdf_version);
if has_alpha {
write!(color, " /SMask {} 0 R", id + 1).expect("writing to a string");
}
let strip_16 = pdf_version < (1, 5) && self.depth == 16;
let reduced;
let (depth, samples): (u8, &[u8]) = if strip_16 {
reduced = self.samples.iter().step_by(2).copied().collect::<Vec<_>>();
(8, &reduced)
} else {
(self.depth, &self.samples)
};
let extra = format!(
"/Type /XObject /Subtype /Image /Width {width} /Height {height} \
/ColorSpace {color} /BitsPerComponent {depth}"
);
let mut stream = objects::stream(&extra, samples, compression);
if !attributes.is_empty() {
// Image attributes are TeX printer bytes and may be non-UTF-8.
stream.splice(3..3, attributes.iter().copied().chain([b'\n']));
}
pdf.push(stream);
if has_alpha {
pdf.push(objects::stream(
&format!(
"/Type /XObject /Subtype /Image /Width {width} /Height {height} \
/ColorSpace /DeviceGray /BitsPerComponent 8"
),
&self.alpha,
compression,
));
}
id
}
}
+1 -1
View File
@@ -2,7 +2,7 @@
use crate::pdf_device::PdfFileOptions;
use std::io::Write;
pub(super) fn stream(extra: &str, data: &[u8], level: u8) -> Vec<u8> {
pub(crate) fn stream(extra: &str, data: &[u8], level: u8) -> Vec<u8> {
let encoded = if level == 0 {
data.to_vec()
} else {
+12 -2
View File
@@ -322,9 +322,16 @@ impl DisplayList {
self.pdf_resources.viewport.as_ref().map_or(1.0, |viewport| viewport.unit())
}
fn svg_paint_items(&self) -> impl Iterator<Item = &DisplayItem> {
self.items
.iter()
.filter(|item| !matches!(item, DisplayItem::PdfImageObject(_)))
}
/// 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 {
let mut right = other.svg_paint_items();
self.width == other.width
&& self.height == other.height
&& self.units == other.units
@@ -333,8 +340,10 @@ impl DisplayList {
&& 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)| {
&& self.svg_paint_items().all(|left| {
let Some(right) = right.next() else {
return false;
};
match (left.native_svg_glyph(), right.native_svg_glyph()) {
(Some(Ok(left)), Some(Ok(right))) => left == right,
(None, None) => {
@@ -344,6 +353,7 @@ impl DisplayList {
_ => false,
}
})
&& right.next().is_none()
}
pub fn push(&mut self, item: DisplayItem) {
+30
View File
@@ -1287,6 +1287,36 @@ PDF、SVG 和归一化来源映射与独立零复用编译一致,同一格式
- `receipt.json` 为 `b4100de1a529f99f870539b79f1e3661e49bdc403faffff593e8678fa404aa08`。
- `checkpoint/receipt.json` 为 `3292cbbb221fc0c4d82261a322b73c12bc777ab3f9be1ad66369bfc78326def0`。
原样 ACM 双栏使用同一格式、44个冻结输入和原字体映射越过首个编号公式。
在 acmtog.tex:618 停于 sample-franklin.png,当时图片入口将其送给 PDF
解析器。该轮回执 `acm-acmtog/receipt.json` 为
`15de2817bb35ab902160236c638966509d2a7f496dfbc957c9be199eb018d548`。
### 原生 PNG 图像
`\pdfximage` 识别图片签名,读取实际 PNG 资源版本。尺寸计算使用 pHYs
中的双轴密度和现有 `\pdfimageresolution`,明确指定的尺寸沿用原生栅格图的
像素宽高比。设备从解码后的真实像素生成灰度、RGB 或索引色图像对象。
透明像素使用软蒙版。PDF 1.4 起输出软蒙版,PDF 1.5 起保留 16 位色样。
页已有显式透明组时沿用该组。图像声明仅用于构造 PDF 对象,在 SVG 直接
绘制的页中跳过声明比较,实际图像引用和需要 PDF 合成的页仍由原设备结果决定。
[pdfTeX 图像读取及发页行为](https://github.com/TeX-Live/texlive-source/blob/trunk/texk/web2c/pdftexdir/writepng.c)
原样 ACM 灰度图片及构造的 RGB、索引色、透明蒙版和 16 位图像组成 11 页
INITEX 对照。11 页的原始 sp 尺寸、查询值、设备图像属性及 144 DPI 彩色像素
与 pdfTeX 一致。原样 PNG SHA-256 及逐页结果记录在
`target/p3-png-native/comparison.json`,回执 SHA-256
`084c547620db998a0284b54d465f2b5b1d3e056b0e7cbfdaf21c3bbc38605a32`。
图片测试共4项通过,覆盖原有 JPEG、旋转 PDF、PDF 预览与本轮 PNG。
在同一原子项目版本中替换 PNG 二进制,续编实用检查点,只重发引用该资源的
第二页,PDF、SVG 与来源映射同独立零复用编译一致。重读生成的对象确认 RGB
与蒙版字节均来自更新后的图像。验证保留了 INITEX 缺类别码、从错误字段读取
断言及设备对象声明使两页重发的初次记录。最终日志 SHA-256 为
`5a1bbb811cbede5c4e24c60a3bfc71ebd1006dd3beb4515b96eb7ccbd40de290`。
原生图像参数仍待覆盖显式 gamma、色深开关、自定义色彩空间及页组查询。
本轮沿用冻结 schema43。原样 ACM 双栏已完成图片读取,并停在图像位置记录的
`\tex_savepos:D`。下一入口为实现随实际发页更新的位置状态和延迟引用。
### PDF 字面中的矩阵与来源映射
来源映射与 PDF 写入共用设备原点的取整。实际字面中的 `q`、`Q` 和
+11
View File
@@ -616,6 +616,17 @@ schema43 优化版用同一 format 入口、44个冻结输入与字体映射越
带负伸缩量或无限收缩阶的陈列胶水,仍未生成完整 PDF。
回执为 `target/p3-pdf-math-extensions-native/acm-acmtog/receipt.json`;SHA-256 为 `07cda676937607f9ed556603c315045dc75c39ac77111b640f57de50e23f06c3`。
保留原始陈列胶水的构建使用同一 schema43、44个输入与字体映射,
原样 ACM 双栏已越过编号公式。首次停止点是 acmtog.tex:618 的
sample-franklin.png,图片入口当时将 PNG 送给 PDF 解析器。回执为
`target/p2-native-display-flexibility/acm-acmtog/receipt.json`,SHA-256 为
`15de2817bb35ab902160236c638966509d2a7f496dfbc957c9be199eb018d548`。
PNG 优化版以同一组输入越过导入。源文件在 acmtog.tex:618 的同一图片
进入标签位置记录,实际停止于未定义的 `\tex_savepos:D`,没有完整 PDF。
`target/p3-png-native/acm-acmtog/receipt.json` 的 SHA-256 为
`1326f9fbc4656f09c16f0b00256d19b7f3235710b574ca89f81368a655d1699e`。
最终矩阵 `target/publisher-template-matrix/acm-official/matrix-schema29-utf8/report.json`
SHA-256 为 `d914d7c7dfa1ee28dff20e77231fef35e390041cde6180bcc361de83288ec9e1`。其 `preparation/acmart` 保存
DocStrip 记录。同目录的前序依赖失败、补充包指纹和原样源均保留。用现有
+101 -2
View File
@@ -1,6 +1,8 @@
use lopdf::{Document, Object, Stream, dictionary};
use std::{fs, path::Path, process::Command};
use texrra_engine::native::{CompileRequest, Entry, NativeCompiler};
use std::{fs, path::Path, process::Command, sync::Arc};
use texrra_engine::native::{
CompileRequest, Entry, NativeCompiler, ProjectDefinition, ProjectSnapshot,
};
use texrra_tex_core::{execution::JobTime, resources::WorldConfig};
fn rotated_document(path: &Path) {
@@ -345,3 +347,100 @@ fn embedded_pdf_preview_uses_current_form_and_retains_the_other_page() {
assert_eq!(current.source_map.pages, independent.source_map.pages);
fs::remove_dir_all(root).unwrap();
}
#[test]
fn png_project_edit_updates_only_the_page_using_the_image() {
use image::ImageEncoder;
let root = std::env::temp_dir().join(format!("texrra-png-edit-{}", std::process::id()));
fs::create_dir(&root).unwrap();
let image = root.join("figure.data");
let entry = root.join("probe.tex");
let encode = |channels: [u8; 8]| -> Arc<[u8]> {
let mut bytes = Vec::new();
image::codecs::png::PngEncoder::new(&mut bytes)
.write_image(&channels, 2, 1, image::ColorType::Rgba8)
.unwrap();
bytes.into()
};
let original = encode([255, 0, 0, 255, 0, 255, 0, 128]);
let replacement = encode([0, 0, 255, 255, 0, 255, 0, 128]);
let prefix = r"\catcode123=1 \catcode125=2
\pdfoutput=1 \pdfminorversion=7 \pdfcompresslevel=0 \pdfobjcompresslevel=0
\pdfpagewidth=120bp \pdfpageheight=120bp \pdfhorigin=4bp \pdfvorigin=4bp
\shipout\vbox{\hrule width12pt height20pt depth0pt}
";
let continuation = r"\pdfximage width36bp {figure.data}
\shipout\hbox{\pdfrefximage\pdflastximage}\end
";
let complete_line = format!("{}\n", "\\relax ".repeat(26));
let source = format!("{prefix}{}{continuation}", complete_line.repeat(40));
let project = ProjectSnapshot::new(ProjectDefinition {
configuration: WorldConfig::new(&root),
revision: 1,
roots: [root.clone()].into(),
files: [
(entry.clone(), Arc::from(source.into_bytes())),
(image.clone(), original),
]
.into(),
directories: Default::default(),
aliases: Default::default(),
generated_roots: [root.clone()].into(),
generated: Default::default(),
})
.unwrap();
let updated = project
.with_file_edits(2, [(image, replacement)].into())
.unwrap();
let mut request = CompileRequest::new(
WorldConfig::new(&root),
entry,
"probe.pdf",
JobTime::new(2026, 11, 21, 600)
.unwrap()
.with_pdf_clock(0, 0)
.unwrap(),
);
request.entry = Entry::Initex;
request.etex = true;
let live = NativeCompiler::default().with_automatic_entry_checkpoints();
let first = live.compile(request.clone().with_project(project)).unwrap();
let next = live
.compile(request.clone().with_project(updated.clone()))
.unwrap();
let patch = next.preview_since(Some(first.revision())).unwrap();
assert!(next.entry_checkpoint_work.reused_steps > 0);
assert_eq!(patch.base_revision, Some(first.revision()));
assert_eq!(patch.pages.len(), 1);
assert_eq!(patch.pages[0].index, 1);
assert_ne!(first.pdf, next.pdf);
let cold = NativeCompiler::default()
.compile(request.with_project(updated))
.unwrap();
assert_eq!(cold.entry_checkpoint_work.reused_steps, 0);
assert_eq!(next.pdf, cold.pdf);
assert_eq!(next.source_map.pages, cold.source_map.pages);
assert_eq!(
next.preview_since(None).unwrap().pages,
cold.preview_since(None).unwrap().pages
);
let document = Document::load_mem(next.pdf.as_deref().unwrap()).unwrap();
let images: Vec<_> = document
.objects
.values()
.filter_map(|object| {
let image = object.as_stream().ok()?;
let mask = image.dict.get(b"SMask").ok()?.as_reference().unwrap();
Some((
image,
document.get_object(mask).unwrap().as_stream().unwrap(),
))
})
.collect();
assert_eq!(images.len(), 1);
assert_eq!(images[0].0.content, [0, 0, 255, 0, 255, 0]);
assert_eq!(images[0].1.content, [255, 128]);
fs::remove_dir_all(root).unwrap();
}