Implement XeTeX OpenType horizontal scaling across layout and preview

This commit is contained in:
gloamxun committed 2026-11-26 10:16:20 +08:00
1 parent cc0246016d
commit 330ecdd03c
7 files changed
+109 -26

No files matched your search

+50 -15
View File
@@ -36,6 +36,8 @@ pub(crate) struct Request {
// bits so it can also be part of the font's deterministic identity.
#[serde(default, skip_serializing_if = "Option::is_none")]
letterspace: Option<u32>,
#[serde(default, skip_serializing_if = "Option::is_none")]
extend: Option<u32>,
}
fn read_decimal_prefix(value: &str) -> f64 {
@@ -92,6 +94,7 @@ impl Request {
language: None,
mapping: None,
letterspace: None,
extend: None,
};
for feature in features
.split([';', ','])
@@ -117,6 +120,12 @@ impl Request {
return Err("OpenType letterspace percentage exceeds the supported range".into());
}
request.letterspace = (value != 0.).then(|| value.to_bits());
} else if let Some(value) = feature.strip_prefix("extend=") {
let value = read_decimal_prefix(value) as f32;
if !value.is_finite() || i32::try_from(points_to_sp(value)).is_err() {
return Err("OpenType extend exceeds the device fixed-point range".into());
}
request.extend = (value != 1.).then(|| value.to_bits());
} else {
feature
.parse::<Feature>()
@@ -133,6 +142,10 @@ impl Request {
})
}
fn horizontal_scale(&self) -> f32 {
self.extend.map_or(1., f32::from_bits)
}
pub(crate) fn resource_names(&self) -> Vec<(ResourceKind, String)> {
match Path::new(&self.file)
.extension()
@@ -271,7 +284,8 @@ impl OpenTypeFont {
|value| scale(i64::from(value)),
)
};
let slant = (-f64::from(face.italic_angle()).to_radians().tan() * 65536.).round() as i32;
let slant = (-f64::from(face.italic_angle()).to_radians().tan() * 65536. + 0.5) as i64;
let slant = (slant as f64 * f64::from(request.horizontal_scale()) + 0.5) as i32;
let mut params = vec![
slant,
0,
@@ -336,13 +350,20 @@ impl OpenTypeFont {
self.request.letter_space(self.size) as i64
}
pub(crate) fn paint_horizontal_scale(&self) -> f64 {
// XDV records the factor in 16.16 and the PDF device emits five decimals.
let fixed = points_to_sp(self.request.horizontal_scale());
(fixed as f64 * 100_000. / 65536.).round() / 100_000.
}
pub(crate) fn italic_correction(&self, glyph: u16) -> Result<i64, String> {
let face = self.face()?;
let glyph = GlyphId(glyph);
let [_, _, right, _] = glyph_control_bounds(&face, glyph);
let advance = f32::from(face.glyph_hor_advance(glyph).unwrap_or(0));
let points = |units| units_to_points(units, self.size, face.units_per_em());
Ok(points_to_sp((points(right) - points(advance)).max(0.)) + self.letter_space())
let overhang = (points(right) - points(advance)).max(0.);
Ok(points_to_sp(overhang * self.request.horizontal_scale()) + self.letter_space())
}
pub(crate) fn glyph_metrics(
@@ -367,9 +388,11 @@ impl OpenTypeFont {
for zone in [0, font_dimensions[4], font_dimensions[7]] {
snap(&mut height, i64::from(zone));
}
let right_bearing = points_to_sp(advance - points(right));
let scale = self.request.horizontal_scale();
let bearing_scale = if scale == 0. { 1. } else { scale };
let right_bearing = points_to_sp((advance - points(right)) * bearing_scale);
Ok([
points_to_sp(advance),
points_to_sp(advance * scale),
height,
depth,
self.letter_space() - right_bearing.min(0),
@@ -420,10 +443,14 @@ impl OpenTypeFont {
);
let bidi = BidiInfo::new(&text, None);
let mut glyphs = Vec::new();
let mut x_origin = 0;
let mut x_origin = 0.;
let mut y_origin = 0.;
let letter_space = self.letter_space();
let mut tracking = 0;
let scale = |value: i64| scale_units(value, self.size, face.tables().head.units_per_em);
let horizontal_scale = self.request.horizontal_scale();
let units = face.tables().head.units_per_em;
let points = |value: i64| units_to_points(value as f32, self.size, units);
let horizontal = |value| points(value) * horizontal_scale;
for paragraph in &bidi.paragraphs {
let (levels, runs) = bidi.visual_runs(paragraph, paragraph.range.clone());
for range in runs {
@@ -456,27 +483,31 @@ impl OpenTypeFont {
for (info, pos) in shaped.glyph_infos().iter().zip(shaped.glyph_positions()) {
let cluster = range.start + info.cluster as usize;
let end = starts[starts.partition_point(|at| *at <= cluster)];
if tracking != 0 && scale(i64::from(pos.x_advance)) == 0 {
let next_x = x + i64::from(pos.x_advance);
if tracking != 0 && points_to_sp(points(i64::from(pos.x_advance))) == 0 {
tracking -= letter_space;
}
let x_position = |value| point_position_to_sp(x_origin + f64::from(horizontal(value)));
glyphs.push(OpenTypeGlyph {
id: info.glyph_id as u16,
x: x_origin + scale(x + i64::from(pos.x_offset)) + tracking,
y: scale(-y - i64::from(pos.y_offset)),
advance: scale(x + i64::from(pos.x_advance)) - scale(x),
x: x_position(x + i64::from(pos.x_offset)) + tracking,
y: point_position_to_sp(y_origin + f64::from(points(-y - i64::from(pos.y_offset)))),
advance: x_position(next_x) - x_position(x),
cluster: cluster..end,
cluster_start: cluster != previous,
});
tracking += letter_space;
x += i64::from(pos.x_advance);
x = next_x;
y += i64::from(pos.y_advance);
previous = cluster;
}
x_origin += scale(x);
x_origin += f64::from(horizontal(x));
y_origin += f64::from(points(-y));
}
}
let mut width = point_position_to_sp(x_origin);
if tracking != 0 {
x_origin += tracking - letter_space;
width += tracking - letter_space;
}
let glyph_extents = (use_glyph_metrics && !glyphs.is_empty())
.then(|| glyph_extents(&face, self.size, &glyphs));
@@ -484,7 +515,7 @@ impl OpenTypeFont {
font: self.clone(),
text,
glyphs,
width: x_origin,
width,
sources,
glyph_extents,
actual_text: false,
@@ -554,7 +585,11 @@ fn units_to_points(value: f32, size: i64, units: u16) -> f32 {
}
fn points_to_sp(points: f32) -> i64 {
(f64::from(points) * 65536. + 0.5) as i64
point_position_to_sp(f64::from(points))
}
fn point_position_to_sp(points: f64) -> i64 {
(points * 65536. + 0.5) as i64
}
fn sized_face_metrics(face: &ttf_parser::Face<'_>, size: i64) -> [i64; 2] {
+1 -1
View File
@@ -857,7 +857,7 @@ fn page_content(
},
DisplayItem::OpenTypeGlyph { x, y, size, font, glyph, text, .. } => {
opentype[&font.id].paint(
&mut opentype_text, &mut content, font.id, *glyph, text,
&mut opentype_text, &mut content, font, *glyph, text,
*size, *x - h, height - *y - v, list.units.bp(1),
);
}
+15 -8
View File
@@ -278,7 +278,7 @@ impl EmbeddedFont {
&self,
run: &mut Option<TextRun>,
output: &mut PageContent,
font: FontId,
font: &OpenTypeFont,
glyph: u16,
text: &str,
size: i64,
@@ -287,14 +287,17 @@ impl EmbeddedFont {
bp_per_unit: f64,
) {
let glyph = &self.glyphs[&glyph];
let horizontal_scale = font.paint_horizontal_scale();
let horizontal_em = size as f64 * horizontal_scale;
let override_text = glyph
.cluster_text
.as_deref()
.is_some_and(|mapped| text != mapped);
if run.as_ref().is_some_and(|state| {
override_text
|| state.font != font
|| state.font != font.id
|| state.size != size
|| (horizontal_em == 0. && x != state.start[0] + state.offset)
|| (y - state.start[1]).abs() as f64 * bp_per_unit > 0.001
|| (x - state.start[0] - state.offset).abs() > size * 3
}) {
@@ -312,26 +315,30 @@ impl EmbeddedFont {
});
let size_bp = size as f64 * bp_per_unit;
output.push_str(&format!(
"BT /U{} {size_bp:.4} Tf 1 0 0 1 {:.3} {:.3} Tm [<",
font.index(),
"BT /U{} {size_bp:.4} Tf {horizontal_scale} 0 0 1 {:.3} {:.3} Tm [<",
font.id.index(),
coordinates[0].0,
coordinates[1].0
));
TextRun {
font,
font: font.id,
size,
start: coordinates.map(|(_, origin)| origin),
offset: x - coordinates[0].1,
}
});
// Move in PDF's thousandth-em text units, tracking widths in TeX sp.
let kernel = ((state.start[0] + state.offset - x) as f64 * 1000. / size as f64) as i64;
let kernel = if horizontal_em == 0. {
0
} else {
((state.start[0] + state.offset - x) as f64 * 1000. / horizontal_em) as i64
};
if kernel != 0 {
output.push_str(&format!("> {kernel} <"));
state.offset -= (kernel as f64 * (size as f64 / 1000.)) as i64;
state.offset -= (kernel as f64 * (horizontal_em / 1000.)) as i64;
}
output.push_str(&format!("{:04X}", glyph.cid));
state.offset += i64::from(glyph.advance) * size / i64::from(self.units);
state.offset += (f64::from(glyph.advance) * horizontal_em / f64::from(self.units)) as i64;
if override_text {
TextRun::finish(run, output);
output.push_str("EMC\n");
+2 -1
View File
@@ -565,9 +565,10 @@ impl DisplayList {
let x = *x as f64 / 65536.;
let y = *y as f64 / 65536.;
let scale = *size as f64 / (65536. * f64::from(face.units_per_em()));
let horizontal = scale * font.paint_horizontal_scale();
if !path.is_empty() {
out.push_str(&format!(
"<g data-font=\\\"{}\\\" data-glyph=\\\"{glyph}\\\" aria-label=\\\"{}\\\"><path d=\\\"{path}\\\" transform=\\\"translate({x:.5} {y:.5}) scale({scale:.9} -{scale:.9})\\\" fill=\\\"#{:02x}{:02x}{:02x}\\\"{fill_opacity}/></g>\n",
"<g data-font=\"{}\" data-glyph=\"{glyph}\" aria-label=\"{}\"><path d=\"{path}\" transform=\"translate({x:.5} {y:.5}) scale({horizontal:.9} -{scale:.9})\" fill=\"#{:02x}{:02x}{:02x}\"{fill_opacity}/></g>\n",
escape(&font.name), escape(text), fill[0], fill[1], fill[2]
));
}
+2 -1
View File
@@ -410,7 +410,8 @@ impl SourceMap {
let ascent = scale(font.ascent);
let descent = scale(font.descent);
Some((PaintKind::OpenTypeGlyph { font: font.id.index(), glyph: *glyph }, Bounds {
x: *x, y: y - ascent, width: *advance, height: ascent + descent,
x: x + advance.min(&0), y: y - ascent,
width: advance.abs(), height: ascent + descent,
}))
}
DisplayItem::Rule {