Implement XeTeX contextual interword spacing and shipout shaping

This commit is contained in:
gloamxun committed 2026-11-26 09:23:45 +08:00
1 parent 7e5428ec35
commit 4a77540e46
23 files changed
+491 -42

No files matched your search

+75 -9
View File
@@ -1,6 +1,7 @@
//! Owned native boxes. Packing follows tex.web hpack/vpackage, not page costs.
use super::*;
use crate::{HorizontalBox, HorizontalItem, Paragraph, ParagraphFont};
mod interword;
mod tail;
pub(super) use tail::TailNodeRef;
mod leaders;
@@ -58,6 +59,9 @@ pub struct NativeBox {
/// Original horizontal semantics, retained before paint-time glue setting.
pub diagnostic: Vec<super::diagnostics::DiagnosticNode>,
pub setting: GlueSetting,
// Prepared only on the disposable shipout box after its glue is set.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub(super) interword_runs: Vec<interword::Run>,
pub badness: i32,
pub diagnostic_eligible: bool,
pub excess: i64,
@@ -240,9 +244,9 @@ impl NativeBox {
}
match &b.content {
BoxContent::Horizontal(nodes) => {
let order = super::direction::visual_order(nodes, rtl && !b.display);
let order = b.horizontal_order(nodes, rtl && !b.display);
let order = order.as_deref();
for index in 0..nodes.len() {
for index in 0..order.map_or(nodes.len(), <[_]>::len) {
let (index, rtl) = order.map_or((index, false), |order| order[index]);
match &nodes[index] {
TextNode::Output(o) => out.push(o),
@@ -358,6 +362,7 @@ impl NativeBox {
| TextNode::MathBoundary { width: w, .. }
| TextNode::AccentKern(w)
| TextNode::AutoKern(w)
| TextNode::SpaceAdjustment(w)
| TextNode::MarginKern { width: w, .. }
| TextNode::Kern { width: w, .. } => HorizontalItem::Box(HorizontalBox {
width: *w as i64,
@@ -368,7 +373,7 @@ impl NativeBox {
penalty: *n as i64,
flagged: false,
},
TextNode::Glue(g) | TextNode::NamedGlue(g, _) => HorizontalItem::Glue {
TextNode::Glue(g) | TextNode::FontSpace(g, _, _) | TextNode::NamedGlue(g, _) => HorizontalItem::Glue {
width: g.width as i64
+ self.setting.adjustment(*g, &mut cumulative, &mut previous),
stretch: 0,
@@ -388,13 +393,71 @@ impl NativeBox {
};
Some(PackedHorizontal::Item(item))
};
let Some(order) = super::direction::visual_order(nodes, rtl) else {
let Some(order) = self.horizontal_order(nodes, rtl) else {
return Some(nodes.iter().filter_map(|node| pack(node).map(|item| (item, false))).collect());
};
// Glue accumulates its rounding in logical order before the device
// reverses a span. Reuse those adjusted widths in visual order.
let mut logical: Vec<_> = nodes.iter().map(pack).collect();
Some(order.into_iter().filter_map(|(i, rtl)| logical[i].take().map(|item| (item, rtl))).collect())
// Accumulate glue rounding in logical order. Glues included in a
// reshaped word were resolved separately and do not update this total.
let retained = if self.interword_runs.is_empty() {
None
} else {
let mut retained = vec![false; nodes.len()];
for &(index, _) in &order {
retained[index] = true;
}
Some(retained)
};
let mut logical: Vec<_> = nodes.iter().enumerate()
.map(|(index, node)| {
if retained.as_ref().is_none_or(|retained| retained[index]) {
pack(node)
} else {
None
}
})
.collect();
for run in &self.interword_runs {
logical[run.nodes.start] = Some(PackedHorizontal::Item(HorizontalItem::Box(
crate::opentype::horizontal_box(&run.word),
)));
}
Some(order.into_iter()
.filter_map(|(index, rtl)| logical[index].take().map(|item| (item, rtl)))
.collect())
}
fn horizontal_order(&self, nodes: &[TextNode], rtl: bool) -> Option<Vec<(usize, bool)>> {
let order = super::direction::visual_order(nodes, rtl);
if self.interword_runs.is_empty() {
return order;
}
let order = order.unwrap_or_else(|| (0..nodes.len()).map(|index| (index, false)).collect());
let mut removed = vec![false; nodes.len()];
for run in &self.interword_runs {
removed[run.nodes.start + 1..run.nodes.end].fill(true);
for &effect in &run.effects {
removed[effect] = true;
}
}
let mut prepared = Vec::with_capacity(order.len());
for (index, rtl) in order {
if removed[index] {
continue;
}
if let Ok(run) = self.interword_runs.binary_search_by_key(&index, |run| run.nodes.start) {
let effects = &self.interword_runs[run].effects;
if rtl {
prepared.extend(effects.iter().rev().map(|&effect| (effect, rtl)));
}
prepared.push((index, rtl));
if !rtl {
prepared.extend(effects.iter().map(|&effect| (effect, rtl)));
}
} else {
prepared.push((index, rtl));
}
}
Some(prepared)
}
pub fn node_count(&self) -> usize {
@@ -599,6 +662,7 @@ pub(super) fn vpack(
content: BoxContent::Vertical(nodes),
diagnostic: Vec::new(),
setting: set,
interword_runs: Vec::new(),
badness,
diagnostic_eligible,
excess,
@@ -666,9 +730,10 @@ pub(super) fn hpack_with_direction_report(
| TextNode::MathBoundary { width: w, .. }
| TextNode::AccentKern(w)
| TextNode::AutoKern(w)
| TextNode::SpaceAdjustment(w)
| TextNode::MarginKern { width: w, .. }
| TextNode::Kern { width: w, .. } => width += *w as i64,
TextNode::Glue(g) | TextNode::NamedGlue(g, _) => {
TextNode::Glue(g) | TextNode::FontSpace(g, _, _) | TextNode::NamedGlue(g, _) => {
width += g.width as i64;
flex(*g, &mut stretch, &mut shrink);
}
@@ -710,6 +775,7 @@ pub(super) fn hpack_with_direction_report(
content: BoxContent::Horizontal(nodes),
diagnostic,
setting: set,
interword_runs: Vec::new(),
badness,
diagnostic_eligible,
excess,
@@ -0,0 +1,227 @@
//! Shape full native word sequences after horizontal glue has been set.
use super::super::paragraph::interword::invisible;
use super::*;
use crate::{opentype::OpenTypeRun, provenance::PaintSource};
use std::{ops::Range, sync::Arc};
#[derive(Clone, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
pub(in crate::execution) struct Run {
pub(super) nodes: Range<usize>,
pub(super) word: Arc<OpenTypeRun>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub(super) effects: Vec<usize>,
}
impl NativeBox {
pub(in crate::execution) fn prepare_interword_shipout(
&mut self,
limit: usize,
cancellation: Option<&Cancellation>,
) -> Result<usize, String> {
let mut remaining = limit;
prepare(self, &mut remaining, cancellation)?;
Ok(limit - remaining)
}
}
fn prepare(
packed: &mut NativeBox,
remaining: &mut usize,
cancellation: Option<&Cancellation>,
) -> Result<(), String> {
if cancellation.is_some_and(Cancellation::is_cancelled) {
return Err("native compilation cancelled".into());
}
if packed.kind.is_unset() {
return Ok(());
}
match &mut packed.content {
BoxContent::Horizontal(nodes) => {
packed.interword_runs = shape_row(nodes, packed.setting, remaining, cancellation)?;
for node in nodes {
let child = match node {
TextNode::Box(item)
| TextNode::MathChar(item)
| TextNode::Glyph { glyph: item, .. } => item.native_box.as_deref_mut(),
TextNode::Leaders(LeaderGlue {
pattern: LeaderPattern::Box(item),
..
}) => Some(item.as_mut()),
_ => None,
};
if let Some(child) = child {
prepare(child, remaining, cancellation)?;
}
}
}
BoxContent::Vertical(nodes) => {
for node in nodes {
let child = match node {
NativeVerticalNode::Box(item)
| NativeVerticalNode::Line(item)
| NativeVerticalNode::Leaders(LeaderGlue {
pattern: LeaderPattern::Box(item),
..
}) => item,
_ => continue,
};
prepare(child, remaining, cancellation)?;
}
}
}
Ok(())
}
fn shape_row(
nodes: &[TextNode],
setting: GlueSetting,
remaining: &mut usize,
cancellation: Option<&Cancellation>,
) -> Result<Vec<Run>, String> {
let next = |start: usize| {
let offset = nodes[start..].iter().position(|node| !invisible(node));
offset.map_or(nodes.len(), |offset| start + offset)
};
let mut runs = Vec::new();
let mut moved_suffix_effects = false;
let mut index = 0;
while let Some(node) = nodes.get(index) {
let start = index;
index += 1;
let TextNode::OpenType(first) = node else {
continue;
};
let mut text = String::new();
let mut sources = Vec::new();
let mut units = 0;
loop {
let mut word_index = next(index);
let space = match nodes.get(word_index) {
Some(TextNode::FontSpace(_, font, origin)) => {
Some((Some(*origin), *font == first.font.id))
}
Some(TextNode::Glue(_)) => Some((None, false)),
_ => None,
};
if let Some((_, canonical)) = space {
let adjustment = matches!(
nodes.get(word_index + 1),
Some(TextNode::SpaceAdjustment(_))
);
if !canonical && !adjustment {
break;
}
word_index = next(word_index + 1 + usize::from(adjustment));
}
let Some(TextNode::OpenType(word)) = nodes.get(word_index) else {
break;
};
if word.font.id != first.font.id {
break;
}
if index == start + 1 {
text.push_str(&first.text);
sources.extend(first.sources.iter().cloned());
units = first.text.encode_utf16().count();
}
if let Some((origin, _)) = space {
if let Some(origin) = origin {
sources.push((text.len(), PaintSource::token(origin)));
}
text.push(' ');
units += 1;
}
units += word.text.encode_utf16().count();
if units > usize::from(u16::MAX) {
return Err("native justified OpenType word capacity exceeded".into());
}
let offset = text.len();
text.push_str(&word.text);
sources.extend(
word.sources
.iter()
.map(|(at, source)| (offset + at, source.clone())),
);
index = word_index + 1;
}
if index == start + 1 {
continue;
}
if cancellation.is_some_and(Cancellation::is_cancelled) {
return Err("native compilation cancelled".into());
}
let mut word = first.font.shape_mapped(text, sources, false)?;
*remaining = remaining
.checked_sub(word.glyphs.len())
.ok_or("native justified OpenType shaping step limit exceeded")?;
let target = nodes[start..index]
.iter()
.map(|node| shipout_width(node, setting))
.sum();
word.actual_text = first.actual_text;
justify(&mut word, target)?;
let mut effects = Vec::new();
if !moved_suffix_effects
&& let Some(offset) = nodes[start + 1..index].iter().position(invisible)
{
// XDV relinks the first invisible node in the old run. The scan
// then follows its new link into the remaining horizontal list.
effects.push(start + 1 + offset);
effects.extend(
nodes[index..]
.iter()
.enumerate()
.filter_map(|(offset, node)| invisible(node).then_some(index + offset)),
);
moved_suffix_effects = true;
}
runs.push(Run {
nodes: start..index,
word: Arc::new(word),
effects,
});
}
Ok(runs)
}
fn shipout_width(node: &TextNode, setting: GlueSetting) -> i64 {
match node {
TextNode::Glue(glue) | TextNode::FontSpace(glue, ..) => {
// XeTeX rounds each consumed space independently before joining.
let (mut cumulative, mut previous) = (0, 0);
i64::from(glue.width) + setting.adjustment(*glue, &mut cumulative, &mut previous)
}
TextNode::OpenType(word) => word.width,
TextNode::SpaceAdjustment(width) => i64::from(*width),
_ => 0,
}
}
fn justify(word: &mut OpenTypeRun, target: i64) -> Result<(), String> {
let difference = target - word.width;
word.width = target;
if difference == 0 || word.glyphs.len() < 2 {
return Ok(());
}
let space = word
.font
.face()?
.glyph_index(' ')
.map_or(0, |glyph| glyph.0);
let spaces = word.glyphs.iter().filter(|glyph| glyph.id == space).count();
let total = if spaces == 0 {
word.glyphs.len() - 1
} else {
spaces
};
let mut consumed = 0;
for glyph in &mut word.glyphs {
glyph.x =
(glyph.x as f64 + difference as f64 * consumed as f64 / total as f64).round() as i64;
if spaces == 0 || glyph.id == space {
consumed += 1;
}
}
Ok(())
}
@@ -57,6 +57,7 @@ pub enum DiagnosticNode {
Unsupported(String),
AccentKern(i32),
AutoKern(i32),
SpaceAdjustment(i32),
MarginKern { width: i32, right: bool },
Direction(DirectionBoundary),
}
@@ -226,13 +227,14 @@ pub(super) fn text_nodes(nodes: &[TextNode]) -> Vec<DiagnosticNode> {
value: *g,
name: Some(*p),
},
TextNode::Glue(g) => DiagnosticNode::Glue {
TextNode::Glue(g) | TextNode::FontSpace(g, _, _) => DiagnosticNode::Glue {
value: *g,
name: None,
},
TextNode::Leaders(leader) => leader_node(leader),
TextNode::AccentKern(width) => DiagnosticNode::AccentKern(*width),
TextNode::AutoKern(width) => DiagnosticNode::AutoKern(*width),
TextNode::SpaceAdjustment(width) => DiagnosticNode::SpaceAdjustment(*width),
TextNode::MarginKern { width, right, .. } => DiagnosticNode::MarginKern {
width: *width,
right: *right,
@@ -522,6 +524,11 @@ impl Printer<'_> {
self.number(i64::from(*width));
self.literal(" (for accent)");
}
DiagnosticNode::SpaceAdjustment(width) => {
self.command("kern");
self.number(i64::from(*width));
self.literal(" (space adjustment)");
}
DiagnosticNode::AutoKern(width) => {
self.command("kern");
self.literal(" ");
@@ -3935,7 +3935,7 @@ impl Executor {
}
Explicitspace => {
if self.paragraph.is_some() {
let space = self.explicit_space()?;
let space = self.explicit_space(Some(&token))?;
self.paragraph.as_mut().unwrap().nodes.push(space);
}
}
@@ -797,6 +797,7 @@ fn empty_alignment_box(width: i64, horizontal: bool, span: Span) -> NativeBox {
},
diagnostic: Vec::new(),
setting: GlueSetting::default(),
interword_runs: Vec::new(),
badness: 0,
diagnostic_eligible: false,
excess: 0,
@@ -857,7 +858,7 @@ fn set_alignment_cell(
match &cell.content {
BoxContent::Horizontal(v) => {
for n in v {
if let TextNode::Glue(g)
if let TextNode::Glue(g) | TextNode::FontSpace(g, _, _)
| TextNode::NamedGlue(g, _)
| TextNode::Leaders(LeaderGlue { glue: g, .. }) = n
{
@@ -1031,7 +1032,7 @@ fn mark_unset(b: &mut NativeBox, span: u8) -> Result<(), String> {
match &b.content {
BoxContent::Horizontal(v) => {
for n in v {
if let TextNode::Glue(g)
if let TextNode::Glue(g) | TextNode::FontSpace(g, _, _)
| TextNode::NamedGlue(g, _)
| TextNode::Leaders(LeaderGlue { glue: g, .. }) = n
{
@@ -522,6 +522,7 @@ impl Executor {
content: BoxContent::Horizontal(Vec::new()),
diagnostic: Vec::new(),
setting: GlueSetting::default(),
interword_runs: Vec::new(),
badness: 0,
diagnostic_eligible: false,
excess: 0,
@@ -152,7 +152,7 @@ impl Executor {
if b.width + q > width {
let mut shrink = [0i64; 4];
for node in &material {
if let TextNode::Glue(g)
if let TextNode::Glue(g) | TextNode::FontSpace(g, _, _)
| TextNode::NamedGlue(g, _)
| TextNode::Leaders(LeaderGlue { glue: g, .. }) = node
{
@@ -180,7 +180,7 @@ impl Executor {
displacement = (width - b.width - e + 1).div_euclid(2);
if matches!(
material.first(),
Some(TextNode::Glue(_) | TextNode::NamedGlue(_, _) | TextNode::Leaders(_))
Some(TextNode::Glue(_) | TextNode::FontSpace(_, _, _) | TextNode::NamedGlue(_, _) | TextNode::Leaders(_))
) {
displacement = 0;
}
@@ -17,10 +17,10 @@ impl Tail {
}
fn text(node: &TextNode) -> Self {
match node {
TextNode::Glue(g)
TextNode::Glue(g) | TextNode::FontSpace(g, _, _)
| TextNode::NamedGlue(g, _)
| TextNode::Leaders(LeaderGlue { glue: g, .. }) => Self::Glue(*g, false),
TextNode::Kern { width, .. } | TextNode::AccentKern(width) | TextNode::AutoKern(width) => {
TextNode::Kern { width, .. } | TextNode::AccentKern(width) | TextNode::AutoKern(width) | TextNode::SpaceAdjustment(width) => {
Self::Kern(*width)
}
TextNode::Penalty(n) => Self::Penalty(*n),
@@ -767,7 +767,7 @@ impl Executor {
_ => MathStyle::ScriptScript,
})),
Explicitspace => {
let space = match self.explicit_space()? {
let space = match self.explicit_space(None)? {
TextNode::NamedGlue(glue, parameter) => {
MathNode::ExplicitSpace(glue, Some(parameter))
}
@@ -261,7 +261,7 @@ impl Executor {
}
pub(super) fn ship_box(
&mut self,
b: NativeBox,
mut b: NativeBox,
files: &mut impl SourceProvider,
) -> Result<(), Error> {
self.native_page_mut()?;
@@ -314,6 +314,14 @@ impl Executor {
pdf,
};
self.trace_shipout(&b, files)?;
if self.state.input_profile() == InputProfile::XeTeX
&& self.read_parameter(Parameter::XeTeXinterwordspaceshaping).width() > 1
{
let limit = self.limits.steps.saturating_sub(self.steps);
let work = b.prepare_interword_shipout(limit, self.cancellation.as_ref())
.map_err(|error| self.error(error, b.span))?;
self.steps += work;
}
let current = self.current;
let (pdf_resource_entries, pdf_page_attributes) = if device.pdf.is_some() {
(
@@ -142,7 +142,7 @@ impl Executor {
});
Ok(())
}
pub(super) fn explicit_space(&mut self) -> Result<TextNode, Error> {
pub(super) fn explicit_space(&mut self, token: Option<&Token>) -> Result<TextNode, Error> {
let glue = self.read_parameter(Parameter::Spaceskip).glue();
if glue != Glue::default() {
return Ok(TextNode::NamedGlue(glue, Parameter::Spaceskip));
@@ -154,6 +154,13 @@ impl Executor {
.fonts
.font(self.state.text_font())
.map_err(|error| self.error(error, self.current))?;
if self.state.input_profile() == InputProfile::XeTeX && font.opentype().is_some()
&& let Some(token) = token
{
return Ok(TextNode::FontSpace(
font.space(), self.state.text_font(), TokenOrigin::from(token),
));
}
Ok(TextNode::Glue(font.space()))
}
@@ -345,7 +352,7 @@ impl Executor {
.insert(Dependency::Parameter(Parameter::Spaceskip));
self.reads
.insert(Dependency::Parameter(Parameter::Xspaceskip));
b.space(&self.state)
b.space(&self.state, TokenOrigin::from(token))
.map_err(|e| self.error(e, token.invocation.unwrap_or(token.span)))?;
}
return Ok(());
@@ -390,6 +397,7 @@ impl Executor {
if self.state.input_profile() == InputProfile::XeTeX {
self.reads.insert(Dependency::Parameter(Parameter::XeTeXuseglyphmetrics));
self.reads.insert(Dependency::Parameter(Parameter::XeTeXgenerateactualtext));
self.reads.insert(Dependency::Parameter(Parameter::XeTeXinterwordspaceshaping));
if !self.restricted() {
self.reads.insert(Dependency::Parameter(Parameter::XeTeXdashbreakstate));
}
@@ -8,9 +8,9 @@ use std::{
sync::{Arc, Mutex, OnceLock, Weak},
};
const SCHEMA: u32 = 72;
const COMPATIBLE_SCHEMAS: [u32; 39] = [
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, 71, SCHEMA,
const SCHEMA: u32 = 73;
const COMPATIBLE_SCHEMAS: [u32; 40] = [
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, 71, 72, SCHEMA,
];
const ENGINE: &str = concat!("texrra-native/", env!("CARGO_PKG_VERSION"));
@@ -329,6 +329,7 @@ fn delimiter_native_box(content: BoxContent, width: i64, height: i64, depth: i64
content,
diagnostic,
setting: GlueSetting::default(),
interword_runs: Vec::new(),
badness: 0,
diagnostic_eligible: false,
excess: 0,
@@ -125,6 +125,7 @@ impl Converter<'_> {
content: BoxContent::Vertical(nodes),
diagnostic: Vec::new(),
setting: GlueSetting::default(),
interword_runs: Vec::new(),
badness: 0,
diagnostic_eligible: false,
excess: 0,
@@ -6,6 +6,7 @@ use crate::opentype::{OpenTypeFont, OpenTypeRun};
mod break_cache;
mod expansion;
pub(super) mod interword;
mod native_hyphenation;
mod protrusion;
pub(super) use protrusion::stored_margin_kern;
@@ -81,6 +82,8 @@ pub enum TextNode {
AutoKern(i32),
MarginKern { width: i32, right: bool, font: FontId, slot: u16 },
Direction(DirectionBoundary),
FontSpace(Glue, FontId, TokenOrigin),
SpaceAdjustment(i32),
}
#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct NativeParagraph {
@@ -276,7 +279,8 @@ impl Builder {
let original_end = run.text.chars().next_back();
let (text, sources) = run.font.map_text(run.text, run.sources)?;
if self.restricted || !xetex {
return self.push_opentype(&run.font, text, sources, state);
self.push_opentype(&run.font, text, sources, state)?;
return self.adjust_interword_space(state);
}
let dash_breaks = state.parameter(Parameter::XeTeXdashbreakstate).width() > 0;
@@ -317,6 +321,23 @@ impl Builder {
if trailing_break {
self.push_explicit_hyphen_break(run.font.id);
}
self.adjust_interword_space(state)
}
fn adjust_interword_space(&mut self, state: &State) -> Result<(), String> {
if state.input_profile() != InputProfile::XeTeX
|| state.parameter(Parameter::XeTeXinterwordspaceshaping).width() <= 0
{
return Ok(());
}
if let Some((after_glue, width, work)) = interword::adjustment(&self.nodes, state)? {
self.font_steps = self.font_steps.checked_add(work)
.filter(|steps| *steps <= self.font_step_limit)
.ok_or("native OpenType shaping step limit exceeded")?;
if width != 0 {
self.nodes.insert(after_glue, TextNode::SpaceAdjustment(width));
}
}
Ok(())
}
@@ -451,7 +472,7 @@ impl Builder {
code
};
}
pub fn space(&mut self, state: &State) -> Result<(), String> {
pub fn space(&mut self, state: &State, origin: TokenOrigin) -> Result<(), String> {
self.finish_text(true, state)?;
let f = state.fonts.font(state.text_font())?;
let g = f.space();
@@ -505,6 +526,11 @@ impl Builder {
};
self.nodes.push(match name {
Some(name) => TextNode::NamedGlue(g, name),
None if factor == 1000 && s == Glue::default()
&& state.input_profile() == InputProfile::XeTeX && f.opentype().is_some() =>
{
TextNode::FontSpace(g, state.text_font(), origin)
}
None => TextNode::Glue(g),
});
Ok(())
@@ -533,10 +559,11 @@ pub(super) fn hyphen_node(state: &State, font: FontId, c: char, origin: TokenOri
fn discardable(n: &TextNode) -> bool {
matches!(
n,
TextNode::Glue(_)
TextNode::Glue(_) | TextNode::FontSpace(_, _, _)
| TextNode::NamedGlue(_, _)
| TextNode::Leaders(_)
| TextNode::Kern { .. }
| TextNode::SpaceAdjustment(_)
| TextNode::MathBoundary { .. }
| TextNode::Direction(_)
| TextNode::Penalty(_)
@@ -548,13 +575,14 @@ fn width(n: &TextNode) -> i64 {
glyph.width
}
TextNode::OpenType(run) => run.width,
TextNode::Glue(g)
TextNode::Glue(g) | TextNode::FontSpace(g, _, _)
| TextNode::NamedGlue(g, _)
| TextNode::Leaders(LeaderGlue { glue: g, .. }) => g.width as i64,
TextNode::Rule(r) => r.dimensions().0,
TextNode::Output(node) => node.dimensions().map_or(0, |(width, _, _)| width),
TextNode::Kern { width: n, .. }
| TextNode::AccentKern(n)
| TextNode::SpaceAdjustment(n)
| TextNode::AutoKern(n)
| TextNode::MarginKern { width: n, .. }
| TextNode::MathBoundary { width: n, .. }
@@ -695,7 +723,7 @@ fn metrics(nodes: &[TextNode], left: Glue, right: Glue) -> (i64, [i64; 4], i64)
let mut shrink = 0;
for g in std::iter::once(left)
.chain(nodes.iter().filter_map(|n| {
if let TextNode::Glue(g)
if let TextNode::Glue(g) | TextNode::FontSpace(g, _, _)
| TextNode::NamedGlue(g, _)
| TextNode::Leaders(LeaderGlue { glue: g, .. }) = n
{
@@ -715,7 +743,7 @@ fn metrics(nodes: &[TextNode], left: Glue, right: Glue) -> (i64, [i64; 4], i64)
.filter(|n| {
!matches!(
n,
TextNode::Glue(_) | TextNode::NamedGlue(_, _) | TextNode::Leaders(_)
TextNode::Glue(_) | TextNode::FontSpace(_, _, _) | TextNode::NamedGlue(_, _) | TextNode::Leaders(_)
)
})
.map(width)
@@ -1204,7 +1232,7 @@ fn pre_display_line_size(
| TextNode::Indent(_)
| TextNode::Rule(_)
);
if let TextNode::Glue(g)
if let TextNode::Glue(g) | TextNode::FontSpace(g, _, _)
| TextNode::NamedGlue(g, _)
| TextNode::Leaders(LeaderGlue { glue: g, .. }) = n
{
@@ -1239,7 +1267,7 @@ pub(super) fn finish(
if b.nodes.last().is_some_and(|n| {
matches!(
n,
TextNode::Glue(_) | TextNode::NamedGlue(_, _) | TextNode::Leaders(_)
TextNode::Glue(_) | TextNode::FontSpace(_, _, _) | TextNode::NamedGlue(_, _) | TextNode::Leaders(_)
)
}) {
b.nodes.pop();
@@ -1262,7 +1290,7 @@ pub(super) fn finish(
.collect();
let shape = state.paragraph_shape().to_vec();
for n in &b.nodes {
if let TextNode::Glue(g)
if let TextNode::Glue(g) | TextNode::FontSpace(g, _, _)
| TextNode::NamedGlue(g, _)
| TextNode::Leaders(LeaderGlue { glue: g, .. }) = n
&& g.shrink.order != 0
@@ -1528,7 +1556,7 @@ fn add_hyphens(
.is_some_and(|n| {
matches!(
n,
TextNode::Glue(_) | TextNode::NamedGlue(_, _) | TextNode::Leaders(_)
TextNode::Glue(_) | TextNode::FontSpace(_, _, _) | TextNode::NamedGlue(_, _) | TextNode::Leaders(_)
)
})
&& !word.is_empty()
@@ -1559,7 +1587,7 @@ fn add_hyphens(
| TextNode::Insertion(_)
| TextNode::Mark(_)
| TextNode::Output(_)
| TextNode::Glue(_)
| TextNode::Glue(_) | TextNode::FontSpace(_, _, _)
| TextNode::NamedGlue(_, _)
| TextNode::Leaders(_)
| TextNode::Penalty(_)
@@ -151,13 +151,14 @@ impl BreakNode {
| TextNode::Output(_)
| TextNode::MathChar(_)
| TextNode::Indent(_) => Self::Content(width(node)),
TextNode::Glue(glue)
TextNode::Glue(glue) | TextNode::FontSpace(glue, _, _)
| TextNode::NamedGlue(glue, _)
| TextNode::Leaders(LeaderGlue { glue, .. }) => Self::Glue(*glue),
TextNode::AccentKern(width) => Self::AccentKern(*width),
TextNode::MarginKern { width, .. } | TextNode::AutoKern(width) => {
Self::Content(i64::from(*width))
}
TextNode::SpaceAdjustment(width) => Self::Kern { width: *width, explicit: false },
TextNode::Kern { width, explicit } => Self::Kern {
width: *width,
explicit: *explicit,
@@ -0,0 +1,63 @@
//! XeTeX contextual width measurement for an interword glue node.
use super::*;
pub(in crate::execution) fn invisible(node: &TextNode) -> bool {
matches!(
node,
TextNode::Language(_)
| TextNode::Penalty(_)
| TextNode::Insertion(_)
| TextNode::Mark(_)
| TextNode::Adjustment(_)
) || matches!(
node,
TextNode::Output(OutputNode {
operation: OutputOperation::Open { .. }
| OutputOperation::Write { .. }
| OutputOperation::Close { .. }
| OutputOperation::Special { .. },
..
})
)
}
pub(super) fn adjustment(
nodes: &[TextNode],
state: &State,
) -> Result<Option<(usize, i32, usize)>, String> {
let Some((TextNode::OpenType(right), prefix)) = nodes.split_last() else {
return Ok(None);
};
let mut preceding = prefix
.iter()
.enumerate()
.rev()
.filter(|(_, node)| !invisible(node));
let Some((
glue_index,
TextNode::Glue(_)
| TextNode::FontSpace(..)
| TextNode::NamedGlue(..)
| TextNode::Leaders(_),
)) = preceding.next()
else {
return Ok(None);
};
let Some((_, TextNode::OpenType(left))) = preceding.next() else {
return Ok(None);
};
if left.font.id != right.font.id {
return Ok(None);
}
let text = format!("{} {}", left.text, right.text);
if text.encode_utf16().count() > usize::from(u16::MAX) {
return Err("native contextual OpenType word capacity exceeded".into());
}
let joined = right.font.shape_mapped(text, Vec::new(), false)?;
let nominal_space = i64::from(state.fonts.font(right.font.id)?.space().width);
let width = joined.width - left.width - right.width - nominal_space;
let width = i32::try_from(width).map_err(|_| "native contextual space width overflow")?;
Ok(Some((glue_index + 1, width, joined.glyphs.len())))
}
@@ -21,11 +21,12 @@ pub(super) fn add_hyphens(
match node {
TextNode::Language(next) => language = *next,
TextNode::Direction(_)
| TextNode::SpaceAdjustment(_)
| TextNode::Output(_)
| TextNode::Kern {
explicit: false, ..
} => {}
TextNode::Glue(_) | TextNode::NamedGlue(_, _) | TextNode::Leaders(_) => {
TextNode::Glue(_) | TextNode::FontSpace(_, _, _) | TextNode::NamedGlue(_, _) | TextNode::Leaders(_) => {
after_glue = auto_breaking;
}
TextNode::MathBoundary { after, .. } => {
@@ -197,12 +198,13 @@ fn following_nodes_allow_hyphenation(nodes: &[TextNode]) -> bool {
| TextNode::Insertion(_)
| TextNode::Mark(_)
| TextNode::Output(_)
| TextNode::Glue(_)
| TextNode::Glue(_) | TextNode::FontSpace(_, _, _)
| TextNode::NamedGlue(_, _)
| TextNode::Leaders(_)
| TextNode::Penalty(_)
| TextNode::AccentKern(_)
| TextNode::AutoKern(_)
| TextNode::SpaceAdjustment(_)
| TextNode::Kern { explicit: true, .. }
)
})
@@ -123,7 +123,7 @@ fn skippable(node: &TextNode) -> bool {
| TextNode::Kern { explicit: false, .. }
| TextNode::Kern { width: 0, .. } => true,
TextNode::Output(node) => node.dimensions().is_none(),
TextNode::Glue(glue)
TextNode::Glue(glue) | TextNode::FontSpace(glue, _, _)
| TextNode::NamedGlue(glue, _)
| TextNode::Leaders(LeaderGlue { glue, .. }) => glue.canonical_zero,
TextNode::Discretionary {
@@ -215,7 +215,7 @@ impl Tracer {
| TextNode::Mark(_)
| TextNode::Output(_) => out.push_str("[]"),
TextNode::Rule(_) => out.push('|'),
TextNode::Glue(g)
TextNode::Glue(g) | TextNode::FontSpace(g, _, _)
| TextNode::NamedGlue(g, _)
| TextNode::Leaders(LeaderGlue { glue: g, .. }) => {
if !g.canonical_zero {
@@ -234,7 +234,7 @@ impl Tracer {
i += usize::from(*replacement_count);
}
TextNode::Kern { .. } | TextNode::AccentKern(_) | TextNode::Penalty(_)
| TextNode::AutoKern(_) | TextNode::MarginKern { .. } => {}
| TextNode::AutoKern(_) | TextNode::SpaceAdjustment(_) | TextNode::MarginKern { .. } => {}
}
i += 1;
}
@@ -127,6 +127,7 @@ pub enum Parameter {
XeTeXprotrudechars,
XeTeXhyphenatablelength,
XeTeXgenerateactualtext,
XeTeXinterwordspaceshaping,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
pub enum ParameterValue {
@@ -159,7 +160,7 @@ impl Parameter {
)
}
pub(super) const XETEX: [Self; 7] = [
pub(super) const XETEX: [Self; 8] = [
Self::XeTeXuseglyphmetrics,
Self::XeTeXdashbreakstate,
Self::Suppressfontnotfounderror,
@@ -167,6 +168,7 @@ impl Parameter {
Self::XeTeXprotrudechars,
Self::XeTeXhyphenatablelength,
Self::XeTeXgenerateactualtext,
Self::XeTeXinterwordspaceshaping,
];
pub const ALL: &'static [Self] = &[
@@ -292,6 +294,7 @@ impl Parameter {
Self::XeTeXprotrudechars,
Self::XeTeXhyphenatablelength,
Self::XeTeXgenerateactualtext,
Self::XeTeXinterwordspaceshaping,
];
pub fn name(self) -> String {
match self {
@@ -302,6 +305,7 @@ impl Parameter {
Self::XeTeXprotrudechars => "XeTeXprotrudechars".into(),
Self::XeTeXhyphenatablelength => "XeTeXhyphenatablelength".into(),
Self::XeTeXgenerateactualtext => "XeTeXgenerateactualtext".into(),
Self::XeTeXinterwordspaceshaping => "XeTeXinterwordspaceshaping".into(),
_ => format!("{self:?}").to_ascii_lowercase(),
}
}