Files
texrra-engine/crates/texrra-tex-core/src/execution/paragraph.rs
T

1923 lines
70 KiB
Rust
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
//! Native horizontal material and paragraph breaking. No command/string parser.
use super::*;
use crate::{HorizontalBox, Paragraph, ParagraphFont, provenance::PaintSource};
use std::{collections::BTreeMap, sync::Arc};
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;
use break_cache::BreakNode;
pub use break_cache::{LineBreakCache, LineBreakWork};
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
pub(super) struct ParagraphShapeLine {
pub indent: i32,
pub width: i32,
}
/// A one-based index, extended by the final element of a nonempty array.
pub(super) fn line_penalty_at(values: &[i32], index: usize) -> Option<i32> {
values.get(index.min(values.len()).wrapping_sub(1)).copied()
}
pub(super) fn shaped_line(shape: &[ParagraphShapeLine], line: usize) -> Option<ParagraphShapeLine> {
shape.get(line).or_else(|| shape.last()).copied()
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub enum ParagraphMode {
#[default]
Vertical,
Horizontal,
Math,
}
#[derive(Clone, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
pub enum TextNode {
Language(HyphenationLanguage),
Glyph {
font: FontId,
glyph: HorizontalBox,
slot: u8,
original: String,
ligature: bool,
left_boundary: bool,
right_boundary: bool,
origins: Vec<Span>,
component_sources: Vec<crate::provenance::PaintSource>,
hyphen_char: Option<char>,
},
OpenType(Arc<OpenTypeRun>),
Box(HorizontalBox),
Rule(NativeRule),
Mark(NativeMark),
Adjustment(NativeAdjustment),
Insertion(NativeInsertion),
Output(OutputNode),
/// A genuine unboxed math character; any italic correction is a kern.
MathChar(HorizontalBox),
MathBoundary {
width: i32,
after: bool,
},
Glue(Glue),
NamedGlue(Glue, Parameter),
/// Zero glue retained by the conversion of a conditional math marker.
ConditionalMathGlue,
Leaders(LeaderGlue),
Kern {
width: i32,
explicit: bool,
},
Indent(i32),
Penalty(i32),
Discretionary {
font: FontId,
automatic: bool,
/// Originating shorthand/automatic hyphen; dimensions and rendering
/// always consume the actual owned branch lists below.
hyphen_char: Option<char>,
pre_break: Vec<TextNode>,
post_break: Vec<TextNode>,
replacement_count: u8,
},
/// Spacing owned by a text accent and protected from leading discard.
AccentKern(i32),
AutoKern(i32),
MarginKern { width: i32, right: bool, font: FontId, slot: u16 },
Direction(DirectionBoundary),
FontSpace(Glue, FontId, TokenOrigin),
SpaceAdjustment(i32),
/// A native XeTeX glyph node carries no text for shaping or hyphenation.
ExplicitOpenTypeGlyph(Arc<OpenTypeRun>),
}
#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct NativeParagraph {
pub initial_language: HyphenationLanguage,
pub nodes: Vec<TextNode>,
pub previous_lines: usize,
pub final_widow: Parameter,
pub pre_display_size: i32,
pub parameters: BTreeMap<Parameter, ParameterValue>,
pub lines: Vec<Paragraph>,
pub line_boxes: Vec<NativeBox>,
pub line_adjustments: Vec<Vec<NativeVerticalNode>>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub line_pre_adjustments: Vec<Vec<NativeVerticalNode>>,
pub diagnostic_lines: Vec<super::diagnostics::DiagnosticBox>,
/// Actual discretionary breaks selected by line breaking (terminal false).
pub discretionary_breaks: Vec<bool>,
/// One summed value per interline gap; zero means no penalty node.
pub interline_penalties: Vec<i32>,
pub badness: Vec<i32>,
pub packed_badness: Vec<i32>,
pub packed_excess: Vec<i64>,
pub packed_diagnostic: Vec<bool>,
pub packed_shrinking: Vec<bool>,
pub pass: u8,
pub parskip: Glue,
pub span: Span,
pub hyphen_min: (usize, usize),
pub missing_glyphs: Vec<(FontId, u8, Span)>,
}
#[derive(Clone, Copy, Debug)]
pub(super) struct XeCharRun {
pub previous: u16,
pub last_ignored: bool,
}
#[derive(Clone, Debug, Default)]
pub(super) struct Builder {
pub initial_language: HyphenationLanguage,
pub current_language: HyphenationLanguage,
pub restricted: bool,
pub nodes: Vec<TextNode>,
pub span: Span,
pub parskip: Glue,
pub space_factor: i32,
pub hyphen_min: (usize, usize),
run: Option<FontRun>,
opentype: Option<PendingOpenType>,
pub cancel_boundary: bool,
pub xe_char_run: Option<XeCharRun>,
pub font_steps: usize,
pub font_step_limit: usize,
pub ligature_carry: super::ligature::Carry,
pub vertical_start: usize,
pub previous_lines: usize,
}
#[derive(Clone, Debug)]
struct FontRun {
font: std::sync::Arc<crate::native_font::NativeFont>,
machine: super::ligature::Machine,
hyphen_char: Option<char>,
}
#[derive(Clone, Debug)]
struct PendingOpenType {
font: Arc<OpenTypeFont>,
text: String,
utf16_units: usize,
sources: Vec<(usize, crate::provenance::PaintSource)>,
}
impl Builder {
pub(super) fn has_unpacked_text(&self) -> bool {
self.opentype.is_some() || self.run.as_ref()
.is_some_and(|run| run.machine.has_unpacked_components())
}
pub(super) fn ligature_work_items(&self) -> usize {
self.run.as_ref().map_or(0, |r| r.machine.resource_items())
+ self.opentype.as_ref().map_or(0, |run| run.sources.len())
}
pub fn start(&mut self, state: &State, span: Span, indent: bool) {
self.span = span;
self.initial_language = HyphenationLanguage::from_state(state);
self.current_language = self.initial_language;
self.parskip = state.parameter(Parameter::Parskip).glue();
self.space_factor = 1000;
self.hyphen_min = (
state
.parameter(Parameter::Lefthyphenmin)
.width()
.clamp(1, 63) as usize,
state
.parameter(Parameter::Righthyphenmin)
.width()
.clamp(1, 63) as usize,
);
if indent {
self.nodes.push(TextNode::Indent(
state.parameter(Parameter::Parindent).width(),
));
}
}
pub fn set_language(&mut self, language: HyphenationLanguage, state: &State) -> Result<(), String> {
self.finish_text(true, state)?;
self.current_language = language;
self.nodes.push(TextNode::Language(language));
Ok(())
}
fn append_shaped(
&mut self,
run: &FontRun,
output: Vec<super::ligature::Output>,
) -> Vec<super::ligature::Component> {
use super::ligature::Output;
let mut missing = Vec::new();
let mut hyphen_break = None;
for item in output {
match item {
Output::Glyph(g) => {
// TeX tests the last consumed character before packing the
// ligature, not the replacement glyph's numeric slot.
let explicit_hyphen = g
.components
.last()
.is_some_and(|c| Some(char::from(c.slot)) == run.hyphen_char);
self.nodes.push(TextNode::Glyph {
font: run.font.id,
glyph: super::fonts::text_glyph_from_font(&run.font, g.slot, g.source),
slot: g.slot,
original: g.components.iter().map(|c| char::from(c.slot)).collect(),
origins: g.components.iter().map(|c| c.origin).collect(),
component_sources: g.components.iter().map(|c| c.source.clone()).collect(),
ligature: g.ligature,
left_boundary: g.left_boundary,
right_boundary: g.right_boundary,
hyphen_char: run.hyphen_char,
});
if explicit_hyphen && !self.restricted {
hyphen_break = Some(self.nodes.len());
self.push_explicit_hyphen_break(run.font.id);
}
}
Output::Kern(width) => self.nodes.push(TextNode::Kern {
width,
explicit: false,
}),
Output::AutoKern { width, after_wrap } => {
let node = TextNode::AutoKern(width);
if after_wrap && hyphen_break.is_some_and(|i| i + 1 == self.nodes.len()) {
self.nodes.insert(self.nodes.len() - 1, node);
} else {
self.nodes.push(node);
}
}
Output::Missing(c) => missing.push(c),
}
}
missing
}
pub fn finish_text(&mut self, right_boundary: bool, state: &State) -> Result<(), String> {
if let Some(run) = self.opentype.take() {
self.finish_opentype(run, state)?;
}
if let Some(mut run) = self.run.take() {
run.machine
.put_carry(std::mem::take(&mut self.ligature_carry));
let output = run.machine.finish(
state.fonts.program(run.font.id)?,
right_boundary,
FontCatalog::auto_kern_for(state, run.font.id),
&mut self.font_steps,
self.font_step_limit,
)?;
let missing = self.append_shaped(&run, output);
self.ligature_carry = run.machine.take_carry();
if !missing.is_empty() {
return Err("unfetched character left at native font boundary".into());
}
}
Ok(())
}
fn push_explicit_hyphen_break(&mut self, font: FontId) {
self.nodes.push(TextNode::Discretionary {
font,
automatic: false,
hyphen_char: None,
pre_break: Vec::new(),
post_break: Vec::new(),
replacement_count: 0,
});
}
fn finish_opentype(&mut self, run: PendingOpenType, state: &State) -> Result<(), String> {
let xetex = state.input_profile() == InputProfile::XeTeX;
let original_end = run.text.chars().next_back();
let (text, sources) = run.font.map_text(run.text, run.sources)?;
if self.restricted || !xetex {
self.push_opentype(&run.font, text, sources, state)?;
return self.adjust_interword_space(state);
}
let dash_breaks = state.parameter(Parameter::XeTeXdashbreakstate).width() > 0;
let hyphen = u32::try_from(state.font_integers(run.font.id).hyphen)
.ok()
.and_then(char::from_u32);
let is_hyphen = |c| Some(c) == hyphen || (dash_breaks && matches!(c, '–' | '—'));
// XeTeX tests the end of the original word for the final discretionary,
// and the characters of the mapped word for interior breakpoints.
let trailing_break = original_end.is_some_and(is_hyphen);
let ends = text.char_indices().filter_map(|(at, c)| {
let end = at + c.len_utf8();
(end < text.len() && is_hyphen(c)).then_some(end)
});
let mut ends = ends.peekable();
if ends.peek().is_none() {
self.push_opentype(&run.font, text, sources, state)?;
} else {
let mut sources = sources.into_iter().peekable();
let mut start = 0;
for end in ends.chain(std::iter::once(text.len())) {
let mut fragment_sources = Vec::new();
while let Some((offset, origin)) = sources.next_if(|(at, _)| *at < end) {
fragment_sources.push((offset - start, origin));
}
self.push_opentype(
&run.font,
text[start..end].to_owned(),
fragment_sources,
state,
)?;
if end != text.len() {
self.push_explicit_hyphen_break(run.font.id);
}
start = end;
}
}
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(())
}
fn push_opentype(
&mut self,
font: &Arc<OpenTypeFont>,
mut text: String,
mut sources: Vec<(usize, PaintSource)>,
state: &State,
) -> Result<(), String> {
let xetex = state.input_profile() == InputProfile::XeTeX;
let use_glyph_metrics =
xetex && state.parameter(Parameter::XeTeXuseglyphmetrics).width() > 0;
// A fresh word takes the current subtype, including when the scanner
// replaces the preceding word. Packing preserves the first subtype.
let previous = match self.nodes.as_slice() {
[.., preceding, TextNode::OpenType(run)]
if xetex && run.font.id == font.id
&& !matches!(preceding, TextNode::Glyph { ligature: false, .. }
| TextNode::Discretionary { .. }) =>
{
Some(run)
}
_ => None,
}.filter(|_| {
!self.nodes.iter().rev().skip(1).take(usize::from(u8::MAX))
.enumerate().any(|(offset, node)| {
matches!(node, TextNode::Discretionary { replacement_count, .. }
if usize::from(*replacement_count) > offset)
})
});
if let Some(previous) = previous {
let offset = previous.text.len();
let mut joined = previous.text.clone();
joined.push_str(&text);
if joined.encode_utf16().count() > usize::from(u16::MAX) {
return Err("native OpenType word capacity exceeded".into());
}
text = joined;
let mut joined_sources = previous.sources.clone();
joined_sources.extend(sources.into_iter().map(|(at, source)| (at + offset, source)));
sources = joined_sources;
}
if previous.is_some() {
self.nodes.pop();
}
let actual_text = xetex && state.parameter(Parameter::XeTeXgenerateactualtext).width() > 0;
if xetex && !self.restricted
&& let Some(locale) = &state.xe_line_break_locale
{
let ends = super::xe_encoding::icu::line_breaks(locale, &text)?;
if !ends.is_empty() {
let glue = state.parameter(Parameter::XeTeXlinebreakskip).glue();
let penalty = state.parameter(Parameter::XeTeXlinebreakpenalty).width();
let use_skip = !glue.canonical_zero;
let mut sources = sources.into_iter().peekable();
let mut start = 0;
for end in ends.into_iter().chain(std::iter::once(text.len())) {
if start != 0 {
if penalty != 0 || !use_skip {
self.nodes.push(TextNode::Penalty(penalty));
}
if use_skip {
self.nodes.push(TextNode::NamedGlue(glue, Parameter::XeTeXlinebreakskip));
}
}
let mut origins = Vec::new();
while let Some((offset, source)) = sources.next_if(|(offset, _)| *offset < end) {
origins.push((offset - start, source));
}
self.shape_opentype(font, text[start..end].to_owned(), origins, use_glyph_metrics, actual_text)?;
start = end;
}
return Ok(());
}
}
self.shape_opentype(font, text, sources, use_glyph_metrics, actual_text)
}
fn shape_opentype(
&mut self,
font: &Arc<OpenTypeFont>,
text: String,
sources: Vec<(usize, PaintSource)>,
use_glyph_metrics: bool,
actual_text: bool,
) -> Result<(), String> {
let mut shaped = font.shape_mapped(text, sources, use_glyph_metrics)?;
shaped.actual_text = actual_text;
self.font_steps = self.font_steps.checked_add(shaped.glyphs.len())
.filter(|steps| *steps <= self.font_step_limit)
.ok_or("native OpenType shaping step limit exceeded")?;
self.nodes.push(TextNode::OpenType(Arc::new(shaped)));
Ok(())
}
pub fn opentype_character(
&mut self, c: char, origin: TokenOrigin, state: &State, font: Arc<OpenTypeFont>,
) -> Result<(), String> {
if self.run.is_some() || self.opentype.as_ref().is_some_and(|r| r.font.id != font.id) {
self.finish_text(true, state)?;
}
self.cancel_boundary = false;
let run = self.opentype.get_or_insert_with(|| PendingOpenType {
font, text: String::new(), utf16_units: 0, sources: Vec::new(),
});
// Native words carry a 16-bit character count in XeTeX.
run.utf16_units += c.len_utf16();
if run.utf16_units > u16::MAX as usize {
return Err("native OpenType word capacity exceeded".into());
}
run.sources.push((run.text.len(), crate::provenance::PaintSource::token(origin)));
run.text.push(c);
Ok(())
}
pub fn character(
&mut self,
c: char,
origin: TokenOrigin,
state: &State,
font: FontId,
hyphen_char: Option<char>,
) -> Result<Vec<super::ligature::Component>, String> {
if self.opentype.is_some() {
self.finish_text(true, state)?;
}
let c = super::ligature::Component {
slot: c as u8,
origin: origin.span,
source: crate::provenance::PaintSource::token(origin),
};
if self
.run
.as_ref()
.is_some_and(|r| r.font.id != font || r.hyphen_char != hyphen_char)
{
self.finish_text(true, state)?;
}
let cancel = self.cancel_boundary;
self.cancel_boundary = false;
if font == FontId::NULL {
return Ok(vec![c]);
}
let mut run = self.run.take().unwrap_or(FontRun {
font: state.fonts.glyph_font(font)?.clone(),
machine: super::ligature::Machine::default(),
hyphen_char,
});
run.machine
.put_carry(std::mem::take(&mut self.ligature_carry));
let output = run.machine.feed(
state.fonts.program(font)?,
c,
cancel,
FontCatalog::auto_kern_for(state, font),
&mut self.font_steps,
self.font_step_limit,
)?;
let missing = self.append_shaped(&run, output);
self.ligature_carry = run.machine.take_carry();
self.run = Some(run);
Ok(missing)
}
pub fn adjust_space_factor(&mut self, code: u16) {
let code = i32::from(code);
if code == 0 {
return;
}
self.space_factor = if code > 1000 && self.space_factor < 1000 {
1000
} else {
code
};
}
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();
let (space, stretch, shrink, extra) = (
g.width as i64,
g.stretch.amount as i64,
g.shrink.amount as i64,
f.extra_space() as i64,
);
let factor = self.space_factor.max(1) as i64;
let x = state.parameter(Parameter::Xspaceskip).glue();
let s = state.parameter(Parameter::Spaceskip).glue();
let (g, name) = if factor >= 2000 && x != Glue::default() {
(x, Some(Parameter::Xspaceskip))
} else if factor == 1000 && s != Glue::default() {
(s, Some(Parameter::Spaceskip))
} else {
let mut g = if s != Glue::default() {
s
} else {
Glue {
canonical_zero: false,
width: space as i32,
stretch: Flex {
amount: stretch as i32,
order: 0,
},
shrink: Flex {
amount: shrink as i32,
order: 0,
},
}
};
if factor >= 2000 {
g.width = g
.width
.checked_add(extra as i32)
.expect("font space within dimension range");
}
let stretch = g.stretch.amount as i64 * factor / 1000;
let shrink = g.shrink.amount as i64 * 1000 / factor;
if [g.width as i64, stretch, shrink]
.iter()
.any(|n| n.abs() > 1073741823)
{
return Err("native space-factor glue overflow".into());
}
g.stretch.amount = stretch as i32;
g.shrink.amount = shrink as i32;
(g, None)
};
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(())
}
}
pub(super) fn hyphen_node(state: &State, font: FontId, c: char, origin: TokenOrigin) -> TextNode {
TextNode::Glyph {
font,
slot: c as u8,
glyph: super::fonts::text_glyph(
state,
font,
c as u8,
crate::provenance::PaintSource::token(origin),
),
original: c.to_string(),
origins: Vec::new(),
component_sources: Vec::new(),
hyphen_char: None,
ligature: false,
left_boundary: false,
right_boundary: false,
}
}
fn discardable(n: &TextNode) -> bool {
matches!(
n,
TextNode::Glue(_) | TextNode::FontSpace(_, _, _)
| TextNode::NamedGlue(_, _)
| TextNode::ConditionalMathGlue
| TextNode::Leaders(_)
| TextNode::Kern { .. }
| TextNode::SpaceAdjustment(_)
| TextNode::MathBoundary { .. }
| TextNode::Direction(_)
| TextNode::Penalty(_)
)
}
fn width(n: &TextNode) -> i64 {
match n {
TextNode::Glyph { glyph, .. } | TextNode::Box(glyph) | TextNode::MathChar(glyph) => {
glyph.width
}
TextNode::OpenType(run) | TextNode::ExplicitOpenTypeGlyph(run) => run.width,
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, .. }
| TextNode::Indent(n) => *n as i64,
_ => 0,
}
}
/// Integer TeX badness, including its saturation and overflow-avoidance rules.
pub fn tex_badness(t: i64, s: i64) -> i32 {
if t == 0 {
return 0;
}
if s <= 0 {
return 10000;
}
let r = if t <= 7230584 {
t * 297 / s
} else if s >= 1663497 {
t / (s / 297)
} else {
t
};
if r > 1290 {
10000
} else {
((r * r * r + 131072) / 262144) as i32
}
}
#[derive(Clone, Copy)]
struct Break {
end: usize,
next: usize,
penalty: i32,
hyphen: bool,
pre_break: Option<usize>,
zero_tail: Option<usize>,
forced: bool,
}
#[derive(Clone)]
struct LineBreaks {
lines: Vec<(Break, i32)>,
final_fill: Option<Glue>,
}
#[derive(Clone, Copy, Default)]
struct FitWidths {
shortfall: i64,
glue: i64,
}
impl FitWidths {
// e-TeX computes the previous line's ratio in scaled points first,
// then applies lastlinefit in thousandths with a second rounding.
fn adjustment(self, available: i64, factor: i64) -> i64 {
if self.shortfall == 0 || self.glue <= 0 || available <= 0 {
return 0;
}
const MAX_DIMEN: i128 = (1 << 30) - 1;
let denominator = i128::from(self.glue);
let product = i128::from(available) * i128::from(self.shortfall.abs());
let scaled = (product + denominator / 2) / denominator;
let scaled = if scaled > MAX_DIMEN {
MAX_DIMEN
} else {
(scaled * i128::from(factor) + 500) / 1000
};
scaled as i64 * self.shortfall.signum()
}
}
#[derive(Clone)]
struct Active {
serial: usize,
previous: usize,
start: usize,
measurement_start: usize,
post_break: Option<usize>,
line: usize,
fitness: u8,
hyphen: bool,
cost: i64,
fit_widths: FitWidths,
path: Vec<(Break, i32)>,
}
fn geometry(
parameters: &BTreeMap<Parameter, ParameterValue>,
shape: &[ParagraphShapeLine],
line: usize,
) -> (i64, i64) {
if let Some(line) = shaped_line(shape, line) {
return (i64::from(line.indent), i64::from(line.width));
}
let get = |p| parameters[&p].width() as i64;
let hang = get(Parameter::Hangindent);
let after = get(Parameter::Hangafter);
let applies = if after >= 0 {
line as i64 >= after
} else {
(line as i64) < -after
};
if applies && hang != 0 {
(hang.max(0), get(Parameter::Hsize) - hang.abs())
} else {
(0, get(Parameter::Hsize))
}
}
fn line_material(
nodes: &[TextNode],
start: usize,
end: usize,
post: Option<usize>,
pre: Option<usize>,
marker: bool,
zero_tail: Option<usize>,
) -> Vec<TextNode> {
let mut material = Vec::new();
if let Some(index) = post {
if let TextNode::Discretionary { post_break, .. } = &nodes[index] {
material.extend_from_slice(post_break);
}
}
material.extend_from_slice(&nodes[start..end]);
// post_line_break keeps a penalty breakpoint in the justified hlist and
// appends rightskip after it. Only the following line's leading penalties
// are discarded; the chosen breakpoint itself is a real retained node.
if marker && let Some(TextNode::Penalty(value)) = nodes.get(end) {
material.push(TextNode::Penalty(*value));
}
if let Some(index) = zero_tail {
material.push(match &nodes[index] {
TextNode::Kern { explicit, .. } => TextNode::Kern {
width: 0,
explicit: *explicit,
},
TextNode::Direction(boundary) => TextNode::Direction(*boundary),
TextNode::MathBoundary { after, .. } => TextNode::MathBoundary {
width: 0,
after: *after,
},
_ => unreachable!("zero-width retained line-break node"),
});
}
if let Some(index) = pre {
if let TextNode::Discretionary {
font, pre_break, ..
} = &nodes[index]
{
if marker {
material.push(TextNode::Discretionary {
font: *font,
automatic: false,
hyphen_char: None,
pre_break: Vec::new(),
post_break: Vec::new(),
replacement_count: 0,
});
}
material.extend_from_slice(pre_break);
}
}
material
}
fn has_post(nodes: &[TextNode], index: Option<usize>) -> bool {
index.is_some_and(
|i| matches!(&nodes[i],TextNode::Discretionary{post_break,..}if !post_break.is_empty()),
)
}
fn metrics(nodes: &[TextNode], left: Glue, right: Glue) -> (i64, [i64; 4], i64) {
let mut natural = 0;
let mut stretch = [0i64; 4];
let mut shrink = 0;
for g in std::iter::once(left)
.chain(nodes.iter().filter_map(|n| {
if let TextNode::Glue(g) | TextNode::FontSpace(g, _, _)
| TextNode::NamedGlue(g, _)
| TextNode::Leaders(LeaderGlue { glue: g, .. }) = n
{
Some(*g)
} else {
None
}
}))
.chain(std::iter::once(right))
{
natural += g.width as i64;
stretch[g.stretch.order as usize] += g.stretch.amount as i64;
shrink += g.shrink.amount as i64;
}
natural += nodes
.iter()
.filter(|n| {
!matches!(
n,
TextNode::Glue(_) | TextNode::FontSpace(_, _, _) | TextNode::NamedGlue(_, _)
| TextNode::ConditionalMathGlue | TextNode::Leaders(_)
)
})
.map(width)
.sum::<i64>();
(natural, stretch, shrink)
}
fn break_lines(
nodes: &[TextNode],
projected: &[BreakNode],
mut margins: Option<&mut protrusion::Search>,
expansion: Option<&expansion::Search>,
state: &mut State,
files: &mut impl SourceProvider,
p: &BTreeMap<Parameter, ParameterValue>,
shape: &[ParagraphShapeLine],
pass: u8,
work: &mut usize,
previous_lines: usize,
trace: &mut super::paragraph_trace::Tracer,
) -> Result<Option<LineBreaks>, String> {
let get = |q| p[&q].width() as i64;
let left = p[&Parameter::Leftskip].glue();
let right = p[&Parameter::Rightskip].glue();
let par_fill = p[&Parameter::Parfillskip].glue();
let fit_factor = get(Parameter::Lastlinefit).min(1000);
let mut infinite_fill = [0; 4];
let fit_last_line = fit_factor > 0
&& par_fill.stretch.amount > 0
&& par_fill.stretch.order > 0
&& (1..4).all(|order| {
[left.stretch, right.stretch]
.into_iter()
.filter(|stretch| stretch.order == order)
.map(|stretch| i64::from(stretch.amount))
.sum::<i64>()
== 0
});
if fit_last_line {
infinite_fill[usize::from(par_fill.stretch.order)] = i64::from(par_fill.stretch.amount);
}
let mut breaks = Vec::new();
let mut auto_breaking = true;
let mut replacement_end = 0;
let widths = break_cache::prefix_widths(projected);
for (i, node) in projected.iter().enumerate() {
if i < replacement_end {
continue;
}
if let BreakNode::Discretionary {
replacement_count, ..
} = node
{
replacement_end = i + 1 + usize::from(*replacement_count);
}
if let BreakNode::MathBoundary { after, .. } = node {
auto_breaking = *after;
}
let b = match node {
BreakNode::Glue(_)
if auto_breaking
&& i > 0
&& matches!(
projected[i - 1],
BreakNode::Content(_)
| BreakNode::AccentKern(_)
| BreakNode::SpaceAdjustment(_)
| BreakNode::Discretionary { .. }
| BreakNode::Kern {
explicit: false,
..
}
) =>
{
Some(Break {
end: i,
next: i + 1,
penalty: 0,
hyphen: false,
pre_break: None,
zero_tail: None,
forced: false,
})
}
BreakNode::Kern { explicit: true, .. } | BreakNode::MathBoundary { .. } | BreakNode::Direction
if auto_breaking && matches!(projected.get(i + 1), Some(BreakNode::Glue(_))) =>
{
Some(Break {
end: i,
next: i + 1,
penalty: 0,
hyphen: false,
pre_break: None,
zero_tail: Some(i),
forced: false,
})
}
BreakNode::Penalty(n) if *n < 10000 => Some(Break {
end: i,
next: i + 1,
penalty: *n,
hyphen: false,
pre_break: None,
zero_tail: None,
forced: *n <= -10000,
}),
BreakNode::Discretionary {
automatic,
pre_break,
replacement_count,
..
} if !*automatic || pass > 0 => Some(Break {
end: i,
next: i + 1 + usize::from(*replacement_count),
penalty: get(if pre_break.is_some() {
Parameter::Hyphenpenalty
} else {
Parameter::Exhyphenpenalty
}) as i32,
hyphen: true,
pre_break: Some(i),
zero_tail: None,
forced: get(if pre_break.is_some() {
Parameter::Hyphenpenalty
} else {
Parameter::Exhyphenpenalty
}) <= -10000,
}),
_ => None,
};
if let Some(b) = b {
breaks.push(b);
}
}
breaks.push(Break {
end: nodes.len(),
next: nodes.len(),
penalty: -10000,
hyphen: true,
pre_break: None,
zero_tail: None,
forced: true,
});
let mut active = vec![Active {
serial: 0,
previous: 0,
start: 0,
measurement_start: 0,
post_break: None,
line: 0,
fitness: 1,
hyphen: false,
cost: 0,
fit_widths: FitWidths::default(),
path: Vec::new(),
}];
let last_special_line = if !shape.is_empty() {
shape.len() - 1
} else if get(Parameter::Hangindent) == 0 {
0
} else {
get(Parameter::Hangafter).unsigned_abs() as usize
};
let merged_class = if get(Parameter::Looseness) == 0 {
// TeX defers flushing easy_line's minima until after all later lines.
// Its active line numbers start at prev_graf + 1, unlike Active::line.
last_special_line.saturating_sub(previous_lines.saturating_add(1))
} else {
usize::MAX
};
let threshold = if pass == 0 {
get(Parameter::Pretolerance)
} else {
get(Parameter::Tolerance)
}
.min(10000);
let final_pass = pass > 0 && (pass == 2 || get(Parameter::Emergencystretch) <= 0);
let mut finals = Vec::new();
let mut serial = 0;
for b in breaks {
if b.penalty >= 10000 {
continue;
}
let final_break = b.end == nodes.len();
let mut added: BTreeMap<(usize, u8, bool), Active> = BTreeMap::new();
let mut kept = Vec::new();
let total = active.len();
for (index, a) in active.into_iter().enumerate() {
*work += 1;
if *work > break_cache::SEARCH_LIMIT {
return Err("native paragraph break work limit exceeded".into());
}
if a.start > b.end {
kept.push(a);
continue;
}
// Discarding leading nodes after a break can also remove the
// implicit terminal penalty and parfill at the end of the list.
let keep_par_fill = final_break
&& (a.serial == 0 || a.start < b.end || has_post(nodes, a.post_break));
let (natural, mut stretch, shrink) = break_cache::candidate_widths(
projected,
&widths,
a.measurement_start,
b.end,
a.post_break,
b.pre_break,
left,
right,
keep_par_fill.then_some(par_fill),
);
if pass == 2 {
stretch[0] += get(Parameter::Emergencystretch);
}
let (_, target) = geometry(p, shape, a.line + previous_lines);
if target < 0 && shape.is_empty() {
return Err("negative native paragraph measure".into());
}
let mut shortfall = target - natural;
let mut margin_variation = expansion::Capacity::default();
if let Some(margins) = margins.as_deref_mut() {
// The active paragraph still ends in parfillskip. A nonzero
// fill stops the right search at the terminal breakpoint.
let right_visible = !keep_par_fill || par_fill.canonical_zero;
let edges = margins.edges(a.start, b.end, a.post_break, b.pre_break, right_visible);
shortfall += i64::from(edges[0].width) + i64::from(edges[1].width);
if shortfall != 0 && expansion.is_some() {
margin_variation = margins.variation(edges, state, files)?;
}
}
let delta = if let Some(expansion) = expansion {
expansion.residual(
shortfall, a.start, b.end, a.post_break, b.pre_break, margin_variation,
)?
} else {
shortfall
};
let infinite = stretch[1..].iter().any(|n| *n != 0);
let fit_adjustment = if fit_last_line
&& keep_par_fill
&& delta > 0
&& stretch[1..] == infinite_fill[1..]
{
let available = if a.fit_widths.shortfall > 0 { stretch[0] } else { shrink };
a.fit_widths
.adjustment(available, fit_factor)
.clamp(-available.max(0), delta)
} else {
0
};
let bad = if fit_adjustment != 0 {
let available = if fit_adjustment > 0 { stretch[0] } else { shrink };
tex_badness(fit_adjustment.abs(), available)
} else if delta >= 0 {
if infinite {
0
} else {
tex_badness(delta, stretch[0])
}
} else if -delta > shrink {
10001
} else {
tex_badness(-delta, shrink)
};
let forced_artificial = final_pass
&& (bad > 10000 || b.forced)
&& kept.is_empty()
&& index + 1 == total
&& added.is_empty();
if bad <= threshold as i32 || forced_artificial {
let shrinking = delta < 0 || fit_adjustment < 0;
let fitness = if shrinking && bad > 12 {
0
} else if bad <= 12 {
1
} else if bad <= 99 {
2
} else {
3
};
let d = get(Parameter::Linepenalty) + bad as i64;
let mut demerits = if forced_artificial {
0
} else if d.abs() >= 10000 {
100000000
} else {
d * d
};
if !forced_artificial && !b.forced {
if b.penalty >= 0 {
demerits = demerits.saturating_add((b.penalty as i64).pow(2));
} else {
demerits = demerits.saturating_sub((b.penalty as i64).pow(2));
}
}
if !forced_artificial && (fitness as i32 - a.fitness as i32).abs() > 1 {
demerits = demerits.saturating_add(get(Parameter::Adjdemerits));
}
if !forced_artificial && a.hyphen && b.hyphen {
demerits = demerits.saturating_add(if final_break {
get(Parameter::Finalhyphendemerits)
} else {
get(Parameter::Doublehyphendemerits)
});
}
trace.material(state, nodes, b.end)?;
trace.push(ParagraphTrace::Feasible {
position: b.end,
kind: if final_break {
ParagraphBreakKind::End
} else {
match &nodes[b.end] {
TextNode::Discretionary { .. } => ParagraphBreakKind::Discretionary,
TextNode::Penalty(_) => ParagraphBreakKind::Penalty,
TextNode::Kern { .. } => ParagraphBreakKind::Kern,
TextNode::MathBoundary { .. } | TextNode::Direction(_) => ParagraphBreakKind::Math,
_ => ParagraphBreakKind::Glue,
}
},
via: a.serial,
badness: bad,
penalty: b.penalty.max(-10000),
demerits: (!forced_artificial).then_some(demerits),
})?;
let mut path = a.path.clone();
path.push((b, bad));
let mut next = b.next;
let mut measurement_start = None;
while !b.pre_break.is_some_and(|i| projected[i].has_post())
&& projected.get(next).is_some_and(BreakNode::discardable)
{
// XeTeX stops subtracting discardable widths at a space
// adjustment during search, then drops it when packing.
if matches!(projected[next], BreakNode::SpaceAdjustment(_)) {
measurement_start.get_or_insert(next);
}
next += 1;
}
let candidate = Active {
serial: 0,
previous: a.serial,
start: next,
measurement_start: measurement_start.unwrap_or(next),
post_break: b.pre_break,
line: a.line + 1,
fitness,
hyphen: b.hyphen,
cost: a.cost.saturating_add(demerits),
fit_widths: if fit_adjustment != 0 {
FitWidths {
shortfall: delta,
glue: fit_adjustment,
}
} else if !fit_last_line || final_break || delta > 0 && infinite {
FitWidths::default()
} else {
let glue = match delta.cmp(&0) {
std::cmp::Ordering::Greater => stretch[0],
std::cmp::Ordering::Less => shrink,
std::cmp::Ordering::Equal => 0,
};
FitWidths { shortfall: delta, glue }
},
path,
};
let key = (a.line.min(merged_class), 3 - fitness, b.hyphen);
// TeX initializes each minimum to awful_bad (2^30-1).
// Costs beyond that bound are not feasible active nodes; this
// matters when the final pass must force an overfull line.
if candidate.cost < (1 << 30) - 1
&& added.get(&key).is_none_or(|old| candidate.cost <= old.cost)
{
added.insert(key, candidate);
}
}
if bad <= 10000 && !b.forced {
kept.push(a);
}
}
let minima: BTreeMap<usize, i64> = added.iter().fold(BTreeMap::new(), |mut m, (k, a)| {
m.entry(k.0)
.and_modify(|v| *v = (*v).min(a.cost))
.or_insert(a.cost);
m
});
let mut added: Vec<_> = added
.into_iter()
.filter(|(k, a)| {
a.cost <= minima[&k.0].saturating_add(get(Parameter::Adjdemerits).abs())
})
.collect();
for (_, a) in &mut added {
serial += 1;
a.serial = serial;
trace.push(ParagraphTrace::Active {
serial,
position: b.end,
line: a.line + previous_lines,
fitness: 3 - a.fitness,
hyphenated: a.hyphen,
demerits: a.cost,
previous: a.previous,
last_line_fit: fit_last_line.then_some(super::ParagraphLineFitTrace {
shortfall: a.fit_widths.shortfall,
glue: a.fit_widths.glue,
final_line: final_break,
}),
})?;
}
trace.after_break(nodes, b.end);
if final_break {
finals = added.into_iter().map(|(_, a)| a).collect();
break;
}
let mut next = kept;
let mut groups: BTreeMap<usize, Vec<Active>> = BTreeMap::new();
for (key, a) in added {
groups.entry(key.0).or_default().push(a);
}
for (class, group) in groups {
if class < merged_class {
let at = next
.iter()
.position(|a| a.line >= group[0].line)
.unwrap_or(next.len());
next.splice(at..at, group);
} else {
next.extend(group);
}
}
active = next;
}
finals.sort_by_key(|a| a.cost);
let Some(best) = finals.first() else {
return Ok(None);
};
let requested = get(Parameter::Looseness);
let mut actual = 0;
let mut chosen = best;
for a in &finals {
let diff = a.line as i64 - best.line as i64;
if (diff < actual && requested <= diff) || (diff > actual && requested >= diff) {
chosen = a;
actual = diff;
} else if diff == actual && a.cost < chosen.cost {
chosen = a;
}
}
let accepted = final_pass || requested == actual;
trace.push(ParagraphTrace::Selection {
serial: chosen.serial,
requested_looseness: requested,
actual_looseness: actual,
accepted,
})?;
if !accepted {
return Ok(None);
}
let final_fill = if chosen.fit_widths.shortfall == 0 {
None
} else {
let width = i64::from(par_fill.width) + chosen.fit_widths.shortfall - chosen.fit_widths.glue;
let mut glue = par_fill;
glue.width = i32::try_from(width).map_err(|_| "native last line fill width overflow")?;
glue.stretch.amount = 0;
Some(glue)
};
Ok(Some(LineBreaks {
lines: chosen.path.clone(),
final_fill,
}))
}
fn pack(
nodes: &[TextNode],
p: &BTreeMap<Parameter, ParameterValue>,
(indent, target): (i64, i64),
par_fill: Option<Glue>,
terminal_marker: bool,
ends_in_pre_break: bool,
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();
let mut material = Vec::new();
if left != Glue::default() {
material.push(TextNode::NamedGlue(left, Parameter::Leftskip));
}
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);
material.extend_from_slice(&nodes[..right_end]);
if par_fill.is_some() {
material.push(TextNode::Penalty(10000));
}
if enabled
&& let Some(kern) = protrusion::margin_kern(state, &nodes[..right_end], true, ends_in_pre_break)?
{
material.push(kern);
}
material.extend_from_slice(&nodes[right_end..]);
if let Some(fill) = par_fill {
material.push(TextNode::NamedGlue(fill, Parameter::Parfillskip));
}
super::direction::close(&mut material, direction_stack);
material.push(TextNode::NamedGlue(
p[&Parameter::Rightskip].glue(),
Parameter::Rightskip,
));
let (mut material, adjustments) = super::marks::extract(material);
if p[&Parameter::Pdfadjustspacing].width() > 0 && state.fonts.has_expansion() {
expansion::pack(state, &mut material, target, files)?;
}
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()],
height: b.height + b.depth,
width: b.width,
depth: b.depth,
font: ParagraphFont::Roman,
font_size: 655360,
left_skip: 0,
line_indents: vec![indent],
line_baselines: vec![b.height],
line_scales: Vec::new(),
centered: false,
right_aligned: false,
};
Ok((paragraph, b, adjustments, shrinking))
}
// TeX init_math scans natural widths and visible nodes, independently of
// rounded glue-setting coordinates. Stretch/shrink before the last visible
// material makes the result max_dimen; trailing fill alone does not.
fn pre_display_line_size(
nodes: &[TextNode],
set: super::boxes::GlueSetting,
indent: i64,
quad: i64,
) -> i32 {
let mut v = indent + 2 * quad;
let mut w = -1073741823;
for n in nodes.iter().cloned() {
let visible = matches!(
n,
TextNode::Glyph { .. }
| TextNode::Box(_)
| TextNode::OpenType(_)
| TextNode::ExplicitOpenTypeGlyph(_)
| TextNode::MathChar(_)
| TextNode::Indent(_)
| TextNode::Rule(_)
);
if let TextNode::Glue(g) | TextNode::FontSpace(g, _, _)
| TextNode::NamedGlue(g, _)
| TextNode::Leaders(LeaderGlue { glue: g, .. }) = n
{
let f = if set.sign > 0 { g.stretch } else { g.shrink };
if set.sign != 0 && f.order == set.order && f.amount != 0 {
v = 1073741823;
}
}
if v < 1073741823 {
v += width(&n);
}
if visible {
w = v.min(1073741823);
if w == 1073741823 {
break;
}
}
}
w as i32
}
pub(super) fn finish(
mut b: Builder,
state: &mut State,
final_widow: Parameter,
steps: &mut usize,
step_limit: usize,
(trace_limit, records): (usize, &mut Vec<super::ParagraphTrace>),
cache: Option<&LineBreakCache>,
files: &mut impl SourceProvider,
) -> Result<NativeParagraph, String> {
b.finish_text(true, state)?;
if b.nodes.last().is_some_and(|n| {
matches!(
n,
TextNode::Glue(_) | TextNode::FontSpace(_, _, _) | TextNode::NamedGlue(_, _)
| TextNode::ConditionalMathGlue | TextNode::Leaders(_)
)
}) {
b.nodes.pop();
}
for n in &b.nodes {
if let TextNode::Discretionary {
font,
hyphen_char: Some(c),
..
} = n
{
if !state.font_has_slot(*font, *c as u8) {
return Err("unsupported native discretionary character".into());
}
}
}
let parameters: BTreeMap<_, _> = Parameter::ALL
.iter()
.map(|p| (*p, state.parameter(*p)))
.collect();
let shape = state.paragraph_shape().to_vec();
for n in &b.nodes {
if let TextNode::Glue(g) | TextNode::FontSpace(g, _, _)
| TextNode::NamedGlue(g, _)
| TextNode::Leaders(LeaderGlue { glue: g, .. }) = n
&& g.shrink.order != 0
&& g.shrink.amount != 0
{
return Err("infinite glue shrinkage found in native paragraph".into());
}
}
for p in [
Parameter::Leftskip,
Parameter::Rightskip,
Parameter::Parfillskip,
Parameter::Baselineskip,
Parameter::Lineskip,
Parameter::Parskip,
] {
let g = parameters[&p].glue();
if g.shrink.order != 0 && g.shrink.amount != 0 {
return Err("unsupported infinite paragraph background glue".into());
}
}
let mut trace = super::paragraph_trace::Tracer::new(state, trace_limit);
let mut missing_glyphs = Vec::new();
let search = (|| {
let mut work = 0;
for pass in 0..3 {
if pass == 0 && parameters[&Parameter::Pretolerance].width() < 0 {
continue;
}
if pass == 1 {
add_hyphens(
&mut b.nodes,
state,
b.initial_language,
&mut missing_glyphs,
steps,
step_limit,
)?;
if state.input_profile() == InputProfile::XeTeX {
native_hyphenation::add_hyphens(
&mut b.nodes, state, b.initial_language, steps, step_limit,
)?;
}
}
trace.pass(pass, parameters[&Parameter::Pretolerance].width() >= 0)?;
if let Some(path) = break_cache::solve(
&b.nodes,
&parameters,
state,
files,
&shape,
pass,
&mut work,
b.previous_lines,
&mut trace,
cache,
)? {
return Ok((path, pass));
}
}
Err(String::from("native paragraph has no legal break sequence"))
})();
*records = trace.into_records();
let (breaks, selected_pass) = search?;
let path = &breaks.lines;
let mut start = 0;
let mut post = None;
let mut lines = Vec::new();
let mut diagnostic_lines = Vec::new();
let mut line_boxes = Vec::new();
let mut line_adjustments = Vec::new();
let mut line_pre_adjustments = Vec::new();
let mut discretionary_breaks = Vec::new();
let mut interline_penalties = Vec::new();
let mut badness = Vec::new();
let mut packed_badness = Vec::new();
let mut packed_excess = Vec::new();
let mut packed_diagnostic = Vec::new();
let mut packed_shrinking = Vec::new();
let mut pre_display_size = -1073741823;
let directions = super::direction::has_directions(&b.nodes);
let mut direction_stack = Vec::new();
let widow_kind = LinePenaltyKind::for_widow_parameter(final_widow);
for (i, (point, bad)) in path.iter().enumerate() {
let mut material = line_material(
&b.nodes,
start,
point.end,
post,
point.pre_break,
true,
point.zero_tail,
);
let dimensions = geometry(&parameters, state.paragraph_shape(), i + b.previous_lines);
let ends_in_pre_break = point.pre_break.is_some_and(|index| {
matches!(&b.nodes[index], TextNode::Discretionary { pre_break, .. } if !pre_break.is_empty())
});
let terminal_marker = point.zero_tail.is_some()
|| matches!(b.nodes.get(point.end), Some(TextNode::Penalty(_)))
|| (point.pre_break.is_some() && !ends_in_pre_break);
let par_fill = (i + 1 == path.len() && (i == 0 || !material.is_empty()))
.then(|| breaks.final_fill.unwrap_or_else(|| parameters[&Parameter::Parfillskip].glue()));
if directions {
// Keep a real breakpoint marker before the synthetic line closers.
super::direction::line(&mut material, &mut direction_stack);
}
let (line, line_box, adjustments, shrinking) = pack(
&material,
&parameters,
dimensions,
par_fill,
terminal_marker,
ends_in_pre_break,
&direction_stack,
state,
b.span,
(steps, step_limit),
files,
)?;
packed_diagnostic.push(line_box.diagnostic_eligible);
packed_shrinking.push(shrinking);
packed_badness.push(line_box.badness);
packed_excess.push(line_box.excess);
if i + 1 == path.len() {
let BoxContent::Horizontal(material) = &line_box.content else {
unreachable!()
};
let quad = i64::from(state.fonts.font(state.text_font())?.quad());
pre_display_size =
pre_display_line_size(material, line_box.setting, line_box.shift, quad);
}
diagnostic_lines.push(super::diagnostics::box_view(&line_box));
line_boxes.push(line_box);
line_pre_adjustments.push(adjustments.pre);
line_adjustments.push(adjustments.post);
lines.push(line);
let disc_break = i + 1 < path.len() && point.hyphen;
discretionary_breaks.push(disc_break);
if i + 1 < path.len() {
// The base array uses prevgraf, including lines before a display.
// Club counts from this segment's start and widow from its end.
let from_start = i + 1;
let from_end = path.len() - from_start;
let term = |kind, index, fallback, applies| {
line_penalty_at(state.line_penalties(kind), index)
.map(i64::from)
.unwrap_or_else(|| if applies { i64::from(parameters[&fallback].width()) } else { 0 })
};
let penalty = term(
LinePenaltyKind::Interline,
b.previous_lines + from_start,
Parameter::Interlinepenalty,
true,
) + term(LinePenaltyKind::Club, from_start, Parameter::Clubpenalty, from_start == 1)
+ term(widow_kind, from_end, final_widow, from_end == 1)
+ if disc_break { i64::from(parameters[&Parameter::Brokenpenalty].width()) } else { 0 };
interline_penalties
.push(i32::try_from(penalty).map_err(|_| "native interline penalty sum overflow")?);
}
badness.push(*bad);
start = point.next;
post = point.pre_break;
// A retained zero-tail breakpoint is already included in the line.
while !has_post(&b.nodes, post) && start < b.nodes.len() && discardable(&b.nodes[start]) {
if directions {
super::direction::observe(&mut direction_stack, &b.nodes[start]);
}
start += 1;
}
}
Ok(NativeParagraph {
initial_language: b.initial_language,
nodes: b.nodes,
previous_lines: b.previous_lines,
final_widow,
pre_display_size,
parameters,
lines,
diagnostic_lines,
line_boxes,
line_adjustments,
line_pre_adjustments: if line_pre_adjustments.iter().all(Vec::is_empty) {
Vec::new()
} else {
line_pre_adjustments
},
discretionary_breaks,
interline_penalties,
badness,
packed_badness,
packed_excess,
packed_diagnostic,
packed_shrinking,
pass: selected_pass,
parskip: b.parskip,
span: b.span,
hyphen_min: b.hyphen_min,
missing_glyphs,
})
}
fn add_hyphens(
nodes: &mut Vec<TextNode>,
state: &State,
mut language: HyphenationLanguage,
missing: &mut Vec<(FontId, u8, Span)>,
steps: &mut usize,
step_limit: usize,
) -> Result<(), String> {
let max_length = super::hyphenation::max_word_length(state);
let (mut start, mut i) = (0, 0);
let mut edits = Vec::new();
let mut word_font = None;
while i <= nodes.len() {
let lower = |c| super::hyphenation::lower_code(state, language.language, c);
let word_node = match nodes.get(i) {
Some(TextNode::Glyph { original, .. }) => original.chars().all(|c| lower(c) != 0),
Some(TextNode::Kern { explicit: false, .. }) => true,
_ => false,
};
let glyph_font = match nodes.get(i) {
Some(TextNode::Glyph { font, .. }) => Some(*font),
_ => None,
};
if word_node && (glyph_font.is_none() || word_font.is_none() || word_font == glyph_font) {
if glyph_font.is_some() {
word_font = glyph_font;
}
i += 1;
continue;
}
let font = word_font.unwrap_or(FontId::NULL);
let mut letters = 0;
let word: String = nodes[start..i]
.iter()
.filter_map(|n| {
if let TextNode::Glyph { original, .. } = n {
Some(original.as_str())
} else {
None
}
})
.take_while(|s| {
let n = s.chars().count();
if letters + n > max_length {
false
} else {
letters += n;
true
}
})
.collect();
if start > 0
&& nodes[..start]
.iter()
.rev()
.find(|n| match n {
TextNode::Language(_)
| TextNode::Direction(_)
| TextNode::Output(_)
| TextNode::Kern {
explicit: false, ..
} => false,
TextNode::Glyph { original, .. } => original
.chars()
.next()
.is_some_and(|c| lower(c) != 0),
_ => true,
})
.is_some_and(|n| {
matches!(
n,
TextNode::Glue(_) | TextNode::FontSpace(_, _, _) | TextNode::NamedGlue(_, _)
| TextNode::ConditionalMathGlue | TextNode::Leaders(_)
)
})
&& !word.is_empty()
&& (state.parameter(Parameter::Uchyph).width() > 0
|| word
.chars()
.next()
.is_some_and(|c| lower(c) == c as u32))
&& state.hyphen_character(font).is_some()
&& nodes[i..]
.iter()
.find(|n| {
!matches!(
n,
TextNode::Glyph { .. }
| TextNode::Kern {
explicit: false,
..
}
)
})
.is_none_or(|n| {
matches!(
n,
TextNode::Language(_)
| TextNode::Direction(_)
| TextNode::Adjustment(_)
| TextNode::Insertion(_)
| TextNode::Mark(_)
| TextNode::Output(_)
| TextNode::Glue(_) | TextNode::FontSpace(_, _, _)
| TextNode::NamedGlue(_, _)
| TextNode::ConditionalMathGlue
| TextNode::Leaders(_)
| TextNode::Penalty(_)
| TextNode::AccentKern(_)
| TextNode::AutoKern(_)
| TextNode::Kern { explicit: true, .. }
)
})
{
let normalized: Vec<_> = word.chars().map(lower).collect();
let points: Vec<_> = state
.hyphenation
.points(language.language, &normalized)
.into_iter()
.filter(|n| {
*n >= usize::from(language.left_min)
&& *n <= letters.saturating_sub(usize::from(language.right_min))
})
.collect();
if !points.is_empty() {
let first=(start..i).find(|j|matches!(&nodes[*j],TextNode::Glyph{original,..}if !original.is_empty())).ok_or("native hyphenation has no original letters")?;
let mut components = Vec::new();
let mut end = first;
for at in first..i {
match &nodes[at] {
TextNode::Glyph {
original,
origins,
component_sources,
..
} => {
if components.len() + original.chars().count() > max_length {
break;
}
components.extend(original.chars().enumerate().map(|(k, c)| {
super::ligature::Component {
slot: c as u8,
origin: origins.get(k).copied().unwrap_or_default(),
source: component_sources.get(k).cloned().unwrap_or_default(),
}
}));
}
_ => {}
}
end = at + 1;
}
let mut seed = None;
let mut begin = first;
let mut left_boundary = false;
if let Some(at) = first.checked_sub(1) {
if let TextNode::Glyph {
font: prior,
slot,
original,
origins,
component_sources,
glyph,
ligature,
left_boundary: hit,
..
} = &nodes[at]
{
if *prior == font {
begin = at;
if original.is_empty() && *hit {
left_boundary = true;
} else {
seed = Some(super::ligature::Glyph {
slot: *slot,
source: glyph
.math_geometry
.as_ref()
.and_then(|g| g.items.first())
.map(|p| p.source.clone())
.unwrap_or_default(),
components: original
.chars()
.enumerate()
.map(|(k, c)| super::ligature::Component {
slot: c as u8,
origin: origins.get(k).copied().unwrap_or_default(),
source: component_sources
.get(k)
.cloned()
.unwrap_or_default(),
})
.collect(),
ligature: *ligature,
left_boundary: *hit,
right_boundary: false,
});
}
} else {
left_boundary = true;
}
} else if matches!(
&nodes[first],
TextNode::Glyph {
left_boundary: true,
..
}
) {
left_boundary = true;
}
}
// TeX reconstitutes against the actual next character in
// the same font, including punctuation outside the word.
let next_character = match nodes.get(end) {
Some(TextNode::Glyph { font: next, slot, original, ligature, .. })
if *next == font =>
{
if *ligature {
original.chars().next().map(|c| c as u8)
} else {
Some(*slot)
}
}
_ => None,
};
let bchar = if next_character.is_some() {
next_character
} else if matches!(
&nodes[end - 1],
TextNode::Glyph { right_boundary: true, .. }
| TextNode::Kern { explicit: false, .. }
) {
state.fonts.glyph_font(font)?.metrics().boundary_char()
} else {
None
};
let replacement = super::reconstitute::word(
state,
font,
components,
seed,
left_boundary,
bchar,
&points,
steps,
step_limit,
missing,
)?;
edits.push((begin, end, replacement));
}
}
if let Some(TextNode::Language(next)) = nodes.get(i) {
language = *next;
}
if word_node {
start = i;
word_font = glyph_font;
i += 1;
} else {
i += 1;
start = i;
word_font = None;
}
}
for (begin, end, replacement) in edits.into_iter().rev() {
nodes.splice(begin..end, replacement);
}
Ok(())
}