Expand native PDF image bounding-box queries

This commit is contained in:
gloamxun committed 2026-11-28 16:20:17 +08:00
1 parent 4fb0f2c89b
commit 2fa11fb971
8 files changed
+141 -31

No files matched your search

@@ -1032,6 +1032,7 @@ impl Executor {
)?;
}
}
Pdfximagebbox => self.expand_pdf_image_bbox(token, files)?,
Pdfstrcmp => {
let left = self.scan_expanded_group(files)?;
let left = self.token_list_text(&left);
@@ -660,6 +660,40 @@ impl Executor {
}));
}
fn registered_pdf_image(&mut self, number: i32) -> Option<&RegisteredImage> {
self.reads.insert(Dependency::PdfImages);
let slot = if self.state.input_profile() == InputProfile::TeX8Bit {
self.reads.insert(Dependency::PdfObjects);
u32::try_from(number).ok()
.and_then(|number| self.state.pdf_objects.as_deref()?.image_slot(number))
} else {
None
};
if let Some(slot) = slot {
return self.pdf_images.get(slot - 1);
}
// Existing format images keep the positional numbers embedded in their macros.
let index = usize::try_from(number).ok()?.checked_sub(1)?;
self.pdf_images.get(index).filter(|registered| registered.image.pdf_object_number.is_none())
}
pub(super) fn expand_pdf_image_bbox(
&mut self, token: &Token, files: &mut impl SourceProvider,
) -> Result<(), Error> {
let number = self.integer(files)?;
let Some(image) = self.registered_pdf_image(number) else {
return self.fail(format!("cannot find referenced image object {number}"));
};
let bbox = image.image.image.pdftex_bbox.unwrap_or([0; 4]);
let coordinate = self.integer(files)?;
let index = match coordinate {
1..=4 => coordinate as usize - 1,
_ => return self.fail(format!("invalid PDF image bounding box coordinate {coordinate}")),
};
let value = super::super::registers::print_scaled_wide(bbox[index]);
self.print_tokens(&format!("{value}pt"), token)
}
pub(super) fn reference_pdf_image(
&mut self,
token: &Token,
@@ -667,23 +701,7 @@ impl Executor {
) -> Result<(), Error> {
self.check_pdf_image()?;
let id = self.integer(files)?;
self.reads.insert(Dependency::PdfImages);
let slot = if self.state.input_profile() == InputProfile::TeX8Bit {
self.reads.insert(Dependency::PdfObjects);
u32::try_from(id).ok()
.and_then(|number| self.state.pdf_objects.as_deref()?.image_slot(number))
} else {
None
};
let image = slot.or_else(|| {
// Existing format images keep the positional numbers embedded in their macros.
let id = usize::try_from(id).ok()?;
self.pdf_images.get(id.checked_sub(1)?)
.filter(|registered| registered.image.pdf_object_number.is_none())
.map(|_| id)
})
.and_then(|id| self.pdf_images.get(id - 1))
.map(|registered| registered.image.clone())
let image = self.registered_pdf_image(id).map(|registered| registered.image.clone())
.ok_or_else(|| self.error(format!("cannot find referenced object {id}"), token.span))?;
self.defer_image(image, token)
}
@@ -16,9 +16,9 @@ use std::{
sync::{Arc, Mutex, OnceLock, Weak},
};
const SCHEMA: u32 = 105;
const COMPATIBLE_SCHEMAS: [u32; 71] = [
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, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, SCHEMA,
const SCHEMA: u32 = 106;
const COMPATIBLE_SCHEMAS: [u32; 72] = [
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, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, SCHEMA,
];
const ENGINE: &str = concat!("texrra-native/", env!("CARGO_PKG_VERSION"));
@@ -229,6 +229,9 @@ impl FormatImage {
if image.schema < 105 {
image.state.install_pdf_thread_commands();
}
if image.schema < 106 {
image.state.install_pdf_image_query_command();
}
let pdf_objects = image.state.pdf_objects.as_deref();
let mut numbered_images = 0;
for (index, saved) in image.pdf_images.iter().enumerate() {
@@ -102,6 +102,7 @@ pub enum Primitive {
Pdfximage,
Pdfrefximage,
Pdflastximage,
Pdfximagebbox,
Pdflastximagepages,
Pdflastximagecolordepth,
Jobname,
@@ -531,6 +532,7 @@ impl Primitive {
| XeTeXfeaturename
| XeTeXselectorname
| Pdfstrcmp
| Pdfximagebbox
| Pdfmatch
| Pdflastmatch
| Pdfuniformdeviate
@@ -949,6 +951,7 @@ const PDFTEX_ONLY_PRIMITIVES: &[(&str, Primitive)] = {
("pdfximage", Pdfximage),
("pdfrefximage", Pdfrefximage),
("pdflastximage", Pdflastximage),
("pdfximagebbox", Pdfximagebbox),
("pdflastximagepages", Pdflastximagepages),
("pdflastximagecolordepth", Pdflastximagecolordepth),
("pdfcreationdate", Pdfcreationdate),
@@ -2007,6 +2010,11 @@ impl State {
self.update_profile_command("pdfthreadmargin", Meaning::Parameter(Parameter::Pdfthreadmargin), enabled);
}
pub(super) fn install_pdf_image_query_command(&mut self) {
let enabled = self.input_profile != super::InputProfile::XeTeX;
self.update_profile_command("pdfximagebbox", Meaning::Primitive(Primitive::Pdfximagebbox), enabled);
}
fn install_pdftex_primitives(&mut self) {
let enabled = self.input_profile != super::InputProfile::XeTeX;
for &(name, primitive) in PDFTEX_ONLY_PRIMITIVES {
+15 -3
View File
@@ -52,6 +52,8 @@ pub struct PdfImage {
extent: [u64; 2],
#[serde(default, skip_serializing_if = "Option::is_none")]
pub(crate) restored_pdf_origin: Option<[i64; 2]>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub(crate) pdftex_bbox: Option<[i64; 4]>,
objects: Vec<Vec<Part>>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub(crate) color_space: Option<i32>,
@@ -423,6 +425,7 @@ impl PdfImage {
natural: self.natural,
extent: self.extent,
restored_pdf_origin: self.restored_pdf_origin,
pdftex_bbox: self.pdftex_bbox,
objects: Vec::new(),
color_space: self.color_space,
imported_fonts: Vec::new(),
@@ -565,6 +568,7 @@ impl PdfImage {
natural,
extent: extent.map(f64::to_bits),
restored_pdf_origin: None,
pdftex_bbox: None,
objects,
color_space,
imported_fonts: Vec::new(),
@@ -617,6 +621,7 @@ impl PdfImage {
natural: natural(bp),
extent: bp.map(f64::to_bits),
restored_pdf_origin: None,
pdftex_bbox: None,
objects: vec![vec![part]],
color_space: None,
imported_fonts: Vec::new(),
@@ -825,12 +830,18 @@ impl PdfImage {
}
Ok(value as i64)
};
let source_sp = |bp: f64| {
(f64::from(bp as f32) * 6_578_176.0 / 100.0).round()
};
let pdftex_bbox = pdftex.then(|| {
// pdfTeX rounds the origin and unrotated extents separately.
let [x, y, w, h] = [left, bottom, right - left, top - bottom]
.map(|value| source_sp(value) as i64);
[x, y, x.saturating_add(w), y.saturating_add(h)]
});
// pdfTeX reopens the PDF with unrotated dimensions for the outer
// placement. The actual page rotation still belongs to the Form.
let (natural, restored_pdf_origin) = if restored {
let source_sp = |bp: f64| {
(f64::from(bp as f32) * 6_578_176.0 / 100.0).round()
};
let [width, height] = [source_sp(right - left), source_sp(top - bottom)];
if ![width, height].into_iter().all(|n| (1.0..=1073741823.0).contains(&n)) {
return Err("invalid image dimensions".into());
@@ -910,6 +921,7 @@ impl PdfImage {
natural,
extent: [width.to_bits(), height.to_bits()],
restored_pdf_origin,
pdftex_bbox,
objects: graph.bodies,
color_space: None,
imported_fonts,
@@ -152,6 +152,7 @@ pub(super) fn read(
device_cid_cff_fonts: Vec::new(),
pdftex_source: None,
restored_pdf_origin: None,
pdftex_bbox: None,
},
warning,
))
+36
View File
@@ -18,6 +18,42 @@
| W6 会话 | 实施中 | 共享库/CLI 与当前原生文字/数学/规则来源进入公共结果;真实 A4 副本九类/27 revision 与独立干净作业页面/PDF/aux/映射一致,新增数学场景独立参考通过;详细失败/捕获重放及宿主/离线/CLI观察已通过;原子项目版本/已知生成初态及TeX流记录已接通;完整副作用/恢复契约、旧来源和性能仍缺 |
| W7 总验收 | 未满足 | 原有和新增测试、原样项目、格式与会话门禁全部通过才能结项 |
## 2026-11-28 原生 PDF 图像页框查询
pdfTeX 模式执行可展开的 \pdfximagebbox。通过实际图像对象编号
读取已选页框,分别圆整原点与未旋转尺寸,再相加得到右上角。
盒的放置尺寸和旋转继续由图像设备处理。PNG 及 JPEG 返回零
坐标,非图像对象编号及越界选择值在展开时诊断。
[参考展开规则](https://github.com/TeX-Live/texlive-source/blob/fb6158926661cb7a7246b3a94a0cb170a9624d5a/texk/web2c/pdftexdir/pdftex.web#L11416-L11429)
· [图像页框读取与精度](https://github.com/TeX-Live/texlive-source/blob/fb6158926661cb7a7246b3a94a0cb170a9624d5a/texk/web2c/pdftexdir/writeimg.c#L292-L304)
最小对照覆盖继承的负原点 MediaBox、按名称选择的旋转 CropBox、
明确缩放、PNG、尺寸赋值和两类拒绝。各坐标文本及 144 DPI 灰度图
一致。schema106 与旧 schema105 重载的查询一致,旧镜像中同名
用户宏保持定义。一个实际 LaTeX article 作业加载原样 graphicx
和 ACM acmart 原版 sampleteaser.pdf,用查询值缩放图像和规则。
查询宽度为 2055.68 pt,aux 和一页 144 DPI 灰度图一致。
发布构建及 11 项图像定向回归通过。
三页格式会话先编辑子文件并复用旧前缀,再移动同尺寸的源 PDF
TrimBox 并修改图像内容。第二次变更使旧检查点失效。规则宽度
从 986726 sp 更新为 1249853 sp,预览仅替换第二页,PDF、
来源映射和预览页面均与同修订独立全量一致。
Springer Nature 的旋转 table.3 坐标差继续保留。参考点目标
扫描只给 FitR 写入原始尺寸,活动矩阵下其他类型的点目标仍读取
这些节点字段。此前丢弃 FitR 的尺寸会改变随后同一目标的坐标。
[参考的节点初始化](https://github.com/TeX-Live/texlive-source/blob/fb6158926661cb7a7246b3a94a0cb170a9624d5a/texk/web2c/pdftexdir/pdftex.web#L35089-L35122)
· [参考的目标出页](https://github.com/TeX-Live/texlive-source/blob/fb6158926661cb7a7246b3a94a0cb170a9624d5a/texk/web2c/pdftexdir/pdftex.web#L36719-L36751)
下一处页构建查询已在 next-insertion 复现。参考 \pdfinsertht
查得活动插入类初始为 0 pt、正常计入为 10 pt、拆分为 14 pt、
更多材料等待续页时仍为 14 pt,输出例程里返回 0 pt。原生在
该查询处报未定义。应直接读取活动页的实际插入类和未缩放尺寸。
回执在 target/p3-native-image-bbox,receipt.json 的 SHA-256 为
b53801b76cfa8179c479c7338b2a314057c3f872fde7a38b239bf67bc88b2745。
## 2026-11-28 原生 PDF 阅读线程
pdfTeX 模式执行 \pdfthread、\pdfstartthread、\pdfendthread 和
+39 -8
View File
@@ -177,12 +177,14 @@ fn rotated_pdf_page_uses_selected_box_real_content_and_source_map() {
fs::create_dir(&root).unwrap();
let source = root.join("vector.pdf");
rotated_document(&source);
let body = r"\catcode123=1 \catcode125=2
let body = r"\catcode123=1 \catcode125=2 \catcode35=6
\pdfoutput=1 \pdfminorversion=5 \pdfobjcompresslevel=0
\pdfpagewidth=200pt \pdfpageheight=220pt \pdfhorigin=8pt \pdfvorigin=12pt
\pdfximage page 1 trimbox {vector.pdf}
\setbox0=\hbox{\pdfrefximage\pdflastximage}
\message{[w=\number\wd0][h=\number\ht0][pages=\the\pdflastximagepages]}
\def\bound#1{\pdfximagebbox\pdflastximage#1}
\immediate\write16{BBOX=\bound1,\bound2,\bound3,\bound4}
\shipout\box0
\end
";
@@ -249,7 +251,12 @@ fn rotated_pdf_page_uses_selected_box_real_content_and_source_map() {
"{}",
String::from_utf8_lossy(&render.stderr)
);
artifacts.push((dims, fs::read(work.join("page.pgm")).unwrap()));
let bounds = log
.lines()
.find(|line| line.starts_with("BBOX="))
.unwrap()
.to_owned();
artifacts.push((dims, bounds, fs::read(work.join("page.pgm")).unwrap()));
if native {
let layout: serde_json::Value =
serde_json::from_slice(&fs::read(work.join("layout.json")).unwrap()).unwrap();
@@ -265,8 +272,9 @@ fn rotated_pdf_page_uses_selected_box_real_content_and_source_map() {
}
}
assert_eq!(artifacts[0].0, artifacts[1].0);
assert_eq!(artifacts[0].1, artifacts[1].1);
assert!(
artifacts[0].1 == artifacts[1].1,
artifacts[0].2 == artifacts[1].2,
"rotated image pixels differ"
);
fs::remove_dir_all(root).unwrap();
@@ -533,7 +541,10 @@ fn png_project_edit_updates_only_the_page_using_the_image() {
#[test]
fn format_image_resource_edits_invalidate_checkpoints_and_update_the_picture_page() {
use texrra_engine::native::dump_format;
use texrra_tex_core::{execution::Cancellation, render::DisplayItem};
use texrra_tex_core::{
execution::Cancellation,
render::{DisplayItem, DisplayList},
};
let root = std::env::temp_dir().join(format!("texrra-format-image-{}", std::process::id()));
fs::create_dir(&root).unwrap();
@@ -548,6 +559,7 @@ fn format_image_resource_edits_invalidate_checkpoints_and_update_the_picture_pag
r"\catcode123=1 \catcode125=2
\pdfoutput=1 \pdfminorversion=5
\pdfximage width40pt trimbox {picture.pdf}
\edef\figureobj{\the\pdflastximage}
\setbox0=\hbox{\pdfrefximage\pdflastximage}
\dump
",
@@ -566,10 +578,17 @@ fn format_image_resource_edits_invalidate_checkpoints_and_update_the_picture_pag
";
let padding = format!("{}\n", "\\relax ".repeat(32)).repeat(48);
let entry = format!(
"{prefix}{padding}\\shipout\\copy0\n\\input tail.tex\n\\shipout\\hbox{{\\vrule width\\tailwidth pt height4pt}}\n\\end\n"
"{prefix}{padding}\\shipout\\vbox{{\\copy0\\hrule width\\pdfximagebbox\\numexpr\\figureobj\\relax 1 height1pt}}\n\\input tail.tex\n\\shipout\\hbox{{\\vrule width\\tailwidth pt height4pt}}\n\\end\n"
);
let original = fs::read(&figure).unwrap();
let mut edited = Document::load_mem(&original).unwrap();
let page = edited.get_pages()[&1];
edited
.get_object_mut(page)
.unwrap()
.as_dict_mut()
.unwrap()
.set("TrimBox", vec![19.into(), 22.into(), 144.into(), 78.into()]);
let mut changed = false;
for object in edited.objects.values_mut() {
let Ok(stream) = object.as_stream_mut() else {
@@ -581,8 +600,8 @@ fn format_image_resource_edits_invalidate_checkpoints_and_update_the_picture_pag
}
}
assert!(changed);
let mut recolored = Vec::new();
edited.save_to(&mut recolored).unwrap();
let mut edited_pdf = Vec::new();
edited.save_to(&mut edited_pdf).unwrap();
let files = [
(seed.clone(), fs::read(&seed).unwrap().into()),
@@ -619,7 +638,7 @@ fn format_image_resource_edits_invalidate_checkpoints_and_update_the_picture_pag
.compile(request.clone().with_project(snapshot.clone()))
.unwrap();
assert!(second.entry_checkpoint_work.reused_steps > 0);
let edits = [(figure.clone(), Some(recolored.into()))].into();
let edits = [(figure.clone(), Some(edited_pdf.into()))].into();
let snapshot = snapshot.with_file_changes(3, edits).unwrap();
let revised = request.with_project(snapshot);
let third = compiler.compile(revised.clone()).unwrap();
@@ -635,6 +654,18 @@ fn format_image_resource_edits_invalidate_checkpoints_and_update_the_picture_pag
third.entry_checkpoint_work
);
let queried_width = |page: &DisplayList| {
page.items
.iter()
.find_map(|item| match item {
DisplayItem::Rule { width, .. } => Some(*width),
_ => None,
})
.unwrap()
};
assert_eq!(queried_width(&second.pages[1]), 986_726);
assert_eq!(queried_width(&third.pages[1]), 1_249_853);
let image_page = &third.pages[1];
let image = image_page
.items