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),