Execute explicit XeTeX glyph nodes across native layout and export

This commit is contained in:
gloamxun committed 2026-11-26 11:54:39 +08:00
1 parent a0922d0105
commit b88283f493
17 files changed
+185 -43

No files matched your search

@@ -354,7 +354,9 @@ impl NativeBox {
TextNode::Glyph { glyph, .. }
| TextNode::Box(glyph)
| TextNode::MathChar(glyph) => HorizontalItem::Box(glyph.clone()),
TextNode::OpenType(run) => HorizontalItem::Box(crate::opentype::horizontal_box(run)),
TextNode::OpenType(run) | TextNode::ExplicitOpenTypeGlyph(run) => {
HorizontalItem::Box(crate::opentype::horizontal_box(run))
}
TextNode::Rule(r) => {
HorizontalItem::Box(r.horizontal_item(self.width, self.height, self.depth))
}
@@ -707,7 +709,7 @@ pub(super) fn hpack_with_direction_report(
height = height.max(glyph.height - shift);
depth = depth.max(glyph.depth + shift);
}
TextNode::OpenType(run) => {
TextNode::OpenType(run) | TextNode::ExplicitOpenTypeGlyph(run) => {
width += run.width;
let [run_height, run_depth] = run.height_depth();
height = height.max(run_height);
@@ -60,6 +60,7 @@ pub enum DiagnosticNode {
SpaceAdjustment(i32),
MarginKern { width: i32, right: bool },
Direction(DirectionBoundary),
OpenTypeGlyph { font: FontId, glyph: u16 },
}
/// A semantic view, without recursively copying the box's painted contents.
#[derive(Clone, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
@@ -188,6 +189,10 @@ pub(super) fn text_nodes(nodes: &[TextNode]) -> Vec<DiagnosticNode> {
font: run.font.id, text: run.text.clone(),
glyphs: run.glyphs.iter().map(|glyph| glyph.id).collect(),
},
TextNode::ExplicitOpenTypeGlyph(run) => DiagnosticNode::OpenTypeGlyph {
font: run.font.id,
glyph: run.glyphs[0].id,
},
TextNode::Box(b) if b.native_box.is_some() => {
DiagnosticNode::Box(box_view(b.native_box.as_ref().unwrap()))
}
@@ -489,6 +494,11 @@ impl Printer<'_> {
self.literal(" ");
self.literal(text);
}
DiagnosticNode::OpenTypeGlyph { font, glyph } => {
let name = self.state.fonts.font(*font)?.identifier_text();
self.command(&name);
self.literal(&format!(" glyph#{glyph}"));
}
DiagnosticNode::Box(b) => self.box_(b, prefix)?,
DiagnosticNode::EmptyBox(w) => {
self.command("hbox");
@@ -2649,6 +2649,7 @@ impl Executor {
let first = self.expanded_non_space(files)?;
let mut used_quotes = false;
let mut name = std::string::String::new();
let xetex = self.state.input_profile() == InputProfile::XeTeX;
if first.token.kind.begin_group() {
loop {
let token = self.required_expanded(files)?;
@@ -2672,6 +2673,11 @@ impl Executor {
TokenKind::Character(' ', CatCode::Space) if quoted => name.push(' '),
TokenKind::Character(_, CatCode::Space) => break,
TokenKind::Character(c, CatCode::Letter | CatCode::Other) => name.push(c),
TokenKind::Character(c, CatCode::MathShift | CatCode::Alignment
| CatCode::Parameter | CatCode::Superscript | CatCode::Subscript) if xetex =>
{
name.push(c);
}
_ => {
self.unread(token)?;
break;
@@ -3248,6 +3254,7 @@ impl Executor {
Primitive::XeTeXrevision => "XeTeXrevision".into(),
Primitive::XeTeXpdffile => "XeTeXpdffile".into(),
Primitive::XeTeXpicfile => "XeTeXpicfile".into(),
Primitive::XeTeXglyph => "XeTeXglyph".into(),
Primitive::XeTeXinputencoding => "XeTeXinputencoding".into(),
Primitive::XeTeXdefaultencoding => "XeTeXdefaultencoding".into(),
Primitive::XeTeXcharclass => "XeTeXcharclass".into(),
@@ -3833,6 +3840,7 @@ impl Executor {
| Meaning::Primitive(
Primitive::Char
| Primitive::Accent
| Primitive::XeTeXglyph
| Primitive::Hskip
| Primitive::Hfil
| Primitive::Hfill
@@ -251,6 +251,7 @@ impl Executor {
n,
TextNode::Glyph { .. }
| TextNode::OpenType(_)
| TextNode::ExplicitOpenTypeGlyph(_)
| TextNode::Kern { .. }
| TextNode::AccentKern(_)
| TextNode::AutoKern(_)
@@ -51,6 +51,7 @@ impl Executor {
XeTeXpdffile | XeTeXpicfile => {
self.scan_xdv_image(token, primitive == XeTeXpdffile, files)?
}
XeTeXglyph => self.append_opentype_glyph(token, files)?,
_ => return Ok(false),
}
Ok(true)
@@ -25,7 +25,7 @@ impl Tail {
}
TextNode::Penalty(n) => Self::Penalty(*n),
TextNode::MarginKern { .. } => Self::Other(15),
TextNode::OpenType(_) => Self::Other(9),
TextNode::OpenType(_) | TextNode::ExplicitOpenTypeGlyph(_) => Self::Other(9),
TextNode::Glyph { ligature, .. } => Self::Other(if *ligature { 7 } else { 0 }),
TextNode::MathChar(_) => Self::Other(0),
TextNode::Box(b) => Self::Other(b.native_box.as_ref().map_or(1, |b| {
@@ -123,6 +123,33 @@ impl Executor {
Ok(())
}
pub(super) fn append_opentype_glyph(
&mut self,
token: &Token,
files: &mut impl SourceProvider,
) -> Result<(), Error> {
if !self.math.is_empty() {
return self.fail(r"You can't use \XeTeXglyph in math mode");
}
self.reads.insert(Dependency::ParagraphMode);
self.reads.insert(Dependency::TextFont);
self.reads.insert(Dependency::FontResources);
let font = self.state.fonts.font(self.state.text_font())
.map_err(|error| self.error(error, token.span))?
.opentype()
.cloned()
.ok_or_else(|| self.error(r"\XeTeXglyph requires a native font", token.span))?;
let value = self.integer(files)?;
let glyph = u16::try_from(value)
.map_err(|_| self.error(format!("Bad glyph number ({value})"), token.span))?;
let glyph_metrics = self.read_parameter(Parameter::XeTeXuseglyphmetrics).width() > 0;
let run = font.explicit_glyph(glyph, PaintSource::token(TokenOrigin::from(token)), glyph_metrics)
.map_err(|error| self.error(error, token.span))?;
let paragraph = self.paragraph.as_mut().expect("explicit glyph enters horizontal mode");
paragraph.nodes.push(TextNode::ExplicitOpenTypeGlyph(Arc::new(run)));
Ok(())
}
pub(super) fn append_italic_correction(&mut self) -> Result<(), Error> {
self.reads.insert(Dependency::ParagraphMode);
self.reads.insert(Dependency::BoxPackState);
@@ -135,6 +162,9 @@ impl Executor {
run.glyphs.last().map_or(Ok(0), |glyph| run.font.italic_correction(glyph.id))
.map_err(|error| self.error(error, self.current))?
}
Some(TextNode::ExplicitOpenTypeGlyph(run)) => run.font
.glyph_overhang(run.glyphs[0].id)
.map_err(|error| self.error(error, self.current))?,
_ => return Ok(()),
};
self.reads.insert(Dependency::FontResources);
@@ -84,6 +84,8 @@ pub enum TextNode {
Direction(DirectionBoundary),
FontSpace(Glue, FontId, TokenOrigin),
SpaceAdjustment(i32),
/// A native XeTeX glyph node carries no text for shaping or hyphenation.
ExplicitOpenTypeGlyph(Arc<OpenTypeRun>),
}
#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct NativeParagraph {
@@ -574,7 +576,7 @@ fn width(n: &TextNode) -> i64 {
TextNode::Glyph { glyph, .. } | TextNode::Box(glyph) | TextNode::MathChar(glyph) => {
glyph.width
}
TextNode::OpenType(run) => run.width,
TextNode::OpenType(run) | TextNode::ExplicitOpenTypeGlyph(run) => run.width,
TextNode::Glue(g) | TextNode::FontSpace(g, _, _)
| TextNode::NamedGlue(g, _)
| TextNode::Leaders(LeaderGlue { glue: g, .. }) => g.width as i64,
@@ -1238,6 +1240,7 @@ fn pre_display_line_size(
TextNode::Glyph { .. }
| TextNode::Box(_)
| TextNode::OpenType(_)
| TextNode::ExplicitOpenTypeGlyph(_)
| TextNode::MathChar(_)
| TextNode::Indent(_)
| TextNode::Rule(_)
@@ -145,6 +145,7 @@ impl BreakNode {
| TextNode::Glyph { .. }
| TextNode::Box(_)
| TextNode::OpenType(_)
| TextNode::ExplicitOpenTypeGlyph(_)
| TextNode::Rule(_)
| TextNode::Mark(_)
| TextNode::Adjustment(_)
@@ -18,7 +18,9 @@ impl Edge {
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::OpenType(run) | TextNode::ExplicitOpenTypeGlyph(run) => {
Self::opentype(run, right)
}
TextNode::MathChar(glyph) => {
use crate::math_engine_tex::MathItem;
match glyph
@@ -188,6 +188,7 @@ impl Tracer {
self.character(state, *font, if *ligature { original } else { &character }, out)?;
}
TextNode::OpenType(run) => self.character(state, run.font.id, &run.text, out)?,
TextNode::ExplicitOpenTypeGlyph(_) => out.push_str("[]"),
TextNode::MathChar(b) => {
if let Some(g) = &b.math_geometry
&& g.items.len() == 1
@@ -389,6 +389,7 @@ pub enum Primitive {
XeTeXdefaultencoding,
XeTeXcharclass,
XeTeXinterchartoks,
XeTeXglyph,
}
impl Primitive {
@@ -1730,6 +1731,7 @@ impl State {
("XeTeXrevision", Primitive::XeTeXrevision),
("XeTeXpdffile", Primitive::XeTeXpdffile),
("XeTeXpicfile", Primitive::XeTeXpicfile),
("XeTeXglyph", Primitive::XeTeXglyph),
("XeTeXpdfpagecount", Primitive::XeTeXpdfpagecount),
("XeTeXinputencoding", Primitive::XeTeXinputencoding),
("XeTeXdefaultencoding", Primitive::XeTeXdefaultencoding),
+59 -8
View File
@@ -418,13 +418,27 @@ impl OpenTypeFont {
}
pub(crate) fn italic_correction(&self, glyph: u16) -> Result<i64, String> {
Ok(self.glyph_overhang(glyph)? + self.letter_space())
}
pub(crate) fn glyph_overhang(&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());
let overhang = (points(right) - points(advance)).max(0.);
Ok(points_to_sp(overhang * self.request.horizontal_scale()) + self.letter_space())
Ok(points_to_sp(overhang * self.request.horizontal_scale()))
}
pub(crate) fn explicit_glyph(
self: &Arc<Self>,
glyph: u16,
source: PaintSource,
use_glyph_metrics: bool,
) -> Result<OpenTypeRun, String> {
let face = self.face()?;
Ok(OpenTypeRun::single_glyph(self, &face, GlyphId(glyph), "", source, use_glyph_metrics))
}
pub(crate) fn glyph_metrics(
@@ -714,6 +728,40 @@ pub struct OpenTypeRun {
}
impl OpenTypeRun {
fn single_glyph(
font: &Arc<OpenTypeFont>,
face: &ttf_parser::Face<'_>,
id: GlyphId,
text: &str,
source: PaintSource,
use_glyph_metrics: bool,
) -> Self {
// An explicit glyph advances by the face's nominal width. Font
// transforms still apply to painting and the italic correction.
let units = face.units_per_em();
let width = scale_units(i64::from(face.glyph_hor_advance(id).unwrap_or(0)), font.size, units);
let glyph_extents = use_glyph_metrics.then(|| {
let [_, bottom, _, top] = glyph_control_bounds(face, id);
[scale_units(top as i64, font.size, units), scale_units(-bottom as i64, font.size, units)]
});
Self {
font: font.clone(),
text: text.into(),
glyphs: vec![OpenTypeGlyph {
id: id.0,
x: 0,
y: 0,
advance: width,
cluster: 0..text.len(),
cluster_start: true,
}],
width,
sources: vec![(0, source)],
glyph_extents,
actual_text: false,
}
}
pub(crate) fn height_depth(&self) -> [i64; 2] {
self.glyph_extents.unwrap_or([self.font.ascent, self.font.descent])
}
@@ -782,14 +830,17 @@ impl OpenTypeRun {
emit(crate::render::DisplayItem::OpenTypeColor(Some(color)), PaintSource::default());
}
for glyph in &self.glyphs {
let first = self
.sources
.partition_point(|(offset, _)| *offset < glyph.cluster.start);
let last = self
.sources
.partition_point(|(offset, _)| *offset < glyph.cluster.end);
let sources = if self.text.is_empty() {
// A glyph identified by number has source provenance without
// a corresponding string of characters.
self.sources.as_slice()
} else {
let first = self.sources.partition_point(|(offset, _)| *offset < glyph.cluster.start);
let last = self.sources.partition_point(|(offset, _)| *offset < glyph.cluster.end);
&self.sources[first..last]
};
let mut source = PaintSource::default();
for (_, component) in &self.sources[first..last] {
for (_, component) in sources {
source.merge(component);
}
emit(
@@ -207,19 +207,9 @@ pub(crate) fn painted_glyph(
) -> (MathGeometry, i64) {
let units = face.units_per_em();
let scale = |value| scale_units(value, font.size, units);
let advance = scale(i64::from(face.glyph_hor_advance(id).unwrap_or(0)));
let glyph = OpenTypeGlyph {
id: id.0,
x: 0,
y: 0,
advance,
cluster: 0..text.len(),
cluster_start: true,
};
let [_, bottom, _, top] = glyph_control_bounds(face, id);
let points = |value| units_to_points(value, font.size, units);
let height = points_to_sp(points(top));
let depth = points_to_sp(points(-bottom));
let run = OpenTypeRun::single_glyph(font, face, id, text, source.clone(), true);
let advance = run.width;
let [height, depth] = run.height_depth();
let italic = face
.tables()
.math
@@ -227,15 +217,6 @@ pub(crate) fn painted_glyph(
.and_then(|info| info.italic_corrections)
.and_then(|values| values.get(id))
.map_or(0, |value| scale(i64::from(value.value)));
let run = OpenTypeRun {
font: font.clone(),
text: text.into(),
glyphs: vec![glyph],
width: advance,
sources: vec![(0, source.clone())],
glyph_extents: Some([height, depth]),
actual_text: false,
};
(
MathGeometry {
metrics: MathBox {
+18 -8
View File
@@ -138,15 +138,25 @@ fn write_font(
let mut embedded = BTreeMap::new();
let width = |value: i64| (value as f64 * 1000. / f64::from(face.units_per_em())).round() as i32;
for (glyph, source) in glyphs {
let advance = face.glyph_hor_advance(GlyphId(glyph)).ok_or_else(|| {
format!(
"OpenType font {} has no advance for glyph {glyph}",
font.name
)
})?;
let cid = remapper.remap(glyph);
let outside_face = glyph >= face.number_of_glyphs();
let (cid, advance) = if outside_face {
// The XDV cursor advances zero for this unmapped glyph number.
(glyph, 0)
} else {
let advance = face.glyph_hor_advance(GlyphId(glyph)).ok_or_else(|| {
format!("OpenType font {} has no advance for glyph {glyph}", font.name)
})?;
(remapper.remap(glyph), advance)
};
fingerprint.update(glyph.to_be_bytes());
write!(widths, "{cid} [{}] ", width(i64::from(advance))).unwrap();
// The PDF device uses the default glyph width for unmapped CIDs,
// independently of the XDV glyph's layout advance.
let pdf_advance = if outside_face {
face.glyph_hor_advance(GlyphId(0)).unwrap_or(0)
} else {
advance
};
write!(widths, "{cid} [{}] ", width(i64::from(pdf_advance))).unwrap();
let unicode = match &font_unicode {
Some(mapping) => mapping.get(&glyph).map(String::as_str),
None => (!source.is_empty()).then_some(source),
+30
View File
@@ -2175,6 +2175,36 @@ PDF,恢复实际 PFB 并反转斜切时复用 1277 步,只替换第二页。
全量编译一致。incremental-receipt.json 的 SHA-256 为
bbc0991b0316e6d76aa58649ec873525f5544ab530d93fe491fc6e16bd00a27d。
### XeTeX 显式字形节点
`\XeTeXglyph` 在 XeTeX 扩展模式读入真实 16 位字形编号,
必要时开启段落并执行 everypar。水平列表保存独立字形节点,参与
装箱、断行、显式断字材料、边缘悬挂及来源定位。字形宽度取自字体,
轮廓变换和斜体修正按活动字体执行。诊断保留实际编号和节点类型。
[TeX Live 的显式字形执行](https://github.com/TeX-Live/texlive-source/blob/279984fab6eaed8d17e02882f2668ab5caac0f27/texk/web2c/xetexdir/xetex.web#L30524-L30548)
原语、段落、CFF 字形编号上限和真实 fontspec 共 8 页、32 个
字形。盒度量、节点类型、空格因子、已成形文字、PDF 提取文本和
144 DPI RGB 光栅与参考一致。逐字形编号、字号与原始坐标一致。
真实 fontspec 实际加载的 CFF 和 TrueType 字体与参考相同。
为新原语从原样 xelatex.ini 转储 schema73,并经真实格式加载执行
fontspec。既有 schema71 可用于继续复编原样 ACL。
XeTeX 的文件式名称扫描接受下划线等字符,按原参数核对字形查询。
首次原生 CFF PDF 将无映射 CID 的设备宽度按布局的零宽写出,
造成 180 个差异像素。修正默认字形设备宽度后逐样本一致。
原版 TrueType 65535 可生成 XDV,xdvipdfmx 的断言中止日志已保存。
三次跨文件切换字形各复用 66 步,只更新第二页。实际 PDF、
SVG、来源身份和来源映射条目与独立全量一致,来源可定位到宏的
定义和调用。12 项 XeTeX 定向回归通过。原样 ACL 的 PDF、aux、
out、bbl 与前版逐字节一致。
回执 `target/p3-xetex-explicit-glyph/receipt.json` 的 SHA-256 为
`2896eef930c6749574f1e582968daf32af7b160bafad1aceb902dd90e4885b3b`。
下一入口为 `\XeTeXglyphbounds` 和 `\XeTeXglyphname`。
`target/p3-xetex-glyph-queries` 保存原样字体、XeTeX 参考查询及
出页,覆盖 CFF、TrueType、字形变换及无映射编号。
### XeTeX OpenType 字体颜色与透明度
XeTeX 的 RGB 和 RGBA 字体选项进入 OpenType 字体状态,实际绘制
+9
View File
@@ -758,6 +758,15 @@ XDV 链接注释接入后,沿原样 ACL 的第二轮辅助文件和 BibTeX
`target/p3-xdv-annotation/receipt.json`。
[链接注释阶段记录](P2_M1_PROGRESS.md#xdv-链接注释与实际矩形)
#### XeTeX 显式字形复编
同一 schema71、真实字体和已收敛的辅助文件原样复编 ACL。
PDF、aux、out、bbl 与前版逐字节一致。真实 fontspec 的显式
CFF 和 TrueType 字形另行核对,原样 ACL 继续沿用既有整页门禁。
回执 `target/p3-xetex-explicit-glyph/receipt.json` 的 SHA-256 为
`2896eef930c6749574f1e582968daf32af7b160bafad1aceb902dd90e4885b3b`。
[显式字形阶段记录](P2_M1_PROGRESS.md#xetex-显式字形节点)
#### XeTeX OpenType 字体颜色复编
原样 ACL 以同一 schema71、真实字体及已收敛的辅助文件复编,