Implement native letterspaced fonts and virtual glyph placement

This commit is contained in:
gloamxun committed 2026-11-21 05:48:44 +08:00
1 parent 6675ab639a
commit f66a5a7e20
13 files changed
+337 -35

No files matched your search

@@ -1096,7 +1096,9 @@ impl Executor {
token.kind = TokenKind::Command(CommandName::Font(font));
return Ok(TheValue::Tokens(vec![token]));
}
Meaning::Primitive(Font | Textfont | Scriptfont | Scriptscriptfont) => {
Meaning::Primitive(
Font | Letterspacefont | Textfont | Scriptfont | Scriptscriptfont,
) => {
let mut token = next.token.clone();
self.unread(next)?;
let font = self.font_identifier(files)?;
@@ -4042,6 +4044,7 @@ impl Executor {
.map_err(|e| self.error(e, self.current))?;
}
Some(Font) => self.define_font(global, files)?,
Some(Letterspacefont) => self.define_letterspaced_font(global, files)?,
Some(Textfont | Scriptfont | Scriptscriptfont) => {
self.math_font_assignment(primitive.unwrap(), global, files)?
}
@@ -401,6 +401,7 @@ impl Executor {
| Readline
| Font
| Fontdimen
| Letterspacefont
| Hyphenchar
| Lpcode
| Rpcode
@@ -1,5 +1,49 @@
use super::*;
impl Executor {
pub(super) fn define_letterspaced_font(
&mut self,
global: bool,
files: &mut impl SourceProvider,
) -> Result<(), Error> {
let name = self.command(files)?;
self.define_traced(name.clone(), Meaning::Font(FontId::NULL), global, files)?;
self.optional_equals(files)?;
let base = self.font_identifier(files)?;
let amount = self.integer(files)?.clamp(-1000, 1000);
let no_ligatures = self.keyword("nolig", files)?;
let defaults = self.font_defaults();
let from = self.sources[self.current.source].name.clone();
let (font, zero_quad) = self
.state
.fonts
.letterspace(
files,
&from,
base,
amount,
no_ligatures,
name.clone(),
defaults,
)
.map_err(|e| self.error(e, self.current))?;
if zero_quad {
files
.observe_diagnostic(
WriteDestination::TerminalAndLog,
"\npdfTeX warning (\\letterspacefont): font has zero em size (\\fontdimen6)\n",
)
.map_err(|e| self.error(e, self.current))?;
}
self.define_traced(name, Meaning::Font(font), global, files)
}
pub(super) fn font_defaults(&mut self) -> FontIntegers {
FontIntegers {
hyphen: self.read_parameter(Parameter::Defaulthyphenchar).width(),
skew: self.read_parameter(Parameter::Defaultskewchar).width(),
}
}
pub(super) fn font_dimension_target(
&mut self,
files: &mut impl SourceProvider,
@@ -54,7 +98,7 @@ impl Executor {
let t = self.expanded_non_space(files)?.token;
let font = match self.meaning(&t) {
Meaning::Font(f) => f,
Meaning::Primitive(Primitive::Font) => {
Meaning::Primitive(Primitive::Font | Primitive::Letterspacefont) => {
self.reads.insert(Dependency::TextFont);
self.state.text_font()
}
@@ -783,7 +783,7 @@ impl Executor {
| Delcode | Count | Countdef | Dimen | Dimendef | Skip | Skipdef | Muskip
| Muskipdef | Toks | Toksdef | Advance | Multiply | Divide | Read | Readline
| Font | Fontdimen | Hyphenchar | Skewchar | Lpcode | Rpcode | Efcode | Pdffontexpand
| Textfont | Scriptfont
| Letterspacefont | Textfont | Scriptfont
| Scriptscriptfont | Endlinechar | Newlinechar | Escapechar | Globaldefs | Time
| Day | Month | Year | BeginGroup | EndGroup | Relax | Message | Errmessage
| Endinput | Showbox | Show | Showthe | Discretionary | DiscretionaryHyphen
@@ -635,10 +635,7 @@ impl Executor {
crate::tfm::FontSize::Design
};
self.reads.insert(Dependency::FontResources);
let defaults = FontIntegers {
hyphen: self.read_parameter(Parameter::Defaulthyphenchar).width(),
skew: self.read_parameter(Parameter::Defaultskewchar).width(),
};
let defaults = self.font_defaults();
let from = self.sources[self.current.source].name.clone();
let font = self
.state
@@ -2,7 +2,8 @@
//! This layer has no master-font names, outline aliases or bundled fallbacks.
use super::{CommandName, Flex, FontIntegers, Glue, SourceProvider};
use crate::{
resources::{ResourceKind, ResourceVersion},
native_font::{LetterspaceProgram, NativeFont},
resources::{LoadedResource, ResourceKind, ResourceVersion},
tfm::{FontSize, TfmMetrics},
};
use sha2::{Digest, Sha256};
@@ -260,18 +261,82 @@ impl FontCatalog {
}
}
}
self.check_font_capacity()?;
let (loaded, metrics) = Self::read_tfm(files, &format!("{area}{name}.tfm"), from, size)?;
self.insert_font((name, area), loaded, metrics, selector, defaults, None)
}
pub(super) fn letterspace(
&mut self,
files: &mut impl SourceProvider,
from: &str,
base: FontId,
amount: i32,
no_ligatures: bool,
selector: CommandName,
defaults: FontIntegers,
) -> Result<(FontId, bool), String> {
self.check_font_capacity()?;
let font = self.font(base)?;
let base_font = self.glyph_font(base)?.clone();
let base_quad = i64::from(font.quad());
let size = FontSize::At(font.size_sp());
let (loaded, mut metrics) =
Self::read_tfm(files, &format!("{}.tfm", font.name), from, size)?;
let mut quad = metrics.param(5);
if quad == 0 && base_quad > 0 {
quad = base_quad;
}
let width_delta = round_ratio(quad, amount, 1000);
metrics.set_letter_spacing(width_delta, quad, no_ligatures);
let shift = round_ratio(base_quad, amount, 2000);
let right = TfmMetrics::encode_vf_move(shift, font.size_sp())?;
let sign = if amount > 0 { "+" } else { "" };
let name = format!("{}{sign}{amount}ls", font.name);
let font = self.insert_font(
(&name, ""),
loaded,
metrics,
selector,
defaults,
Some(LetterspaceProgram { base: base_font, right }),
)?;
Ok((font, quad == 0))
}
fn check_font_capacity(&self) -> Result<(), String> {
if self.fonts.len() >= self.limits.fonts as usize {
return Err("native font capacity exceeded".into());
}
let loaded = files.resource(ResourceKind::Tfm, &format!("{area}{name}.tfm"), from)?;
Ok(())
}
fn read_tfm(
files: &mut impl SourceProvider,
name: &str,
from: &str,
size: FontSize,
) -> Result<(LoadedResource, TfmMetrics), String> {
let loaded = files.resource(ResourceKind::Tfm, name, from)?;
if loaded.version.bytes != loaded.data.len() as u64
|| loaded.version.sha256 != format!("{:x}", Sha256::digest(&loaded.data))
{
return Err("font resource version does not match its actual TFM bytes".into());
}
// Do not parse at design size first: zero entries are validated after
// scaling, and a file can be legal only at the requested size.
// Zero entries are validated after scaling at the requested size.
let metrics = TfmMetrics::parse_at(&loaded.data, size)?;
Ok((loaded, metrics))
}
fn insert_font(
&mut self,
(name, area): (&str, &str),
loaded: LoadedResource,
metrics: TfmMetrics,
selector: CommandName,
defaults: FontIntegers,
letter_spacing: Option<LetterspaceProgram>,
) -> Result<FontId, String> {
let count = metrics.parameter_count();
if count > self.limits.parameter_words - self.parameter_words {
return Err("native font parameter capacity exceeded".into());
@@ -293,12 +358,13 @@ impl FontCatalog {
}
};
let id = FontId(self.fonts.len() as u32);
let glyph_font = Arc::new(crate::native_font::NativeFont {
let glyph_font = Arc::new(NativeFont {
id,
name: name.into(),
metrics: Arc::new(metrics),
resource: self.resources[resource].clone(),
expansion: 0,
letter_spacing,
});
self.fonts.push(FontInstance {
name: name.into(),
@@ -437,3 +503,8 @@ impl FontCatalog {
}))
}
}
fn round_ratio(value: i64, numerator: i32, denominator: i64) -> i64 {
let product = value * i64::from(numerator);
product.signum() * ((product.abs() + denominator / 2) / denominator)
}
@@ -8,9 +8,9 @@ use std::{
sync::{Arc, Mutex, OnceLock, Weak},
};
const SCHEMA: u32 = 48;
const COMPATIBLE_SCHEMAS: [u32; 17] = [
27, 28, 31, 32, 33, 34, 35, 36, 37, 38, 39, 43, 44, 45, 46, 47, SCHEMA,
const SCHEMA: u32 = 49;
const COMPATIBLE_SCHEMAS: [u32; 18] = [
27, 28, 31, 32, 33, 34, 35, 36, 37, 38, 39, 43, 44, 45, 46, 47, 48, SCHEMA,
];
const ENGINE: &str = concat!("texrra-native/", env!("CARGO_PKG_VERSION"));
@@ -203,6 +203,7 @@ pub enum Primitive {
Setlanguage,
Font,
Fontname,
Letterspacefont,
Fontdimen,
Fontcharwd,
Fontcharht,
@@ -797,6 +798,7 @@ impl Default for State {
("efcode", Efcode),
("pdffontexpand", Pdffontexpand),
("fontname", Fontname),
("letterspacefont", Letterspacefont),
("fontdimen", Fontdimen),
("skewchar", Skewchar),
("mathchar", Mathchar),
+10
View File
@@ -67,6 +67,15 @@ pub struct NativeFont {
/// outline program are the original font at the original point size.
#[serde(default, skip_serializing_if = "unexpanded")]
pub expansion: i32,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub letter_spacing: Option<LetterspaceProgram>,
}
/// Virtual character packets use the selected font and an encoded right move.
#[derive(Clone, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
pub struct LetterspaceProgram {
pub base: Arc<NativeFont>,
pub right: i32,
}
pub(crate) fn unexpanded(amount: &i32) -> bool {
*amount == 0
@@ -91,6 +100,7 @@ impl NativeFont {
|| (self.id == other.id
&& self.name == other.name
&& (Arc::ptr_eq(&self.metrics, &other.metrics) || self.metrics == other.metrics)
&& self.letter_spacing == other.letter_spacing
&& self.resource.version == other.resource.version
&& (Arc::ptr_eq(&self.resource.data, &other.resource.data)
|| self.resource.data == other.resource.data))
@@ -45,6 +45,33 @@ fn offset(point: i64, delta: i64) -> Result<i64, String> {
}
impl<'a, F: SourceProvider> Expansion<'a, F> {
fn is_virtual(&mut self, font: &Arc<NativeFont>) -> Result<bool, String> {
Ok(font.letter_spacing.is_some() || self.lookup(font)?.is_some())
}
fn with_expansion(&mut self, font: Arc<NativeFont>, ratio: i32) -> Arc<NativeFont> {
if ratio == 0 {
return font;
}
self.expanded_fonts
.entry((font.id, ratio))
.or_insert_with(|| {
Arc::new(NativeFont {
expansion: ratio,
..font.as_ref().clone()
})
})
.clone()
}
fn count_commands(&mut self, count: usize) -> Result<(), String> {
self.commands += count;
if self.commands > 5_000_000 {
return Err("VF expansion command limit exceeded".into());
}
Ok(())
}
fn lookup(&mut self, font: &Arc<NativeFont>) -> Result<Option<Arc<LoadedVirtual>>, String> {
if let Some((old, vf)) = self.virtuals.get(&font.id) {
if !Arc::ptr_eq(old, font) && !old.same_base(font) {
@@ -107,6 +134,7 @@ impl<'a, F: SourceProvider> Expansion<'a, F> {
name: local.name.clone(),
metrics: Arc::new(metrics),
expansion: 0,
letter_spacing: None,
resource: FontResource {
version: file.version,
data: Arc::new(file.data),
@@ -122,6 +150,31 @@ impl<'a, F: SourceProvider> Expansion<'a, F> {
output: &mut Vec<DisplayItem>,
depth: usize,
) -> Result<(), String> {
if let Some(program) = &glyph.font.letter_spacing {
if depth >= 16 {
return Err("VF recursion limit exceeded".into());
}
self.count_commands(3)?;
let movement = TfmMetrics::scale_fix_word(program.right, glyph.size)?;
let font = self.with_expansion(program.base.clone(), glyph.font.expansion);
if !font.has_slot(glyph.slot) {
return Err(format!(
"VF local font {} has no TFM slot {}",
font.name, glyph.slot
));
}
return self.expand(
Glyph {
x: offset(glyph.x, movement)?,
y: glyph.y,
size: font.size_sp(),
font,
slot: glyph.slot,
},
output,
depth + 1,
);
}
let Some(vf) = self.lookup(&glyph.font)? else {
output.push(DisplayItem::NativeGlyph {
x: glyph.x,
@@ -151,10 +204,7 @@ impl<'a, F: SourceProvider> Expansion<'a, F> {
let mut stack = Vec::new();
let mut local = vf.program.default_font;
for command in &packet.commands {
self.commands += 1;
if self.commands > 5_000_000 {
return Err("VF expansion command limit exceeded".into());
}
self.count_commands(1)?;
match *command {
Command::Character { slot, advance } => {
let id = local.ok_or("VF character has no selected local font")?;
@@ -166,17 +216,7 @@ impl<'a, F: SourceProvider> Expansion<'a, F> {
font.name
));
}
let font = if glyph.font.expansion == 0 {
font
} else {
self.expanded_fonts
.entry((font.id, glyph.font.expansion))
.or_insert_with(|| Arc::new(NativeFont {
expansion: glyph.font.expansion,
..font.as_ref().clone()
}))
.clone()
};
let font = self.with_expansion(font, glyph.font.expansion);
let width = font.advance(slot);
let size = font.size_sp();
self.expand(
@@ -277,7 +317,7 @@ pub(super) fn expand_pages(
for item in &page.items {
if let DisplayItem::NativeGlyph { font, .. } = item {
expansion.last_id = expansion.last_id.max(font.id.index());
uses_vf |= expansion.lookup(font)?.is_some();
uses_vf |= expansion.is_virtual(font)?;
}
}
}
@@ -308,7 +348,7 @@ pub(super) fn expand_pages(
slot,
..
} = item
&& expansion.lookup(font)?.is_some()
&& expansion.is_virtual(font)?
{
expansion.expand(
Glyph {
+58 -3
View File
@@ -63,6 +63,9 @@ pub struct TfmMetrics {
ec: u16,
char_info: Vec<CharInfo>,
widths: Vec<i32>,
// The virtual font changes the already scaled widths by a uniform amount.
#[serde(default, skip_serializing_if = "Option::is_none")]
letter_spacing: Option<LetterspaceMetrics>,
heights: Vec<i32>,
depths: Vec<i32>,
italics: Vec<i32>,
@@ -73,6 +76,12 @@ pub struct TfmMetrics {
boundary_char: Option<u8>,
boundary_label: Option<usize>,
}
#[derive(Clone, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
struct LetterspaceMetrics {
width_delta: i64,
quad: i64,
}
impl TfmMetrics {
pub fn parse(bytes: &[u8]) -> Result<Self, String> {
Self::parse_at(bytes, FontSize::Design)
@@ -186,6 +195,7 @@ impl TfmMetrics {
ec: ec as u16,
char_info,
widths,
letter_spacing: None,
heights,
depths,
italics,
@@ -304,6 +314,11 @@ impl TfmMetrics {
if a != 0 && a != 255 {
return Err("TFM metric must be between -16 and 16".into());
}
let (z, alpha, beta) = Self::fix_word_scale(size);
let n = ((i64::from(d) * z / 256 + i64::from(c) * z) / 256 + i64::from(b) * z) / beta;
Ok(if a == 0 { n } else { n - alpha })
}
fn fix_word_scale(size: i64) -> (i64, i64, i64) {
let (mut z, mut alpha) = (size, 16i64);
while z >= 1 << 23 {
z /= 2;
@@ -311,9 +326,25 @@ impl TfmMetrics {
}
let beta = 256 / alpha;
let alpha = alpha * z;
let n = ((i64::from(d) * z / 256 + i64::from(c) * z) / 256 + i64::from(b) * z) / beta;
Ok(if a == 0 { n } else { n - alpha })
(z, alpha, beta)
}
/// Match the VF packet encoder before decoding with TeX's fixed-point scale.
pub(crate) fn encode_vf_move(movement: i64, size: i64) -> Result<i32, String> {
FontSize::At(size).validate()?;
let (z, alpha, beta) = Self::fix_word_scale(size);
let (prefix, magnitude) = if movement < 0 {
(0xff00_0000, alpha + movement)
} else {
(0, movement)
};
let fraction = magnitude * beta * 65_536 / z;
if !(0..1 << 24).contains(&fraction) {
return Err("letterspaced font movement is outside VF fixed-point range".into());
}
Ok((prefix | fraction as u32) as i32)
}
pub fn at_size(&self, requested: FontSize) -> Result<Self, String> {
let mut font = self.clone();
font.size = Self::resolve_size(self.design_size, requested)?;
@@ -355,7 +386,28 @@ impl TfmMetrics {
})
}
pub fn width(&self, c: char) -> i64 {
self.dimension(c, &self.widths, |i| i.width_index)
let Some(info) = self.char_info(c).filter(|info| info.width_index != 0) else {
return 0;
};
self.scaled(self.widths[usize::from(info.width_index)])
.expect("validated TFM metric")
+ self.letter_spacing.as_ref().map_or(0, |metrics| metrics.width_delta)
}
pub(crate) fn set_letter_spacing(
&mut self,
width_delta: i64,
quad: i64,
no_ligatures: bool,
) {
self.letter_spacing = Some(LetterspaceMetrics { width_delta, quad });
if no_ligatures {
for info in &mut self.char_info {
if info.width_index != 0 && info.tag == 1 {
info.tag = 0;
}
}
}
}
pub fn height(&self, c: char) -> i64 {
self.dimension(c, &self.heights, |i| i.height_index)
@@ -371,6 +423,9 @@ impl TfmMetrics {
}
/// Zero-based fontdimen. Slant is 16.16 and independent of the font size.
pub fn param(&self, index: usize) -> i64 {
if index == 5 && let Some(metrics) = &self.letter_spacing {
return metrics.quad;
}
self.params.get(index).map_or(0, |raw| {
if index == 0 {
i64::from(*raw).div_euclid(16)
@@ -184,6 +184,56 @@ fn actual_times_virtual_small_caps_use_scaled_local_type1_and_source_origins() {
render(&root, &revision.execution, &pages);
}
#[test]
fn letterspacing_uses_fresh_widths_and_the_selected_fonts_live_quad() {
let (root, mut host) = fixture("letterspacing");
let bytes = br"\catcode123=1 \catcode125=2
\pdfoutput=1 \pdfcompresslevel=0 \pdfobjcompresslevel=0
\pdfpagewidth=90pt \pdfpageheight=65pt \pdfhorigin=5pt \pdfvorigin=5pt
\font\base=ptmrc7t at 12pt \fontdimen6\base=20pt
\letterspacefont\spaced=\base 100
\letterspacefont\tight=\base -137 nolig
\message{[\number\fontdimen6\base,\number\fontdimen6\spaced,\number\fontcharwd\spaced 65,\number\fontcharwd\tight 65]}
\shipout\vbox{\hbox{\spaced aB AV fi}\kern5pt\hbox{\tight aB AV fi}}\end";
reference(&root, bytes);
let revision = execute(&root, bytes, &mut host);
assert!(revision.execution.events.iter().any(|event| {
matches!(event, Event::Message { text, .. } if text == "[1310720,786432,685766,499382]")
}));
let mut pages = revision.execution.shipout_display_lists().unwrap();
for (name, has_kern) in [("ptmrc7t+100ls", true), ("ptmrc7t-137ls", false)] {
let font = pages[0]
.items
.iter()
.find_map(|item| match item {
DisplayItem::NativeGlyph { font, .. } if font.name == name => Some(font),
_ => None,
})
.unwrap();
assert_eq!(
font.metrics().lig_kern(Some(b'A'), b'V').is_some(),
has_kern
);
}
resolve_native_fonts(&mut pages, &mut host).unwrap();
let map = SourceMap::from_revision(&revision, &pages).unwrap();
assert!(
map.pages[0]
.entries
.iter()
.any(|entry| { entry.source.derivations.contains(&Derivation::FontProgram) })
);
assert!(
host.0
.trace()
.reads
.iter()
.any(|r| r.path.ends_with("utmr8a.pfb"))
);
render(&root, &revision.execution, &pages);
}
fn tfm_width(tfm: &[u8], slot: u8) -> [u8; 4] {
let field = |index: usize| {
u16::from_be_bytes(tfm[2 * index..2 * index + 2].try_into().unwrap()) as usize
+29
View File
@@ -1471,6 +1471,35 @@ pdfTeX 兼容 profile 仍为1.40.22。下一项按原始 TFM 与虚拟字体位
`\letterspacefont`,再用未修改的 LaTeX 后端核对版本分支。
[TeX Live showstream.ch](https://github.com/TeX-Live/texlive-source/blob/trunk/texk/web2c/showstream.ch)
### 原生字距字体
`\letterspacefont` 以原字号重新读取实际 TFM。字宽按新 TFM 的 quad
调整,字形使用选定基础字体的实时 quad 编码 VF 位移。新 quad 为零
且基础 quad 为正时继承后者,两者均为零时发出警告。普通空格参数
来自重新读取的 TFM。nolig 清除字符的连字与字偶程序入口,保留边界
程序。真实基础 VF 可以继续递归解析,其 Type 1 轮廓与来源映射沿用
原生虚拟字体设备路径。
四份独立 pdfTeX INITEX 对照覆盖常规尺寸、11.001pt、Times 虚拟字体及
受控的零 quad。四份诊断列表、字宽、空格宽度和 144 dpi 栅格均完全
一致,PDF 词框最大差为 0bp。15项字体、格式与虚拟字体回归通过。
schema49 的字距字体转储后,与直接编译的盒宽和栅格一致。schema48
旧格式仍可加载并生成 PDF。
只把第二页使用的字距从100改为137,编辑器复用894步,只替换第二页。
两版 A 字宽分别为557057sp、581305sp,更新版的 PDF、SVG、实际宽度
写出文件和归一化来源映射均与独立零复用全量一致。证据目录
target/p2-letter-space-native,参考回执 SHA-256
dc5ebd316a29ffcca6cbfec143001d0875abd8e737c55642ba93e4e42222ff41,
续编回执 SHA-256
8ae6deb55a501eebd7aba71727d86718f643f4cda8b4ed37c5a388854d926de9。
pdfTeX 兼容 profile 保持1.40.22。按 1.40.23 至 1.40.24 发布差异继续
处理自动字偶与边缘悬挂、警告起行及高级诊断列表,再验证未修改的
LaTeX 后端结构目的地分支。
[TeX Live 实现](https://github.com/TeX-Live/texlive-source/blob/trunk/texk/web2c/pdftexdir/pdftex.web)
与 [pdfTeX 发布记录](https://github.com/TeX-Live/texlive-source/blob/trunk/texk/web2c/pdftexdir/NEWS)。
### PDF 字面中的矩阵与来源映射
来源映射与 PDF 写入共用设备原点的取整。实际字面中的 `q`、`Q` 和