Honor pdfTeX character program tags and qualify PLOS ONE

This commit is contained in:
gloamxun committed 2026-11-29 06:26:35 +08:00
1 parent 84ad682939
commit a1585339b9
21 files changed
+308 -28

No files matched your search

@@ -2564,6 +2564,16 @@ impl Executor {
self.state.fonts.protrusion_code(font, slot as u8, right)
})
}
Meaning::Primitive(Primitive::Tagcode) => {
let (font, slot) = self.font_character_target(files)?;
self.reads.insert(Dependency::FontResources);
self.state.fonts.tag_code(font, slot).map_err(|error| self.error(error, self.current))
}
Meaning::Primitive(Primitive::Pdfnoligatures) => {
let font = self.font_identifier(files)?;
self.reads.insert(Dependency::FontResources);
self.state.fonts.no_ligatures(font).map_err(|error| self.error(error, self.current))
}
Meaning::Primitive(p @ (Primitive::Hyphenchar | Primitive::Skewchar)) => {
let font = self.font_identifier(files)?;
let values = self.state.font_integers(font);
@@ -4746,6 +4756,20 @@ impl Executor {
self.state.fonts.set_protrusion_code(font, slot as u8, right, code);
}
}
Some(Tagcode) => {
let (font, slot) = self.font_character_target(files)?;
self.optional_equals(files)?;
let mask = self.integer(files)?;
self.finish_text(true)?;
self.state.fonts.clear_tag_code(font, slot, mask)
.map_err(|error| self.error(error, self.current))?;
}
Some(Pdfnoligatures) => {
let font = self.font_identifier(files)?;
self.finish_text(true)?;
self.state.fonts.suppress_ligatures(font)
.map_err(|error| self.error(error, self.current))?;
}
Some(Hyphenchar | Skewchar) => {
let font = self.font_identifier(files)?;
self.optional_equals(files)?;
@@ -418,6 +418,8 @@ impl Executor {
| Knaccode
| Efcode
| Pdffontexpand
| Pdfnoligatures
| Tagcode
| Skewchar
| Textfont
| Scriptfont
@@ -896,7 +896,7 @@ impl Executor {
| Umathcode | Umathcodenum
| Delcode | Udelcode | Udelcodenum | Count | Countdef | Dimen | Dimendef | Skip | Skipdef | Muskip
| Muskipdef | Toks | Toksdef | Advance | Multiply | Divide | Read | Readline
| Font | Fontdimen | Hyphenchar | Skewchar | Lpcode | Rpcode | Efcode | Pdffontexpand
| Font | Fontdimen | Hyphenchar | Skewchar | Lpcode | Rpcode | Efcode | Pdffontexpand | Pdfnoligatures | Tagcode
| Knbccode | Knaccode | Letterspacefont | Textfont | Scriptfont
| Scriptscriptfont | Endlinechar | Newlinechar | Escapechar | Globaldefs | Time
| Day | Month | Year | BeginGroup | EndGroup | Relax | DeferredPrimitive | Message | Errmessage
@@ -242,6 +242,8 @@ impl Executor {
| Primitive::LinePenalties(_)
| Primitive::Prevgraf
| Primitive::Spacefactor
| Primitive::Pdfnoligatures
| Primitive::Tagcode
| Primitive::Hyphenchar
| Primitive::Lpcode
| Primitive::Rpcode
@@ -5,7 +5,7 @@ use crate::{
native_font::{LetterspaceProgram, NativeFont},
opentype::{OpenTypeFont, Request},
resources::{LoadedResource, ResourceKind, ResourceVersion},
tfm::{FontSize, TfmMetrics},
tfm::{ExtensibleRecipe, FontSize, LigKernCommand, TfmMetrics},
};
use sha2::{Digest, Sha256};
use std::{collections::BTreeMap, sync::Arc};
@@ -64,6 +64,10 @@ pub struct FontInstance {
opentype: Option<Arc<OpenTypeFont>>,
parameters: Arc<Vec<i32>>,
integers: FontIntegers,
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
suppress_ligature_tags: bool,
#[serde(default, skip_serializing_if = "ClearedFontTags::is_empty")]
cleared_tags: ClearedFontTags,
selector: CommandName,
#[serde(default, skip_serializing_if = "Option::is_none")]
expansion_origin: Option<(FontId, i32)>,
@@ -143,6 +147,79 @@ impl FontInstance {
}
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
struct ClearedFontTags([u64; 4]);
impl ClearedFontTags {
fn is_empty(&self) -> bool {
self.0 == [0; 4]
}
fn contains(&self, slot: u8) -> bool {
self.0[usize::from(slot / 64)] & (1 << (slot % 64)) != 0
}
fn insert(&mut self, slot: u8) {
self.0[usize::from(slot / 64)] |= 1 << (slot % 64);
}
}
/// Job-owned character programs retain the original font used for painting.
#[derive(Clone, Copy)]
pub(super) struct FontProgram<'a> {
metrics: &'a TfmMetrics,
suppress_ligature_tags: bool,
cleared_tags: &'a ClearedFontTags,
}
impl FontProgram<'_> {
fn tag(self, slot: u8) -> i32 {
let tag = self.metrics.glyph_tag_code(slot);
if tag > 0 && (self.cleared_tags.contains(slot) || (tag == 1 && self.suppress_ligature_tags)) {
0
} else {
tag
}
}
pub fn lig_kern(self, left: Option<u8>, right: u8) -> Option<LigKernCommand> {
if left.is_some_and(|slot| self.suppress_ligature_tags || self.cleared_tags.contains(slot)) {
return None;
}
// The separate left-boundary program is unaffected.
self.metrics.lig_kern(left, right)
}
pub fn kern(self, left: u8, right: u8) -> i64 {
match self.lig_kern(Some(left), right) {
Some(LigKernCommand::Kern(value)) => value,
_ => 0,
}
}
pub fn next_larger(self, slot: u8) -> Option<u8> {
if self.cleared_tags.contains(slot) {
return None;
}
self.metrics.next_larger(char::from(slot))
}
pub fn extensible_recipe(self, slot: u8) -> Option<ExtensibleRecipe> {
if self.cleared_tags.contains(slot) {
return None;
}
self.metrics.extensible_recipe(char::from(slot))
}
}
impl std::ops::Deref for FontProgram<'_> {
type Target = TfmMetrics;
fn deref(&self) -> &Self::Target {
self.metrics
}
}
/// Raw slot and sized integer metrics, with the identity needed by subsequent
/// list/geometry consumers. Missing slots produce no character node.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
@@ -265,6 +342,8 @@ impl FontCatalog {
hyphen: 45,
skew: -1,
},
suppress_ligature_tags: false,
cleared_tags: ClearedFontTags::default(),
selector: CommandName::Control("nullfont".into()),
expansion_origin: None,
automatic_expansion: false,
@@ -454,6 +533,8 @@ impl FontCatalog {
opentype: Some(font),
parameters: Arc::new(parameters),
integers: defaults,
suppress_ligature_tags: false,
cleared_tags: ClearedFontTags::default(),
selector,
expansion_origin: None,
automatic_expansion: false,
@@ -620,6 +701,8 @@ impl FontCatalog {
opentype: None,
parameters: Arc::new(parameters),
integers: defaults,
suppress_ligature_tags: false,
cleared_tags: ClearedFontTags::default(),
selector,
expansion_origin: None,
automatic_expansion: false,
@@ -1139,6 +1222,46 @@ impl FontCatalog {
}
}
pub(super) fn program(&self, id: FontId) -> Result<FontProgram<'_>, String> {
let font = self.font(id)?;
let metrics = font.metrics().ok_or("native TFM character program is unavailable")?;
Ok(FontProgram {
metrics,
suppress_ligature_tags: font.suppress_ligature_tags,
cleared_tags: &font.cleared_tags,
})
}
pub(super) fn no_ligatures(&self, id: FontId) -> Result<i32, String> {
if self.font(id)?.metrics().is_none() {
return Ok(1);
}
let program = self.program(id)?;
Ok(i32::from(!(0..=u8::MAX).any(|slot| matches!(program.tag(slot), 1 | 4))))
}
pub(super) fn suppress_ligatures(&mut self, id: FontId) -> Result<(), String> {
if self.font(id)?.glyph_font.is_some() {
self.fonts[id.0 as usize].suppress_ligature_tags = true;
}
Ok(())
}
pub(super) fn tag_code(&self, id: FontId, slot: u8) -> Result<i32, String> {
if self.font(id)?.metrics().is_none() {
return Ok(-1);
}
Ok(self.program(id)?.tag(slot))
}
pub(super) fn clear_tag_code(&mut self, id: FontId, slot: u8, mask: i32) -> Result<(), String> {
let current = self.tag_code(id, slot)?;
if current > 0 && current & (-mask.clamp(-7, 0)) != 0 {
self.fonts[id.0 as usize].cleared_tags.insert(slot);
}
Ok(())
}
pub fn set_integers(&mut self, id: FontId, integers: FontIntegers) -> Result<(), String> {
self.font(id)?;
self.fonts[id.0 as usize].integers = integers;
@@ -16,9 +16,9 @@ use std::{
sync::{Arc, Mutex, OnceLock, Weak},
};
const SCHEMA: u32 = 110;
const COMPATIBLE_SCHEMAS: [u32; 76] = [
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, 106, 107, 108, 109, SCHEMA,
const SCHEMA: u32 = 111;
const COMPATIBLE_SCHEMAS: [u32; 77] = [
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, 106, 107, 108, 109, 110, SCHEMA,
];
const ENGINE: &str = concat!("texrra-native/", env!("CARGO_PKG_VERSION"));
@@ -244,6 +244,9 @@ impl FormatImage {
if image.schema < 110 {
image.state.install_filedump_command();
}
if image.schema < 111 {
image.state.install_pdf_font_tag_commands();
}
let pdf_objects = image.state.pdf_objects.as_deref();
let mut numbered_images = 0;
for (index, saved) in image.pdf_images.iter().enumerate() {
@@ -1,9 +1,9 @@
//! Streaming TFM cursor/ligature-stack execution. A raw input character is
//! fetched only after the pending cursor asks for one; inserted ligatures can
//! therefore retain or consume components without inventing source characters.
use super::{Span, font_catalog::AutoKern};
use super::{Span, font_catalog::{AutoKern, FontProgram}};
use crate::provenance::{Derivation, PaintSource};
use crate::tfm::{LigKernCommand, TfmMetrics};
use crate::tfm::LigKernCommand;
use std::collections::VecDeque;
#[derive(Clone, Debug, PartialEq, Eq)]
@@ -109,7 +109,7 @@ impl Machine {
/// word. Its cursor shares the actual slots, components, ligature stack
/// and boundary packing with normal text execution.
pub fn reconstitute(
f: &TfmMetrics,
f: FontProgram<'_>,
hu: &[Option<Component>],
mut j: usize,
n: usize,
@@ -302,7 +302,7 @@ impl Machine {
}
pub fn feed(
&mut self,
f: &TfmMetrics,
f: FontProgram<'_>,
c: Component,
cancel_left: bool,
auto_kern: Option<AutoKern<'_>>,
@@ -341,7 +341,7 @@ impl Machine {
}
pub fn finish(
&mut self,
f: &TfmMetrics,
f: FontProgram<'_>,
right_boundary: bool,
auto_kern: Option<AutoKern<'_>>,
steps: &mut usize,
@@ -374,7 +374,7 @@ impl Machine {
out.push(Output::Glyph(glyph));
}
}
fn advance(&mut self, f: &TfmMetrics, out: &mut Vec<Output>) {
fn advance(&mut self, f: FontProgram<'_>, out: &mut Vec<Output>) {
if let Some(mut right) = self.stack.pop_front() {
if right.raw && !f.has_slot(right.glyph.slot) {
out.push(Output::Missing(
@@ -392,7 +392,7 @@ impl Machine {
}
fn pump(
&mut self,
f: &TfmMetrics,
f: FontProgram<'_>,
ending: bool,
auto_kern: Option<AutoKern<'_>>,
steps: &mut usize,
@@ -22,10 +22,10 @@ impl Converter<'_> {
n.nucleus = MathField::Empty;
} else if opentype.is_none()
&& let Ok(code) = u8::try_from(self.state.font_integers(base_font).skew)
&& let Ok(base_id) = self.state.fonts.glyph_font(base_font)
&& let Ok(program) = self.state.fonts.program(base_font)
&& let Ok(slot) = u8::try_from(c.slot)
{
skew = base_id.metrics().kern(char::from(slot), char::from(code));
skew = program.kern(slot, code);
}
}
let mut base = self.field(&n.nucleus, style.cramped_style(), &n.source.nucleus)?;
@@ -99,10 +99,9 @@ impl Converter<'_> {
(mark, x)
} else {
// Classic accents choose the last TFM list tag that fits the base.
let id = self.font(accent.family, style)?;
let metrics = id.metrics();
let metrics = self.state.fonts.program(font)?;
let mut visited = std::collections::BTreeSet::new();
while let Some(next) = metrics.next_larger(char::from(accent.slot as u8)) {
while let Some(next) = metrics.next_larger(accent.slot as u8) {
if !visited.insert(accent.slot) {
return Err("cyclic native accent size list".into());
}
@@ -125,7 +125,7 @@ impl Converter<'_> {
continue;
}
let id = self.state.fonts.glyph_font(font)?;
let m = id.metrics();
let m = self.state.fonts.program(font)?;
let Ok(mut slot) = u8::try_from(c.slot) else {
continue;
};
@@ -134,7 +134,7 @@ impl Converter<'_> {
if !visited.insert(slot) {
return Err("cyclic native delimiter size list".into());
}
if m.extensible_recipe(char::from(slot)).is_some() {
if m.extensible_recipe(slot).is_some() {
opentype_best = None;
best = Some((id, slot));
break 'search;
@@ -148,7 +148,7 @@ impl Converter<'_> {
break 'search;
}
}
let Some(next) = m.next_larger(char::from(slot)) else {
let Some(next) = m.next_larger(slot) else {
break;
};
slot = next;
@@ -163,7 +163,7 @@ impl Converter<'_> {
metrics.width, metrics.height, metrics.depth,
)
} else if let Some((id, slot)) = best {
if let Some(recipe) = id.metrics().extensible_recipe(char::from(slot)) {
if let Some(recipe) = self.state.fonts.program(id.id)?.extensible_recipe(slot) {
let repeat = character(id, recipe.repeat, source)?;
let unit = repeat.metrics.height + repeat.metrics.depth;
let mut extent = 0;
@@ -120,7 +120,7 @@ impl Converter<'_> {
} else {
let face = self.font(c.family, style)?;
if style.display()
&& let Some(next) = face.metrics().next_larger(char::from(c.slot as u8))
&& let Some(next) = self.state.fonts.program(id)?.next_larger(c.slot as u8)
&& self.state.font_has_slot(id, next)
{
c.slot = u32::from(next);
@@ -51,7 +51,7 @@ impl Converter<'_> {
let Ok(right) = u8::try_from(b.slot) else {
return Ok(());
};
match face.metrics().lig_kern(Some(a.slot as u8), right) {
match self.state.fonts.program(font)?.lig_kern(Some(a.slot as u8), right) {
Some(LigKernCommand::Kern(amount)) => {
if processed + pending.len() + 2 > self.node_limit {
return Err("native math noad capacity exceeded".into());
@@ -258,7 +258,7 @@ impl Builder {
run.machine
.put_carry(std::mem::take(&mut self.ligature_carry));
let output = run.machine.finish(
run.font.metrics(),
state.fonts.program(run.font.id)?,
right_boundary,
FontCatalog::auto_kern_for(state, run.font.id),
&mut self.font_steps,
@@ -498,7 +498,7 @@ impl Builder {
run.machine
.put_carry(std::mem::take(&mut self.ligature_carry));
let output = run.machine.feed(
run.font.metrics(),
state.fonts.program(font)?,
c,
cancel,
FontCatalog::auto_kern_for(state, font),
@@ -118,7 +118,7 @@ fn measure(
}
let variant = state.fonts.expansion_limit(font.id, amount)?;
Ok(match right {
Some(right) => variant.metrics().kern(char::from(slot), char::from(right)),
Some(right) => state.fonts.program(variant.id)?.kern(slot, right),
None => variant.advance(slot),
})
};
@@ -430,7 +430,7 @@ pub(super) fn pack(
let capacity = measure(state, left.font, left.slot, i64::from(width), Some(right.slot))?;
let variation = if ratio < 0 { capacity.shrink } else { capacity.stretch };
if variation != 0 && ratio != 0 {
let kern = left.font.metrics().kern(char::from(left.slot), char::from(right.slot));
let kern = state.fonts.program(left.font.id)?.kern(left.slot, right.slot);
let width = i32::try_from(kern)
.map_err(|_| "native font kern exceeds the scaled point range")?;
material[i] = TextNode::Kern { width, explicit: false };
@@ -49,7 +49,7 @@ pub(super) fn word(
missing: &mut Vec<(FontId, u8, Span)>,
) -> Result<Vec<TextNode>, String> {
let face = state.fonts.glyph_font(font)?.clone();
let f = face.metrics();
let f = state.fonts.program(font)?;
let hyphen = state
.hyphen_character(font)
.ok_or("native reconstitution requires a valid hyphen slot")? as u8;
@@ -362,6 +362,8 @@ pub enum Primitive {
Knaccode,
Efcode,
Pdffontexpand,
Pdfnoligatures,
Tagcode,
Pdfobj,
Pdfrefobj,
Pdflastobj,
@@ -987,6 +989,8 @@ const PDFTEX_ONLY_PRIMITIVES: &[(&str, Primitive)] = {
("knaccode", Knaccode),
("efcode", Efcode),
("pdffontexpand", Pdffontexpand),
("pdfnoligatures", Pdfnoligatures),
("tagcode", Tagcode),
("letterspacefont", Letterspacefont),
("pdffilesize", Pdffilesize),
("pdffilemoddate", Pdffilemoddate),
@@ -2083,6 +2087,16 @@ impl State {
self.update_profile_command("pdfinsertht", Meaning::Primitive(Primitive::Pdfinsertht), enabled);
}
pub(super) fn install_pdf_font_tag_commands(&mut self) {
let enabled = self.input_profile != super::InputProfile::XeTeX;
for (name, primitive) in [
("pdfnoligatures", Primitive::Pdfnoligatures),
("tagcode", Primitive::Tagcode),
] {
self.update_profile_command(name, Meaning::Primitive(primitive), enabled);
}
}
pub(super) fn install_filedump_command(&mut self) {
let name = if self.input_profile == super::InputProfile::XeTeX {
"filedump"
+12
View File
@@ -483,6 +483,18 @@ impl TfmMetrics {
}
})
}
pub(crate) fn glyph_tag_code(&self, slot: u8) -> i32 {
match self.char_info(char::from(slot)) {
Some(info) if info.width_index != 0 => match info.tag {
1 => 1,
2 => 2,
3 => 4,
_ => 0,
},
_ => -1,
}
}
pub fn lig_kern_program(&self) -> &[LigKernInstruction] {
&self.lig_kern
}