Use physical Type 1 glyph widths in XeTeX PDF output

This commit is contained in:
gloamxun committed 2026-11-28 06:23:12 +08:00
1 parent 885911485e
commit b22e127e93
11 files changed
+210 -33

No files matched your search

+9 -1
View File
@@ -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),
})
+14 -7
View File
@@ -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) => {
+28 -12
View File
@@ -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);
+8
View File
@@ -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);
+36 -11
View File
@@ -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))?;
}
}
}