Substitute CMR10 ligatures in route-D paragraphs

This commit is contained in:
gloamxun committed 2026-10-20 21:04:24 +08:00
1 parent 641fc1c14b
commit ac63a3db92
4 files changed
+84 -10

No files matched your search

+4
View File
@@ -38,6 +38,10 @@ impl Cmr10Metrics {
metrics().italic(character)
}
pub fn ligature(&self, left: char, right: char) -> Option<(char, char)> {
metrics().ligature(left, right)
}
pub fn kern(&self, left: char, right: char) -> i64 {
metrics().kern(left, right)
}
+40 -3
View File
@@ -347,7 +347,24 @@ pub fn text_items_with_font(
} else {
std::collections::HashSet::new()
};
for (character_index, character) in word.chars().enumerate() {
let original: Vec<char> = word.chars().collect();
let mut resolved: Vec<(char, char)> = Vec::new();
let mut cursor = 0;
while cursor < original.len() {
if cursor + 1 < original.len() {
if let Some((unicode, slot)) = font.ligature(original[cursor], original[cursor + 1])
{
resolved.push((unicode, slot));
cursor += 2;
continue;
}
}
let character = original[cursor];
resolved.push((character, character));
cursor += 1;
}
let ligated = resolved.len() != original.len();
for (character_index, (character, slot)) in resolved.into_iter().enumerate() {
if let (Some(index), Some(left)) = (previous_box, previous_character) {
let kern = font.kern(left, character);
if kern != 0 {
@@ -359,13 +376,17 @@ pub fn text_items_with_font(
previous_box = Some(items.len());
previous_character = Some(character);
items.push(HorizontalItem::Box(HorizontalBox {
width: font.width(character),
width: font.width(slot),
height: style.line_height,
depth: 0,
character: Some(character),
}));
let boundary = character_index + 1;
if points.contains(&boundary) && boundary >= 2 && boundary + 2 <= word.chars().count() {
if !ligated
&& points.contains(&boundary)
&& boundary >= 2
&& boundary + 2 <= word.chars().count()
{
items.push(HorizontalItem::Discretionary {
pre_break_width: font.width('-'),
no_break_width: 0,
@@ -508,6 +529,22 @@ mod tests {
assert!(paragraph.lines.len() > 1);
}
#[test]
fn fi_ligature_reduces_character_boxes() {
let font = crate::cmr10::Cmr10Metrics::new();
let style = ParagraphStyle::default();
let items = text_items_with_font("fi", &style, &font);
let boxes: Vec<_> = items
.iter()
.filter_map(|item| match item {
HorizontalItem::Box(box_) => Some(box_),
_ => None,
})
.collect();
assert_eq!(boxes.len(), 1);
assert_eq!(boxes[0].character, Some('\u{FB01}'));
}
#[test]
fn cmr10_font_drives_character_widths() {
let font = crate::cmr10::Cmr10Metrics::new();
+37 -4
View File
@@ -35,6 +35,7 @@ pub struct TfmMetrics {
italics: Vec<i32>,
params: Vec<i32>,
kerns: std::collections::HashMap<(char, char), i64>,
ligatures: std::collections::HashMap<(char, char), (char, char)>,
}
impl TfmMetrics {
@@ -136,7 +137,7 @@ impl TfmMetrics {
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(
let (kerns, ligatures) = parse_kerns(
bytes,
lig_kern_offset,
usize::from(nl),
@@ -157,6 +158,7 @@ impl TfmMetrics {
italics,
params,
kerns,
ligatures,
})
}
@@ -178,6 +180,11 @@ impl TfmMetrics {
self.kerns.get(&(left, right)).copied().unwrap_or(0)
}
/// Ligature replacement for a pair, as (Unicode display char, TFM slot char).
pub fn ligature(&self, left: char, right: char) -> Option<(char, char)> {
self.ligatures.get(&(left, right)).copied()
}
fn index_for(&self, character: char) -> Option<usize> {
let code = u32::from(character);
if code < u32::from(self.bc) || code > u32::from(self.ec) {
@@ -258,8 +265,12 @@ fn parse_kerns(
char_info: &[CharInfo],
bc: u32,
design_size_pt: f64,
) -> std::collections::HashMap<(char, char), i64> {
) -> (
std::collections::HashMap<(char, char), i64>,
std::collections::HashMap<(char, char), (char, char)>,
) {
let mut kerns = std::collections::HashMap::new();
let mut ligatures = std::collections::HashMap::new();
for (index, info) in char_info.iter().enumerate() {
if info.tag != 1 {
continue;
@@ -272,7 +283,21 @@ fn parse_kerns(
break;
};
let (skip, next, op, remainder) = (entry[0], entry[1], entry[2], entry[3]);
if op >= 128 {
if op < 128 {
let slot_char = char::from_u32(bc + u32::from(remainder)).unwrap_or('?');
let unicode = match remainder {
11 => Some('\u{FB00}'),
12 => Some('\u{FB01}'),
13 => Some('\u{FB02}'),
14 => Some('\u{FB03}'),
15 => Some('\u{FB04}'),
_ => None,
};
if let Some(unicode) = unicode {
let right = char::from_u32(u32::from(next)).unwrap_or('?');
ligatures.insert((left, right), (unicode, slot_char));
}
} else {
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('?');
@@ -286,7 +311,7 @@ fn parse_kerns(
cursor += usize::from(skip) + 1;
}
}
kerns
(kerns, ligatures)
}
#[cfg(test)]
@@ -308,6 +333,14 @@ mod tests {
assert!(font.depth('g') > 0);
}
#[test]
fn cmr10_has_an_fi_ligature() {
let font = cmr10();
let (unicode, slot) = font.ligature('f', 'i').expect("fi ligature");
assert_eq!(unicode, '\u{FB01}');
assert_eq!(slot, char::from_u32(u32::from(font.bc) + 12).unwrap());
}
#[test]
fn missing_characters_have_zero_metrics() {
let font = cmr10();
+3 -3
View File
@@ -229,7 +229,7 @@ for a later overlaid slash.
| M2 vertical/page builder | partial | vsize, topskip, insertions, marks, Rust output hook, top/bottom floats, float-page/text fractions, rules, vskip, penalties; interpreted `\output` 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/kern pairs; all five text faces embed Liberation Serif/Mono as Type0 CID fonts with Identity-H, ToUnicode and `/W` glyph widths; no Base-14 dependency; SVG carries family/weight/style |
| M5 NFSS/TFM | partial | runtime `cmr10.tfm` widths/heights/depths/kern pairs and ff/fi/fl/ffi/ffl ligatures; all five text faces embed Liberation Serif/Mono as Type0 CID fonts with Identity-H, ToUnicode and `/W` glyph widths; no Base-14 dependency; 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 five embedded Liberation Type0/CID faces (Identity-H + ToUnicode + `/W` arrays), filled rectangles, diagonal rules, raw-RGB `/XObject` images, `/Annots` URI links and arbitrary `/special` operators. Ligature substitution, italic correction and full NFSS family switching remain open.
M5 (partial): display-list text carries `FontFace::{Roman,Bold,Italic,BoldItalic,Mono}`. Roman/Bold/Italic/BoldItalic/Mono text are painted with embedded Liberation Type0/CID fonts, each with a ToUnicode CMap and `/W` width array. `cmr10.tfm` is parsed at runtime for widths, heights/depths and kern pairs; real ligature substitutions and true NFSS family switching remain open.
M5 (partial): display-list text carries `FontFace::{Roman,Bold,Italic,BoldItalic,Mono}`. Roman/Bold/Italic/BoldItalic/Mono text are painted with embedded Liberation Type0/CID fonts, each with a ToUnicode CMap and `/W` width array. `cmr10.tfm` is parsed at runtime for widths, heights/depths, kern pairs and ff/fi/fl/ffi/ffl ligatures; true NFSS family switching and italic correction 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, glyph heights/depths and kern pairs. all five text faces embed Liberation Serif/Mono as Type0/Identity-H with `/W` widths; ligature substitution and full NFSS family switching are not implemented.
- **M5**: `cmr10.tfm` is parsed at runtime with widths, glyph heights/depths and kern pairs. all five text faces embed Liberation Serif/Mono as Type0/Identity-H with `/W` widths; ff/fi/fl/ffi/ffl ligatures come from TFM, but full NFSS family switching and italic correction 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