Use physical Type 1 glyph widths in XeTeX PDF output
This commit is contained in:
1 parent
885911485e
commit
b22e127e93
11 files changed
+210
-33
No files matched your search
@@ -38,6 +38,8 @@ pub struct NativeFontPaint {
|
||||
pub(crate) descriptor_flags: Option<i32>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub(crate) xdv_descriptor: Option<XdvDescriptor>,
|
||||
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
|
||||
pub(crate) xdv_widths: BTreeMap<u8, i64>,
|
||||
pub resources: Vec<crate::resources::ResourceVersion>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
program_index: Option<usize>,
|
||||
@@ -551,6 +553,7 @@ fn resolve_physical_fonts(
|
||||
subset: false,
|
||||
descriptor_flags: None,
|
||||
xdv_descriptor: None,
|
||||
xdv_widths: BTreeMap::new(),
|
||||
resources: entry.as_ref().and_then(|entry| entry.version.as_ref())
|
||||
.or(default_version).cloned().into_iter()
|
||||
.chain(std::iter::once(resource.version)).collect(),
|
||||
@@ -626,6 +629,7 @@ fn resolve_physical_fonts(
|
||||
} else {
|
||||
None
|
||||
},
|
||||
xdv_widths: BTreeMap::new(),
|
||||
resources,
|
||||
program_index,
|
||||
},
|
||||
@@ -646,7 +650,11 @@ fn resolve_physical_fonts(
|
||||
font.name
|
||||
));
|
||||
}
|
||||
paint.glyph_paths.insert(slot, outlines.glyph_path(name)?);
|
||||
let (path, width) = outlines.glyph_path_and_width(name)?;
|
||||
paint.glyph_paths.insert(slot, path);
|
||||
if paint.xdv_descriptor.is_some() {
|
||||
paint.xdv_widths.insert(slot, width);
|
||||
}
|
||||
}
|
||||
resolved.insert(id, key);
|
||||
}
|
||||
|
||||
@@ -6,7 +6,7 @@ use super::{
|
||||
use crate::{execution::SourceProvider, resources::ResourceKind};
|
||||
use read_fonts::ps::cff::CffFontRef;
|
||||
use rustybuzz::ttf_parser::{Face, GlyphId, Tag};
|
||||
use std::{collections::BTreeSet, sync::Arc};
|
||||
use std::{collections::{BTreeMap, BTreeSet}, sync::Arc};
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
|
||||
pub struct OpenTypeCffProgram {
|
||||
@@ -132,6 +132,7 @@ pub(super) fn resolve(
|
||||
subset: false,
|
||||
descriptor_flags: outline.descriptor_flags,
|
||||
xdv_descriptor: None,
|
||||
xdv_widths: BTreeMap::new(),
|
||||
resources,
|
||||
program_index: Some(program_index),
|
||||
})
|
||||
|
||||
@@ -139,6 +139,7 @@ pub(super) fn resolve(
|
||||
subset: false,
|
||||
descriptor_flags: entry.descriptor_flags,
|
||||
xdv_descriptor: None,
|
||||
xdv_widths: BTreeMap::new(),
|
||||
resources,
|
||||
program_index: None,
|
||||
})
|
||||
|
||||
@@ -224,6 +224,7 @@ pub(super) fn resolve(
|
||||
subset: outline.subset,
|
||||
descriptor_flags: outline.descriptor_flags,
|
||||
xdv_descriptor: None,
|
||||
xdv_widths: BTreeMap::new(),
|
||||
resources,
|
||||
program_index: Some(program_index),
|
||||
})
|
||||
|
||||
@@ -1854,17 +1854,24 @@ fn write_native_font(
|
||||
let last = *used.keys().next_back().unwrap();
|
||||
let widths = (first..=last)
|
||||
.map(|slot| {
|
||||
format!(
|
||||
"{:.1}",
|
||||
let width = if paint.xdv_descriptor.is_some() {
|
||||
if used.contains_key(&slot) {
|
||||
*paint.xdv_widths.get(&slot).ok_or_else(|| format!(
|
||||
"native XeTeX font {} has no PDF width for slot {slot}", face.name,
|
||||
))?
|
||||
} else {
|
||||
0
|
||||
}
|
||||
} else {
|
||||
native_font_units(
|
||||
m.width(char::from(slot)),
|
||||
native_pdf_font_size(m.size_sp()),
|
||||
10_000
|
||||
) as f64
|
||||
/ 10.0
|
||||
)
|
||||
10_000,
|
||||
)
|
||||
};
|
||||
Ok(format!("{:.1}", width as f64 / 10.0))
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
.collect::<Result<Vec<_>, String>>()?
|
||||
.join(" ");
|
||||
let (subtype, descriptor, name, widths, encoding, has_glyph_unicode) = match &paint.program {
|
||||
NativeFontProgram::Type1(font) => {
|
||||
|
||||
@@ -82,8 +82,15 @@ impl NativeText {
|
||||
}
|
||||
let (mut shift, shift_out) = state.horizontal_move(x, state.effective_size);
|
||||
let (v, v_out) = state.vertical_move(y, digits);
|
||||
if first || v != 0 || shift.abs() >= 32768 || space == Some(SpaceUse::Dedicated)
|
||||
|| (!state.xdv && expansion_changed)
|
||||
let reset_line = if state.xdv {
|
||||
let delta = x - state.start_h - state.delta_h;
|
||||
!state.opened
|
||||
|| v != 0
|
||||
|| delta.abs() > 3 * Self::expanded_size(state.effective_size, state.expansion)
|
||||
} else {
|
||||
v != 0 || shift.abs() >= 32768 || expansion_changed
|
||||
};
|
||||
if first || reset_line || space == Some(SpaceUse::Dedicated)
|
||||
{
|
||||
state.close_string(out);
|
||||
if !state.xdv && (font.expansion != 0 || state.expansion != 0) {
|
||||
@@ -135,7 +142,7 @@ impl NativeText {
|
||||
if self.font != Some(font.id) {
|
||||
self.close_string(out);
|
||||
let (number, size) = divide_scaled(font.size_sp(), 6_578_176, 6);
|
||||
self.effective_size = size;
|
||||
self.effective_size = if self.xdv { font.size_sp() } else { size };
|
||||
self.font = Some(font.id);
|
||||
if !out.measuring {
|
||||
out.push_str(&format!(
|
||||
@@ -154,18 +161,22 @@ impl NativeText {
|
||||
slot: u8,
|
||||
size: i64,
|
||||
) -> i64 {
|
||||
let expansion = if self.xdv { font.expansion } else { self.expansion };
|
||||
if self.xdv {
|
||||
// xdvipdfmx follows the advances in the DVI/XDV stream. The PDF
|
||||
// viewer separately uses the embedded font's declared widths.
|
||||
return crate::pdf_device::magnify(
|
||||
font.metrics().xdv_width(slot),
|
||||
1000 + font.expansion,
|
||||
);
|
||||
}
|
||||
let expansion = self.expansion;
|
||||
let advance = match &paint.program {
|
||||
crate::native_font::NativeFontProgram::Pk(pk) => pk.advances[&slot],
|
||||
_ => {
|
||||
let factor = i64::from(1000 + expansion);
|
||||
let width = if !self.xdv || font.layout_metrics.is_some() {
|
||||
Self::round_scale(font.advance(slot), 1000, factor)
|
||||
} else {
|
||||
font.metrics().width(char::from(slot))
|
||||
};
|
||||
let width = Self::round_scale(font.advance(slot), 1000, factor);
|
||||
let (units, advance) = divide_scaled(width, size, 4);
|
||||
if expansion != 0 && !self.xdv {
|
||||
if expansion != 0 {
|
||||
Self::round_scale(size * units, 1, 10_000)
|
||||
} else {
|
||||
advance
|
||||
@@ -177,8 +188,13 @@ impl NativeText {
|
||||
|
||||
fn horizontal_move(&self, x: i64, size: i64) -> (i64, i64) {
|
||||
let delta = x - self.start_h - self.delta_h;
|
||||
if self.expansion == 0 || self.xdv {
|
||||
return divide_scaled(delta, Self::expanded_size(size, self.expansion), 3);
|
||||
if self.xdv {
|
||||
let size = Self::expanded_size(size, self.expansion);
|
||||
let units = delta * 1000 / size;
|
||||
return (units, units * size / 1000);
|
||||
}
|
||||
if self.expansion == 0 {
|
||||
return divide_scaled(delta, size, 3);
|
||||
}
|
||||
let unscaled = Self::round_scale(delta, 1000, i64::from(1000 + self.expansion));
|
||||
let (units, _) = divide_scaled(unscaled, size, 3);
|
||||
|
||||
@@ -407,6 +407,14 @@ impl TfmMetrics {
|
||||
self.scale_horizontal(width)
|
||||
}
|
||||
|
||||
/// Width used when reading a legacy TFM glyph on the XDV device. The
|
||||
/// driver rounds the exact fixword product to a scaled point.
|
||||
pub(crate) fn xdv_width(&self, slot: u8) -> i64 {
|
||||
let Some(info) = self.char_info(char::from(slot)) else { return 0 };
|
||||
let product = i64::from(self.widths[usize::from(info.width_index)]) * self.size;
|
||||
product.signum() * ((product.abs() + (1 << 19)) >> 20)
|
||||
}
|
||||
|
||||
pub(crate) fn expand_horizontal(&mut self, amount: i32) -> Result<(), String> {
|
||||
let apply = |value| {
|
||||
let scaled = crate::pdf_device::magnify(self.scale_horizontal(value), 1000 + amount);
|
||||
|
||||
@@ -437,7 +437,7 @@ impl Type1Outlines {
|
||||
let mut include = |y: f64| {
|
||||
bound = Some(bound.map_or(y, |old| if top { old.max(y) } else { old.min(y) }));
|
||||
};
|
||||
for command in self.commands(name, 0, &mut budget, None)? {
|
||||
for command in self.glyph(name, 0, &mut budget, None)?.commands {
|
||||
match command {
|
||||
Command::Move(_, y) | Command::Line(_, y) => include(y),
|
||||
Command::Curve(_, a, _, b, _, c) => {
|
||||
@@ -463,13 +463,13 @@ impl Type1Outlines {
|
||||
pub fn has_glyph(&self, name: &str) -> bool {
|
||||
self.glyphs.contains_key(name)
|
||||
}
|
||||
fn commands(
|
||||
fn glyph(
|
||||
&self,
|
||||
name: &str,
|
||||
depth: usize,
|
||||
budget: &mut usize,
|
||||
mut usage: Option<&mut GlyphUse>,
|
||||
) -> Result<Vec<Command>, String> {
|
||||
) -> Result<Type1Glyph, String> {
|
||||
if depth > 32 {
|
||||
return Err("Type1 composite recursion capacity exceeded".into());
|
||||
}
|
||||
@@ -488,6 +488,7 @@ impl Type1Outlines {
|
||||
x: 0.,
|
||||
y: 0.,
|
||||
sbx: 0.,
|
||||
width: 0.,
|
||||
open: false,
|
||||
flex: false,
|
||||
other_results: 0,
|
||||
@@ -495,11 +496,21 @@ impl Type1Outlines {
|
||||
if !run.execute(code, depth, budget)? {
|
||||
return Err("Type1 glyph program has no endchar/seac".into());
|
||||
}
|
||||
Ok(run.commands)
|
||||
Ok(Type1Glyph {
|
||||
commands: run.commands,
|
||||
width: run.width,
|
||||
})
|
||||
}
|
||||
|
||||
pub fn glyph_path(&self, name: &str) -> Result<String, String> {
|
||||
self.glyph_path_and_width(name).map(|(path, _)| path)
|
||||
}
|
||||
|
||||
/// Return the vector outline and the Type 1 program's PDF width in tenths
|
||||
/// of a thousandth of an em, using the font's own matrix.
|
||||
pub(crate) fn glyph_path_and_width(&self, name: &str) -> Result<(String, i64), String> {
|
||||
let mut budget = 1_000_000;
|
||||
let commands = self.commands(name, 0, &mut budget, None)?;
|
||||
let glyph = self.glyph(name, 0, &mut budget, None)?;
|
||||
let point = |x: f64, y: f64| {
|
||||
(
|
||||
(self.matrix[0] * x + self.matrix[2] * y + self.matrix[4]) * 1000.,
|
||||
@@ -518,7 +529,7 @@ impl Type1Outlines {
|
||||
Ok(format!("{} {}", number(x)?, number(y)?))
|
||||
};
|
||||
let mut out = String::new();
|
||||
for command in commands {
|
||||
for command in glyph.commands {
|
||||
match command {
|
||||
Command::Move(x, y) => out.push_str(&format!("M{}", pair(x, y)?)),
|
||||
Command::Line(x, y) => out.push_str(&format!("L{}", pair(x, y)?)),
|
||||
@@ -528,9 +539,19 @@ impl Type1Outlines {
|
||||
Command::Close => out.push('Z'),
|
||||
}
|
||||
}
|
||||
Ok(out)
|
||||
let width = (glyph.width * (10_000. * self.matrix[0]) + 0.5).floor();
|
||||
if !width.is_finite() {
|
||||
return Err("nonfinite Type1 glyph width".into());
|
||||
}
|
||||
Ok((out, width as i64))
|
||||
}
|
||||
}
|
||||
|
||||
struct Type1Glyph {
|
||||
commands: Vec<Command>,
|
||||
width: f64,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
enum Command {
|
||||
Move(f64, f64),
|
||||
@@ -565,6 +586,7 @@ struct Runner<'a, 'u> {
|
||||
x: f64,
|
||||
y: f64,
|
||||
sbx: f64,
|
||||
width: f64,
|
||||
open: bool,
|
||||
flex: bool,
|
||||
other_results: usize,
|
||||
@@ -714,6 +736,7 @@ impl Runner<'_, '_> {
|
||||
let v = self.args(2)?;
|
||||
self.sbx = v[0];
|
||||
self.x = v[0];
|
||||
self.width = v[1];
|
||||
}
|
||||
14 => {
|
||||
self.args(0)?;
|
||||
@@ -746,12 +769,13 @@ impl Runner<'_, '_> {
|
||||
}
|
||||
let name = standard_encoding(i as u8)
|
||||
.ok_or("unassigned seac StandardEncoding slot")?;
|
||||
let mut commands =
|
||||
self.font.commands(name, depth + 1, budget, self.usage.as_deref_mut())?;
|
||||
for c in &mut commands {
|
||||
let mut glyph = self.font.glyph(
|
||||
name, depth + 1, budget, self.usage.as_deref_mut(),
|
||||
)?;
|
||||
for c in &mut glyph.commands {
|
||||
c.translate(dx, dy);
|
||||
}
|
||||
self.commands.extend(commands);
|
||||
self.commands.extend(glyph.commands);
|
||||
}
|
||||
return Ok(true);
|
||||
}
|
||||
@@ -760,6 +784,7 @@ impl Runner<'_, '_> {
|
||||
self.sbx = v[0];
|
||||
self.x = v[0];
|
||||
self.y = v[1];
|
||||
self.width = v[2];
|
||||
}
|
||||
12 => {
|
||||
let b = self.pop()?;
|
||||
|
||||
@@ -53,7 +53,7 @@ pub(crate) fn write_subset(
|
||||
for name in std::iter::once(".notdef").chain(requested.iter().map(String::as_str)) {
|
||||
if outlines.has_glyph(name) && !usage.names.contains(name) {
|
||||
let mut budget = 1_000_000;
|
||||
outlines.commands(name, 0, &mut budget, Some(&mut usage))?;
|
||||
outlines.glyph(name, 0, &mut budget, Some(&mut usage))?;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -819,6 +819,49 @@ letterspace-fresh.log 和 device-pdftex-spaced-moved.log。
|
||||
[原版字距虚拟字体构造](https://github.com/TeX-Live/texlive-source/blob/fb6158926661cb7a7246b3a94a0cb170a9624d5a/texk/web2c/pdftexdir/pdftex.web#L16400-L16492)
|
||||
[原版格式所写字体字段](https://github.com/TeX-Live/texlive-source/blob/fb6158926661cb7a7246b3a94a0cb170a9624d5a/texk/web2c/pdftexdir/pdftex.web#L30627-L30696)
|
||||
|
||||
### XeTeX Type 1 字幅和传统字体的文字定位
|
||||
|
||||
原生 Type 1 字形解释器在生成实际轮廓时一并取出 hsbw 或
|
||||
sbw 的宽度,按嵌入字体的 FontMatrix 归一化。XDV 的 PDF
|
||||
Widths 使用实际编码所指向的字形程序,范围内未用字符的
|
||||
宽度为零。传统字体换字时,驱动光标用按 XDV 规则舍入的
|
||||
原始 TFM 度量。在切换字体或移动超出三个 em 时结束
|
||||
当前字符串,再从文字行原点移动。TeX 盒宽和 pdfTeX
|
||||
入口的度量不变。
|
||||
[实际 Type 1 字幅](https://github.com/TeX-Live/texlive-source/blob/fb6158926661cb7a7246b3a94a0cb170a9624d5a/texk/dvipdfm-x/type1.c#L276-L348)
|
||||
[XDV 选择字体和移动](https://github.com/TeX-Live/texlive-source/blob/fb6158926661cb7a7246b3a94a0cb170a9624d5a/texk/dvipdfm-x/pdfdev.c#L840-L895)
|
||||
|
||||
两项实际字体探针比较 CMMI9、CMR10 以及不同字符槽引用
|
||||
实际 CMR10 W 和 A 的重新编码。PDF 字宽、词框及灰度图
|
||||
与参考一致,TeX 盒宽保持一致。四项 XeTeX 管线和六项
|
||||
传统字体设备回归通过。Type 1 轮廓套件的三项通过。余下一项
|
||||
在 PDF BaseFont 断言处失败,独立检出上一版 8859114 后在
|
||||
同一断言复现。原断言与两次日志 core-type1.log 和
|
||||
prior-type1.log 保留。
|
||||
四页会话中,用两个实际 Type 1 字体编辑项目文件并移动
|
||||
子文件正文。x 的 PDF 字幅按字体版本从 582 到 571 再恢复。
|
||||
三次成功修订只更新第 2 页,后两次各复用 66 步。PDF、
|
||||
测量页面、SVG、来源映射与 aux 等于独立全量。物理字体
|
||||
读错时保留最近发布的预览及 aux。
|
||||
|
||||
官方 xeCJK 原样样稿复编后 515 个原始字形的位置、字体及字号
|
||||
与原生上一轮相同。380 个词框现在逐项与参考一致,40 条出页
|
||||
警告和 aux 继续相同。传统字体 PDF 仍嵌入实际 Type 1 程序,
|
||||
参考使用 Type1C 子集。灰度图仍有 174 个像素差,集中于两
|
||||
个 Latin Modern B。原样输入、原版对照、旧结果和原失败记录
|
||||
保留。证据在 target/p3-xetex-type1-widths,receipt.json 为
|
||||
6c0c80300edeb2dea4fdefe67ed9f952f45640b4d2c42c2b37dd696851da7dd3,
|
||||
revision.log 为 d5213a6ddf20966719864d48ec7655165ca8d5ae51fb04e8b7f09696305827af。
|
||||
|
||||
下一入口是 XDV 在同一文本对象内切换 OpenType 字体时连续
|
||||
使用相对定位。next-font-switch 的四字形见证仍差 87 像素,
|
||||
原版使用一个 BT 和三个 Td,原生使用三个 BT。对上轮 PDF
|
||||
替换这两处相对定位的隔离实验消除了全部 174 个像素差。
|
||||
单独换成相同参考字体资源或替换原点的表示时,174 像素差
|
||||
保持。实验文件仅用于定位,原样项目的原生 PDF 仍保持实际
|
||||
差异。next-font-switch/summary.log 为
|
||||
3a039098a44e98f3ee02b56698e3dbc02469729e0057dabad10296e085d6076a。
|
||||
|
||||
### XeTeX 出页的未认领 special
|
||||
|
||||
按 xdvipdfmx 的分派语法识别 PDF、XeTeX、dvips、颜色、tpic、
|
||||
|
||||
@@ -707,6 +707,73 @@ fn font_mapping_changes_recover_and_update_the_page_that_used_the_resource() {
|
||||
fs::remove_dir_all(p).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn xetex_type1_widths_follow_the_encoded_glyph_program() {
|
||||
use lopdf::{Document, Object, content::Content};
|
||||
use texrra_tex_core::execution::InputProfile;
|
||||
|
||||
let root = directory("xetex-type1-widths");
|
||||
let mut job = request(&root);
|
||||
job.input_profile = InputProfile::XeTeX;
|
||||
job.world.paths.insert(
|
||||
ResourceKind::Map,
|
||||
vec![SearchPath::directory(root.clone(), false)],
|
||||
);
|
||||
fs::write(
|
||||
root.join("pdftex.map"),
|
||||
b"cmmi10 CMMI10 <cmmi10.pfb\ncmr10 CMR10 <cmr10.pfb\n",
|
||||
)
|
||||
.unwrap();
|
||||
fs::write(
|
||||
root.join("main.tex"),
|
||||
br"\catcode123=1 \catcode125=2
|
||||
\font\italic=cmmi10 \font\roman=cmr10
|
||||
\shipout\hbox{\italic xYvx\kern10pt\roman AVW}
|
||||
\end",
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
let result = NativeCompiler::default().compile(job).unwrap();
|
||||
let pdf = Document::load_mem(result.pdf.as_deref().unwrap()).unwrap();
|
||||
let width = |name: &[u8], slot: u8| {
|
||||
let font = pdf
|
||||
.objects
|
||||
.values()
|
||||
.filter_map(|object| object.as_dict().ok())
|
||||
.find(|font| {
|
||||
font.get(b"BaseFont")
|
||||
.and_then(Object::as_name)
|
||||
.is_ok_and(|base_font| base_font.rsplit(|&byte| byte == b'+').next() == Some(name))
|
||||
})
|
||||
.unwrap();
|
||||
let first = font.get(b"FirstChar").unwrap().as_i64().unwrap();
|
||||
let widths = pdf.dereference(font.get(b"Widths").unwrap()).unwrap().1;
|
||||
match widths.as_array().unwrap()[(i64::from(slot) - first) as usize] {
|
||||
Object::Integer(width) => width as f64,
|
||||
Object::Real(width) => width,
|
||||
ref object => panic!("invalid font width {object:?}"),
|
||||
}
|
||||
};
|
||||
assert_eq!(width(b"CMMI10", b'Y'), 580.0);
|
||||
assert_eq!(width(b"CMMI10", b'Z'), 0.0);
|
||||
assert_eq!(width(b"CMMI10", b'v'), 484.0);
|
||||
assert_eq!(width(b"CMMI10", b'x'), 571.0);
|
||||
assert_eq!(width(b"CMR10", b'W'), 1027.0);
|
||||
|
||||
let page = pdf.get_page_content(pdf.get_pages()[&1]).unwrap();
|
||||
let content = Content::decode(&page).unwrap();
|
||||
let operators = content
|
||||
.operations
|
||||
.iter()
|
||||
.filter_map(|operation| match operation.operator.as_str() {
|
||||
operator @ ("BT" | "ET" | "Tf" | "Td" | "TJ") => Some(operator),
|
||||
_ => None,
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
assert_eq!(operators, ["BT", "Tf", "Td", "TJ", "Tf", "Td", "TJ", "ET"]);
|
||||
fs::remove_dir_all(root).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn xetex_unclaimed_special_warns_at_shipout_and_retains_the_whatsit() {
|
||||
use texrra_tex_core::execution::{Event, InputProfile};
|
||||
|
||||
Reference in new issue
Block a user