Rejoin XeTeX OpenType word fragments while packing horizontal boxes

This commit is contained in:
gloamxun committed 2026-11-25 22:29:53 +08:00
1 parent fa27e0985f
commit 3e9a639f1d
6 files changed
+156 -4

No files matched your search

@@ -5,6 +5,7 @@ mod tail;
pub(super) use tail::TailNodeRef;
mod leaders;
mod legacy_fonts;
mod native_words;
pub use leaders::{LeaderGlue, LeaderMode, LeaderPattern};
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
@@ -617,7 +618,7 @@ pub(super) fn hpack(
span: Span,
state: &State,
) -> Result<NativeBox, String> {
hpack_with_direction_report(nodes, spec, span, state).map(|(packed, _)| packed)
hpack_with_direction_report(nodes, spec, span, state, None).map(|(packed, _)| packed)
}
pub(super) fn hpack_with_direction_report(
@@ -625,7 +626,12 @@ pub(super) fn hpack_with_direction_report(
spec: PackSpec,
span: Span,
state: &State,
shaping_budget: Option<(&mut usize, usize)>,
) -> Result<(NativeBox, (usize, usize)), String> {
if state.input_profile() == InputProfile::XeTeX {
let glyph_metrics = state.parameter(Parameter::XeTeXuseglyphmetrics).width() > 0;
native_words::rejoin(&mut nodes, glyph_metrics, shaping_budget)?;
}
let direction_problems = super::direction::complete_box(&mut nodes);
let (mut width, mut height, mut depth) = (0, 0, 0);
let (mut stretch, mut shrink) = ([0; 4], [0; 4]);
@@ -0,0 +1,93 @@
//! Reassemble XeTeX native word fragments in the physical horizontal list.
use super::TextNode;
use std::sync::Arc;
pub(super) fn rejoin(
nodes: &mut Vec<TextNode>,
glyph_metrics: bool,
mut shaping_budget: Option<(&mut usize, usize)>,
) -> Result<(), String> {
let mut index = 0;
let mut replacement_left = 0;
let mut edits = Vec::new();
while let Some(node) = nodes.get(index) {
let begin = index;
index += 1;
if let TextNode::Discretionary {
replacement_count, ..
} = node
{
replacement_left = *replacement_count;
continue;
}
if replacement_left > 0 {
replacement_left -= 1;
continue;
}
let TextNode::OpenType(first) = node else {
continue;
};
// Each retained discretionary may bridge one pair of fragments.
// Starting inside a live replacement would invalidate its node count.
loop {
let next = index
+ usize::from(matches!(
nodes.get(index),
Some(TextNode::Discretionary { .. })
));
if !matches!(nodes.get(next), Some(TextNode::OpenType(run)) if run.font.id == first.font.id)
{
break;
}
index = next + 1;
}
if index == begin + 1 {
continue;
}
let mut text = String::new();
let mut sources = Vec::new();
let mut units = 0;
for node in &nodes[begin..index] {
if let TextNode::OpenType(run) = node {
units += run.text.encode_utf16().count();
if units > usize::from(u16::MAX) {
return Err("native OpenType word capacity exceeded".into());
}
let offset = text.len();
sources.extend(
run.sources
.iter()
.map(|(at, source)| (offset + at, source.clone())),
);
text.push_str(&run.text);
}
}
let word = first.font.shape_mapped(text, sources, glyph_metrics)?;
if let Some((steps, limit)) = &mut shaping_budget {
**steps = steps
.checked_add(word.glyphs.len())
.filter(|work| work <= limit)
.ok_or("native OpenType packing step limit exceeded")?;
}
edits.push((begin, index, Arc::new(word)));
}
if !edits.is_empty() {
let mut edits = edits.into_iter().peekable();
let mut index = 0;
let mut discard_until = 0;
nodes.retain_mut(|node| {
let at = index;
index += 1;
if at < discard_until {
return false;
}
if let Some((_, end, word)) = edits.next_if(|(begin, _, _)| *begin == at) {
*node = TextNode::OpenType(word);
discard_until = end;
}
true
});
}
Ok(())
}
@@ -250,6 +250,7 @@ impl Executor {
!matches!(
n,
TextNode::Glyph { .. }
| TextNode::OpenType(_)
| TextNode::Kern { .. }
| TextNode::AccentKern(_)
| TextNode::AutoKern(_)
@@ -776,7 +777,13 @@ impl Executor {
} else {
b.nodes
};
boxes::hpack_with_direction_report(nodes, frame.spec, frame.span, &self.state)
if self.state.input_profile() == InputProfile::XeTeX {
self.reads.insert(Dependency::Parameter(Parameter::XeTeXuseglyphmetrics));
}
boxes::hpack_with_direction_report(
nodes, frame.spec, frame.span, &self.state,
Some((&mut self.steps, self.limits.steps)),
)
} else {
boxes::vpack(
self.vertical.take_nodes(),
@@ -1082,6 +1082,7 @@ fn pack(
direction_stack: &[super::direction::Region],
state: &mut State,
span: Span,
shaping_budget: (&mut usize, usize),
files: &mut impl SourceProvider,
) -> Result<(Paragraph, NativeBox, super::marks::MigratingMaterial, bool), String> {
let left = p[&Parameter::Leftskip].glue();
@@ -1119,15 +1120,16 @@ fn pack(
if p[&Parameter::Pdfadjustspacing].width() > 0 && state.fonts.has_expansion() {
expansion::pack(state, &mut material, target, files)?;
}
let shrinking = material.iter().map(width).sum::<i64>() > target;
let mut b = super::boxes::hpack(
let (mut b, _) = super::boxes::hpack_with_direction_report(
material,
super::boxes::PackSpec::To(
i32::try_from(target).map_err(|_| "native line width overflow")?,
),
span,
state,
Some(shaping_budget),
)?;
let shrinking = b.setting.sign < 0 || b.excess > 0;
b.shift = indent;
let paragraph = Paragraph {
lines: vec![b.horizontal_items().unwrap()],
@@ -1338,6 +1340,7 @@ pub(super) fn finish(
&direction_stack,
state,
b.span,
(steps, step_limit),
files,
)?;
packed_diagnostic.push(line_box.diagnostic_eligible);