Render Type1 map slant and extension in PDF and SVG

This commit is contained in:
gloamxun committed 2026-11-21 10:04:48 +08:00
1 parent 28dfba5a5e
commit 3caf1eced2
7 files changed
+274 -70

No files matched your search

+23 -17
View File
@@ -5,7 +5,7 @@ use crate::{
execution::{FontId, FontResource},
resources::{LoadedResource, ResourceVersion},
tfm::TfmMetrics,
type1::Type1Font,
type1::{Type1Font, Type1Transform},
type1_outline::Type1Outlines,
};
use std::{
@@ -30,6 +30,8 @@ pub struct NativeFontPaint {
program_index: Option<usize>,
}
pub(crate) type Type1ProgramKey<'a> = (&'a ResourceVersion, Type1Transform);
impl NativeFontPaint {
pub(crate) fn has_pdf_space(&self, font: &NativeFont) -> bool {
// pdfTeX requires the space name in an actual map re-encoding.
@@ -38,12 +40,10 @@ impl NativeFontPaint {
&& self.encoding[32] == "space"
&& font.metrics().width(' ') > 65_782
}
pub(crate) fn type1_resource(&self) -> Option<&crate::resources::ResourceVersion> {
pub(crate) fn type1_program_key(&self) -> Option<Type1ProgramKey<'_>> {
match &self.program {
NativeFontProgram::Type1(_) => {
// The physical font follows the map, before any encoding resource.
self.resources.get(self.program_index.unwrap_or(1))
}
NativeFontProgram::Type1(font) => self.resources.get(self.program_index.unwrap_or(1))
.map(|version| (version, font.transform)),
NativeFontProgram::Pk(_) => None,
}
}
@@ -192,7 +192,7 @@ const MAX_CACHED_PFB_BYTES: usize = 256 * 1024;
/// Decoded Type 1 programs shared across revisions in one compiler.
#[derive(Default)]
pub struct NativeFontCache {
type1: Mutex<VecDeque<(ResourceVersion, Arc<DecodedType1>)>>,
type1: Mutex<VecDeque<((ResourceVersion, Type1Transform), Arc<DecodedType1>)>>,
}
struct DecodedType1 {
@@ -203,16 +203,21 @@ struct DecodedType1 {
}
impl DecodedType1 {
fn from_pfb(resource: &LoadedResource) -> Result<Self, String> {
let program = Type1Font::from_pfb(&resource.data).ok_or_else(|| {
fn from_pfb(resource: &LoadedResource, transform: Type1Transform) -> Result<Self, String> {
let mut program = Type1Font::from_pfb(&resource.data).ok_or_else(|| {
format!(
"invalid Type1 PFB program: {}",
resource.version.path.display()
)
})?;
program.apply_map_transform(transform)?;
let outlines = Type1Outlines::parse(&program)?;
let bbox = outlines.normalized_bbox(program.bbox);
let stem_v = outlines.stem_v();
let (bbox, stem_v) = if transform.is_identity() {
(outlines.normalized_bbox(program.bbox), outlines.stem_v())
} else {
// The PDF descriptor keeps the Type1 program's own font units.
(program.bbox, outlines.raw_stem_v())
};
Ok(Self {
program,
outlines,
@@ -225,25 +230,25 @@ impl DecodedType1 {
impl NativeFontCache {
// The caller reads the actual resource and verifies its bytes on this
// revision before asking for the decoded representation.
fn type1(&self, resource: &LoadedResource) -> Result<Arc<DecodedType1>, String> {
fn type1(&self, resource: &LoadedResource, transform: Type1Transform) -> Result<Arc<DecodedType1>, String> {
if resource.data.len() > MAX_CACHED_PFB_BYTES {
return DecodedType1::from_pfb(resource).map(Arc::new);
return DecodedType1::from_pfb(resource, transform).map(Arc::new);
}
let mut entries = self.type1.lock().expect("native Type 1 cache poisoned");
if let Some(index) = entries
.iter()
.position(|(version, _)| *version == resource.version)
.position(|((version, cached_transform), _)| *version == resource.version && *cached_transform == transform)
{
let entry = entries.remove(index).expect("cached Type 1 index exists");
let decoded = entry.1.clone();
entries.push_back(entry);
return Ok(decoded);
}
let decoded = Arc::new(DecodedType1::from_pfb(resource)?);
let decoded = Arc::new(DecodedType1::from_pfb(resource, transform)?);
if entries.len() == MAX_TYPE1_PROGRAMS {
entries.pop_front();
}
entries.push_back((resource.version.clone(), decoded.clone()));
entries.push_back(((resource.version.clone(), transform), decoded.clone()));
Ok(decoded)
}
@@ -447,11 +452,12 @@ fn resolve_physical_fonts(
version.map(|version| version.sha256.clone()),
file.to_owned(),
outline.encoding.clone(),
outline.transform,
);
if !cache.contains_key(&key) {
let from = outline.from.to_string_lossy();
let resource = actual_resource(files, ResourceKind::Type1, file, &from)?;
let decoded = font_cache.type1(&resource)?;
let decoded = font_cache.type1(&resource, outline.transform)?;
let program = &decoded.program;
let mut resources: Vec<_> = version.cloned().into_iter().collect();
let program_index = Some(resources.len());
+44 -16
View File
@@ -3,6 +3,7 @@ use super::{NativeFont, verify_resource};
use crate::{
execution::{FontId, SourceProvider},
resources::{LoadedResource, ResourceKind, ResourceVersion},
type1::Type1Transform,
};
use std::{
collections::{BTreeMap, BTreeSet},
@@ -17,7 +18,8 @@ pub(super) struct MapEntry {
file: Option<String>,
pub encoding: Option<String>,
postscript_name: bool,
unsupported_transform: Option<String>,
#[serde(default, skip_serializing_if = "Type1Transform::is_identity")]
pub transform: Type1Transform,
}
impl MapEntry {
@@ -26,11 +28,6 @@ impl MapEntry {
}
pub(super) fn type1_file(&self, name: &str) -> Result<&str, String> {
if let Some(value) = &self.unsupported_transform {
return Err(format!(
"native font map transform is not implemented: {value}"
));
}
let file = self.file.as_deref().ok_or_else(|| {
format!("font map {name} has no embedded Type1 program; mapped device fonts require their actual support")
})?;
@@ -87,18 +84,28 @@ fn parse_map_line(
file: None,
encoding: None,
postscript_name: false,
unsupported_transform: None,
transform: Type1Transform::default(),
};
for (index, (quote, value)) in fields.into_iter().skip(1).enumerate() {
if quote {
let words: Vec<_> = value.split_whitespace().collect();
// pdfTeX ignores PostScript names and ReEncodeFont words;
// the actual .enc file supplies the encoding vector.
if words
.iter()
.any(|w| matches!(*w, "SlantFont" | "ExtendFont"))
{
entry.unsupported_transform.get_or_insert(value);
let mut previous = "";
for word in value.split_ascii_whitespace() {
let (operation, number) = if let Some(prefix) = word.strip_suffix("SlantFont") {
(&mut entry.transform.slant, prefix)
} else if let Some(prefix) = word.strip_suffix("ExtendFont") {
(&mut entry.transform.extend, prefix)
} else {
previous = word;
continue;
};
let number = if number.is_empty() { previous } else { number };
if let Ok(value) = number.parse::<f32>() {
if !value.is_finite() {
return Err(format!("invalid Type1 map transform for {name}"));
}
*operation = (value * 1000.).round() as i32;
}
previous = word;
}
} else if value.starts_with('<') {
let path = value.trim_start_matches('<').trim_start_matches('[');
@@ -111,6 +118,27 @@ fn parse_map_line(
entry.postscript_name = true;
}
}
if entry.transform.extend == 1000 {
entry.transform.extend = 0;
}
if entry.transform.slant.unsigned_abs() > 1000 || entry.transform.extend.unsigned_abs() > 2000 {
return Err(format!("Type1 map transform out of range for {name}"));
}
if !entry.transform.is_identity()
&& entry.file.as_deref().is_none_or(|file| {
let extension = Path::new(file)
.extension()
.and_then(|ext| ext.to_str())
.unwrap_or("");
["ttf", "ttc", "otf"]
.iter()
.any(|ext| extension.eq_ignore_ascii_case(ext))
})
{
return Err(format!(
"SlantFont/ExtendFont require an embedded Type1 program for {name}"
));
}
Ok(Some((name, entry)))
}
@@ -360,6 +388,6 @@ pub(super) fn dedicated_space_map(font: &NativeFont) -> MapEntry {
file: Some("pdftexspace.pfb".into()),
encoding: None,
postscript_name: false,
unsupported_transform: None,
transform: Type1Transform::default(),
}
}
+15 -11
View File
@@ -1573,7 +1573,11 @@ fn write_native_type1_descriptor(
let x_height = units(metrics.x_height());
let flags =
4 | if font.is_fixed_pitch { 1 } else { 0 } | if font.italic_angle != "0" { 64 } else { 0 };
let angle = &font.italic_angle;
let angle = if font.transform.slant == 0 {
font.italic_angle.clone()
} else {
font.italic_angle.parse::<f64>().unwrap_or(0.).round().to_string()
};
let stem_v = paint.stem_v;
objects.push(format!("<< /Type /FontDescriptor /FontName /{name} /Flags {flags} /FontBBox [{left} {bottom} {right} {top}] /ItalicAngle {angle} /Ascent {ascent} /Descent {descent} /CapHeight {cap} /XHeight {x_height} /StemV {stem_v} /FontFile {program} 0 R >>").into_bytes());
objects.push(objects::stream(
@@ -1587,15 +1591,15 @@ fn write_native_type1_descriptor(
descriptor
}
fn write_native_font(
fn write_native_font<'font>(
objects: &mut Vec<Vec<u8>>,
face: &crate::native_font::NativeFont,
paint: &crate::native_font::NativeFontPaint,
paint: &'font crate::native_font::NativeFontPaint,
used: &BTreeMap<u8, char>,
compression: u8,
options: Option<crate::pdf_unicode::PdfFinalOptions<'_>>,
diagnostics: &mut Vec<String>,
descriptors: &mut HashMap<&crate::resources::ResourceVersion, NativeType1Descriptor<'_>>,
descriptors: &mut HashMap<crate::native_font::Type1ProgramKey<'font>, NativeType1Descriptor<'_>>,
) -> usize {
let font = match &paint.program {
crate::native_font::NativeFontProgram::Type1(font) => font,
@@ -1606,7 +1610,7 @@ fn write_native_font(
let id = objects.len() + 1;
objects.push(Vec::new());
let m = face.metrics();
let descriptor = match paint.type1_resource().and_then(|key| descriptors.get_mut(key)) {
let descriptor = match paint.type1_program_key().and_then(|key| descriptors.get_mut(&key)) {
Some(shared) => *shared.object.get_or_insert_with(|| {
write_native_type1_descriptor(objects, font, paint, shared.metrics, compression)
}),
@@ -1992,9 +1996,9 @@ fn write_pdf(
let entry = native_used.entry(font.id).or_insert_with(|| {
// pdfTeX registers one font object per scalable TFM name
// when used and writes those objects in reverse order.
// The last newly used TFM for a PFB supplies its shared
// The last newly used TFM for an embedded variant supplies its shared
// descriptor, while each font keeps its own encoding.
if let Some(program) = paint.type1_resource() {
if let Some(program) = paint.type1_program_key() {
if type1_names.insert((program, font.name.as_str())) {
type1_descriptors.insert(
program,
@@ -2023,14 +2027,14 @@ fn write_pdf(
}
}
let mut native_font_ids = BTreeMap::new();
for (id, (face, paint, used)) in native_used {
for (&id, (face, paint, used)) in &native_used {
native_font_ids.insert(
id,
write_native_font(
&mut objects,
&face,
&paint,
&used,
face,
paint,
used,
final_compression.unwrap_or(0).max(0).min(9) as u8,
unicode,
diagnostics,
+122 -1
View File
@@ -7,7 +7,7 @@
//! characters to the codes the program expects.
use crate::type1_outline::Tokens;
use std::collections::BTreeMap;
use std::{collections::BTreeMap, ops::Range};
fn builtin_encoding(header: &[u8]) -> Result<Vec<String>, String> {
let mut tokens = Tokens::new(header);
@@ -103,6 +103,73 @@ fn copy_encoding_slots(tokens: &mut Tokens<'_>, encoding: &mut [String]) -> Resu
Ok(())
}
/// Map operations stored in thousandths, with zero denoting the default.
#[derive(
Clone,
Copy,
Debug,
Default,
PartialEq,
Eq,
PartialOrd,
Ord,
Hash,
serde::Serialize,
serde::Deserialize,
)]
pub(crate) struct Type1Transform {
pub slant: i32,
pub extend: i32,
}
impl Type1Transform {
pub fn is_identity(&self) -> bool {
*self == Self::default()
}
}
pub(crate) fn font_matrix(header: &str) -> Result<(Range<usize>, [f64; 6]), String> {
let rest = header
.split_once("/FontMatrix")
.ok_or("missing Type1 FontMatrix")?
.1
.trim_start();
let close = match rest.as_bytes().first() {
Some(b'[') => ']',
Some(b'{') => '}',
_ => return Err("invalid Type1 FontMatrix".into()),
};
let text = rest[1..]
.split_once(close)
.ok_or("unterminated FontMatrix")?
.0;
let start = header.len() - rest.len() + 1;
let values: Vec<f64> = text
.split_whitespace()
.map(str::parse)
.collect::<Result<_, _>>()
.map_err(|_| "invalid FontMatrix number")?;
let matrix: [f64; 6] = values
.try_into()
.map_err(|_| "FontMatrix requires six numbers")?;
if matrix.iter().any(|v| !v.is_finite()) || matrix[0] * matrix[3] == matrix[1] * matrix[2] {
return Err("invalid singular/nonfinite FontMatrix".into());
}
Ok((start..start + text.len(), matrix))
}
fn header_field(header: &str, key: &str) -> Option<Range<usize>> {
let rest = header.split_once(key)?.1.trim_start();
let value = rest.split_whitespace().next()?;
let start = header.len() - rest.len();
Some(start..start + value.len())
}
fn type1_number(value: f64) -> String {
// Type1 map transforms are serialized to six significant decimal digits.
format!("{value:.5e}").parse::<f64>().unwrap().to_string()
}
/// A Type1 font program ready to be written as a PDF `/FontFile` stream.
#[derive(Clone, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
pub struct Type1Font {
@@ -122,6 +189,8 @@ pub struct Type1Font {
pub length3: usize,
codes: BTreeMap<String, u8>,
encoding: Vec<String>,
#[serde(default, skip_serializing_if = "Type1Transform::is_identity")]
pub(crate) transform: Type1Transform,
}
impl Type1Font {
@@ -240,9 +309,61 @@ impl Type1Font {
length3,
codes,
encoding,
transform: Type1Transform::default(),
})
}
pub(crate) fn apply_map_transform(&mut self, transform: Type1Transform) -> Result<(), String> {
if transform.is_identity() {
return Ok(());
}
let mut header = std::str::from_utf8(&self.program[..self.length1])
.map_err(|_| "unsupported non-UTF8 Type1 header")?
.to_owned();
let (range, matrix) = font_matrix(&header)?;
let mut matrix = matrix.map(|value| f64::from(value as f32));
let slant = f64::from(transform.slant) / 1000.;
let extend = f64::from(transform.extend) / 1000.;
for i in [0, 2, 4] {
if transform.slant != 0 {
matrix[i] = f64::from((matrix[i] + matrix[i + 1] * slant) as f32);
}
if transform.extend != 0 {
matrix[i] = f64::from((matrix[i] * extend) as f32);
}
}
if matrix.iter().any(|value| !value.is_finite()) {
return Err("nonfinite Type1 map transform".into());
}
let numbers: Vec<_> = matrix.into_iter().map(type1_number).collect();
header.replace_range(range, &numbers.join(" "));
if transform.slant != 0 {
if let Some(range) = header_field(&header, "/ItalicAngle") {
let original: f32 = self
.italic_angle
.parse()
.map_err(|_| "invalid Type1 ItalicAngle")?;
let modified = (f64::from(original) - slant.atan().to_degrees()) as f32;
if !modified.is_finite() {
return Err("nonfinite Type1 ItalicAngle after slant".into());
}
self.italic_angle = type1_number(f64::from(modified));
header.replace_range(range, &self.italic_angle);
}
self.name.push_str(&format!("-Slant_{}", transform.slant));
}
if transform.extend != 0 {
self.name.push_str(&format!("-Extend_{}", transform.extend));
}
let name = header_field(&header, "/FontName").ok_or("missing Type1 FontName")?;
header.replace_range(name, &format!("/{}", self.name));
self.program.splice(..self.length1, header.bytes());
self.length1 = header.len();
self.transform = transform;
Ok(())
}
/// PDF character code for `ch`, using the font's own encoding.
pub fn code_for(&self, ch: char) -> Option<u8> {
glyph_names(ch)
+5 -25
View File
@@ -1,6 +1,6 @@
//! Type1 eexec/charstring execution for unhinted vector output. The PDF keeps
//! the original hinted program; SVG executes its actual paths and components.
use crate::type1::{Type1Font, standard_encoding};
use crate::type1::{Type1Font, font_matrix, standard_encoding};
use std::collections::BTreeMap;
fn decrypt(data: &[u8], mut key: u16, skip: usize) -> Result<Vec<u8>, String> {
if data.len() < skip {
@@ -239,30 +239,7 @@ impl Type1Outlines {
.ok_or("invalid Type1 header")?,
)
.map_err(|_| "unsupported non-UTF8 Type1 header")?;
let rest = header
.split("/FontMatrix")
.nth(1)
.ok_or("missing Type1 FontMatrix")?
.trim_start();
let close = match rest.as_bytes().first() {
Some(b'[') => ']',
Some(b'{') => '}',
_ => return Err("invalid Type1 FontMatrix".into()),
};
let values: Vec<f64> = rest[1..]
.split_once(close)
.ok_or("unterminated FontMatrix")?
.0
.split_whitespace()
.map(str::parse)
.collect::<Result<_, _>>()
.map_err(|_| "invalid FontMatrix number")?;
let matrix: [f64; 6] = values
.try_into()
.map_err(|_| "FontMatrix requires six numbers")?;
if matrix.iter().any(|v| !v.is_finite()) || matrix[0] * matrix[3] == matrix[1] * matrix[2] {
return Err("invalid singular/nonfinite FontMatrix".into());
}
let (_, matrix) = font_matrix(header)?;
Ok(Self {
subrs,
glyphs,
@@ -275,6 +252,9 @@ impl Type1Outlines {
self.std_vw
.map_or(0, |w| (w * self.matrix[0].abs() * 1000.).round() as i32)
}
pub(crate) fn raw_stem_v(&self) -> i32 {
self.std_vw.unwrap_or(0.) as i32
}
pub fn normalized_bbox(&self, bbox: [i32; 4]) -> [i32; 4] {
let matrix = self.matrix.map(|n| n * 1000.);
let mut result = [
@@ -358,3 +358,46 @@ fn font_map_file_binds_new_font_ids_and_locks_used_entries() {
}
fs::remove_dir_all(map).unwrap();
}
#[test]
fn pdf_and_svg_keep_distinct_transformations_of_the_same_type1_file() {
let mut files = Files::new(600);
let execution = native(
r#"\pdfcompresslevel=0
\pdfmapline{cmr10 CMR10 ".82 ExtendFont -.167 SlantFont" <cmr10.pfb}
\pdfmapline{cmr7 CMR10 ".167 SlantFont" <cmr10.pfb}
\font\combined=cmr10 \font\slanted=cmr7
\shipout\hbox{\combined A}
\shipout\hbox{\slanted A}
\end"#,
&mut files,
)
.unwrap();
let mut pages = execution.shipout_display_lists().unwrap();
resolve_native_fonts(&mut pages, &mut files).unwrap();
let svg = |page: usize| pages[page].try_to_svg().unwrap();
for (i, name) in ["CMR10-Slant_-167-Extend_820", "CMR10-Slant_167"].iter().enumerate() {
use texrra_tex_core::{render::DisplayItem, type1_outline::Type1Outlines};
let paint = pages[i].items.iter().find_map(|item| match item {
DisplayItem::NativeGlyph { paint, .. } => paint.as_deref(),
_ => None,
}).unwrap();
let NativeFontProgram::Type1(program) = &paint.program else {
panic!("expected transformed Type1 program");
};
assert_eq!(&program.name, name);
let expected = Type1Outlines::parse(program).unwrap().glyph_path("A").unwrap();
assert!(svg(i).contains(&expected));
}
let pdf = shipout_lists_to_native_pdf(&pages, execution.state.pdf_final_options()).unwrap();
let pdf = String::from_utf8_lossy(&pdf);
for (name, matrix) in [
("CMR10-Slant_-167-Extend_820", "[0.00082 0 -0.00013694 0.001 0 0]"),
("CMR10-Slant_167", "[0.001 0 0.000167 0.001 0 0]"),
] {
assert!(pdf.contains(&format!("/BaseFont /{name}")));
assert!(pdf.contains(&format!("/FontName /{name} def")));
assert!(pdf.contains(&format!("/FontMatrix {matrix}")));
}
assert_eq!(pdf.matches("/Type /FontDescriptor").count(), 2);
}
+22
View File
@@ -2153,6 +2153,28 @@ pdfTeX 均成功出页,原生报告具体变换缺口。
回执为 target/p3-dynamic-font-map/next-transform-receipt.json,
SHA-256 43653db3aa5765408347e6af2d45878a4bfe44edf2a4a7f0babf7df4dd95c23a。
### Type1 字体映射的斜切与横向缩放
SlantFont 和 ExtendFont 以千分数保存,先斜切再沿 X 轴缩放。
Type1 的 FontMatrix 进入 PDF 嵌入程序,同时供原生 SVG 字形求值。
原始 TFM 继续提供布局度量。同一个实际 PFB 的不同变换分别识别,
在修订间缓存与 PDF 描述符中各自保留字体身份。
[pdfTeX 的矩阵、斜角和字体名称处理](https://github.com/TeX-Live/texlive-source/blob/trunk/texk/web2c/pdftexdir/writet1.c#L545-L670)
[pdfTeX 的字体描述符键](https://github.com/TeX-Live/texlive-source/blob/trunk/texk/web2c/pdftexdir/writefont.c#L24-L40)
两份冻结 Times 用例,加上任务内映射和默认映射两条多字体路径,共
四个作业八页。PDF 词框和 600 dpi 彩色像素一致,字体矩阵、斜角、
字体边界和垂直笔画宽度与 pdfTeX 一致。核对实际 TFM、PFB、编码
和映射的资源指纹。15 项 Type1、PK 和 VF 定向回归通过。
回执 target/p3-type1-map-transform/receipt.json 的 SHA-256 为
344b2c437071c8e08612b0f51bcebede574f23e04eae9360e149368b512803bc。
三页项目只改实际映射资源。改为引用不存在的 PFB 时保留上一版
PDF,恢复实际 PFB 并反转斜切时复用 1277 步,只替换第二页。
排版和来源映射保持一致,更新后的 PDF、SVG 和来源映射与独立
全量编译一致。incremental-receipt.json 的 SHA-256 为
bbc0991b0316e6d76aa58649ec873525f5544ab530d93fe491fc6e16bd00a27d。
### 原生段落边缘悬挂
`\pdfprotrudechars`、`\lpcode`、`\rpcode` 接入实际字体槽和水平