Render XeTeX OpenType math accents and stretch constructions
This commit is contained in:
1 parent
01b3931ae0
commit
821631778e
16 files changed
+825
-144
No files matched your search
@@ -245,6 +245,7 @@ impl Executor {
|
||||
class,
|
||||
limits: OperatorLimits::Display,
|
||||
accent: None,
|
||||
accent_style: AccentStyle::default(),
|
||||
rule: None,
|
||||
vcenter: false,
|
||||
nucleus,
|
||||
@@ -706,12 +707,28 @@ impl Executor {
|
||||
n.source.operator = PaintSource::token(TokenOrigin::from(token));
|
||||
b.pending = Some(FieldTarget::Nucleus(i));
|
||||
}
|
||||
Mathaccent => {
|
||||
let code = self.integer(files)?;
|
||||
if !(0..32768).contains(&code) {
|
||||
return self.fail("mathaccent must be in 0..32767");
|
||||
}
|
||||
let (_, accent) = self.decode_math_char(code as u16);
|
||||
Mathaccent | Umathaccent => {
|
||||
let (accent, accent_style) = if *p == Umathaccent {
|
||||
let mode = if self.keyword("fixed", files)? {
|
||||
AccentStyle::Fixed
|
||||
} else if self.keyword("bottom", files)? {
|
||||
if self.keyword("fixed", files)? {
|
||||
AccentStyle::BottomFixed
|
||||
} else {
|
||||
AccentStyle::Bottom
|
||||
}
|
||||
} else {
|
||||
AccentStyle::Top
|
||||
};
|
||||
let code = self.scan_unicode_math_code(true, files)?;
|
||||
(self.explicit_math_code(code)?.1, mode)
|
||||
} else {
|
||||
let code = self.integer(files)?;
|
||||
if !(0..32768).contains(&code) {
|
||||
return self.fail("mathaccent must be in 0..32767");
|
||||
}
|
||||
(self.decode_math_char(code as u16).1, AccentStyle::Top)
|
||||
};
|
||||
self.new_noad(NoadClass::Ord, MathField::Empty, token.span);
|
||||
let b = self.math.last_mut().unwrap();
|
||||
let i = b.nodes.len() - 1;
|
||||
@@ -719,6 +736,7 @@ impl Executor {
|
||||
unreachable!()
|
||||
};
|
||||
n.accent = Some(accent);
|
||||
n.accent_style = accent_style;
|
||||
n.source.operator = PaintSource::token(TokenOrigin::from(token));
|
||||
b.pending = Some(FieldTarget::Nucleus(i));
|
||||
}
|
||||
|
||||
@@ -8,9 +8,9 @@ use std::{
|
||||
sync::{Arc, Mutex, OnceLock, Weak},
|
||||
};
|
||||
|
||||
const SCHEMA: u32 = 66;
|
||||
const COMPATIBLE_SCHEMAS: [u32; 33] = [
|
||||
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, SCHEMA,
|
||||
const SCHEMA: u32 = 67;
|
||||
const COMPATIBLE_SCHEMAS: [u32; 34] = [
|
||||
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, SCHEMA,
|
||||
];
|
||||
const ENGINE: &str = concat!("texrra-native/", env!("CARGO_PKG_VERSION"));
|
||||
|
||||
|
||||
@@ -149,12 +149,37 @@ pub enum MathRulePosition {
|
||||
Over,
|
||||
Under,
|
||||
}
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
|
||||
pub enum AccentStyle {
|
||||
#[default]
|
||||
Top,
|
||||
Fixed,
|
||||
Bottom,
|
||||
BottomFixed,
|
||||
}
|
||||
|
||||
impl AccentStyle {
|
||||
fn is_default(&self) -> bool {
|
||||
*self == Self::Top
|
||||
}
|
||||
|
||||
pub(super) fn bottom(self) -> bool {
|
||||
matches!(self, Self::Bottom | Self::BottomFixed)
|
||||
}
|
||||
|
||||
pub(super) fn fixed(self) -> bool {
|
||||
matches!(self, Self::Fixed | Self::BottomFixed)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
|
||||
pub struct Noad {
|
||||
pub source: NoadSource,
|
||||
pub class: NoadClass,
|
||||
pub limits: OperatorLimits,
|
||||
pub accent: Option<MathChar>,
|
||||
#[serde(default, skip_serializing_if = "AccentStyle::is_default")]
|
||||
pub accent_style: AccentStyle,
|
||||
pub rule: Option<MathRulePosition>,
|
||||
/// A vcenter noad retains its natural vertical box until math conversion,
|
||||
/// when the current style selects the symbol font's mathematical axis.
|
||||
@@ -363,11 +388,7 @@ pub(super) struct Converter<'a> {
|
||||
pub node_limit: usize,
|
||||
}
|
||||
impl Converter<'_> {
|
||||
pub(super) fn font(
|
||||
&self,
|
||||
family: u8,
|
||||
style: MathStyle,
|
||||
) -> Result<&std::sync::Arc<crate::native_font::NativeFont>, String> {
|
||||
pub(super) fn family_font(&self, family: u8, style: MathStyle) -> Result<FontId, String> {
|
||||
let id = self.state.math_font(style.size_index() as u8, family);
|
||||
if id == FontId::NULL {
|
||||
return Err(format!(
|
||||
@@ -375,38 +396,49 @@ impl Converter<'_> {
|
||||
style.size_index()
|
||||
));
|
||||
}
|
||||
self.state.fonts.glyph_font(id).map_err(|_| {
|
||||
format!("native math family {family} size {} requires OpenType math layout here", style.size_index())
|
||||
})
|
||||
Ok(id)
|
||||
}
|
||||
|
||||
pub(super) fn font(
|
||||
&self,
|
||||
family: u8,
|
||||
style: MathStyle,
|
||||
) -> Result<&std::sync::Arc<crate::native_font::NativeFont>, String> {
|
||||
self.state.fonts.glyph_font(self.family_font(family, style)?)
|
||||
}
|
||||
|
||||
pub fn validate(&self) -> Result<(), String> {
|
||||
for s in [MathStyle::Text, MathStyle::Script, MathStyle::ScriptScript] {
|
||||
if self
|
||||
.state
|
||||
.fonts
|
||||
.font(self.font(2, s)?.id)?
|
||||
.parameters()
|
||||
.len()
|
||||
< 22
|
||||
|| self
|
||||
.state
|
||||
.fonts
|
||||
.font(self.font(3, s)?.id)?
|
||||
.parameters()
|
||||
.len()
|
||||
< 13
|
||||
{
|
||||
return Err("insufficient native symbol/extension font parameters".into());
|
||||
for style in [MathStyle::Text, MathStyle::Script, MathStyle::ScriptScript] {
|
||||
for (family, required) in [(2, 22), (3, 13)] {
|
||||
let font = self.state.fonts.font(self.family_font(family, style)?)?;
|
||||
let sufficient = if let Some(font) = font.opentype() {
|
||||
crate::opentype::MathConstants::read(font)?.is_some()
|
||||
} else {
|
||||
font.parameters().len() >= required
|
||||
};
|
||||
if !sufficient {
|
||||
return Err("insufficient native symbol/extension font parameters".into());
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(super) fn params(&self, style: MathStyle) -> Result<MathParams, String> {
|
||||
let symbol = self.state.fonts.font(self.font(2, style)?.id)?.parameters();
|
||||
let extension = self.state.fonts.font(self.font(3, style)?.id)?.parameters();
|
||||
use crate::opentype::MathConstants;
|
||||
let symbol = self.state.fonts.font(self.family_font(2, style)?)?;
|
||||
let extension = self.state.fonts.font(self.family_font(3, style)?)?;
|
||||
let symbol_math = symbol.opentype().map(|font| MathConstants::read(font)).transpose()?.flatten();
|
||||
let extension_math = extension.opentype().map(|font| MathConstants::read(font)).transpose()?.flatten();
|
||||
Ok(MathParams::from_parameters(
|
||||
|n| i64::from(symbol[n]),
|
||||
|n| i64::from(extension[n]),
|
||||
|n| symbol_math.as_ref().map_or_else(
|
||||
|| i64::from(symbol.parameters()[n]),
|
||||
|math| math.symbol_parameter(n),
|
||||
),
|
||||
|n| extension_math.as_ref().map_or_else(
|
||||
|| i64::from(extension.parameters()[n]),
|
||||
|math| math.extension_parameter(n),
|
||||
),
|
||||
))
|
||||
}
|
||||
pub(super) fn has_math_char(&self, id: FontId, slot: u32) -> Result<bool, String> {
|
||||
@@ -427,7 +459,7 @@ impl Converter<'_> {
|
||||
let font = self.state.math_font(style.size_index() as u8, c.family);
|
||||
if font == FontId::NULL {
|
||||
// Keep the same diagnostic as the legacy fetch path.
|
||||
self.font(c.family, style)?;
|
||||
self.family_font(c.family, style)?;
|
||||
}
|
||||
if !self.has_math_char(font, c.slot)? {
|
||||
self.missing.borrow_mut().push((font, c.slot));
|
||||
@@ -580,10 +612,7 @@ impl Converter<'_> {
|
||||
// A missing accent leaves an ordinary fetched nucleus,
|
||||
// including its character/trailing-kern visibility.
|
||||
if let Some(accent) = n.accent {
|
||||
self.font(accent.family, style)?;
|
||||
let font = self
|
||||
.state
|
||||
.math_font(style.size_index() as u8, accent.family);
|
||||
let font = self.family_font(accent.family, style)?;
|
||||
if !self.has_math_char(font, accent.slot)? {
|
||||
self.missing.borrow_mut().push((font, accent.slot));
|
||||
n.accent = None;
|
||||
|
||||
@@ -1,41 +1,51 @@
|
||||
//! TeX make_math_accent over actual font state and measured native noads.
|
||||
use super::{math::*, *};
|
||||
use crate::math_engine_tex::{MathGeometry, MathStyle, place_scripts};
|
||||
use crate::{
|
||||
math_engine_tex::{MathGeometry, MathStyle, place_scripts},
|
||||
opentype::{self, MathConstants, Stretch},
|
||||
};
|
||||
impl Converter<'_> {
|
||||
pub(super) fn accent(&self, original: &Noad, style: MathStyle) -> Result<MathGeometry, String> {
|
||||
let mut n = original.clone();
|
||||
let mut accent = n.accent.take().unwrap();
|
||||
let id = self.font(accent.family, style)?;
|
||||
let font = self
|
||||
.state
|
||||
.math_font(style.size_index() as u8, accent.family);
|
||||
let font = self.family_font(accent.family, style)?;
|
||||
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_id = self.font(c.family, style)?;
|
||||
let base_font = self.state.math_font(style.size_index() as u8, c.family);
|
||||
let base_font = self.family_font(c.family, style)?;
|
||||
if !self.has_math_char(base_font, c.slot)? {
|
||||
self.missing.borrow_mut().push((base_font, c.slot));
|
||||
n.nucleus = MathField::Empty;
|
||||
} else if let Ok(code) = u8::try_from(self.state.font_integers(base_font).skew) {
|
||||
skew = base_id.metrics().kern(char::from(c.slot as u8), char::from(code));
|
||||
} else if opentype.is_none()
|
||||
&& let Ok(code) = u8::try_from(self.state.font_integers(base_font).skew)
|
||||
&& let Ok(base_id) = self.state.fonts.glyph_font(base_font)
|
||||
&& let Ok(slot) = u8::try_from(c.slot)
|
||||
{
|
||||
skew = base_id.metrics().kern(char::from(slot), char::from(code));
|
||||
}
|
||||
}
|
||||
let mut base = self.field(&n.nucleus, style.cramped_style(), &n.source.nucleus)?;
|
||||
let width = base.metrics.width;
|
||||
let mut height = base.metrics.height;
|
||||
// Larger accents are chosen by actual TFM list tags and advance widths.
|
||||
let metrics = id.metrics();
|
||||
let mut visited = std::collections::BTreeSet::new();
|
||||
while let Some(next) = metrics.next_larger(char::from(accent.slot as u8)) {
|
||||
if !visited.insert(accent.slot) {
|
||||
return Err("cyclic native accent size list".into());
|
||||
let attachment = if opentype.is_some() && !bottom {
|
||||
self.accent_base_attachment(&n.nucleus, style, &n.source.nucleus)?
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let accent_height = if let Some(face) = opentype
|
||||
&& let Some(math) = MathConstants::read(face)?
|
||||
{
|
||||
if bottom {
|
||||
0
|
||||
} else {
|
||||
math.measure(math.values.accent_base_height())
|
||||
}
|
||||
if !self.state.font_has_slot(font, next) || metrics.width(char::from(next)) > width {
|
||||
break;
|
||||
}
|
||||
accent.slot = u32::from(next);
|
||||
}
|
||||
let mut delta = height.min(i64::from(self.state.fonts.font(font)?.x_height()));
|
||||
} else {
|
||||
i64::from(accent_font.x_height())
|
||||
};
|
||||
let mut delta = height.min(accent_height);
|
||||
if matches!(n.nucleus, MathField::Char(_)) && (n.sub.is_some() || n.sup.is_some()) {
|
||||
// TeX moves scripts inside the nucleus, preserving the original
|
||||
// un-scripted width for accent centering and choosing the variant.
|
||||
@@ -50,16 +60,78 @@ impl Converter<'_> {
|
||||
.operator
|
||||
.clone()
|
||||
.derived(crate::provenance::Derivation::Accent);
|
||||
let (mark, _) = self.glyph(accent, style, &source)?;
|
||||
let x = skew + (width - mark.metrics.width + 1).div_euclid(2);
|
||||
let y = -base.metrics.height + delta - mark.metrics.depth;
|
||||
let (mark, x) = if let Some(face) = opentype {
|
||||
let (mut glyph, italic) = self.glyph(accent, style, &source)?;
|
||||
glyph.metrics.width -= italic;
|
||||
let original = opentype::single_glyph(&glyph).ok_or("missing OpenType accent glyph")?;
|
||||
let positioned = if n.accent_style.fixed() {
|
||||
(glyph, Some(original))
|
||||
} else {
|
||||
let character =
|
||||
char::from_u32(accent.slot).ok_or("invalid OpenType accent scalar")?;
|
||||
let stretched = opentype::stretch_glyph(
|
||||
face,
|
||||
original,
|
||||
character,
|
||||
&source,
|
||||
Stretch::Horizontal,
|
||||
width,
|
||||
self.delimiter_glyph_limit
|
||||
.saturating_sub(self.delimiter_glyphs.get()),
|
||||
)?;
|
||||
self.reserve_delimiter_glyphs(stretched.geometry.items.len())?;
|
||||
(stretched.geometry, stretched.glyph)
|
||||
};
|
||||
let (mut mark, selected) = positioned;
|
||||
let anchor = selected
|
||||
.map(|glyph| opentype::accent_attachment(face, glyph))
|
||||
.transpose()?
|
||||
.unwrap_or((mark.metrics.width + 1).div_euclid(2));
|
||||
if bottom {
|
||||
mark.metrics.height = mark.metrics.height.max(0);
|
||||
} else {
|
||||
mark.metrics.depth = mark.metrics.depth.max(0);
|
||||
}
|
||||
let x = attachment.unwrap_or((width + 1).div_euclid(2)) - anchor;
|
||||
(mark, x)
|
||||
} else {
|
||||
// Classic accents choose the last TFM list tag that fits the base.
|
||||
let id = self.font(accent.family, style)?;
|
||||
let metrics = id.metrics();
|
||||
let mut visited = std::collections::BTreeSet::new();
|
||||
while let Some(next) = metrics.next_larger(char::from(accent.slot as u8)) {
|
||||
if !visited.insert(accent.slot) {
|
||||
return Err("cyclic native accent size list".into());
|
||||
}
|
||||
if !self.state.font_has_slot(font, next) || metrics.width(char::from(next)) > width
|
||||
{
|
||||
break;
|
||||
}
|
||||
accent.slot = u32::from(next);
|
||||
}
|
||||
let (mark, _) = self.glyph(accent, style, &source)?;
|
||||
let x = skew + (width - mark.metrics.width + 1).div_euclid(2);
|
||||
(mark, x)
|
||||
};
|
||||
let y = if bottom {
|
||||
base.metrics.depth + mark.metrics.height
|
||||
} else {
|
||||
-base.metrics.height + delta - mark.metrics.depth
|
||||
};
|
||||
let result_width = base.metrics.width;
|
||||
let result_depth = base.metrics.depth;
|
||||
let result_height =
|
||||
height.max(base.metrics.height + mark.metrics.height + mark.metrics.depth - delta);
|
||||
let (result_height, result_depth) = if bottom {
|
||||
(base.metrics.height, y + mark.metrics.depth)
|
||||
} else {
|
||||
(height.max(mark.metrics.height - y), base.metrics.depth)
|
||||
};
|
||||
let mut result = MathGeometry::default();
|
||||
result.append(mark, x, y);
|
||||
result.append(base, 0, 0);
|
||||
if bottom {
|
||||
result.append(base, 0, 0);
|
||||
result.append(mark, x, y);
|
||||
} else {
|
||||
result.append(mark, x, y);
|
||||
result.append(base, 0, 0);
|
||||
}
|
||||
result.metrics.width = result_width;
|
||||
result.metrics.height = result_height;
|
||||
result.metrics.depth = result_depth;
|
||||
@@ -88,4 +160,36 @@ impl Converter<'_> {
|
||||
self.state.parameter(Parameter::Scriptspace).width() as i64,
|
||||
))
|
||||
}
|
||||
|
||||
fn accent_base_attachment<'a>(
|
||||
&self,
|
||||
mut field: &'a MathField,
|
||||
style: MathStyle,
|
||||
mut source: &'a FieldSource,
|
||||
) -> Result<Option<i64>, String> {
|
||||
while let MathField::List(list) = field {
|
||||
let Some(MathNode::Noad(noad)) = list.first() else {
|
||||
return Ok(None);
|
||||
};
|
||||
if noad.accent.is_none() {
|
||||
return Ok(None);
|
||||
}
|
||||
field = &noad.nucleus;
|
||||
source = &noad.source.nucleus;
|
||||
}
|
||||
let MathField::Char(base) = *field else {
|
||||
return Ok(None);
|
||||
};
|
||||
let font = self
|
||||
.state
|
||||
.fonts
|
||||
.font(self.family_font(base.family, style)?)?;
|
||||
let Some(face) = font.opentype() else {
|
||||
return Ok(None);
|
||||
};
|
||||
let (geometry, _) = self.glyph(base, style, &source.paint)?;
|
||||
opentype::single_glyph(&geometry)
|
||||
.map(|glyph| opentype::accent_attachment(face, glyph))
|
||||
.transpose()
|
||||
}
|
||||
}
|
||||
@@ -51,7 +51,7 @@ impl Converter<'_> {
|
||||
metrics.depth,
|
||||
))
|
||||
}
|
||||
fn reserve_delimiter_glyphs(&self, n: usize) -> Result<(), String> {
|
||||
pub(super) fn reserve_delimiter_glyphs(&self, n: usize) -> Result<(), String> {
|
||||
let used = self
|
||||
.delimiter_glyphs
|
||||
.get()
|
||||
@@ -95,6 +95,7 @@ impl Converter<'_> {
|
||||
source: &PaintSource,
|
||||
) -> Result<NativeBox, String> {
|
||||
let mut best = None;
|
||||
let mut opentype_best = None;
|
||||
let mut largest = 0;
|
||||
'search: for c in [value.small, value.large] {
|
||||
// (family 0, slot 0) is the null delimiter, not a Gamma request.
|
||||
@@ -106,8 +107,22 @@ impl Converter<'_> {
|
||||
if font == FontId::NULL {
|
||||
continue;
|
||||
}
|
||||
if self.state.fonts.font(font)?.opentype().is_some() {
|
||||
return Err("native OpenType delimiter requires MATH variants and assemblies".into());
|
||||
if let Some(face) = self.state.fonts.font(font)?.opentype() {
|
||||
let Some(character) = char::from_u32(c.slot) else { continue };
|
||||
let Some(glyph) = face.face()?.glyph_index(character) else { continue };
|
||||
let shaped = crate::opentype::stretch_glyph(
|
||||
face, glyph.0, character, source, crate::opentype::Stretch::Vertical, target,
|
||||
self.delimiter_glyph_limit.saturating_sub(self.delimiter_glyphs.get()),
|
||||
)?;
|
||||
let metrics = shaped.geometry.metrics;
|
||||
let enough = shaped.sufficient;
|
||||
largest = metrics.height + metrics.depth;
|
||||
best = None;
|
||||
opentype_best = Some(shaped.geometry);
|
||||
if enough {
|
||||
break 'search;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
let id = self.state.fonts.glyph_font(font)?;
|
||||
let m = id.metrics();
|
||||
@@ -120,12 +135,14 @@ impl Converter<'_> {
|
||||
return Err("cyclic native delimiter size list".into());
|
||||
}
|
||||
if m.extensible_recipe(char::from(slot)).is_some() {
|
||||
opentype_best = None;
|
||||
best = Some((id, slot));
|
||||
break 'search;
|
||||
}
|
||||
let extent = m.height(char::from(slot)) + m.depth(char::from(slot));
|
||||
if extent > largest {
|
||||
largest = extent;
|
||||
opentype_best = None;
|
||||
best = Some((id, slot));
|
||||
if extent >= target {
|
||||
break 'search;
|
||||
@@ -138,7 +155,14 @@ impl Converter<'_> {
|
||||
}
|
||||
}
|
||||
}
|
||||
let result = if let Some((id, slot)) = best {
|
||||
let result = if let Some(geometry) = opentype_best {
|
||||
self.reserve_delimiter_glyphs(geometry.items.len())?;
|
||||
let metrics = geometry.metrics;
|
||||
delimiter_native_box(
|
||||
BoxContent::Horizontal(vec![TextNode::Box(super::math::math_box(geometry))]),
|
||||
metrics.width, metrics.height, metrics.depth,
|
||||
)
|
||||
} else if let Some((id, slot)) = best {
|
||||
if let Some(recipe) = id.metrics().extensible_recipe(char::from(slot)) {
|
||||
let repeat = character(id, recipe.repeat, source)?;
|
||||
let unit = repeat.metrics.height + repeat.metrics.depth;
|
||||
@@ -219,13 +243,26 @@ impl Converter<'_> {
|
||||
source.radical.as_deref().unwrap_or(&FieldSource::UNKNOWN),
|
||||
)?;
|
||||
let extent = body.metrics.height + body.metrics.depth;
|
||||
let thickness = params.rule_thickness;
|
||||
let mut clearance = thickness
|
||||
+ if style.display() {
|
||||
let id = self.state.math_font(style.size_index() as u8, delimiter.small.family);
|
||||
let selected = self.state.fonts.font(id)?;
|
||||
let constants = selected.opentype().map(|font| crate::opentype::MathConstants::read(font))
|
||||
.transpose()?.flatten();
|
||||
let (thickness, mut clearance) = if let Some(math) = &constants {
|
||||
let gap = if style.display() {
|
||||
math.values.radical_display_style_vertical_gap()
|
||||
} else {
|
||||
math.values.radical_vertical_gap()
|
||||
};
|
||||
(math.measure(math.values.radical_rule_thickness()), math.measure(gap))
|
||||
} else {
|
||||
let thickness = params.rule_thickness;
|
||||
let clearance = thickness + if style.display() {
|
||||
params.x_height.abs()
|
||||
} else {
|
||||
thickness.abs()
|
||||
} / 4;
|
||||
(thickness, clearance)
|
||||
};
|
||||
let sign_source = source.paint.clone().derived(Derivation::Radical);
|
||||
let mut sign = self.delimiter_box(
|
||||
delimiter,
|
||||
@@ -233,6 +270,14 @@ impl Converter<'_> {
|
||||
extent + clearance + thickness,
|
||||
&sign_source,
|
||||
)?;
|
||||
if constants.is_some() {
|
||||
let baseline = sign.metrics.height - thickness;
|
||||
for item in &mut sign.items {
|
||||
item.y += baseline;
|
||||
}
|
||||
sign.metrics.depth += baseline;
|
||||
sign.metrics.height = thickness;
|
||||
}
|
||||
let excess = sign.metrics.depth - extent - clearance;
|
||||
if excess > 0 {
|
||||
clearance += (excess + 1) / 2;
|
||||
|
||||
@@ -14,6 +14,12 @@ impl Converter<'_> {
|
||||
) -> Result<NativeBox, String> {
|
||||
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
|
||||
.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)?;
|
||||
@@ -36,7 +42,15 @@ impl Converter<'_> {
|
||||
};
|
||||
let half = (thickness + 1).div_euclid(2);
|
||||
if thickness == 0 {
|
||||
let clearance = if style.display() { 7 } else { 3 } * params.rule_thickness;
|
||||
let clearance = if let Some(math) = &constants {
|
||||
math.measure(if style.display() {
|
||||
math.values.stack_display_style_gap_min()
|
||||
} else {
|
||||
math.values.stack_gap_min()
|
||||
})
|
||||
} else {
|
||||
(if style.display() { 7 } else { 3 }) * params.rule_thickness
|
||||
};
|
||||
let delta =
|
||||
(clearance - ((up - upper.depth) - (lower.height - down)) + 1).div_euclid(2);
|
||||
if delta > 0 {
|
||||
@@ -44,13 +58,29 @@ impl Converter<'_> {
|
||||
down += delta;
|
||||
}
|
||||
} else {
|
||||
let clearance = if style.display() {
|
||||
3 * thickness
|
||||
let (above, below) = if let Some(math) = &constants {
|
||||
let (above, below) = if style.display() {
|
||||
(
|
||||
math.values.fraction_num_display_style_gap_min(),
|
||||
math.values.fraction_denom_display_style_gap_min(),
|
||||
)
|
||||
} else {
|
||||
(
|
||||
math.values.fraction_numerator_gap_min(),
|
||||
math.values.fraction_denominator_gap_min(),
|
||||
)
|
||||
};
|
||||
(math.measure(above), math.measure(below))
|
||||
} else {
|
||||
thickness
|
||||
let clearance = if style.display() {
|
||||
3 * thickness
|
||||
} else {
|
||||
thickness
|
||||
};
|
||||
(clearance, clearance)
|
||||
};
|
||||
up = up.max(upper.depth + params.axis_height + half + clearance);
|
||||
down = down.max(lower.height - params.axis_height + half + clearance);
|
||||
up = up.max(upper.depth + params.axis_height + half + above);
|
||||
down = down.max(lower.height - params.axis_height + half + below);
|
||||
}
|
||||
let width = upper.width;
|
||||
let height = up + upper.height;
|
||||
|
||||
@@ -85,27 +85,48 @@ impl Converter<'_> {
|
||||
None
|
||||
};
|
||||
let (mut body, italic) = if let MathField::Char(mut c) = n.nucleus {
|
||||
let face = self.font(c.family, style)?;
|
||||
let id = self.family_font(c.family, style)?;
|
||||
let mut source = n.source.nucleus.clone();
|
||||
let (mut b, italic) = if !self.has_math_char(face.id, c.slot)? {
|
||||
self.missing.borrow_mut().push((face.id, c.slot));
|
||||
let font = self.state.fonts.font(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)
|
||||
} else if let Some(face) = font.opentype() {
|
||||
use crate::opentype::{self, MathConstants, Stretch};
|
||||
let (mut body, mut italic) = self.glyph(c, style, &source.paint)?;
|
||||
body.metrics.width -= italic;
|
||||
if style.display() && let Some(math) = MathConstants::read(face)? {
|
||||
let min = crate::opentype::scale_units(
|
||||
i64::from(math.values.display_operator_min_height()),
|
||||
face.size, face.face()?.units_per_em(),
|
||||
);
|
||||
let target = min.max((body.metrics.height + body.metrics.depth) * 5 / 4);
|
||||
let glyph = opentype::single_glyph(&body).ok_or("missing OpenType operator glyph")?;
|
||||
let character = char::from_u32(c.slot).ok_or("invalid OpenType operator scalar")?;
|
||||
let variant = opentype::stretch_glyph(
|
||||
face, glyph, character,
|
||||
&source.paint.clone().derived(crate::provenance::Derivation::MathVariant),
|
||||
Stretch::Vertical, target,
|
||||
self.delimiter_glyph_limit.saturating_sub(self.delimiter_glyphs.get()),
|
||||
)?;
|
||||
self.reserve_delimiter_glyphs(variant.geometry.items.len())?;
|
||||
body = variant.geometry;
|
||||
italic = variant.italic;
|
||||
}
|
||||
(self.pack_field(vec![TextNode::MathChar(super::math::math_box(body))])?, italic)
|
||||
} else {
|
||||
if style.display() {
|
||||
if let Some(next) = face.metrics().next_larger(char::from(c.slot as u8)) {
|
||||
if self.state.font_has_slot(face.id, next) {
|
||||
c.slot = u32::from(next);
|
||||
source.paint = source
|
||||
.paint
|
||||
.derived(crate::provenance::Derivation::MathVariant);
|
||||
}
|
||||
}
|
||||
let face = self.font(c.family, style)?;
|
||||
if style.display()
|
||||
&& let Some(next) = face.metrics().next_larger(char::from(c.slot as u8))
|
||||
&& self.state.font_has_slot(id, next)
|
||||
{
|
||||
c.slot = u32::from(next);
|
||||
source.paint = source
|
||||
.paint
|
||||
.derived(crate::provenance::Derivation::MathVariant);
|
||||
}
|
||||
let italic = face.metrics().italic(char::from(c.slot as u8));
|
||||
(
|
||||
self.owned_field(&MathField::Char(c), style, &source)?,
|
||||
italic,
|
||||
)
|
||||
(self.owned_field(&MathField::Char(c), style, &source)?, italic)
|
||||
};
|
||||
if n.sub.is_some() && !limits {
|
||||
b.width -= italic;
|
||||
|
||||
@@ -101,6 +101,7 @@ impl Converter<'_> {
|
||||
class: NoadClass::Ord,
|
||||
limits: OperatorLimits::Display,
|
||||
accent: None,
|
||||
accent_style: AccentStyle::default(),
|
||||
rule: None,
|
||||
vcenter: false,
|
||||
nucleus: if operation == 11 {
|
||||
|
||||
@@ -126,6 +126,25 @@ impl Converter<'_> {
|
||||
.as_ref()
|
||||
.map(|f| self.owned_field(f, style.sub(), &n.source.sub))
|
||||
.transpose()?;
|
||||
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()
|
||||
&& let Some(math) = crate::opentype::MathConstants::read(face)?
|
||||
{
|
||||
Some(geometry::ScriptBounds {
|
||||
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(),
|
||||
),
|
||||
})
|
||||
} else {
|
||||
None
|
||||
}
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let (_, placement) = geometry::place_scripts_with_layout(
|
||||
body,
|
||||
upper.as_ref().map(NativeBox::geometry).transpose()?,
|
||||
@@ -136,6 +155,7 @@ impl Converter<'_> {
|
||||
self.params(style.sup())?,
|
||||
style,
|
||||
i64::from(self.state.parameter(Parameter::Scriptspace).width()),
|
||||
script_bounds,
|
||||
);
|
||||
let space = i64::from(self.state.parameter(Parameter::Scriptspace).width());
|
||||
let scripts = match (upper, lower) {
|
||||
|
||||
@@ -72,7 +72,7 @@ pub use job::{IoState, JobParameter, JobTime, OutputNode, OutputOperation, Write
|
||||
pub use marks::{NativeAdjustment, NativeMark, PageMarks, SplitMarks};
|
||||
pub(crate) use math::paint_native_math;
|
||||
pub use math::{
|
||||
Delimiter, FieldSource, FractionSpec, MathChar, MathField, MathNode, MathRulePosition,
|
||||
AccentStyle, Delimiter, FieldSource, FractionSpec, MathChar, MathField, MathNode, MathRulePosition,
|
||||
NativeDisplay, NativeMath, Noad, NoadClass, NoadSource, OperatorLimits,
|
||||
};
|
||||
pub use math_code::MathCode;
|
||||
|
||||
@@ -380,6 +380,7 @@ pub enum Primitive {
|
||||
Udelcodenum,
|
||||
Udelimiter,
|
||||
Uradical,
|
||||
Umathaccent,
|
||||
}
|
||||
|
||||
impl Primitive {
|
||||
@@ -882,6 +883,8 @@ const XETEX_PRIMITIVE_ALIASES: &[(&str, Primitive)] = {
|
||||
("XeTeXdelimiter", Udelimiter),
|
||||
("Uradical", Uradical),
|
||||
("XeTeXradical", Uradical),
|
||||
("Umathaccent", Umathaccent),
|
||||
("XeTeXmathaccent", Umathaccent),
|
||||
]
|
||||
};
|
||||
|
||||
|
||||
@@ -150,6 +150,14 @@ pub struct MathParams {
|
||||
pub big_op_spacing: [i64; 5],
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub(crate) struct ScriptBounds {
|
||||
pub subscript_top_max: i64,
|
||||
pub superscript_bottom_min: i64,
|
||||
pub paired_gap: i64,
|
||||
pub paired_superscript_bottom: i64,
|
||||
}
|
||||
|
||||
impl MathParams {
|
||||
pub fn for_style(style: MathStyle) -> Self {
|
||||
Self::from_metrics(
|
||||
@@ -523,6 +531,7 @@ pub(crate) fn place_scripts(
|
||||
drop,
|
||||
style,
|
||||
script_space,
|
||||
None,
|
||||
)
|
||||
.0
|
||||
}
|
||||
@@ -541,8 +550,15 @@ pub(crate) fn place_scripts_with_layout(
|
||||
drop: MathParams,
|
||||
style: MathStyle,
|
||||
script_space: i64,
|
||||
script_bounds: Option<ScriptBounds>,
|
||||
) -> (MathGeometry, ScriptPlacement) {
|
||||
let has_sub = lower.is_some();
|
||||
let bounds = script_bounds.unwrap_or(ScriptBounds {
|
||||
subscript_top_max: 4 * params.x_height.abs() / 5,
|
||||
superscript_bottom_min: params.x_height.abs() / 4,
|
||||
paired_gap: 4 * params.rule_thickness,
|
||||
paired_superscript_bottom: 4 * params.x_height.abs() / 5,
|
||||
});
|
||||
let mut up = if single {
|
||||
0
|
||||
} else {
|
||||
@@ -563,22 +579,22 @@ pub(crate) fn place_scripts_with_layout(
|
||||
};
|
||||
up = up
|
||||
.max(min)
|
||||
.max(upper.metrics.depth + params.x_height.abs() / 4);
|
||||
.max(upper.metrics.depth + bounds.superscript_bottom_min);
|
||||
}
|
||||
if let Some(lower) = &lower {
|
||||
if let Some(upper) = &upper {
|
||||
down = down.max(params.sub2);
|
||||
let gap = up - upper.metrics.depth - lower.metrics.height + down;
|
||||
if gap < 4 * params.rule_thickness {
|
||||
down += 4 * params.rule_thickness - gap;
|
||||
let lift = (4 * params.x_height.abs() / 5 - (up - upper.metrics.depth)).max(0);
|
||||
if gap < bounds.paired_gap {
|
||||
down += bounds.paired_gap - gap;
|
||||
let lift = (bounds.paired_superscript_bottom - (up - upper.metrics.depth)).max(0);
|
||||
up += lift;
|
||||
down -= lift;
|
||||
}
|
||||
} else {
|
||||
down = down
|
||||
.max(params.sub1)
|
||||
.max(lower.metrics.height - 4 * params.x_height.abs() / 5);
|
||||
.max(lower.metrics.height - bounds.subscript_top_max);
|
||||
}
|
||||
}
|
||||
let start = body.metrics.width;
|
||||
|
||||
@@ -19,6 +19,8 @@ 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};
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
|
||||
pub(crate) struct Request {
|
||||
@@ -305,7 +307,15 @@ impl OpenTypeFont {
|
||||
.request
|
||||
.features
|
||||
.iter()
|
||||
.map(|feature| feature.parse::<Feature>())
|
||||
.map(|option| {
|
||||
let mut feature = option.parse::<Feature>()?;
|
||||
if option.starts_with('+') && option.contains('=') {
|
||||
// XeTeX's alternate indices start at zero. HarfBuzz
|
||||
// reserves zero for disabled features.
|
||||
feature.value = feature.value.saturating_add(1);
|
||||
}
|
||||
Ok::<_, &'static str>(feature)
|
||||
})
|
||||
.collect::<Result<_, _>>()
|
||||
.map_err(|_| "invalid OpenType feature in job state")?;
|
||||
let script = self
|
||||
@@ -475,45 +485,16 @@ pub(crate) fn math_glyph(
|
||||
character: char,
|
||||
source: &PaintSource,
|
||||
) -> Result<(crate::math_engine_tex::MathGeometry, i64), String> {
|
||||
use crate::{
|
||||
math::MathBox,
|
||||
math_engine_tex::{MathGeometry, MathItem, PositionedItem},
|
||||
};
|
||||
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 {
|
||||
let run = font.shape_mapped(text, sources, false)?;
|
||||
let [glyph] = run.glyphs.as_slice() else {
|
||||
return Err("OpenType math character did not select one glyph".into());
|
||||
};
|
||||
let face = font.face()?;
|
||||
let id = GlyphId(glyph.id);
|
||||
let scale = |value: i64| scale_units(value, font.size, face.units_per_em());
|
||||
let advance = scale(i64::from(face.glyph_hor_advance(id).unwrap_or(0)));
|
||||
let bounds = face.glyph_bounding_box(id);
|
||||
let height = scale(i64::from(bounds.map_or(0, |b| b.y_max)));
|
||||
let depth = scale(-i64::from(bounds.map_or(0, |b| b.y_min)));
|
||||
let italic = face
|
||||
.tables()
|
||||
.math
|
||||
.and_then(|table| table.glyph_info)
|
||||
.and_then(|info| info.italic_corrections)
|
||||
.and_then(|values| values.get(id))
|
||||
.map_or(0, |value| scale(i64::from(value.value)));
|
||||
glyph.x = 0;
|
||||
glyph.y = 0;
|
||||
glyph.advance = advance;
|
||||
run.width = advance;
|
||||
Ok((
|
||||
MathGeometry {
|
||||
metrics: MathBox { width: advance + italic, height, depth },
|
||||
items: vec![PositionedItem {
|
||||
source: source.clone(),
|
||||
x: 0,
|
||||
y: 0,
|
||||
item: MathItem::OpenType(Arc::new(run)),
|
||||
}],
|
||||
},
|
||||
italic,
|
||||
))
|
||||
let (mut geometry, italic) =
|
||||
math_layout::painted_glyph(font, &face, GlyphId(glyph.id), &run.text, source);
|
||||
geometry.metrics.width += italic;
|
||||
Ok((geometry, italic))
|
||||
}
|
||||
|
||||
pub(crate) fn horizontal_box(run: &Arc<OpenTypeRun>) -> crate::HorizontalBox {
|
||||
|
||||
@@ -105,7 +105,7 @@ pub(super) fn append_math_parameters(
|
||||
}
|
||||
}
|
||||
|
||||
fn math_constant_bytes<'a>(face: &ttf_parser::Face<'a>) -> Option<&'a [u8]> {
|
||||
pub(super) fn math_constant_bytes<'a>(face: &ttf_parser::Face<'a>) -> Option<&'a [u8]> {
|
||||
let table = face.raw_face().table(Tag::from_bytes(b"MATH"))?;
|
||||
face.tables().math?.constants?;
|
||||
let offset = usize::from(u16::from_be_bytes(table.get(4..6)?.try_into().ok()?));
|
||||
|
||||
@@ -0,0 +1,382 @@
|
||||
//! Measurements and stretch constructions from a selected OpenType MATH face.
|
||||
use super::*;
|
||||
use crate::{
|
||||
math::MathBox,
|
||||
math_engine_tex::{MathGeometry, MathItem, PositionedItem},
|
||||
};
|
||||
use ttf_parser::math::{Constants, GlyphConstruction, MathValue, Variants};
|
||||
|
||||
pub(crate) struct MathConstants<'a> {
|
||||
pub(crate) values: Constants<'a>,
|
||||
size: i64,
|
||||
units: u16,
|
||||
}
|
||||
|
||||
impl<'a> MathConstants<'a> {
|
||||
pub(crate) fn read(font: &'a OpenTypeFont) -> Result<Option<Self>, String> {
|
||||
let face = font.face()?;
|
||||
if font_info::math_constant_bytes(&face).is_none() {
|
||||
return Ok(None);
|
||||
}
|
||||
Ok(face
|
||||
.tables()
|
||||
.math
|
||||
.and_then(|table| table.constants)
|
||||
.map(|values| Self {
|
||||
values,
|
||||
size: font.size,
|
||||
units: face.units_per_em(),
|
||||
}))
|
||||
}
|
||||
|
||||
pub(crate) fn measure(&self, value: MathValue<'_>) -> i64 {
|
||||
scale_units(i64::from(value.value), self.size, self.units)
|
||||
}
|
||||
|
||||
pub(crate) fn symbol_parameter(&self, index: usize) -> i64 {
|
||||
let c = &self.values;
|
||||
match index {
|
||||
5 => return self.size,
|
||||
19 => {
|
||||
return scale_units(
|
||||
i64::from(c.delimited_sub_formula_min_height()),
|
||||
self.size,
|
||||
self.units,
|
||||
);
|
||||
}
|
||||
20 => return (3 * self.size / 2).min(self.symbol_parameter(19)),
|
||||
_ => {}
|
||||
}
|
||||
self.measure(match index {
|
||||
4 => c.accent_base_height(),
|
||||
7 => c.fraction_numerator_display_style_shift_up(),
|
||||
8 => c.fraction_numerator_shift_up(),
|
||||
9 => c.stack_top_shift_up(),
|
||||
10 => c.fraction_denominator_display_style_shift_down(),
|
||||
11 => c.fraction_denominator_shift_down(),
|
||||
12 | 13 => c.superscript_shift_up(),
|
||||
14 => c.superscript_shift_up_cramped(),
|
||||
15 | 16 => c.subscript_shift_down(),
|
||||
17 => c.superscript_baseline_drop_max(),
|
||||
18 => c.subscript_baseline_drop_min(),
|
||||
21 => c.axis_height(),
|
||||
_ => unreachable!("math symbol parameter index"),
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn extension_parameter(&self, index: usize) -> i64 {
|
||||
let c = &self.values;
|
||||
self.measure(match index {
|
||||
7 => c.fraction_rule_thickness(),
|
||||
8 => c.upper_limit_gap_min(),
|
||||
9 => c.lower_limit_gap_min(),
|
||||
10 => c.upper_limit_baseline_rise_min(),
|
||||
11 => c.lower_limit_baseline_drop_min(),
|
||||
12 => c.stack_gap_min(),
|
||||
_ => unreachable!("math extension parameter index"),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn single_glyph(geometry: &MathGeometry) -> Option<u16> {
|
||||
let [item] = geometry.items.as_slice() else {
|
||||
return None;
|
||||
};
|
||||
match &item.item {
|
||||
MathItem::OpenType(run) if run.glyphs.len() == 1 => Some(run.glyphs[0].id),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn accent_attachment(font: &OpenTypeFont, glyph: u16) -> Result<i64, String> {
|
||||
let face = font.face()?;
|
||||
let id = GlyphId(glyph);
|
||||
let position = face
|
||||
.tables()
|
||||
.math
|
||||
.and_then(|table| table.glyph_info)
|
||||
.and_then(|info| info.top_accent_attachments)
|
||||
.and_then(|values| values.get(id))
|
||||
.map_or_else(
|
||||
|| i64::from(face.glyph_hor_advance(id).unwrap_or(0)) / 2,
|
||||
|value| i64::from(value.value),
|
||||
);
|
||||
Ok(scale_units(position, font.size, face.units_per_em()))
|
||||
}
|
||||
|
||||
pub(crate) fn painted_glyph(
|
||||
font: &Arc<OpenTypeFont>,
|
||||
face: &ttf_parser::Face<'_>,
|
||||
id: GlyphId,
|
||||
text: &str,
|
||||
source: &PaintSource,
|
||||
) -> (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 mut outline = VerticalControlBox::default();
|
||||
face.outline_glyph(id, &mut outline);
|
||||
let [bottom, top] = outline.0.unwrap_or_default();
|
||||
let points = |value| value * (font.size as f32 / 65536.) / f32::from(units);
|
||||
let height = points_to_sp(points(top));
|
||||
let depth = points_to_sp(points(-bottom));
|
||||
let italic = face
|
||||
.tables()
|
||||
.math
|
||||
.and_then(|table| table.glyph_info)
|
||||
.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]),
|
||||
};
|
||||
(
|
||||
MathGeometry {
|
||||
metrics: MathBox {
|
||||
width: advance,
|
||||
height,
|
||||
depth,
|
||||
},
|
||||
items: vec![PositionedItem {
|
||||
x: 0,
|
||||
y: 0,
|
||||
item: MathItem::OpenType(Arc::new(run)),
|
||||
source: source.clone(),
|
||||
}],
|
||||
},
|
||||
italic,
|
||||
)
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
pub(crate) enum Stretch {
|
||||
Horizontal,
|
||||
Vertical,
|
||||
}
|
||||
|
||||
pub(crate) struct StretchedGlyph {
|
||||
pub geometry: MathGeometry,
|
||||
pub glyph: Option<u16>,
|
||||
pub italic: i64,
|
||||
pub sufficient: bool,
|
||||
}
|
||||
|
||||
pub(crate) fn stretch_glyph(
|
||||
font: &Arc<OpenTypeFont>,
|
||||
glyph: u16,
|
||||
character: char,
|
||||
source: &PaintSource,
|
||||
direction: Stretch,
|
||||
target: i64,
|
||||
glyph_limit: usize,
|
||||
) -> Result<StretchedGlyph, String> {
|
||||
let face = font.face()?;
|
||||
let id = GlyphId(glyph);
|
||||
let scale = |v: u16| scale_units(i64::from(v), font.size, face.units_per_em());
|
||||
let horizontal = matches!(direction, Stretch::Horizontal);
|
||||
let variants = face.tables().math.and_then(|table| table.variants);
|
||||
let construction: Option<GlyphConstruction<'_>> = variants.and_then(|v| {
|
||||
if horizontal {
|
||||
v.horizontal_constructions.get(id)
|
||||
} else {
|
||||
v.vertical_constructions.get(id)
|
||||
}
|
||||
});
|
||||
let mut selected = id;
|
||||
let mut enough = false;
|
||||
if let Some(construction) = construction {
|
||||
for variant in construction.variants {
|
||||
let advance = scale(variant.advance_measurement);
|
||||
if horizontal && advance > target {
|
||||
enough = true;
|
||||
break;
|
||||
}
|
||||
if advance > 0 {
|
||||
selected = variant.variant_glyph;
|
||||
}
|
||||
if advance >= target {
|
||||
enough = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if !enough && let Some(recipe) = construction.assembly {
|
||||
let parts: Vec<_> = recipe
|
||||
.parts
|
||||
.into_iter()
|
||||
.map(|part| Part {
|
||||
glyph: part.glyph_id,
|
||||
advance: scale(part.full_advance),
|
||||
start: scale(part.start_connector_length),
|
||||
end: scale(part.end_connector_length),
|
||||
extender: part.part_flags.extender(),
|
||||
})
|
||||
.collect();
|
||||
if !parts.is_empty() {
|
||||
let min = variants.map_or(0, |v: Variants<'_>| scale(v.min_connector_overlap));
|
||||
let geometry = assemble(
|
||||
&parts,
|
||||
min,
|
||||
target,
|
||||
glyph_limit,
|
||||
horizontal,
|
||||
|glyph, first| {
|
||||
let mut buffer = [0; 4];
|
||||
let text = if first {
|
||||
character.encode_utf8(&mut buffer)
|
||||
} else {
|
||||
""
|
||||
};
|
||||
painted_glyph(font, &face, glyph, text, source).0
|
||||
},
|
||||
)?;
|
||||
return Ok(StretchedGlyph {
|
||||
geometry,
|
||||
glyph: None,
|
||||
italic: 0,
|
||||
sufficient: true,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut text = [0; 4];
|
||||
let (geometry, italic) = painted_glyph(
|
||||
font,
|
||||
&face,
|
||||
selected,
|
||||
character.encode_utf8(&mut text),
|
||||
source,
|
||||
);
|
||||
let extent = if horizontal {
|
||||
geometry.metrics.width
|
||||
} else {
|
||||
geometry.metrics.height + geometry.metrics.depth
|
||||
};
|
||||
Ok(StretchedGlyph {
|
||||
geometry,
|
||||
glyph: Some(selected.0),
|
||||
italic,
|
||||
sufficient: enough || extent >= target,
|
||||
})
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
struct Part {
|
||||
glyph: GlyphId,
|
||||
advance: i64,
|
||||
start: i64,
|
||||
end: i64,
|
||||
extender: bool,
|
||||
}
|
||||
|
||||
fn assemble(
|
||||
parts: &[Part],
|
||||
min: i64,
|
||||
target: i64,
|
||||
glyph_limit: usize,
|
||||
horizontal: bool,
|
||||
paint: impl Fn(GlyphId, bool) -> MathGeometry,
|
||||
) -> Result<MathGeometry, String> {
|
||||
let parts_for = |repeats| {
|
||||
parts.iter().flat_map(move |part| {
|
||||
std::iter::repeat_n(part, if part.extender { repeats } else { 1 })
|
||||
})
|
||||
};
|
||||
let max_extent = |repeats| {
|
||||
let mut previous = 0;
|
||||
parts_for(repeats)
|
||||
.map(|part| {
|
||||
let overlap = min.min(previous).min(part.start);
|
||||
previous = part.end;
|
||||
part.advance - overlap
|
||||
})
|
||||
.sum::<i64>()
|
||||
};
|
||||
let extenders = parts.iter().filter(|part| part.extender).count();
|
||||
let repeats = if extenders == 0 || max_extent(0) >= target {
|
||||
0
|
||||
} else {
|
||||
let first = max_extent(1);
|
||||
let step = max_extent(2) - first;
|
||||
if first >= target {
|
||||
1
|
||||
} else if step > 0 {
|
||||
1 + usize::try_from((target - first + step - 1) / step)
|
||||
.map_err(|_| "OpenType MATH assembly exceeds glyph capacity")?
|
||||
} else {
|
||||
return Err("OpenType MATH extenders do not increase assembly extent".into());
|
||||
}
|
||||
};
|
||||
let count = parts.len() - extenders + extenders.saturating_mul(repeats);
|
||||
if count == 0 || count > glyph_limit {
|
||||
return Err("OpenType MATH assembly exceeds glyph capacity".into());
|
||||
}
|
||||
|
||||
let mut natural = 0;
|
||||
let mut stretch = 0;
|
||||
let mut previous = 0;
|
||||
let components: Vec<_> = parts_for(repeats)
|
||||
.enumerate()
|
||||
.map(|(index, part)| {
|
||||
let glyph = paint(part.glyph, index == 0);
|
||||
let overlap = previous.min(part.start);
|
||||
previous = part.end;
|
||||
let flexibility = overlap - overlap.min(min);
|
||||
let advance = if horizontal {
|
||||
glyph.metrics.width
|
||||
} else {
|
||||
glyph.metrics.height + glyph.metrics.depth
|
||||
};
|
||||
natural += advance - overlap;
|
||||
stretch += flexibility;
|
||||
(glyph, advance, overlap, flexibility)
|
||||
})
|
||||
.collect();
|
||||
let expand = (target - natural).clamp(0, stretch);
|
||||
let ratio = if stretch == 0 {
|
||||
0.
|
||||
} else {
|
||||
expand as f64 / stretch as f64
|
||||
};
|
||||
let rounded_glue = |stretch: i64| (stretch as f64 * ratio).round() as i64;
|
||||
let mut out = MathGeometry::default();
|
||||
let mut stretched = 0;
|
||||
if horizontal {
|
||||
let mut cursor = 0;
|
||||
for (glyph, advance, overlap, flexibility) in components {
|
||||
let next = stretched + flexibility;
|
||||
cursor += -overlap + rounded_glue(next) - rounded_glue(stretched);
|
||||
stretched = next;
|
||||
out.append(glyph, cursor, 0);
|
||||
cursor += advance;
|
||||
}
|
||||
out.metrics.width = cursor;
|
||||
} else {
|
||||
// The MATH table lists parts from bottom to top. A vertical math
|
||||
// list ships out from its top, accumulating glue in that order.
|
||||
let mut cursor = -natural - expand;
|
||||
for (glyph, advance, overlap, flexibility) in components.into_iter().rev() {
|
||||
out.metrics.width = out.metrics.width.max(glyph.metrics.width);
|
||||
let baseline = cursor + glyph.metrics.height;
|
||||
out.append(glyph, 0, baseline);
|
||||
let next = stretched + flexibility;
|
||||
cursor += advance - overlap + rounded_glue(next) - rounded_glue(stretched);
|
||||
stretched = next;
|
||||
}
|
||||
out.metrics.height = natural + expand;
|
||||
out.metrics.depth = 0;
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
@@ -2175,6 +2175,37 @@ PDF,恢复实际 PFB 并反转斜切时复用 1277 步,只替换第二页。
|
||||
全量编译一致。incremental-receipt.json 的 SHA-256 为
|
||||
bbc0991b0316e6d76aa58649ec873525f5544ab530d93fe491fc6e16bd00a27d。
|
||||
|
||||
### XeTeX OpenType MATH 重音、伸缩与公式出页
|
||||
|
||||
\Umathaccent 进入真实重音节点并保存 fixed、bottom 及其组合。
|
||||
OpenType 数学家族从实际 MATH 表取得符号家族、分数、脚标和
|
||||
运算符度量。横向和竖向变体以及拼装读取同一字体的字形、
|
||||
连接器和重叠量,再经真实数学盒和统一 PDF 设备绘制。
|
||||
XeTeX 从零开始的 OpenType 特性变体索引按参考语义交给 shaping,
|
||||
包括真实脚标字体使用的 +ssty=0 和 +ssty=1。
|
||||
[XeTeX OpenType 数学度量](https://github.com/TeX-Live/texlive-source/blob/trunk/texk/web2c/xetexdir/XeTeXOTMath.cpp)
|
||||
[XeTeX 特性变体索引](https://github.com/TeX-Live/texlive-source/blob/trunk/texk/web2c/xetexdir/XeTeX_ext.c#L1016-L1030)
|
||||
|
||||
12 项 INITEX 盒宽、高、深全部与 XeTeX 一致。在保持字体和源码
|
||||
身份的 XDV 对照中,97 个字形和 3 条规则的编号、字号及坐标一致。
|
||||
一组带成对定界符的分数内部有两个字形仍偏 196 sp。证据保存在
|
||||
target/p3-xetex-math-layout/receipt.json。此前记录的分数
|
||||
617546 × 733348 sp、深 449577 sp 也已匹配实际 XDV。
|
||||
既有数学、定界符和 profile 定向回归通过。旧 schema66 仍生成
|
||||
逐字节一致的 Unicode article PDF 和 aux。
|
||||
|
||||
原样 xelatex.ini 生成 schema67。原样 unicode-math、fontspec
|
||||
与 Latin Modern Math 经该格式生成一页 PDF,纸张尺寸和 aux
|
||||
与 XeTeX 一致,144 dpi 灰度光栅的 1938816 个像素全部一致。
|
||||
严格 XDV 对照仍记录根式区域的 5 个字形与 1 条规则纵向偏 8 sp。
|
||||
5000 万步的原始失败已保留。用 1.5 亿步的执行上限取得该次出页。
|
||||
这些记录用于功能核对,实时延迟仍走原定测量门禁。
|
||||
|
||||
三页会话的子文件从短重音编辑到长上括号拼装。错误家族保留
|
||||
上一版,修正后复用 1500 步,只更新第 2 页。PDF、SVG 和来源
|
||||
映射与同修订的独立全量一致。回执位于
|
||||
target/p3-xetex-math-layout/revisions/receipt.json。
|
||||
|
||||
### XeTeX 扩展定界符代码表与原语
|
||||
|
||||
\delcode、\Udelcode 和 \Udelcodenum 访问同一张代码表。XeTeX
|
||||
|
||||
Reference in new issue
Block a user