Use shaped glyph edges for XeTeX protrusion and line breaking

This commit is contained in:
gloamxun committed 2026-11-25 19:09:56 +08:00
1 parent 5df90f113c
commit 6826efbeb1
12 files changed
+231 -39

No files matched your search

+14 -4
View File
@@ -2281,8 +2281,13 @@ impl Executor {
Ok(self.state.fonts.auto_kern_code(font, slot, p == Primitive::Knaccode))
}
Meaning::Primitive(p @ (Primitive::Lpcode | Primitive::Rpcode)) => {
let (font, slot) = self.font_character_target(files)?;
Ok(self.state.fonts.protrusion_code(font, slot, p == Primitive::Rpcode))
let (font, slot) = self.protrusion_target(files)?;
let right = p == Primitive::Rpcode;
Ok(if self.state.input_profile() == InputProfile::XeTeX {
self.state.fonts.xe_protrusion_code(font, slot, right)
} else {
self.state.fonts.protrusion_code(font, slot as u8, right)
})
}
Meaning::Primitive(p @ (Primitive::Hyphenchar | Primitive::Skewchar)) => {
let font = self.font_identifier(files)?;
@@ -4344,10 +4349,15 @@ impl Executor {
self.state.fonts.set_auto_kern_code(font, slot, primitive == Some(Knaccode), code);
}
Some(Lpcode | Rpcode) => {
let (font, slot) = self.font_character_target(files)?;
let (font, slot) = self.protrusion_target(files)?;
self.optional_equals(files)?;
let code = self.integer(files)?;
self.state.fonts.set_protrusion_code(font, slot, primitive == Some(Rpcode), code);
let right = primitive == Some(Rpcode);
if self.state.input_profile() == InputProfile::XeTeX {
self.state.fonts.set_xe_protrusion_code(font, slot, right, code);
} else {
self.state.fonts.set_protrusion_code(font, slot as u8, right, code);
}
}
Some(Hyphenchar | Skewchar) => {
let font = self.font_identifier(files)?;
@@ -103,6 +103,38 @@ impl Executor {
_ => unreachable!(),
} as i32)
}
pub(super) fn protrusion_target(
&mut self,
files: &mut impl SourceProvider,
) -> Result<(FontId, i32), Error> {
self.reads.insert(Dependency::FontResources);
if self.state.input_profile() != InputProfile::XeTeX {
let (font, slot) = self.font_character_target(files)?;
return Ok((font, i32::from(slot)));
}
let id = self.font_identifier(files)?;
let opentype = self.state.fonts.font(id)
.map_err(|error| self.error(error, self.current))?.opentype().cloned();
let slot = if let Some(font) = opentype {
if self.keyword("/", files)? {
let name = self.filename(files)?;
font.face().map_err(|error| self.error(error, self.current))?
.glyph_index_by_name(&name).map_or(0, |glyph| i32::from(glyph.0))
} else if self.keyword("u", files)? {
let slot = self.character_number("XeTeX glyph character", 65535, files)?;
let face = font.face().map_err(|error| self.error(error, self.current))?;
char::from_u32(slot).and_then(|c| face.glyph_index(c))
.map_or(0, |glyph| i32::from(glyph.0))
} else {
self.integer(files)?
}
} else {
self.character_number("XeTeX font character", 65535, files)? as i32
};
Ok((id, slot))
}
pub(super) fn xetex_font_query(
&mut self,
command: Primitive,
@@ -226,6 +226,8 @@ pub struct FontCatalog {
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
protrusion: BTreeMap<FontId, BTreeMap<u8, [i16; 2]>>,
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
xe_protrusion: BTreeMap<FontId, BTreeMap<i32, [i32; 2]>>,
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
auto_kern: BTreeMap<FontId, BTreeMap<u8, [i16; 2]>>,
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
expansion: BTreeMap<FontId, FontExpansion>,
@@ -271,6 +273,7 @@ impl FontCatalog {
parameter_owners: BTreeMap::new(),
limits,
protrusion: BTreeMap::new(),
xe_protrusion: BTreeMap::new(),
auto_kern: BTreeMap::new(),
expansion: BTreeMap::new(),
external_expansion: BTreeMap::new(),
@@ -701,6 +704,32 @@ impl FontCatalog {
self.protrusion.entry(font).or_default().entry(slot).or_default()[usize::from(right)] = code;
}
}
pub(super) fn xe_protrusion_code(&self, font: FontId, slot: i32, right: bool) -> i32 {
self.xe_protrusion
.get(&font)
.and_then(|codes| codes.get(&slot))
.map_or(0, |codes| codes[usize::from(right)])
}
pub(super) fn set_xe_protrusion_code(
&mut self, font: FontId, slot: i32, right: bool, code: i32,
) {
let side = usize::from(right);
if code != 0 {
self.xe_protrusion.entry(font).or_default().entry(slot).or_default()[side] = code;
} else if let Some(table) = self.xe_protrusion.get_mut(&font) {
if let Some(pair) = table.get_mut(&slot) {
pair[side] = 0;
if *pair == [0; 2] {
table.remove(&slot);
}
}
if table.is_empty() {
self.xe_protrusion.remove(&font);
}
}
}
pub(super) fn has_auto_kern_codes(&self) -> bool {
!self.auto_kern.is_empty()
}
@@ -1006,6 +1035,7 @@ impl FontCatalog {
self.external_expansion.clear();
self.expansion_codes.clear();
self.protrusion.clear();
self.xe_protrusion.clear();
self.auto_kern.clear();
self.pdf_settings.clear();
}
@@ -8,9 +8,9 @@ use std::{
sync::{Arc, Mutex, OnceLock, Weak},
};
const SCHEMA: u32 = 70;
const COMPATIBLE_SCHEMAS: [u32; 37] = [
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, 64, 65, 66, 67, 68, 69, SCHEMA,
const SCHEMA: u32 = 71;
const COMPATIBLE_SCHEMAS: [u32; 38] = [
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, 64, 65, 66, 67, 68, 69, 70, SCHEMA,
];
const ENGINE: &str = concat!("texrra-native/", env!("CARGO_PKG_VERSION"));
@@ -78,7 +78,7 @@ pub enum TextNode {
/// Spacing owned by a text accent and protected from leading discard.
AccentKern(i32),
AutoKern(i32),
MarginKern { width: i32, right: bool, font: FontId, slot: u8 },
MarginKern { width: i32, right: bool, font: FontId, slot: u16 },
Direction(DirectionBoundary),
}
#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
@@ -1088,8 +1088,8 @@ fn pack(
if left != Glue::default() {
material.push(TextNode::NamedGlue(left, Parameter::Leftskip));
}
let enabled = p[&Parameter::Pdfprotrudechars].width() > 0;
if enabled && let Some(kern) = protrusion::margin_kern(state, nodes, false, false) {
let enabled = protrusion::level(state, p) > 0;
if enabled && let Some(kern) = protrusion::margin_kern(state, nodes, false, false)? {
material.push(kern);
}
let right_end = nodes.len() - usize::from(terminal_marker);
@@ -1098,7 +1098,7 @@ fn pack(
material.push(TextNode::Penalty(10000));
}
if enabled
&& let Some(kern) = protrusion::margin_kern(state, &nodes[..right_end], true, ends_in_pre_break)
&& let Some(kern) = protrusion::margin_kern(state, &nodes[..right_end], true, ends_in_pre_break)?
{
material.push(kern);
}
@@ -289,7 +289,7 @@ pub(super) fn solve(
.then(|| expansion::Search::new(state, source))
.transpose()?;
let expand_margins = expansion.is_some();
let mut margins = (parameters[&Parameter::Pdfprotrudechars].width() > 1)
let mut margins = (protrusion::level(state, parameters) > 1)
.then(|| protrusion::Search::new(state, source, expand_margins))
.transpose()?;
let retained = nodes.len()
@@ -385,6 +385,7 @@ pub(super) fn pack(
let TextNode::MarginKern { width, right, font, slot } = *node else {
continue;
};
let Ok(slot) = u8::try_from(slot) else { continue };
for (ratio, limit) in [(1000, &mut capacity.stretch), (-1000, &mut capacity.shrink)] {
if let Some((expanded, _)) = fonts.margin(state, font, slot, right, ratio, files)? {
*limit += i64::from(expanded) - i64::from(width);
@@ -408,7 +409,9 @@ pub(super) fn pack(
pdf_device::divide_scaled(shortfall.clamp(-available, available), available, 3).0 as i32;
for i in 0..material.len() {
if let TextNode::MarginKern { ref mut width, right, ref mut font, slot } = material[i] {
if let Some((expanded, selected)) = fonts.margin(state, *font, slot, right, ratio, files)? {
if let Ok(slot) = u8::try_from(slot)
&& let Some((expanded, selected)) = fonts.margin(state, *font, slot, right, ratio, files)?
{
*width = expanded;
*font = selected;
}
@@ -1,4 +1,4 @@
//! The same font-slot widths drive break search and the owned margin kerns.
//! The same shaped edges drive break search and the owned margin kerns.
use super::*;
#[derive(Clone, Copy)]
@@ -6,12 +6,19 @@ enum Edge {
Skip,
Solid,
Glyph(FontId, u8),
OpenType(FontId, u16),
}
impl Edge {
fn character(node: &TextNode) -> Self {
fn opentype(run: &OpenTypeRun, right: bool) -> Self {
let glyph = if right { run.glyphs.last() } else { run.glyphs.first() };
glyph.map_or(Self::Solid, |glyph| Self::OpenType(run.font.id, glyph.id))
}
fn character(node: &TextNode, right: bool) -> Self {
match node {
TextNode::Glyph { font, slot, .. } => Self::Glyph(*font, *slot),
TextNode::OpenType(run) => Self::opentype(run, right),
TextNode::MathChar(glyph) => {
use crate::math_engine_tex::MathItem;
match glyph
@@ -21,6 +28,7 @@ impl Edge {
{
Some([item]) => match &item.item {
MathItem::NativeGlyph { font, slot, .. } => Self::Glyph(font.id, *slot),
MathItem::OpenType(run) => Self::opentype(run, right),
_ => Self::Solid,
},
_ => Self::Solid,
@@ -44,7 +52,7 @@ impl Edge {
_ => Self::Solid,
},
_ if skippable(node) => Self::Skip,
_ => Self::character(node),
_ => Self::character(node, right),
}
}
@@ -63,25 +71,38 @@ impl Edge {
Self::Skip
}
fn width(self, state: &State, right: bool) -> i32 {
let Self::Glyph(font, slot) = self else {
return 0;
fn width(self, state: &State, right: bool) -> Result<i32, String> {
let xe = state.input_profile() == InputProfile::XeTeX;
let (font, code) = match self {
Self::Glyph(font, slot) if !xe => (font, state.fonts.protrusion_code(font, slot, right)),
Self::Glyph(font, slot) => (font, state.fonts.xe_protrusion_code(font, i32::from(slot), right)),
Self::OpenType(font, glyph) if xe => (font, state.fonts.xe_protrusion_code(font, i32::from(glyph), right)),
_ => return Ok(0),
};
let code = state.fonts.protrusion_code(font, slot, right);
if code == 0 {
return 0;
return Ok(0);
}
let quad = state
.fonts
.font(font)
.expect("marginal glyph's font is live")
.quad();
let quad = state.fonts.font(font)?.quad();
let scaled = i64::from(quad) * i64::from(code);
// Round to the nearest sp, taking half a unit away from zero.
(scaled.signum() * ((scaled.abs() + 500) / 1000)) as i32
// XeTeX's signed remainder does not round up for negative factors.
let rounding = if xe && code < 0 { 0 } else { 500 };
let width = scaled.signum() * ((scaled.abs() + rounding) / 1000);
if width.abs() > 1073741823 {
return Err("native character protrusion exceeds dimension capacity".into());
}
Ok(width as i32)
}
}
pub(super) fn level(state: &State, parameters: &BTreeMap<Parameter, ParameterValue>) -> i32 {
let parameter = if state.input_profile() == InputProfile::XeTeX {
Parameter::XeTeXprotrudechars
} else {
Parameter::Pdfprotrudechars
};
parameters[&parameter].width()
}
fn skippable(node: &TextNode) -> bool {
match node {
TextNode::Box(boxed) => matches!(
@@ -141,22 +162,24 @@ pub(super) fn margin_kern(
nodes: &[TextNode],
right: bool,
direct: bool,
) -> Option<TextNode> {
) -> Result<Option<TextNode>, String> {
let edge = if direct {
nodes.last().map_or(Edge::Solid, Edge::character)
nodes.last().map_or(Edge::Solid, |node| Edge::character(node, right))
} else {
Edge::list(nodes, right)
};
let Edge::Glyph(font, slot) = edge else {
return None;
let (font, slot) = match edge {
Edge::Glyph(font, slot) => (font, u16::from(slot)),
Edge::OpenType(font, glyph) => (font, glyph),
_ => return Ok(None),
};
let width = -edge.width(state, right);
(width != 0).then_some(TextNode::MarginKern {
let width = -edge.width(state, right)?;
Ok((width != 0).then_some(TextNode::MarginKern {
width,
right,
font,
slot,
})
}))
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
@@ -185,7 +208,7 @@ impl Search {
let mut variations = BTreeMap::new();
let mut project = |edge: Edge, right| -> Result<EdgeMeasure, String> {
use std::collections::btree_map::Entry;
let width = edge.width(state, right);
let width = edge.width(state, right)?;
let mut expanding = None;
if expand && let Edge::Glyph(font, slot) = edge {
let key = (font, slot);
@@ -210,9 +233,9 @@ impl Search {
};
if let TextNode::Discretionary { pre_break, post_break, .. } = node {
widths[i].pre = pre_break.last()
.map(|node| project(Edge::character(node), true)).transpose()?;
.map(|node| project(Edge::character(node, true), true)).transpose()?;
widths[i].post = post_break.first()
.map(|node| project(Edge::character(node), false)).transpose()?;
.map(|node| project(Edge::character(node, false), false)).transpose()?;
}
}
for (i, node) in nodes.iter().enumerate().rev() {
@@ -124,6 +124,7 @@ pub enum Parameter {
Suppressfontnotfounderror,
TeXXeTstate,
XeTeXinterchartokenstate,
XeTeXprotrudechars,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
pub enum ParameterValue {
@@ -156,11 +157,12 @@ impl Parameter {
)
}
pub(super) const XETEX: [Self; 4] = [
pub(super) const XETEX: [Self; 5] = [
Self::XeTeXuseglyphmetrics,
Self::XeTeXdashbreakstate,
Self::Suppressfontnotfounderror,
Self::XeTeXinterchartokenstate,
Self::XeTeXprotrudechars,
];
pub const ALL: &'static [Self] = &[
@@ -283,6 +285,7 @@ impl Parameter {
Self::Suppressfontnotfounderror,
Self::TeXXeTstate,
Self::XeTeXinterchartokenstate,
Self::XeTeXprotrudechars,
];
pub fn name(self) -> String {
match self {
@@ -290,6 +293,7 @@ impl Parameter {
Self::XeTeXdashbreakstate => "XeTeXdashbreakstate".into(),
Self::TeXXeTstate => "TeXXeTstate".into(),
Self::XeTeXinterchartokenstate => "XeTeXinterchartokenstate".into(),
Self::XeTeXprotrudechars => "XeTeXprotrudechars".into(),
_ => format!("{self:?}").to_ascii_lowercase(),
}
}
@@ -396,3 +396,48 @@ fn xetex_inter_character_lists_follow_text_runs_and_shared_grouping() {
assert!(result.reads.contains(&Dependency::XeCharClass(67)));
assert!(result.reads.contains(&Dependency::XeInterCharTokens(4098)));
}
#[test]
fn xetex_protrusion_level_scopes_and_font_codes_are_job_local() {
let state = State::initex()
.with_etex()
.with_input_profile(InputProfile::XeTeX);
let seed = r"\catcode123=1 \catcode125=2
\XeTeXprotrudechars=2
\lpcode\nullfont65535=-1800
\message{\the\lpcode\nullfont65535}
\dump";
let execution = run(state.clone(), seed);
assert_eq!(messages(&execution), ["-1800"]);
let image = FormatImage::from_dump(execution, Vec::new(), Vec::new())
.unwrap()
.encode()
.unwrap();
let executor = FormatImage::decode(&image)
.unwrap()
.new_job(
state.profile(),
InputProfile::XeTeX,
JobTime::new(2025, 10, 9, 0).unwrap(),
Limits::default(),
|_| Ok(seed.as_bytes().to_vec()),
)
.unwrap();
let result = executor
.with_native_pages()
.run(
source(
r"\message{\the\XeTeXprotrudechars/\the\lpcode\nullfont65535}
\begingroup
\XeTeXprotrudechars=1 \lpcode\nullfont65535=1600
\message{\the\XeTeXprotrudechars/\the\lpcode\nullfont65535}
\endgroup
\message{\the\XeTeXprotrudechars/\the\lpcode\nullfont65535}
\shipout\hbox{\vrule width5pt height3pt depth0pt}
\end",
),
&mut TestDevice,
)
.unwrap();
assert_eq!(messages(&result), ["2/0", "1/1600", "2/1600"]);
}
+38
View File
@@ -2175,6 +2175,44 @@ PDF,恢复实际 PFB 并反转斜切时复用 1277 步,只替换第二页。
全量编译一致。incremental-receipt.json 的 SHA-256 为
bbc0991b0316e6d76aa58649ec873525f5544ab530d93fe491fc6e16bd00a27d。
### XeTeX 字形边缘悬挂与断行
XeTeX profile 执行 `\XeTeXprotrudechars`。级别 1 在封装实际行时
插入左右悬挂 kern,级别 2 也将相同的边缘宽度用于断行候选评估。
`\lpcode` 和 `\rpcode` 使用实际字体。OpenType 支持数字、Unicode
字符选择器和字形名,TFM 使用原有字符编号。XeTeX 的字体值保存为完整
有符号整数,按作业全局生效,重载格式只保留悬挂级别。OpenType 边缘
从成形结果取实际字形。断行缓存核对实际边缘度量,封装和导出
都使用真实列表节点。
[XeTeX 字体量存储](https://github.com/TeX-Live/texlive-source/blob/279984fab6eaed8d17e02882f2668ab5caac0f27/texk/web2c/xetexdir/hz.cpp#L39-L75)
[XeTeX 行首与行尾的成形字形](https://github.com/TeX-Live/texlive-source/blob/279984fab6eaed8d17e02882f2668ab5caac0f27/texk/web2c/xetexdir/XeTeX_ext.c#L2921-L2942)
五份同源探测的数值一致,包括字形 464、负悬挂、组内设置及
25 至 40 pt 行宽的三级对照。25 pt 段落在级别 0、1、2 分别排为
6、6、3 行。三份出页样例的 54 个字形坐标和 9 页 144 DPI 灰度逐像素
一致。XeTeX profile 7 项和 pdfTeX 悬挂定向回归 1 项通过。最小格式
重载与真实 XeTeX 同源一致,旧 schema70 原生格式实际加载出页。
原子项目按 `3 → 6 → 3` 连续编辑悬挂值。辅助文件版本相同时,两次
都复用 156 步和 5 次宿主调用。辅助文件版本改变时,第二次回退到
重新执行,复用了 1 次断行搜索。四次都只替换第二页,PDF、SVG、
来源映射和辅助文件与同版本独立全量一致。原始中断和初次检查点
拒绝的证据均保留。对照目录为 `target/p3-xetex-protrusion`。
原样 `xelatex.ini` 转储 schema71。原样 ACL 越过 microtype 设置,
排到 `acl_lualatex.tex:101` 的 `\end{document}` 并尝试发页。
此次停在 `hxetex.def:232:19` 的 `pdf:docinfo`,尚未生成 PDF。
十份原样输入的摘要与上一轮相同。回执
`target/p3-xetex-protrusion/receipt.json` 的 SHA-256 为
`85ff89f6f7a4ef8ab656c172d17c2668420ebe311b169f33225c66aa958b5969`。
下一入口是将 XDV 页上的 `pdf:docinfo` 连接到真实文档信息字典,
按发页顺序合并,保留 PDF 字符串与 Unicode。真实参考见
`target/p3-xetex-protrusion/next-docinfo`。两页对照保留首个实际页的
Subject 和 Creator,用第二页覆盖 Title 和 Author,并验证 UTF-16BE
标题。未发出的盒子不影响最终元数据。
[上游 xdvipdfmx 文档字典合并](https://github.com/TeX-Live/texlive-source/blob/279984fab6eaed8d17e02882f2668ab5caac0f27/texk/dvipdfm-x/spc_pdfm.c)
### XeTeX 字符类别与文字运行间插入
XeTeX 扩展 profile 支持 `\XeTeXcharclass`、`\XeTeXinterchartoks`
+7
View File
@@ -716,6 +716,13 @@ Noto Sans Arabic 及冻结 Type 1 映射。几次缺包和字体名称探测的
诊断、原样输入与格式身份保留在 `target/p3-xetex-interchar/receipt.json`。
[字符类别阶段记录](P2_M1_PROGRESS.md#xetex-字符类别与文字运行间插入)
XeTeX 字形悬挂接入后,按上一轮冻结的十份 ACL 文件和字体复编。
未修改的 `xelatex.ini` 成功转储 schema71。样稿已越过 microtype,
排到 `acl_lualatex.tex:101` 的 `\end{document}`,首个发页尝试停在
`hxetex.def:232:19` 的 `pdf:docinfo`。本轮保留首次真实发页的失败证据,
原生尚未输出 PDF。回执 `target/p3-xetex-protrusion/receipt.json`。
[字形悬挂阶段记录](P2_M1_PROGRESS.md#xetex-字形边缘悬挂与断行)
### 原样 Elsevier CAS 双栏与 NeurIPS 2025
以 `767c8ff`、既有真实 schema51 和参考格式复验官方 CAS 双栏。