Apply CMR10 kern pairs in route-D paragraphs

This commit is contained in:
gloamxun committed 2026-10-20 20:52:54 +08:00
1 parent a09398811f
commit 867bace1c9
4 files changed
+99 -5

No files matched your search

+4
View File
@@ -38,6 +38,10 @@ impl Cmr10Metrics {
metrics().italic(character)
}
pub fn kern(&self, left: char, right: char) -> i64 {
metrics().kern(left, right)
}
pub fn space(&self) -> i64 {
metrics().space()
}
+31
View File
@@ -327,6 +327,8 @@ pub fn text_items_with_font(
let hyphenator = hyphenate::Hyphenator::plain_tex_en_us();
let caser = hyphenate::AsciiLowerCaser::default();
let words: Vec<&str> = text.split_whitespace().collect();
let mut previous_box: Option<usize> = None;
let mut previous_character: Option<char> = None;
for (word_index, word) in words.iter().enumerate() {
if word_index > 0 {
items.push(HorizontalItem::Glue {
@@ -346,6 +348,16 @@ pub fn text_items_with_font(
std::collections::HashSet::new()
};
for (character_index, character) in word.chars().enumerate() {
if let (Some(index), Some(left)) = (previous_box, previous_character) {
let kern = font.kern(left, character);
if kern != 0 {
if let Some(HorizontalItem::Box(previous)) = items.get_mut(index) {
previous.width += kern;
}
}
}
previous_box = Some(items.len());
previous_character = Some(character);
items.push(HorizontalItem::Box(HorizontalBox {
width: font.width(character),
height: style.line_height,
@@ -512,6 +524,25 @@ mod tests {
assert!(paragraph.height > 0);
}
#[test]
fn cmr10_kerning_reduces_adjacent_character_width() {
let font = crate::cmr10::Cmr10Metrics::new();
assert!(font.kern('A', 'V') < 0);
let style = ParagraphStyle::default();
let items = text_items_with_font("AV", &style, &font);
let total: i64 = items
.iter()
.map(|item| match item {
HorizontalItem::Box(box_) => box_.width,
HorizontalItem::Glue { width, .. } => *width,
_ => 0,
})
.sum();
assert_eq!(
total,
font.width('A') + font.width('V') + font.kern('A', 'V')
);
}
#[test]
fn left_skip_narrows_the_measure_and_offsets_the_paragraph() {
let narrow = ParagraphStyle {
+61 -2
View File
@@ -19,6 +19,8 @@ pub struct CharInfo {
pub depth_index: u8,
pub italic_index: u8,
pub tag: u8,
/// Start offset into the lig/kern instruction table (tag 1).
pub lig_kern_start: usize,
}
#[derive(Clone, Debug)]
@@ -32,6 +34,7 @@ pub struct TfmMetrics {
depths: Vec<i32>,
italics: Vec<i32>,
params: Vec<i32>,
kerns: std::collections::HashMap<(char, char), i64>,
}
impl TfmMetrics {
@@ -98,8 +101,9 @@ impl TfmMetrics {
width_index: bytes[offset],
height_index: bytes[offset + 1] >> 4,
depth_index: bytes[offset + 1] & 0x0f,
italic_index: bytes[offset + 2],
tag: bytes[offset + 3],
italic_index: bytes[offset + 2] >> 2,
tag: bytes[offset + 2] & 0x03,
lig_kern_start: usize::from(bytes[offset + 3]),
});
}
@@ -131,6 +135,16 @@ impl TfmMetrics {
let depths = table(depth_offset, nd, "depth")?;
let italics = table(italic_offset, ni, "italic")?;
let params = table(params_offset, np, "parameter")?;
let kern_table = table(kern_offset, nk, "kern")?;
let kerns = parse_kerns(
bytes,
lig_kern_offset,
usize::from(nl),
&kern_table,
&char_info,
u32::from(bc),
design_size_pt,
);
Ok(Self {
design_size_pt,
@@ -142,6 +156,7 @@ impl TfmMetrics {
depths,
italics,
params,
kerns,
})
}
@@ -158,6 +173,11 @@ impl TfmMetrics {
(f64::from(raw) * self.design_size_pt / 16.0).round() as i64
}
/// Kerning between two characters, in scaled points.
pub fn kern(&self, left: char, right: char) -> i64 {
self.kerns.get(&(left, right)).copied().unwrap_or(0)
}
fn index_for(&self, character: char) -> Option<usize> {
let code = u32::from(character);
if code < u32::from(self.bc) || code > u32::from(self.ec) {
@@ -230,6 +250,45 @@ impl TfmMetrics {
}
}
fn parse_kerns(
bytes: &[u8],
lig_kern_offset: usize,
instruction_count: usize,
kern_table: &[i32],
char_info: &[CharInfo],
bc: u32,
design_size_pt: f64,
) -> std::collections::HashMap<(char, char), i64> {
let mut kerns = std::collections::HashMap::new();
for (index, info) in char_info.iter().enumerate() {
if info.tag != 1 {
continue;
}
let left = char::from_u32(bc + index as u32).unwrap_or('?');
let mut cursor = info.lig_kern_start;
while cursor < instruction_count {
let offset = lig_kern_offset + cursor * 4;
let Some(entry) = bytes.get(offset..offset + 4) else {
break;
};
let (skip, next, op, remainder) = (entry[0], entry[1], entry[2], entry[3]);
if op >= 128 {
let kern_index = usize::from(op - 128) * 256 + usize::from(remainder);
if let Some(raw) = kern_table.get(kern_index) {
let right = char::from_u32(u32::from(next)).unwrap_or('?');
let value = (f64::from(*raw) * design_size_pt / 16.0).round() as i64;
kerns.insert((left, right), value);
}
}
if skip >= 128 {
break;
}
cursor += usize::from(skip) + 1;
}
}
kerns
}
#[cfg(test)]
mod tests {
use super::*;
+3 -3
View File
@@ -229,7 +229,7 @@ for a later overlaid slash.
| M2 vertical/page builder | partial | vsize, topskip, insertions, marks, output hook, top/bottom floats, rules, vskip, penalties; interpreted `\output` and float pages absent |
| M3 halign | partial | natural columns, spans, omit, hline rows, templates, noalign skip, rules; no PDF painter |
| M4 math | partial | atoms, scripts, fractions, roots, delimiters, accents, operators, classes, braces, boxed, negated; no math painter/shrink wrapping |
| M5 NFSS/TFM | partial | runtime `cmr10.tfm` widths/heights/depths; Roman text embeds Liberation Serif as a Type0 CID font with Identity-H and ToUnicode; Bold/Italic/Mono still use Base-14 faces; SVG carries family/weight/style |
| M5 NFSS/TFM | partial | runtime `cmr10.tfm` widths/heights/depths/kern pairs; Roman text embeds Liberation Serif as a Type0 CID font with Identity-H and ToUnicode; Bold/Italic/Mono still use Base-14 faces; SVG carries family/weight/style |
| M6 specials/XObject | partial | raw specials, RGB image XObjects, URI link annotations; class/package execution absent |
| M7 incremental integration | partial | edit replay + page hashes, not wired into v1 preview |
@@ -251,7 +251,7 @@ M3 painter: `Page::display_list()` and `Halign::display_list()` produce absolute
PDF writer: `crates/texrra-tex-core/src/pdf.rs` writes multi-page PDF 1.4 with an embedded Liberation Serif Type0/CID font (Identity-H + ToUnicode) for Roman text, Base-14 faces for the other styles, filled rectangles, diagonal rules, raw-RGB `/XObject` images, `/Annots` URI links and arbitrary `/special` operators. Real NFSS faces and subsets for bold/italic remain open.
M5 (partial): display-list text carries `FontFace::{Roman,Bold,Italic,BoldItalic,Mono}`. Roman text is painted with an embedded Liberation Serif Type0/CID font and a ToUnicode CMap; the other faces still map to Base-14 Times/Courier. `cmr10.tfm` is parsed at runtime for widths and heights/depths; ligature/kern tables and true NFSS family switching remain open.
M5 (partial): display-list text carries `FontFace::{Roman,Bold,Italic,BoldItalic,Mono}`. Roman text is painted with an embedded Liberation Serif Type0/CID font and a ToUnicode CMap; the other faces still map to Base-14 Times/Courier. `cmr10.tfm` is parsed at runtime for widths, heights/depths and kern pairs; real ligature substitutions and true NFSS family switching remain open.
M6 (partial): `DisplayItem::Image` becomes a PDF XObject; `DisplayItem::Link` becomes `/Annots /Subtype /Link /URI`; `DisplayItem::Special` injects raw content-stream operators. SVG previews show images as grey rectangles and specials as comments.
@@ -288,7 +288,7 @@ deliberately open rather than approximated:
- **M1**: TeX tolerance/demerits are still fitted to a few fixtures; multi-width
pdfTeX line breaks and full hyphenation demerits are not reproduced generally.
- **M5**: `cmr10.tfm` is parsed at runtime with widths and glyph heights/depths. Roman text embeds Liberation Serif as Type0/Identity-H, but bold/italic/mono still use Base-14 faces; ligature/kern tables and full NFSS family switching are not implemented.
- **M5**: `cmr10.tfm` is parsed at runtime with widths, glyph heights/depths and kern pairs. Roman text embeds Liberation Serif as Type0/Identity-H, but bold/italic/mono still use Base-14 faces; ligature substitution and full NFSS family switching are not implemented.
- **M6**: `\output`, `\insert`, mark/float output policies, class-file execution and
math limit policies are only partially modeled.
- **M7**: the route-D engine is not yet wired into the v1 live preview. The server