Measure native XeTeX glyphs and break after mapped dashes

This commit is contained in:
gloamxun committed 2026-11-21 12:58:25 +08:00
1 parent c548ca8e9f
commit facecbf790
9 files changed
+332 -35

No files matched your search

@@ -608,8 +608,9 @@ pub(super) fn hpack(
}
TextNode::OpenType(run) => {
width += run.width;
height = height.max(run.font.ascent);
depth = depth.max(run.font.descent);
let [run_height, run_depth] = run.height_depth();
height = height.max(run_height);
depth = depth.max(run_depth);
}
TextNode::Rule(r) => {
let (w, h, d) = r.dimensions();
@@ -387,6 +387,12 @@ impl Executor {
self.reads.insert(Dependency::FontResources);
self.reads.insert(Dependency::TextFont);
if let Some(font) = opentype {
if self.state.input_profile() == InputProfile::XeTeX {
self.reads.insert(Dependency::Parameter(Parameter::XeTeXuseglyphmetrics));
if !self.restricted() {
self.reads.insert(Dependency::Parameter(Parameter::XeTeXdashbreakstate));
}
}
return self.paragraph.as_mut().unwrap()
.opentype_character(c, TokenOrigin::from(token), &self.state, font)
.map_err(|e| self.error(e, token.invocation.unwrap_or(token.span)));
@@ -8,9 +8,9 @@ use std::{
sync::{Arc, Mutex, OnceLock, Weak},
};
const SCHEMA: u32 = 61;
const COMPATIBLE_SCHEMAS: [u32; 30] = [
27, 28, 31, 32, 33, 34, 35, 36, 37, 38, 39, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, SCHEMA,
const SCHEMA: u32 = 62;
const COMPATIBLE_SCHEMAS: [u32; 31] = [
27, 28, 31, 32, 33, 34, 35, 36, 37, 38, 39, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, SCHEMA,
];
const ENGINE: &str = concat!("texrra-native/", env!("CARGO_PKG_VERSION"));
@@ -1,6 +1,6 @@
//! Native horizontal material and paragraph breaking. No command/string parser.
use super::*;
use crate::{HorizontalBox, Paragraph, ParagraphFont};
use crate::{HorizontalBox, Paragraph, ParagraphFont, provenance::PaintSource};
use std::{collections::BTreeMap, sync::Arc};
use crate::opentype::{OpenTypeFont, OpenTypeRun};
@@ -209,14 +209,7 @@ impl Builder {
});
if explicit_hyphen && !self.restricted {
hyphen_break = Some(self.nodes.len());
self.nodes.push(TextNode::Discretionary {
font: run.font.id,
automatic: false,
hyphen_char: None,
pre_break: Vec::new(),
post_break: Vec::new(),
replacement_count: 0,
});
self.push_explicit_hyphen_break(run.font.id);
}
}
Output::Kern(width) => self.nodes.push(TextNode::Kern {
@@ -238,11 +231,7 @@ impl Builder {
}
pub fn finish_text(&mut self, right_boundary: bool, state: &State) -> Result<(), String> {
if let Some(run) = self.opentype.take() {
let shaped = run.font.shape(run.text, run.sources)?;
self.font_steps = self.font_steps.checked_add(shaped.glyphs.len())
.filter(|steps| *steps <= self.font_step_limit)
.ok_or("native OpenType shaping step limit exceeded")?;
self.nodes.push(TextNode::OpenType(Arc::new(shaped)));
self.finish_opentype(run, state)?;
}
if let Some(mut run) = self.run.take() {
run.machine
@@ -262,6 +251,83 @@ impl Builder {
}
Ok(())
}
fn push_explicit_hyphen_break(&mut self, font: FontId) {
self.nodes.push(TextNode::Discretionary {
font,
automatic: false,
hyphen_char: None,
pre_break: Vec::new(),
post_break: Vec::new(),
replacement_count: 0,
});
}
fn finish_opentype(&mut self, run: PendingOpenType, state: &State) -> Result<(), String> {
let xetex = state.input_profile() == InputProfile::XeTeX;
let use_glyph_metrics =
xetex && state.parameter(Parameter::XeTeXuseglyphmetrics).width() > 0;
let original_end = run.text.chars().next_back();
let (text, sources) = run.font.map_text(run.text, run.sources)?;
if self.restricted || !xetex {
return self.push_opentype(&run.font, text, sources, use_glyph_metrics);
}
let dash_breaks = state.parameter(Parameter::XeTeXdashbreakstate).width() > 0;
let hyphen = u32::try_from(state.font_integers(run.font.id).hyphen)
.ok()
.and_then(char::from_u32);
let is_hyphen = |c| Some(c) == hyphen || (dash_breaks && matches!(c, '–' | '—'));
// XeTeX tests the end of the original word for the final discretionary,
// and the characters of the mapped word for interior breakpoints.
let trailing_break = original_end.is_some_and(is_hyphen);
let ends = text.char_indices().filter_map(|(at, c)| {
let end = at + c.len_utf8();
(end < text.len() && is_hyphen(c)).then_some(end)
});
let mut ends = ends.peekable();
if ends.peek().is_none() {
self.push_opentype(&run.font, text, sources, use_glyph_metrics)?;
} else {
let mut sources = sources.into_iter().peekable();
let mut start = 0;
for end in ends.chain(std::iter::once(text.len())) {
let mut fragment_sources = Vec::new();
while let Some((offset, origin)) = sources.next_if(|(at, _)| *at < end) {
fragment_sources.push((offset - start, origin));
}
self.push_opentype(
&run.font,
text[start..end].to_owned(),
fragment_sources,
use_glyph_metrics,
)?;
if end != text.len() {
self.push_explicit_hyphen_break(run.font.id);
}
start = end;
}
}
if trailing_break {
self.push_explicit_hyphen_break(run.font.id);
}
Ok(())
}
fn push_opentype(
&mut self,
font: &Arc<OpenTypeFont>,
text: String,
sources: Vec<(usize, PaintSource)>,
use_glyph_metrics: bool,
) -> Result<(), String> {
let shaped = font.shape_mapped(text, sources, use_glyph_metrics)?;
self.font_steps = self.font_steps.checked_add(shaped.glyphs.len())
.filter(|steps| *steps <= self.font_step_limit)
.ok_or("native OpenType shaping step limit exceeded")?;
self.nodes.push(TextNode::OpenType(Arc::new(shaped)));
Ok(())
}
pub fn opentype_character(
&mut self, c: char, origin: TokenOrigin, state: &State, font: Arc<OpenTypeFont>,
) -> Result<(), String> {
@@ -119,6 +119,8 @@ pub enum Parameter {
Pdfappendkern,
Pdfadjustspacing,
Partokencontext,
XeTeXuseglyphmetrics,
XeTeXdashbreakstate,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
pub enum ParameterValue {
@@ -151,6 +153,8 @@ impl Parameter {
)
}
pub(super) const XETEX: [Self; 2] = [Self::XeTeXuseglyphmetrics, Self::XeTeXdashbreakstate];
pub const ALL: &'static [Self] = &[
Self::Pdfoutput,
Self::Pdfmajorversion,
@@ -266,9 +270,15 @@ impl Parameter {
Self::Pdfappendkern,
Self::Pdfadjustspacing,
Self::Partokencontext,
Self::XeTeXuseglyphmetrics,
Self::XeTeXdashbreakstate,
];
pub fn name(self) -> String {
format!("{self:?}").to_ascii_lowercase()
match self {
Self::XeTeXuseglyphmetrics => "XeTeXuseglyphmetrics".into(),
Self::XeTeXdashbreakstate => "XeTeXdashbreakstate".into(),
_ => format!("{self:?}").to_ascii_lowercase(),
}
}
pub fn kind(self) -> Option<RegisterKind> {
match self {
@@ -1144,7 +1144,7 @@ impl Default for State {
| Parameter::Tracingnesting
| Parameter::Tracingassigns
| Parameter::Savingvdiscards
) {
) || Parameter::XETEX.contains(p) {
continue;
}
state
@@ -1637,6 +1637,13 @@ impl State {
] {
self.update_profile_command(name, Meaning::Primitive(primitive), enabled);
}
for parameter in Parameter::XETEX {
self.update_profile_command(
&parameter.name(),
Meaning::Parameter(parameter),
enabled,
);
}
}
pub(super) fn profile_primitive_name(&self, primitive: Primitive) -> Option<&'static str> {
+83 -13
View File
@@ -277,16 +277,24 @@ impl OpenTypeFont {
]))
}
pub(crate) fn shape(
pub(crate) fn map_text(
&self,
text: String,
sources: Vec<(usize, PaintSource)>,
) -> Result<(String, Vec<(usize, PaintSource)>), String> {
if let Some(mapping) = &self.mapping {
mapping.apply(&text, &sources)
} else {
Ok((text, sources))
}
}
pub(crate) fn shape_mapped(
self: &Arc<Self>,
text: String,
sources: Vec<(usize, PaintSource)>,
use_glyph_metrics: bool,
) -> Result<OpenTypeRun, String> {
let (text, sources) = if let Some(mapping) = &self.mapping {
mapping.apply(&text, &sources)?
} else {
(text, sources)
};
let face = Face::from_slice(&self.resource.data, self.request.index)
.ok_or("invalid OpenType shaping face")?;
let features: Vec<_> = self
@@ -357,20 +365,76 @@ impl OpenTypeFont {
x_origin += scale(x);
}
}
let glyph_extents = (use_glyph_metrics && !glyphs.is_empty())
.then(|| glyph_extents(&face, self.size, &glyphs));
Ok(OpenTypeRun {
font: self.clone(),
text,
glyphs,
width: x_origin,
sources,
glyph_extents,
})
}
}
// FreeType's unscaled control box includes off-curve points. In particular
// it can be larger than the tight bounds of a CFF cubic outline.
#[derive(Default)]
struct VerticalControlBox(Option<[f32; 2]>);
impl VerticalControlBox {
fn point(&mut self, y: f32) {
let y = y.round();
let bounds = self.0.get_or_insert([y, y]);
bounds[0] = bounds[0].min(y);
bounds[1] = bounds[1].max(y);
}
}
impl ttf_parser::OutlineBuilder for VerticalControlBox {
fn move_to(&mut self, _: f32, y: f32) {
self.point(y);
}
fn line_to(&mut self, _: f32, y: f32) {
self.point(y);
}
fn quad_to(&mut self, _: f32, control: f32, _: f32, y: f32) {
self.point(control);
self.point(y);
}
fn curve_to(&mut self, _: f32, first: f32, _: f32, second: f32, _: f32, y: f32) {
self.point(first);
self.point(second);
self.point(y);
}
fn close(&mut self) {}
}
fn glyph_extents(face: &Face<'_>, size: i64, glyphs: &[OpenTypeGlyph]) -> [i64; 2] {
let mut minimum = f32::INFINITY;
let mut maximum = f32::NEG_INFINITY;
let points = |units| units * (size as f32 / 65536.) / f32::from(face.tables().head.units_per_em);
for glyph in glyphs {
let mut outline = VerticalControlBox::default();
let [bottom, top] = if face.outline_glyph(GlyphId(glyph.id), &mut outline).is_some() {
outline.0.unwrap_or_default()
} else {
[0., 0.]
};
let baseline = -(glyph.y as f32 / 65536.);
minimum = minimum.min(baseline + points(bottom));
maximum = maximum.max(baseline + points(top));
}
[points_to_sp(maximum), -points_to_sp(minimum)]
}
fn points_to_sp(points: f32) -> i64 {
(f64::from(points) * 65536. + 0.5) as i64
}
pub(crate) fn scale_units(value: i64, size: i64, units: u16) -> i64 {
let points = (value as f32 * (size as f32 / 65536.)) / f32::from(units);
// XeTeX converts the float point position by adding 0.5 and truncating.
(f64::from(points) * 65536. + 0.5) as i64
points_to_sp(points)
}
#[derive(Clone, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
@@ -390,6 +454,14 @@ pub struct OpenTypeRun {
pub glyphs: Vec<OpenTypeGlyph>,
pub width: i64,
pub sources: Vec<(usize, PaintSource)>,
#[serde(default, skip_serializing_if = "Option::is_none")]
glyph_extents: Option<[i64; 2]>,
}
impl OpenTypeRun {
pub(crate) fn height_depth(&self) -> [i64; 2] {
self.glyph_extents.unwrap_or([self.font.ascent, self.font.descent])
}
}
/// Materialize a single native math glyph using the final selected glyph,
@@ -403,7 +475,8 @@ pub(crate) fn math_glyph(
math::MathBox,
math_engine_tex::{MathGeometry, MathItem, PositionedItem},
};
let mut run = font.shape(character.to_string(), vec![(0, source.clone())])?;
let (text, sources) = font.map_text(character.to_string(), vec![(0, source.clone())])?;
let mut run = font.shape_mapped(text, sources, false)?;
let [glyph] = run.glyphs.as_mut_slice() else {
return Err("OpenType math character did not select one glyph".into());
};
@@ -444,11 +517,8 @@ pub(crate) fn horizontal_box(run: &Arc<OpenTypeRun>) -> crate::HorizontalBox {
math::MathBox,
math_engine_tex::{MathGeometry, MathItem, PositionedItem},
};
let metrics = MathBox {
width: run.width,
height: run.font.ascent,
depth: run.font.descent,
};
let [height, depth] = run.height_depth();
let metrics = MathBox { width: run.width, height, depth };
crate::HorizontalBox {
width: metrics.width,
height: metrics.height,
+28 -1
View File
@@ -2175,6 +2175,33 @@ PDF,恢复实际 PFB 并反转斜切时复用 1277 步,只替换第二页。
全量编译一致。incremental-receipt.json 的 SHA-256 为
bbc0991b0316e6d76aa58649ec873525f5544ab530d93fe491fc6e16bd00a27d。
### XeTeX 字形外框与破折号断行
XeTeX 扩展模式启用两个有实际消费者的可分组整数。
\XeTeXuseglyphmetrics 为正时,OpenType 横向节点合并字形的未缩放
控制点外框与 shaping 的纵向偏移,并保存测得的盒高和深度。
\XeTeXdashbreakstate 为正时,普通段落在应用 TECkit 以后识别短破折号和
长破折号,在相应位置使用实际 discretionary。restricted hbox 仍作为
整段文本 shaping。TeX 宏和字形保留原来的输入来源。
14 项定向回归通过。真实 XeTeX 对照的 Latin Modern 普通文本、带组合
附标字形和 Liberation Serif 两个模式共 62 个字形,编号与 sp 坐标逐项
一致。两份 Latin Modern 600 dpi 光栅逐像素一致。映射所得破折号段落
在参考和原生中均由一行变成两行。三页会话只修改开关子文件,复用 982 步,
只替换第二页,PDF、页面和来源映射与独立全量一致。
原样 xelatex.ini 成功生成 schema62。未修改的 LaTeX 内核将两个开关
均设为 1,重载同一份 article 后,49 个字形编号与横纵 sp 坐标均与
XeTeX 一致。大小写诊断、实际 aux 和一页 600 dpi 灰度图均一致。
上一阶段的两组纵向差异在本次对照中归零。
证据见 target/p3-xetex-glyph-metrics/article-native/receipt.json 与
同目录的 directed-receipt.json。graphics-reference 和 graphics-native
保留原样 graphicx
的下一项实际能力缺口,宏执行到 \XeTeXpdffile。参考以同一份本地 PDF
测得实际插图盒 4736286 × 6129203 sp,深度为 0。
[XeTeX 字形外框与定位](https://github.com/TeX-Live/texlive-source/blob/trunk/texk/web2c/xetexdir/XeTeX_ext.c#L2122-L2160)
[XeTeX 映射后的破折号断点](https://github.com/TeX-Live/texlive-source/blob/trunk/texk/web2c/xetexdir/xetex.web#L22510-L22520)
### TECkit 字体映射与原样 XeLaTeX article
原样 xelatex.ini 在明确的 XeTeX 模式下执行到 \dump。优化版读取实际
@@ -2199,7 +2226,7 @@ TECkit 编译的自定义映射,源字节和字体一致,600 dpi 灰度图
原样 article 经原版 size10.clo、TU 字体定义与 l3backend-xetex.def 输出一页
PDF。与参考的 49 个字形编号及横向位置完全一致,Unicode 大小写诊断
和实际 aux 字节一致。当前纵向坐标仍有 412404 和 702833 sp 的差异。
和实际 aux 字节一致。该阶段纵向坐标有 412404 和 702833 sp 的差异。
LaTeX 默认在第 22125 行同时启用 \XeTeXuseglyphmetrics 和
\XeTeXdashbreakstate。参考探测在 glyph metrics 开关两侧测得实际盒高
和深度改变,内嵌映射破折号处的断行也由一行变两行。两项仍需接入真实
+110
View File
@@ -707,6 +707,116 @@ fn font_mapping_changes_recover_and_update_the_page_that_used_the_resource() {
fs::remove_dir_all(p).unwrap();
}
#[test]
fn xetex_glyph_bounds_and_dash_breaks_follow_revision_local_parameters() {
use texrra_tex_core::execution::{Event, InputProfile};
let p = directory("xetex-glyph-metrics");
let mut request = request(&p);
request.world = WorldConfig::new(&p);
request.input_profile = InputProfile::XeTeX;
let settings = p.join("switches.tex");
let padding = format!("{}\n", "\\relax ".repeat(26)).repeat(45);
let source = format!(
r#"
\catcode123=1 \catcode125=2
\font\selected="[LiberationSerif-Regular.ttf]" at 10pt
\selected
\shipout\hbox{{First page}}
{padding}
\input switches.tex
\setbox0=\hbox{{ag}}
\message{{BOX=\number\ht0,\number\dp0}}
\hsize=48pt \pretolerance=-1 \tolerance=10000 \parfillskip=0pt plus1fil
\setbox1=\vbox{{\noindent AAAAA—BBBBB\par \message{{LINES=\the\prevgraf}}}}
\shipout\vbox{{\box0\box1}}
\shipout\hbox{{\vrule width9pt height8pt}}
\end
"#
);
let project = ProjectSnapshot::new(ProjectDefinition {
configuration: request.world.clone(),
revision: 1,
roots: [p.clone()].into(),
files: [
(p.join("main.tex"), Arc::from(source.into_bytes())),
(
p.join("LiberationSerif-Regular.ttf"),
Arc::from(
include_bytes!("../assets/fonts-subset/LiberationSerif-Regular.ttf").as_slice(),
),
),
(
settings.clone(),
Arc::from(br"\XeTeXuseglyphmetrics=0 \XeTeXdashbreakstate=0".as_slice()),
),
]
.into(),
directories: Default::default(),
aliases: Default::default(),
generated_roots: [p.clone()].into(),
generated: Default::default(),
})
.unwrap();
let compiler = NativeCompiler::default().with_automatic_entry_checkpoints();
let before = compiler
.compile(request.clone().with_project(project.clone()))
.unwrap();
let edited = project
.with_file_edits(
2,
[(
settings,
Arc::from(br"\XeTeXuseglyphmetrics=1 \XeTeXdashbreakstate=1".as_slice()),
)]
.into(),
)
.unwrap();
let request = request.with_project(edited);
let resumed = compiler.compile(request.clone()).unwrap();
let full = NativeCompiler::default().compile(request).unwrap();
// Box dimensions and line counts from XeTeX INITEX with the same font file.
for (document, expected) in [
(&before, ["BOX=584000,141759", "LINES=1"]),
(&resumed, ["BOX=336320,141439", "LINES=2"]),
] {
let messages: Vec<_> = document
.execution
.execution
.events
.iter()
.filter_map(|event| match event {
Event::Message { text, .. }
if text.starts_with("BOX=") || text.starts_with("LINES=") =>
{
Some(text.as_str())
}
_ => None,
})
.collect();
assert_eq!(messages, expected);
}
assert!(resumed.entry_checkpoint_work.reused_steps > 0);
assert_eq!(resumed.pdf, full.pdf);
assert_eq!(resumed.pages, full.pages);
assert_eq!(resumed.source_map.pages, full.source_map.pages);
let changes = resumed.preview_since(Some(before.revision())).unwrap();
assert_eq!(
changes
.pages
.iter()
.map(|page| page.index)
.collect::<Vec<_>>(),
[1]
);
eprintln!(
"XeTeX metrics and dash edit reused {} steps",
resumed.entry_checkpoint_work.reused_steps
);
fs::remove_dir_all(p).unwrap();
}
#[test]
fn checkpoint_keeps_late_special_tokens_until_the_updated_page_is_shipped() {
let p = directory("late-special");