Support native PDF font dictionaries and running link controls

This commit is contained in:
gloamxun committed 2026-11-21 02:46:57 +08:00
1 parent 60d7411dfe
commit b647bd8dcd
19 files changed
+180 -13

No files matched your search

@@ -611,6 +611,8 @@ impl Printer<'_> {
self.command(match node {
LinkNode::Start(_) => "pdfstartlink",
LinkNode::End => "pdfendlink",
LinkNode::Running(false) => "pdfrunninglinkoff",
LinkNode::Running(true) => "pdfrunninglinkon",
LinkNode::Destination { .. } => "pdfdest",
});
}
@@ -218,6 +218,7 @@ pub struct Executor {
io: IoState,
pdf_colors: crate::pdf_device::PdfColorStacks,
pdf_link_stack: Vec<pdf_links::ActiveLink>,
pdf_running_links: bool,
#[cfg(all(target_os = "linux", target_env = "gnu"))]
pdf_last_match: Option<Arc<pdf_match::PdfMatch>>,
pdf_catalog_tokens: Vec<Token>,
@@ -382,6 +383,7 @@ impl Executor {
io: IoState::default(),
pdf_colors: Default::default(),
pdf_link_stack: Vec::new(),
pdf_running_links: true,
#[cfg(all(target_os = "linux", target_env = "gnu"))]
pdf_last_match: None,
pdf_catalog_tokens: Vec::new(),
@@ -3603,6 +3605,9 @@ impl Executor {
return self.fail("misplaced native alignment command");
}
Pdfglyphtounicode => self.glyph_to_unicode(files)?,
Pdffontattr | Pdfnobuiltintounicode => {
self.pdf_font_settings(primitive, files)?;
}
Explicitspace => {
if self.paragraph.is_some() {
let space = self.explicit_space()?;
@@ -3786,7 +3791,7 @@ impl Executor {
Pdfsave | Pdfsetmatrix | Pdfrestore | Pdfliteral => {
self.scan_pdf_graphics(primitive, token.span, files)?
}
Pdfstartlink | Pdfendlink | Pdfdest => {
Pdfstartlink | Pdfendlink | Pdfdest | Pdfrunninglinkoff | Pdfrunninglinkon => {
self.scan_pdf_link(primitive, token.span, files)?;
}
Pdfsetrandomseed => {
@@ -44,6 +44,31 @@ impl Executor {
}
Ok(())
}
pub(super) fn pdf_font_settings(
&mut self,
primitive: Primitive,
files: &mut impl SourceProvider,
) -> Result<(), Error> {
if self.read_parameter(Parameter::Pdfoutput).width() <= 0 {
return self.fail("native PDF font settings are unavailable in DVI mode");
}
let font = self.font_identifier(files)?;
if font == FontId::NULL {
return self.fail("invalid PDF font identifier");
}
match primitive {
Primitive::Pdffontattr => {
let tokens = self.scan_expanded_group(files)?;
let attributes = self.pdf_token_bytes(&tokens)?;
self.state.fonts.pdf_settings.entry(font).or_default().attributes = attributes;
}
Primitive::Pdfnobuiltintounicode => {
self.state.fonts.pdf_settings.entry(font).or_default().omit_builtin_unicode = true;
}
_ => unreachable!(),
}
Ok(())
}
pub(super) fn pdf_page_data(
&mut self,
files: &mut impl SourceProvider,
@@ -548,6 +548,8 @@ impl Executor {
Hbox | Vbox | Vtop | Box | Copy | Setbox | Wd | Ht | Dp | Lastbox | Raise
| Lower | Vsplit | Mark | Marks | Vadjust | Insert | Shipout | Openout
| Closeout | Write | Pdfcolorstack | Pdfsave | Pdfsetmatrix | Pdfrestore | Pdfcatalog | Pdfoutline
| Pdfglyphtounicode | Pdffontattr | Pdfnobuiltintounicode
| Pdfrunninglinkoff | Pdfrunninglinkon
| Ignorespaces | Unskip | Unkern | Unpenalty => {
return Ok(false);
}
@@ -353,7 +353,7 @@ impl Executor {
return self.fail("\\pdfendlink used without \\pdfstartlink");
}
LinkNode::End => link_depth -= 1,
LinkNode::Destination { .. } => {}
LinkNode::Running(_) | LinkNode::Destination { .. } => {}
}
} else {
self.output_node(output, files)?;
@@ -111,7 +111,10 @@ impl Executor {
if self.native_page.is_none() || self.read_parameter(Parameter::Pdfoutput).width() <= 0 {
return self.fail("PDF link operation not allowed in DVI mode");
}
if command != Primitive::Pdfdest && self.paragraph.is_none() && self.math.is_empty() {
if matches!(command, Primitive::Pdfstartlink | Primitive::Pdfendlink)
&& self.paragraph.is_none()
&& self.math.is_empty()
{
return self.fail(if command == Primitive::Pdfstartlink {
"\\pdfstartlink cannot be used in vertical mode"
} else {
@@ -167,6 +170,9 @@ impl Executor {
})
}
Primitive::Pdfendlink => LinkNode::End,
Primitive::Pdfrunninglinkoff | Primitive::Pdfrunninglinkon => {
LinkNode::Running(command == Primitive::Pdfrunninglinkon)
}
Primitive::Pdfdest => {
let destination = if self.keyword("name", files)? {
DestinationId::Name(self.scan_pdf_tokens(files)?)
@@ -248,7 +254,7 @@ impl Executor {
Some(PdfGraphics::Literal { .. }) => {}
None => failure = Some(self.error("missing PDF transform at link shipout", self.current)),
},
BoxPaint::RowStart(row) => {
BoxPaint::RowStart(row) if self.pdf_running_links => {
for link in active.iter_mut().filter(|link| {
link.level == row.level && link.layout.width.is_none()
}) {
@@ -292,6 +298,7 @@ impl Executor {
}
link.end_segment(&mut output, x, margin);
}
LinkNode::Running(enabled) => self.pdf_running_links = *enabled,
LinkNode::Destination { destination, view } => {
let destination = match destination {
DestinationId::Name(tokens) => DestinationId::Name(self.token_list_text(tokens)),
@@ -145,6 +145,12 @@ pub(super) struct FontExpansion {
pub step: i32,
}
#[derive(Clone, Debug, Default, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
pub(crate) struct PdfFontSettings {
pub(crate) attributes: Vec<u8>,
pub(crate) omit_builtin_unicode: bool,
}
#[derive(Clone, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
pub struct FontCatalog {
fonts: Vec<FontInstance>,
@@ -157,6 +163,8 @@ pub struct FontCatalog {
expansion: BTreeMap<FontId, FontExpansion>,
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
expansion_codes: BTreeMap<FontId, BTreeMap<u8, u16>>,
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
pub(super) pdf_settings: BTreeMap<FontId, PdfFontSettings>,
}
impl Default for FontCatalog {
fn default() -> Self {
@@ -189,8 +197,12 @@ impl FontCatalog {
protrusion: BTreeMap::new(),
expansion: BTreeMap::new(),
expansion_codes: BTreeMap::new(),
pdf_settings: BTreeMap::new(),
})
}
pub(crate) fn pdf_settings(&self, id: FontId) -> Option<&PdfFontSettings> {
self.pdf_settings.get(&id)
}
pub fn fonts(&self) -> &[FontInstance] {
&self.fonts
}
@@ -8,7 +8,7 @@ use std::{
sync::{Arc, Mutex, OnceLock, Weak},
};
const SCHEMA: u32 = 40;
const SCHEMA: u32 = 41;
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"));
+32 -2
View File
@@ -46,7 +46,7 @@ pub use statistics::{
HostResourceUsage, MaterialUsage, ResourceUsage, StackUsage, StateUsage, StatisticsPhase,
StatisticsReport,
};
use std::collections::BTreeSet;
use std::collections::{BTreeMap, BTreeSet};
use std::fmt;
pub use boxes::{
@@ -692,10 +692,14 @@ impl Execution {
&self,
pages: &mut [crate::render::DisplayList],
) -> Result<(), Error> {
use crate::pdf_device::page_resources::{PdfObjects, PageResources};
use crate::pdf_device::page_resources::{
PageResources, PdfObjects, font_attributes_affect_paint,
};
use std::collections::btree_map::Entry;
use crate::render::DisplayItem;
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 {
let states = page.items.iter().filter_map(|item| match item {
DisplayItem::PdfColor(program) => Some(&program.graphics_states),
@@ -706,6 +710,32 @@ impl Execution {
).map_err(|message| Error::at(
&self.sources, self.state.input_profile(), message, Span::default(),
))?;
if self.state.fonts.pdf_settings.is_empty() {
continue;
}
for item in &page.items {
let DisplayItem::NativeGlyph { font, .. } = item else {
continue;
};
let affects_paint = match font_affects_paint.entry(font.id) {
Entry::Occupied(entry) => *entry.get(),
Entry::Vacant(entry) => {
let affects_paint = self.state.fonts.pdf_settings(font.id)
.filter(|settings| !settings.attributes.is_empty())
.map(|settings| font_attributes_affect_paint(&settings.attributes))
.transpose()
.map_err(|message| Error::at(
&self.sources, self.state.input_profile(), message, Span::default(),
))?
.unwrap_or(false);
*entry.insert(affects_paint)
}
};
if affects_paint {
page.pdf_resources.needs_pdf_for_preview = true;
break;
}
}
}
Ok(())
}
@@ -107,6 +107,8 @@ pub enum Primitive {
Pdfsave,
Pdfstartlink,
Pdfendlink,
Pdfrunninglinkoff,
Pdfrunninglinkon,
Pdfdest,
Pdfcatalog,
Pdfoutline,
@@ -114,6 +116,8 @@ pub enum Primitive {
Pdfsetmatrix,
Pdfrestore,
Pdfglyphtounicode,
Pdffontattr,
Pdfnobuiltintounicode,
Currentgrouplevel,
Currentgrouptype,
Unless,
@@ -984,6 +988,8 @@ impl Default for State {
("pdfsave", Pdfsave),
("pdfstartlink", Pdfstartlink),
("pdfendlink", Pdfendlink),
("pdfrunninglinkoff", Pdfrunninglinkoff),
("pdfrunninglinkon", Pdfrunninglinkon),
("pdfdest", Pdfdest),
("pdfcatalog", Pdfcatalog),
("pdfoutline", Pdfoutline),
@@ -991,6 +997,8 @@ impl Default for State {
("pdfsetmatrix", Pdfsetmatrix),
("pdfrestore", Pdfrestore),
("pdfglyphtounicode", Pdfglyphtounicode),
("pdffontattr", Pdffontattr),
("pdfnobuiltintounicode", Pdfnobuiltintounicode),
("dump", Dump),
("indent", Indent),
("noindent", Noindent),
@@ -1406,6 +1414,7 @@ impl State {
self.pdf_objects = None;
}
self.pdf_info.clear();
self.fonts.pdf_settings.clear();
self
}
pub fn is_initex(&self) -> bool {
@@ -1418,6 +1427,7 @@ impl State {
compression: self.parameter(Parameter::Pdfcompresslevel).width(),
generate_unicode: self.parameter(Parameter::Pdfgentounicode).width(),
glyph_unicode: &self.glyph_unicode,
fonts: &self.fonts,
catalog: self.pdf_catalog.as_deref(),
objects: self.pdf_objects.as_deref(),
info: crate::pdf_device::PdfInfo {
+20 -2
View File
@@ -1325,7 +1325,12 @@ fn native_pdf(
return Err("invalid native PDF final stream compression level".into());
}
let raw_objects = unicode.and_then(|options| options.objects);
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())
{
let (catalog, info) = if raw_objects.is_some() {
@@ -1337,7 +1342,7 @@ fn native_pdf(
(None, None)
};
Some(crate::pdf_device::page_resources::ResourceOutput::prepare(
pages, raw_objects, catalog, info,
pages, raw_objects, font_attributes, catalog, info,
)?)
} else {
None
@@ -1566,7 +1571,9 @@ fn write_native_font(
.collect::<Vec<_>>()
.join(" ");
let cmap = if let Some(options) = options {
if options.generate_unicode > 0 && !options.glyph_unicode.is_empty() {
if options.fonts.pdf_settings(face.id).is_some_and(|settings| settings.omit_builtin_unicode) {
None
} else if options.generate_unicode > 0 && !options.glyph_unicode.is_empty() {
let texts = paint
.encoding
.iter()
@@ -2089,6 +2096,17 @@ fn write_pdf(
}
let remapped = resources.map(|resources| resources.append(&mut objects, diagnostics));
if let Some(resources) = &remapped {
for (font, entries) in &resources.fonts {
if !entries.is_empty() {
let body = &mut objects[native_font_ids[font] - 1];
body.truncate(body.len() - 2);
body.extend_from_slice(b"\n");
body.extend_from_slice(entries);
body.extend_from_slice(b"\n>>");
}
}
}
let mut kids = Vec::new();
let mut page_ids: Vec<usize> = Vec::new();
let mut destinations = BTreeMap::new();
@@ -41,6 +41,7 @@ pub enum DestinationId<T> {
pub enum LinkNode {
Start(LinkStart),
End,
Running(bool),
Destination {
destination: DestinationId<Vec<Token>>,
view: DestinationView,
@@ -1,4 +1,5 @@
//! Native PDF objects and extra resources captured at page shipout.
use crate::execution::FontId;
use lopdf::{
Dictionary, Object, Stream,
content::{Content, Operation},
@@ -294,6 +295,11 @@ fn parse_entries(bytes: &[u8]) -> Result<Dictionary, String> {
}
}
pub(crate) fn font_attributes_affect_paint(bytes: &[u8]) -> Result<bool, String> {
let attributes = parse_entries(bytes)?;
Ok(attributes.iter().any(|(name, _)| name != b"ToUnicode"))
}
fn encode_value(object: Object) -> Result<Vec<u8>, String> {
if let Object::Stream(stream) = object {
let mut output = encode_value(Object::Dictionary(stream.dict))?;
@@ -405,6 +411,7 @@ pub(crate) struct ResourceOutput {
page_references: BTreeMap<u32, u32>,
link_references: BTreeMap<u32, Option<(usize, usize)>>,
page_entries: Vec<Dictionary>,
font_entries: BTreeMap<FontId, Dictionary>,
annotation_entries: Vec<Vec<Option<Dictionary>>>,
catalog: Option<Dictionary>,
info: Option<Dictionary>,
@@ -412,6 +419,7 @@ pub(crate) struct ResourceOutput {
pub(crate) struct RemappedResources {
pub pages: Vec<Vec<u8>>,
pub fonts: BTreeMap<FontId, Vec<u8>>,
pub page_objects: BTreeMap<usize, usize>,
pub link_objects: BTreeMap<(usize, usize), usize>,
pub annotations: Vec<Vec<Option<Vec<u8>>>>,
@@ -423,6 +431,7 @@ impl ResourceOutput {
pub(crate) fn prepare(
pages: &[crate::render::DisplayList],
objects: Option<&PdfObjects>,
fonts: BTreeMap<FontId, &[u8]>,
catalog: Option<&[u8]>,
info: Option<&[u8]>,
) -> Result<Self, String> {
@@ -440,10 +449,14 @@ impl ResourceOutput {
Ok(entries)
})
.collect::<Result<Vec<_>, String>>()?;
let font_entries = fonts
.into_iter()
.map(|(font, entries)| Ok((font, parse_entries(entries)?)))
.collect::<Result<BTreeMap<_, _>, String>>()?;
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(catalog.iter()).chain(info.iter()) {
for dictionary in page_entries.iter().chain(font_entries.values()).chain(&catalog).chain(&info) {
for (_, entry) in dictionary.iter() {
references(entry, &mut pending)?;
}
@@ -509,6 +522,7 @@ impl ResourceOutput {
page_references: objects.page_references.clone(),
link_references,
page_entries,
font_entries,
annotation_entries,
catalog,
info,
@@ -567,6 +581,9 @@ impl ResourceOutput {
};
RemappedResources {
pages: self.page_entries.into_iter().map(&encode).collect(),
fonts: self.font_entries.into_iter()
.map(|(font, dictionary)| (font, encode(dictionary)))
.collect(),
page_objects,
link_objects,
annotations: self.annotation_entries.into_iter()
@@ -128,6 +128,7 @@ pub struct PdfFinalOptions<'a> {
pub compression: i32,
pub generate_unicode: i32,
pub glyph_unicode: &'a GlyphUnicodeMap,
pub fonts: &'a crate::execution::FontCatalog,
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>,
@@ -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"], 40);
assert_eq!(payload["schema"], 41);
let state = State::initex().with_etex();
let loaded = FormatImage::decode(&bytes)
.unwrap()
@@ -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"], 40);
assert_eq!(original["schema"], 41);
for (schema, expected) in [
(1, "incompatible native format"),
(2, "incompatible native format"),
@@ -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"], 40);
assert_eq!(payload["schema"], 41);
let executor = FormatImage::decode(&bytes)
.unwrap()
.new_job(
+26
View File
@@ -1152,6 +1152,32 @@ schema40 保存格式中的链接保留项,并将最近链接恢复为0。实
- `receipt.json` 为 `c1fa0672ac47cf23093a4cb9d4d2e3c384c9a6ee6c9755a6bab3dd8ee60f6f20`。
- `checkpoint/receipt.json` 为 `7d3af1417582a36aa782ce0f91354624d77e8492100286a1e941e8b072d17f36`。
### PDF 字体字典与跨行链接开关
\pdffontattr 与 \pdfnobuiltintounicode 读取真实字体标识,保存作业内该字体的
最终字典字段和内建 ToUnicode 开关。赋值跨组生效,覆盖同一字体上较早的
字段。转储与重载后的格式保留字体及全局 glyph Unicode 表,清除这两项
作业专用设置。PDF 写出只为实际出页字体处理字段,并将其中的间接引用与
真实 CMap 流一同编号。仅含 ToUnicode 的字体字段沿用原生 SVG 绘制。
[pdfTeX 字体字典写出](https://github.com/TeX-Live/texlive-source/blob/trunk/texk/web2c/pdftexdir/writefont.c#L504-L553)
\pdfrunninglinkoff 与 \pdfrunninglinkon 成为原生列表中的设备 whatsit。
发页遍历遇到开关才更新状态,后续同深度横盒按状态生成跨行链接续段。
未发页盒内的开关不执行,普通链接的首个注释仍生成。检查点保存发页后的
开关和活动链接栈。原样 ACM 双栏的 schema40 在标题处需要该能力,详见
[模板复验](PUBLISHER_TEMPLATE_MATRIX.md#acm-的三类官方样例)。
[pdfTeX 的横盒链接续段](https://github.com/TeX-Live/texlive-source/blob/trunk/texk/web2c/pdftexdir/pdftex.web#L18791-L18797)
schema41 的定向对照从自定义文件 CMap 与内建 CMap 分别提取出 Ω 和 A,
四页 144 DPI 灰度图逐像素一致,跨页四个链接矩形完全一致,并核对格式重载
与实际资源读取。联合编辑切换链接续段和 CMap,续编复用1007步,未重发
任何 SVG。PDF、SVG、归一化来源映射与同版本独立零复用编译一致。
证据在 `target/p3-pdf-font-attrs-native`。
- `receipt.json` 为 `39935858ea599a9f24af122487bd8dbe302174107ae08264707b2e344ec380d9`。
- `checkpoint/receipt.json` 为 `232cf92c3e493e7825fe3fa9433054d9464eaf5735797e02a27ef51d329da025`。
### PDF 字面中的矩阵与来源映射
来源映射与 PDF 写入共用设备原点的取整。实际字面中的 `q`、`Q` 和
+11
View File
@@ -579,6 +579,17 @@ PDF。同一作业中,`cmap` 的 `\pdffontattr` 能力检查发出退出告警
映射已核对。`target/p3-margin-kern-query-native/acm-acmtog/receipt.json`
为 `32080c820174aa79f545b79c747324d755cfbe170d54b3823492e7c51ba5b517`。
schema40 优化版在同一原样格式和44个冻结输入上越过 \pdflastlink,
在 acmtog.tex:265 的标题处理尝试执行 \tex_pdfrunninglinkoff:D
时停止。该轮未形成 PDF。原样格式载入和错误日志保存在
`target/p3-pdf-lastlink-native`。
- `acm-format/receipt.json` 为 `75203141b59054dbafc38df2a8e284fc8b011da12ac12f8c798189b44441f10b`。
- `acm-acmtog/receipt.json` 为 `f39ef1bd74e91e4e6c2b3ce9a51138b5e3b9e9e13a994d47cb995311ed4cdebe`。
schema41 实现跨行链接开关和 cmap 需要的字体字典能力。原样双栏复验正在
使用原来的 TeX 输入、模板和映射重建格式,继续保留每轮结果。
最终矩阵 `target/publisher-template-matrix/acm-official/matrix-schema29-utf8/report.json`
SHA-256 为 `d914d7c7dfa1ee28dff20e77231fef35e390041cde6180bcc361de83288ec9e1`。其 `preparation/acmart` 保存
DocStrip 记录。同目录的前序依赖失败、补充包指纹和原样源均保留。用现有