Use shaped glyph edges for XeTeX protrusion and line breaking

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

No files matched your search

+14 -4
View File
@@ -2281,8 +2281,13 @@ impl Executor {
Ok(self.state.fonts.auto_kern_code(font, slot, p == Primitive::Knaccode))
}
Meaning::Primitive(p @ (Primitive::Lpcode | Primitive::Rpcode)) => {
let (font, slot) = self.font_character_target(files)?;
Ok(self.state.fonts.protrusion_code(font, slot, p == Primitive::Rpcode))
let (font, slot) = self.protrusion_target(files)?;
let right = p == Primitive::Rpcode;
Ok(if self.state.input_profile() == InputProfile::XeTeX {
self.state.fonts.xe_protrusion_code(font, slot, right)
} else {
self.state.fonts.protrusion_code(font, slot as u8, right)
})
}
Meaning::Primitive(p @ (Primitive::Hyphenchar | Primitive::Skewchar)) => {
let font = self.font_identifier(files)?;
@@ -4344,10 +4349,15 @@ impl Executor {
self.state.fonts.set_auto_kern_code(font, slot, primitive == Some(Knaccode), code);
}
Some(Lpcode | Rpcode) => {
let (font, slot) = self.font_character_target(files)?;
let (font, slot) = self.protrusion_target(files)?;
self.optional_equals(files)?;
let code = self.integer(files)?;
self.state.fonts.set_protrusion_code(font, slot, primitive == Some(Rpcode), code);
let right = primitive == Some(Rpcode);
if self.state.input_profile() == InputProfile::XeTeX {
self.state.fonts.set_xe_protrusion_code(font, slot, right, code);
} else {
self.state.fonts.set_protrusion_code(font, slot as u8, right, code);
}
}
Some(Hyphenchar | Skewchar) => {
let font = self.font_identifier(files)?;
@@ -103,6 +103,38 @@ impl Executor {
_ => unreachable!(),
} as i32)
}
pub(super) fn protrusion_target(
&mut self,
files: &mut impl SourceProvider,
) -> Result<(FontId, i32), Error> {
self.reads.insert(Dependency::FontResources);
if self.state.input_profile() != InputProfile::XeTeX {
let (font, slot) = self.font_character_target(files)?;
return Ok((font, i32::from(slot)));
}
let id = self.font_identifier(files)?;
let opentype = self.state.fonts.font(id)
.map_err(|error| self.error(error, self.current))?.opentype().cloned();
let slot = if let Some(font) = opentype {
if self.keyword("/", files)? {
let name = self.filename(files)?;
font.face().map_err(|error| self.error(error, self.current))?
.glyph_index_by_name(&name).map_or(0, |glyph| i32::from(glyph.0))
} else if self.keyword("u", files)? {
let slot = self.character_number("XeTeX glyph character", 65535, files)?;
let face = font.face().map_err(|error| self.error(error, self.current))?;
char::from_u32(slot).and_then(|c| face.glyph_index(c))
.map_or(0, |glyph| i32::from(glyph.0))
} else {
self.integer(files)?
}
} else {
self.character_number("XeTeX font character", 65535, files)? as i32
};
Ok((id, slot))
}
pub(super) fn xetex_font_query(
&mut self,
command: Primitive,
@@ -226,6 +226,8 @@ pub struct FontCatalog {
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
protrusion: BTreeMap<FontId, BTreeMap<u8, [i16; 2]>>,
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
xe_protrusion: BTreeMap<FontId, BTreeMap<i32, [i32; 2]>>,
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
auto_kern: BTreeMap<FontId, BTreeMap<u8, [i16; 2]>>,
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
expansion: BTreeMap<FontId, FontExpansion>,
@@ -271,6 +273,7 @@ impl FontCatalog {
parameter_owners: BTreeMap::new(),
limits,
protrusion: BTreeMap::new(),
xe_protrusion: BTreeMap::new(),
auto_kern: BTreeMap::new(),
expansion: BTreeMap::new(),
external_expansion: BTreeMap::new(),
@@ -701,6 +704,32 @@ impl FontCatalog {
self.protrusion.entry(font).or_default().entry(slot).or_default()[usize::from(right)] = code;
}
}
pub(super) fn xe_protrusion_code(&self, font: FontId, slot: i32, right: bool) -> i32 {
self.xe_protrusion
.get(&font)
.and_then(|codes| codes.get(&slot))
.map_or(0, |codes| codes[usize::from(right)])
}
pub(super) fn set_xe_protrusion_code(
&mut self, font: FontId, slot: i32, right: bool, code: i32,
) {
let side = usize::from(right);
if code != 0 {
self.xe_protrusion.entry(font).or_default().entry(slot).or_default()[side] = code;
} else if let Some(table) = self.xe_protrusion.get_mut(&font) {
if let Some(pair) = table.get_mut(&slot) {
pair[side] = 0;
if *pair == [0; 2] {
table.remove(&slot);
}
}
if table.is_empty() {
self.xe_protrusion.remove(&font);
}
}
}
pub(super) fn has_auto_kern_codes(&self) -> bool {
!self.auto_kern.is_empty()
}
@@ -1006,6 +1035,7 @@ impl FontCatalog {
self.external_expansion.clear();
self.expansion_codes.clear();
self.protrusion.clear();
self.xe_protrusion.clear();
self.auto_kern.clear();
self.pdf_settings.clear();
}
@@ -8,9 +8,9 @@ use std::{
sync::{Arc, Mutex, OnceLock, Weak},
};
const SCHEMA: u32 = 70;
const COMPATIBLE_SCHEMAS: [u32; 37] = [
27, 28, 31, 32, 33, 34, 35, 36, 37, 38, 39, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 64, 65, 66, 67, 68, 69, SCHEMA,
const SCHEMA: u32 = 71;
const COMPATIBLE_SCHEMAS: [u32; 38] = [
27, 28, 31, 32, 33, 34, 35, 36, 37, 38, 39, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 64, 65, 66, 67, 68, 69, 70, SCHEMA,
];
const ENGINE: &str = concat!("texrra-native/", env!("CARGO_PKG_VERSION"));
@@ -78,7 +78,7 @@ pub enum TextNode {
/// Spacing owned by a text accent and protected from leading discard.
AccentKern(i32),
AutoKern(i32),
MarginKern { width: i32, right: bool, font: FontId, slot: u8 },
MarginKern { width: i32, right: bool, font: FontId, slot: u16 },
Direction(DirectionBoundary),
}
#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
@@ -1088,8 +1088,8 @@ fn pack(
if left != Glue::default() {
material.push(TextNode::NamedGlue(left, Parameter::Leftskip));
}
let enabled = p[&Parameter::Pdfprotrudechars].width() > 0;
if enabled && let Some(kern) = protrusion::margin_kern(state, nodes, false, false) {
let enabled = protrusion::level(state, p) > 0;
if enabled && let Some(kern) = protrusion::margin_kern(state, nodes, false, false)? {
material.push(kern);
}
let right_end = nodes.len() - usize::from(terminal_marker);
@@ -1098,7 +1098,7 @@ fn pack(
material.push(TextNode::Penalty(10000));
}
if enabled
&& let Some(kern) = protrusion::margin_kern(state, &nodes[..right_end], true, ends_in_pre_break)
&& let Some(kern) = protrusion::margin_kern(state, &nodes[..right_end], true, ends_in_pre_break)?
{
material.push(kern);
}
@@ -289,7 +289,7 @@ pub(super) fn solve(
.then(|| expansion::Search::new(state, source))
.transpose()?;
let expand_margins = expansion.is_some();
let mut margins = (parameters[&Parameter::Pdfprotrudechars].width() > 1)
let mut margins = (protrusion::level(state, parameters) > 1)
.then(|| protrusion::Search::new(state, source, expand_margins))
.transpose()?;
let retained = nodes.len()
@@ -385,6 +385,7 @@ pub(super) fn pack(
let TextNode::MarginKern { width, right, font, slot } = *node else {
continue;
};
let Ok(slot) = u8::try_from(slot) else { continue };
for (ratio, limit) in [(1000, &mut capacity.stretch), (-1000, &mut capacity.shrink)] {
if let Some((expanded, _)) = fonts.margin(state, font, slot, right, ratio, files)? {
*limit += i64::from(expanded) - i64::from(width);
@@ -408,7 +409,9 @@ pub(super) fn pack(
pdf_device::divide_scaled(shortfall.clamp(-available, available), available, 3).0 as i32;
for i in 0..material.len() {
if let TextNode::MarginKern { ref mut width, right, ref mut font, slot } = material[i] {
if let Some((expanded, selected)) = fonts.margin(state, *font, slot, right, ratio, files)? {
if let Ok(slot) = u8::try_from(slot)
&& let Some((expanded, selected)) = fonts.margin(state, *font, slot, right, ratio, files)?
{
*width = expanded;
*font = selected;
}
@@ -1,4 +1,4 @@
//! The same font-slot widths drive break search and the owned margin kerns.
//! The same shaped edges drive break search and the owned margin kerns.
use super::*;
#[derive(Clone, Copy)]
@@ -6,12 +6,19 @@ enum Edge {
Skip,
Solid,
Glyph(FontId, u8),
OpenType(FontId, u16),
}
impl Edge {
fn character(node: &TextNode) -> Self {
fn opentype(run: &OpenTypeRun, right: bool) -> Self {
let glyph = if right { run.glyphs.last() } else { run.glyphs.first() };
glyph.map_or(Self::Solid, |glyph| Self::OpenType(run.font.id, glyph.id))
}
fn character(node: &TextNode, right: bool) -> Self {
match node {
TextNode::Glyph { font, slot, .. } => Self::Glyph(*font, *slot),
TextNode::OpenType(run) => Self::opentype(run, right),
TextNode::MathChar(glyph) => {
use crate::math_engine_tex::MathItem;
match glyph
@@ -21,6 +28,7 @@ impl Edge {
{
Some([item]) => match &item.item {
MathItem::NativeGlyph { font, slot, .. } => Self::Glyph(font.id, *slot),
MathItem::OpenType(run) => Self::opentype(run, right),
_ => Self::Solid,
},
_ => Self::Solid,
@@ -44,7 +52,7 @@ impl Edge {
_ => Self::Solid,
},
_ if skippable(node) => Self::Skip,
_ => Self::character(node),
_ => Self::character(node, right),
}
}
@@ -63,25 +71,38 @@ impl Edge {
Self::Skip
}
fn width(self, state: &State, right: bool) -> i32 {
let Self::Glyph(font, slot) = self else {
return 0;
fn width(self, state: &State, right: bool) -> Result<i32, String> {
let xe = state.input_profile() == InputProfile::XeTeX;
let (font, code) = match self {
Self::Glyph(font, slot) if !xe => (font, state.fonts.protrusion_code(font, slot, right)),
Self::Glyph(font, slot) => (font, state.fonts.xe_protrusion_code(font, i32::from(slot), right)),
Self::OpenType(font, glyph) if xe => (font, state.fonts.xe_protrusion_code(font, i32::from(glyph), right)),
_ => return Ok(0),
};
let code = state.fonts.protrusion_code(font, slot, right);
if code == 0 {
return 0;
return Ok(0);
}
let quad = state
.fonts
.font(font)
.expect("marginal glyph's font is live")
.quad();
let quad = state.fonts.font(font)?.quad();
let scaled = i64::from(quad) * i64::from(code);
// Round to the nearest sp, taking half a unit away from zero.
(scaled.signum() * ((scaled.abs() + 500) / 1000)) as i32
// XeTeX's signed remainder does not round up for negative factors.
let rounding = if xe && code < 0 { 0 } else { 500 };
let width = scaled.signum() * ((scaled.abs() + rounding) / 1000);
if width.abs() > 1073741823 {
return Err("native character protrusion exceeds dimension capacity".into());
}
Ok(width as i32)
}
}
pub(super) fn level(state: &State, parameters: &BTreeMap<Parameter, ParameterValue>) -> i32 {
let parameter = if state.input_profile() == InputProfile::XeTeX {
Parameter::XeTeXprotrudechars
} else {
Parameter::Pdfprotrudechars
};
parameters[&parameter].width()
}
fn skippable(node: &TextNode) -> bool {
match node {
TextNode::Box(boxed) => matches!(
@@ -141,22 +162,24 @@ pub(super) fn margin_kern(
nodes: &[TextNode],
right: bool,
direct: bool,
) -> Option<TextNode> {
) -> Result<Option<TextNode>, String> {
let edge = if direct {
nodes.last().map_or(Edge::Solid, Edge::character)
nodes.last().map_or(Edge::Solid, |node| Edge::character(node, right))
} else {
Edge::list(nodes, right)
};
let Edge::Glyph(font, slot) = edge else {
return None;
let (font, slot) = match edge {
Edge::Glyph(font, slot) => (font, u16::from(slot)),
Edge::OpenType(font, glyph) => (font, glyph),
_ => return Ok(None),
};
let width = -edge.width(state, right);
(width != 0).then_some(TextNode::MarginKern {
let width = -edge.width(state, right)?;
Ok((width != 0).then_some(TextNode::MarginKern {
width,
right,
font,
slot,
})
}))
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
@@ -185,7 +208,7 @@ impl Search {
let mut variations = BTreeMap::new();
let mut project = |edge: Edge, right| -> Result<EdgeMeasure, String> {
use std::collections::btree_map::Entry;
let width = edge.width(state, right);
let width = edge.width(state, right)?;
let mut expanding = None;
if expand && let Edge::Glyph(font, slot) = edge {
let key = (font, slot);
@@ -210,9 +233,9 @@ impl Search {
};
if let TextNode::Discretionary { pre_break, post_break, .. } = node {
widths[i].pre = pre_break.last()
.map(|node| project(Edge::character(node), true)).transpose()?;
.map(|node| project(Edge::character(node, true), true)).transpose()?;
widths[i].post = post_break.first()
.map(|node| project(Edge::character(node), false)).transpose()?;
.map(|node| project(Edge::character(node, false), false)).transpose()?;
}
}
for (i, node) in nodes.iter().enumerate().rev() {
@@ -124,6 +124,7 @@ pub enum Parameter {
Suppressfontnotfounderror,
TeXXeTstate,
XeTeXinterchartokenstate,
XeTeXprotrudechars,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
pub enum ParameterValue {
@@ -156,11 +157,12 @@ impl Parameter {
)
}
pub(super) const XETEX: [Self; 4] = [
pub(super) const XETEX: [Self; 5] = [
Self::XeTeXuseglyphmetrics,
Self::XeTeXdashbreakstate,
Self::Suppressfontnotfounderror,
Self::XeTeXinterchartokenstate,
Self::XeTeXprotrudechars,
];
pub const ALL: &'static [Self] = &[
@@ -283,6 +285,7 @@ impl Parameter {
Self::Suppressfontnotfounderror,
Self::TeXXeTstate,
Self::XeTeXinterchartokenstate,
Self::XeTeXprotrudechars,
];
pub fn name(self) -> String {
match self {
@@ -290,6 +293,7 @@ impl Parameter {
Self::XeTeXdashbreakstate => "XeTeXdashbreakstate".into(),
Self::TeXXeTstate => "TeXXeTstate".into(),
Self::XeTeXinterchartokenstate => "XeTeXinterchartokenstate".into(),
Self::XeTeXprotrudechars => "XeTeXprotrudechars".into(),
_ => format!("{self:?}").to_ascii_lowercase(),
}
}