diff --git a/crates/texrra-tex-core/src/execution/engine/math.rs b/crates/texrra-tex-core/src/execution/engine/math.rs index 322a7ed..09d48b2 100644 --- a/crates/texrra-tex-core/src/execution/engine/math.rs +++ b/crates/texrra-tex-core/src/execution/engine/math.rs @@ -463,6 +463,7 @@ impl Executor { horizontal_packs: std::cell::Cell::new(0), last_pack_badness: std::cell::Cell::new(None), missing: std::cell::RefCell::new(Vec::new()), + current_math_font: std::cell::Cell::new(FontId::NULL), delimiter_glyphs: std::cell::Cell::new(0), delimiter_glyph_limit: self.limits.tokens, steps: std::cell::Cell::new(self.steps), diff --git a/crates/texrra-tex-core/src/execution/math.rs b/crates/texrra-tex-core/src/execution/math.rs index 26912d8..64bc66d 100644 --- a/crates/texrra-tex-core/src/execution/math.rs +++ b/crates/texrra-tex-core/src/execution/math.rs @@ -381,6 +381,8 @@ pub(super) struct Converter<'a> { pub horizontal_packs: std::cell::Cell, pub last_pack_badness: std::cell::Cell>, pub missing: std::cell::RefCell>, + /// XeTeX reads some MATH constants from the last fetched math font. + pub current_math_font: std::cell::Cell, pub delimiter_glyphs: std::cell::Cell, pub delimiter_glyph_limit: usize, pub steps: std::cell::Cell, @@ -457,6 +459,7 @@ impl Converter<'_> { source: &PaintSource, ) -> Result<(MathGeometry, i64), String> { let font = self.state.math_font(style.size_index() as u8, c.family); + self.current_math_font.set(font); if font == FontId::NULL { // Keep the same diagnostic as the legacy fetch path. self.family_font(c.family, style)?; @@ -628,6 +631,7 @@ impl Converter<'_> { self.font(c.family, style)?; } if !self.has_math_char(font, c.slot)? { + self.current_math_font.set(font); self.missing.borrow_mut().push((font, c.slot)); n.nucleus = MathField::Empty; } diff --git a/crates/texrra-tex-core/src/execution/math_accent.rs b/crates/texrra-tex-core/src/execution/math_accent.rs index 9f0c5e8..043799c 100644 --- a/crates/texrra-tex-core/src/execution/math_accent.rs +++ b/crates/texrra-tex-core/src/execution/math_accent.rs @@ -9,12 +9,14 @@ impl Converter<'_> { let mut n = original.clone(); let mut accent = n.accent.take().unwrap(); let font = self.family_font(accent.family, style)?; + self.current_math_font.set(font); let accent_font = self.state.fonts.font(font)?; let opentype = accent_font.opentype(); let bottom = n.accent_style.bottom(); let mut skew = 0; if let MathField::Char(c) = n.nucleus { let base_font = self.family_font(c.family, style)?; + self.current_math_font.set(base_font); if !self.has_math_char(base_font, c.slot)? { self.missing.borrow_mut().push((base_font, c.slot)); n.nucleus = MathField::Empty; @@ -60,6 +62,7 @@ impl Converter<'_> { .operator .clone() .derived(crate::provenance::Derivation::Accent); + let nucleus_font = self.current_math_font.get(); let (mark, x) = if let Some(face) = opentype { let (mut glyph, italic) = self.glyph(accent, style, &source)?; glyph.metrics.width -= italic; @@ -113,6 +116,9 @@ impl Converter<'_> { let x = skew + (width - mark.metrics.width + 1).div_euclid(2); (mark, x) }; + // Drawing the already fetched accent does not replace the font left + // by clean_box on the nucleus. + self.current_math_font.set(nucleus_font); let y = if bottom { base.metrics.depth + mark.metrics.height } else { @@ -148,6 +154,7 @@ impl Converter<'_> { .as_ref() .map(|f| self.field(f, style.sub(), &n.source.sub)) .transpose()?; + self.current_math_font.set(nucleus_font); Ok(place_scripts( result, upper, @@ -187,7 +194,10 @@ impl Converter<'_> { let Some(face) = font.opentype() else { return Ok(None); }; - let (geometry, _) = self.glyph(base, style, &source.paint)?; + let Some(character) = char::from_u32(base.slot) else { + return Ok(None); + }; + let (geometry, _) = opentype::math_glyph(face, character, &source.paint)?; opentype::single_glyph(&geometry) .map(|glyph| opentype::accent_attachment(face, glyph)) .transpose() diff --git a/crates/texrra-tex-core/src/execution/math_fraction.rs b/crates/texrra-tex-core/src/execution/math_fraction.rs index 140403a..1a94f45 100644 --- a/crates/texrra-tex-core/src/execution/math_fraction.rs +++ b/crates/texrra-tex-core/src/execution/math_fraction.rs @@ -14,15 +14,17 @@ impl Converter<'_> { ) -> Result { let params = self.params(style)?; let thickness = spec.thickness.map_or(params.rule_thickness, i64::from); - let extension = self.state.fonts.font(self.family_font(3, style)?)?; - let constants = extension + let mut upper = self.pack_field(self.convert(numerator, style.numerator(), false)?.0)?; + let mut lower = + self.pack_field(self.convert(denominator, style.denominator(), false)?.0)?; + // clean_box restores the math style and leaves the last fetched font. + // XeTeX takes the two fraction clearances from that font. + let current = self.state.fonts.font(self.current_math_font.get())?; + let constants = current .opentype() .map(|font| crate::opentype::MathConstants::read(font)) .transpose()? .flatten(); - let mut upper = self.pack_field(self.convert(numerator, style.numerator(), false)?.0)?; - let mut lower = - self.pack_field(self.convert(denominator, style.denominator(), false)?.0)?; if upper.width < lower.width { upper = self.rebox_math(upper, lower.width)?; } else { diff --git a/crates/texrra-tex-core/src/execution/math_op.rs b/crates/texrra-tex-core/src/execution/math_op.rs index 859123f..bb8acf2 100644 --- a/crates/texrra-tex-core/src/execution/math_op.rs +++ b/crates/texrra-tex-core/src/execution/math_op.rs @@ -70,6 +70,7 @@ impl Converter<'_> { style: MathStyle, ) -> Result, String> { let params = self.params(style)?; + let start_font = self.current_math_font.get(); let limits = n.limits == OperatorLimits::AboveBelow || (n.limits == OperatorLimits::Display && style.display()); // TeX cleans the upper limit first for a sub-mlist nucleus, but fetches @@ -88,6 +89,7 @@ impl Converter<'_> { let id = self.family_font(c.family, style)?; let mut source = n.source.nucleus.clone(); let font = self.state.fonts.font(id)?; + self.current_math_font.set(id); let (mut b, italic) = if !self.has_math_char(id, c.slot)? { self.missing.borrow_mut().push((id, c.slot)); (self.pack_field(Vec::new())?, 0) @@ -146,6 +148,11 @@ impl Converter<'_> { side.nucleus = MathField::Box(Box::new(body)); return self.script_noad(&side, style, false, italic); } + let limits_font = if matches!(n.nucleus, MathField::Char(_)) { + self.current_math_font.get() + } else { + start_font + }; let mut upper = if let Some(upper) = early_upper { upper } else { @@ -164,6 +171,7 @@ impl Converter<'_> { .as_ref() .map(|f| self.owned_field(f, style.sub(), &n.source.sub)) .transpose()?; + self.current_math_font.set(limits_font); let width = body .width .max(upper.as_ref().map_or(0, |b| b.width)) diff --git a/crates/texrra-tex-core/src/execution/math_scripts.rs b/crates/texrra-tex-core/src/execution/math_scripts.rs index 0b5d52f..bfd8d25 100644 --- a/crates/texrra-tex-core/src/execution/math_scripts.rs +++ b/crates/texrra-tex-core/src/execution/math_scripts.rs @@ -1,6 +1,9 @@ //! Owned make_scripts lists. The same layout decisions drive paint and boxes. use super::{math::*, *}; -use crate::math_engine_tex::{self as geometry, MathGeometry, MathStyle}; +use crate::{ + math_engine_tex::{self as geometry, MathGeometry, MathStyle}, + opentype::{self, OpenTypeFont, ScriptSide}, +}; impl Converter<'_> { pub(super) fn pack_field(&self, nodes: Vec) -> Result { // clean_box reuses a sole unshifted box, including a vertical one. @@ -116,6 +119,7 @@ impl Converter<'_> { (g, box_italic) } }; + let base_font = self.current_math_font.get(); let upper = n .sup .as_ref() @@ -126,6 +130,7 @@ impl Converter<'_> { .as_ref() .map(|f| self.owned_field(f, style.sub(), &n.source.sub)) .transpose()?; + self.current_math_font.set(base_font); let script_bounds = if let MathField::Char(c) | MathField::TextChar(c) = n.nucleus { let font = self.state.fonts.font(self.family_font(c.family, style)?)?; if let Some(face) = font.opentype() @@ -135,9 +140,8 @@ impl Converter<'_> { subscript_top_max: math.measure(math.values.subscript_top_max()), superscript_bottom_min: math.measure(math.values.superscript_bottom_min()), paired_gap: math.measure(math.values.sub_superscript_gap_min()), - paired_superscript_bottom: math.measure( - math.values.superscript_bottom_max_with_subscript(), - ), + paired_superscript_bottom: math + .measure(math.values.superscript_bottom_max_with_subscript()), }) } else { None @@ -145,6 +149,15 @@ impl Converter<'_> { } else { None }; + let base_glyph = if matches!(n.nucleus, MathField::Char(_) | MathField::TextChar(_)) { + self.state + .fonts + .font(base_font)? + .opentype() + .zip(opentype::single_glyph(&body)) + } else { + None + }; let (_, placement) = geometry::place_scripts_with_layout( body, upper.as_ref().map(NativeBox::geometry).transpose()?, @@ -157,12 +170,28 @@ impl Converter<'_> { i64::from(self.state.parameter(Parameter::Scriptspace).width()), script_bounds, ); + let kern = if let Some((font, glyph)) = base_glyph { + let (script, side, shift) = if lower.is_some() { + (n.sub.as_ref(), ScriptSide::Lower, placement.down) + } else { + (n.sup.as_ref(), ScriptSide::Upper, placement.up) + }; + self.script_kern((font, glyph), script, style, side, shift)? + } else { + 0 + }; + if kern != 0 { + nodes.push(TextNode::Kern { + width: i32::try_from(kern).map_err(|_| "native math script kern overflow")?, + explicit: false, + }); + } let space = i64::from(self.state.parameter(Parameter::Scriptspace).width()); let scripts = match (upper, lower) { (Some(mut upper), Some(mut lower)) => { upper.width += space; lower.width += space; - upper.shift = italic; + upper.shift = italic - kern; let gap = placement.up - upper.depth - lower.height + placement.down; let mut b = super::boxes::vpack( vec![ @@ -195,4 +224,63 @@ impl Converter<'_> { nodes.push(TextNode::Box(scripts.horizontal_item())); Ok(nodes) } + + fn script_kern( + &self, + base: (&OpenTypeFont, u16), + script: Option<&MathField>, + style: MathStyle, + side: ScriptSide, + shift: i64, + ) -> Result { + let Some((character, style)) = + script.and_then(|field| first_script_char(field, style.sub())) + else { + return Ok(0); + }; + let id = self.family_font(character.family, style)?; + let Some(font) = self.state.fonts.font(id)?.opentype() else { + return Ok(0); + }; + let Some(scalar) = char::from_u32(character.slot) else { + return Ok(0); + }; + if !self.has_math_char(id, character.slot)? { + return Ok(0); + } + let (geometry, _) = opentype::math_glyph(font, scalar, &Default::default())?; + let Some(glyph) = opentype::single_glyph(&geometry) else { + return Ok(0); + }; + opentype::script_kern(base, (font, glyph), side, shift) + } +} + +fn first_script_char(field: &MathField, mut style: MathStyle) -> Option<(MathChar, MathStyle)> { + let mut list = match field { + MathField::Char(c) => return Some((*c, style)), + MathField::List(list) => list.as_slice(), + _ => return None, + }; + loop { + let (node, rest) = list.split_first()?; + list = rest; + match node { + MathNode::Style(next) => style = *next, + MathNode::Choice(branches) => list = &branches[usize::from(style as u8 / 2)], + MathNode::Kern { .. } | MathNode::Glue(_) | MathNode::ExplicitSpace(..) => {} + MathNode::Noad(n) + if n.class != NoadClass::Inner + && n.accent.is_none() + && n.rule.is_none() + && !n.vcenter => + { + return match n.nucleus { + MathField::Char(c) => Some((c, style)), + _ => None, + }; + } + _ => return None, + } + } } diff --git a/crates/texrra-tex-core/src/opentype.rs b/crates/texrra-tex-core/src/opentype.rs index 6fec162..be1ee09 100644 --- a/crates/texrra-tex-core/src/opentype.rs +++ b/crates/texrra-tex-core/src/opentype.rs @@ -20,7 +20,7 @@ use unicode_bidi::BidiInfo; mod font_info; pub(crate) use font_info::LayoutTags; mod math_layout; -pub(crate) use math_layout::{MathConstants, Stretch, accent_attachment, single_glyph, stretch_glyph}; +pub(crate) use math_layout::{MathConstants, ScriptSide, Stretch, accent_attachment, script_kern, single_glyph, stretch_glyph}; #[derive(Clone, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)] pub(crate) struct Request { diff --git a/crates/texrra-tex-core/src/opentype/math_layout.rs b/crates/texrra-tex-core/src/opentype/math_layout.rs index bbae8ae..2dee951 100644 --- a/crates/texrra-tex-core/src/opentype/math_layout.rs +++ b/crates/texrra-tex-core/src/opentype/math_layout.rs @@ -88,6 +88,102 @@ pub(crate) fn single_glyph(geometry: &MathGeometry) -> Option { } } +#[derive(Clone, Copy)] +pub(crate) enum ScriptSide { + Upper, + Lower, +} + +/// Apply the XeTeX corner sums at the two glyph contact heights. +pub(crate) fn script_kern( + (base, base_glyph): (&OpenTypeFont, u16), + (script, script_glyph): (&OpenTypeFont, u16), + side: ScriptSide, + shift: i64, +) -> Result { + use ttf_parser::math::Kern; + fn value_at(kern: Option<&Kern<'_>>, height: i32) -> i32 { + let Some(kern) = kern else { return 0 }; + let (mut lo, mut hi) = (0, kern.count()); + while lo < hi { + let mid = lo + (hi - lo) / 2; + if kern + .height(mid) + .is_some_and(|value| i32::from(value.value) <= height) + { + lo = mid + 1; + } else { + hi = mid; + } + } + kern.kern(lo).map_or(0, |value| i32::from(value.value)) + } + let base_face = base.face()?; + let script_face = script.face()?; + let base_id = GlyphId(base_glyph); + let script_id = GlyphId(script_glyph); + let base_info = base_face + .tables() + .math + .and_then(|m| m.glyph_info) + .and_then(|info| info.kern_infos) + .and_then(|kerns| kerns.get(base_id)); + let script_info = script_face + .tables() + .math + .and_then(|m| m.glyph_info) + .and_then(|info| info.kern_infos) + .and_then(|kerns| kerns.get(script_id)); + let (base_kern, script_kern) = match side { + ScriptSide::Upper => ( + base_info.and_then(|i| i.top_right), + script_info.and_then(|i| i.bottom_left), + ), + ScriptSide::Lower => ( + base_info.and_then(|i| i.bottom_right), + script_info.and_then(|i| i.top_left), + ), + }; + if base_kern.is_none() && script_kern.is_none() { + return Ok(0); + } + let bounds = |face: &ttf_parser::Face<'_>, glyph| { + let mut outline = VerticalControlBox::default(); + face.outline_glyph(glyph, &mut outline); + let [bottom, top] = outline.0.unwrap_or_default(); + [top as i32, -bottom as i32] + }; + let [base_height, base_depth] = bounds(&base_face, base_id); + let [script_height, script_depth] = bounds(&script_face, script_id); + let shift = (shift as f32 * f32::from(base_face.units_per_em()) / base.size as f32) as i32; + let scale = script.size as f32 / base.size as f32; + let (a, b) = match side { + ScriptSide::Upper => ( + ( + (shift as f32 - scale * script_depth as f32) as i32, + -script_depth, + ), + (base_height, ((base_height - shift) as f32 / scale) as i32), + ), + ScriptSide::Lower => ( + ( + (scale * script_height as f32 - shift as f32) as i32, + script_height, + ), + (-base_depth, ((shift - base_depth) as f32 / scale) as i32), + ), + }; + let sum = |(base_height, script_height)| { + (value_at(base_kern.as_ref(), base_height) as f32 + + scale * value_at(script_kern.as_ref(), script_height) as f32) as i32 + }; + Ok(scale_units( + i64::from(sum(a).max(sum(b))), + base.size, + base_face.units_per_em(), + )) +} + pub(crate) fn accent_attachment(font: &OpenTypeFont, glyph: u16) -> Result { let face = font.face()?; let id = GlyphId(glyph); diff --git a/docs/P2_M1_PROGRESS.md b/docs/P2_M1_PROGRESS.md index 0360b41..90ff15c 100644 --- a/docs/P2_M1_PROGRESS.md +++ b/docs/P2_M1_PROGRESS.md @@ -2175,6 +2175,40 @@ PDF,恢复实际 PFB 并反转斜切时复用 1277 步,只替换第二页。 全量编译一致。incremental-receipt.json 的 SHA-256 为 bbc0991b0316e6d76aa58649ec873525f5544ab530d93fe491fc6e16bd00a27d。 +### XeTeX 数学脚标字距与分数当前字体 + +OpenType 脚标字距从基础和脚标的实际字形读取四角 MATH 表, +按脚标所在样式、字形接触高度和两个字体的尺寸求值。支持只带 +上标、只带下标和同时带上下标的盒与横向 kern。脚标开头的显式 +kern、胶、样式和 mathchoice 按 XeTeX 的实际扫描方式处理。 +[XeTeX 数学脚标字距](https://github.com/TeX-Live/texlive-source/blob/trunk/texk/web2c/xetexdir/XeTeXOTMath.cpp) + +分数间距使用清理分母后最后取用的数学字体。形状查询、绘制 +已选重音以及清理脚标时保留参考引擎的当前字体语义。 +上一阶段的 196 sp 和 8 sp 纵向差异均消除。原样 Latin Modern +Math INITEX 的 12 个盒、99 个字形和 3 条规则全部匹配。原样 +unicode-math 重用同一 schema67,30 个字形和 3 条规则坐标、 +aux 和 144 dpi 光栅全部匹配。 + +实测 STIX Two Math 的 12 个脚标盒与 6 个分数当前字体盒均 +匹配 XeTeX。对照覆盖正负字距、复合上下标、不同脚标样式、 +不透明盒、空分母及重音和分母采用不同字号的情况。 +40 个字形和 5 条规则的坐标全部一致。14 项定向回归通过。 +同源源码、字体哈希、逐盒测量和坐标证据位于 +target/p3-xetex-math-kern/receipt.json。 +[STIX Two Math 发行包](https://ctan.org/pkg/stix2-otf) + +三页会话把第二页的同一脚标从 7pt 样式切换到 10pt。途中 +提交非法字体家族时保留上一版。修复后只更新第二页并复用 +1559 步,PDF、SVG、来源映射和对应修订的独立全量一致。 +回执位于 target/p3-xetex-math-kern/revisions/receipt.json。 + +新入口使用真实系统字体名 STIX Two Math。私有 Fontconfig +测试树只包含同一个 CTAN 字体。XeTeX 的独立原语查询得到字体 +类型 2 和 alpha 字形 885。通过 fontspec 按名加载的原样包样稿 +生成一页,XDV 指向该实际文件。原生样稿复现 fontspec 找不到 +该字体。材料位于 target/p3-xetex-named-font。 + ### XeTeX OpenType MATH 重音、伸缩与公式出页 \Umathaccent 进入真实重音节点并保存 fixed、bottom 及其组合。