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

1537 lines
53 KiB
Rust

//! Native horizontal material and paragraph breaking. No command/string parser.
use super::*;
use crate::{HorizontalBox, Paragraph, ParagraphFont};
use std::collections::BTreeMap;
mod break_cache;
mod expansion;
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,
}
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>,
},
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),
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: u8 },
}
#[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, 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>,
pub cancel_boundary: bool,
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>,
}
impl Builder {
pub(super) fn has_unpacked_text(&self) -> bool {
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())
}
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.nodes.push(TextNode::Discretionary {
font: run.font.id,
automatic: false,
hyphen_char: None,
pre_break: Vec::new(),
post_break: Vec::new(),
replacement_count: 0,
});
}
}
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(mut run) = self.run.take() {
run.machine
.put_carry(std::mem::take(&mut self.ligature_carry));
let output = run.machine.finish(
run.font.metrics(),
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(())
}
pub fn character(
&mut self,
c: char,
origin: TokenOrigin,
state: &State,
font: FontId,
hyphen_char: Option<char>,
) -> Result<Vec<super::ligature::Component>, String> {
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(
run.font.metrics(),
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) -> 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 => 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::NamedGlue(_, _)
| TextNode::Leaders(_)
| TextNode::Kern { .. }
| TextNode::MathBoundary { .. }
| TextNode::Penalty(_)
)
}
fn width(n: &TextNode) -> i64 {
match n {
TextNode::Glyph { glyph, .. } | TextNode::Box(glyph) | TextNode::MathChar(glyph) => {
glyph.width
}
TextNode::Glue(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::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 Active {
serial: usize,
previous: usize,
start: usize,
post_break: Option<usize>,
line: usize,
fitness: u8,
hyphen: bool,
cost: i64,
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::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::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::NamedGlue(_, _) | TextNode::Leaders(_)
)
})
.map(width)
.sum::<i64>();
(natural, stretch, shrink)
}
fn break_lines(
nodes: &[TextNode],
projected: &[BreakNode],
margins: Option<&protrusion::Search>,
expansion: Option<&expansion::Search>,
p: &BTreeMap<Parameter, ParameterValue>,
shape: &[ParagraphShapeLine],
pass: u8,
work: &mut usize,
previous_lines: usize,
trace: &mut super::paragraph_trace::Tracer<'_>,
) -> Result<Option<Vec<(Break, i32)>>, String> {
let get = |q| p[&q].width() as i64;
let left = p[&Parameter::Leftskip].glue();
let right = p[&Parameter::Rightskip].glue();
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::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 { .. }
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,
post_break: None,
line: 0,
fitness: 1,
hyphen: false,
cost: 0,
path: Vec::new(),
}];
let special = if get(Parameter::Looseness) != 0 {
usize::MAX
} else if !shape.is_empty() {
(shape.len() - 1).saturating_sub(previous_lines)
} else if get(Parameter::Hangindent) == 0 {
0
} else {
get(Parameter::Hangafter).unsigned_abs() as usize
};
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;
}
let mut right = right;
if final_break {
let fill = p[&Parameter::Parfillskip].glue();
right = right.add(fill).map_err(str::to_owned)?;
}
let (natural, mut stretch, shrink) = break_cache::candidate_widths(
projected,
&widths,
a.start,
b.end,
a.post_break,
b.pre_break,
left,
right,
);
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 hanging = margins.map_or(0, |margins| {
// The active paragraph still ends in parfillskip. A nonzero
// fill stops the right search at the terminal breakpoint.
let right_visible = !final_break
|| p[&Parameter::Parfillskip].glue().canonical_zero;
margins.width(a.start, b.end, a.post_break, b.pre_break, right_visible)
});
let shortfall = target - natural + hanging;
let delta = expansion.map_or(shortfall, |expansion| {
expansion.residual(shortfall, a.start, b.end, a.post_break, b.pre_break)
});
let infinite = stretch[1..].iter().any(|n| *n != 0);
let bad = 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 fitness = if delta < 0 && 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(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 { .. } => 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;
while !b.pre_break.is_some_and(|i| projected[i].has_post())
&& projected.get(next).is_some_and(BreakNode::discardable)
{
next += 1;
}
let candidate = Active {
serial: 0,
previous: a.serial,
start: next,
post_break: b.pre_break,
line: a.line + 1,
fitness,
hyphen: b.hyphen,
cost: a.cost.saturating_add(demerits),
path,
};
let key = (a.line.min(special), 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,
})?;
}
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 < special {
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);
}
Ok(Some(chosen.path.clone()))
}
fn pack(
nodes: &[TextNode],
p: &BTreeMap<Parameter, ParameterValue>,
(indent, target): (i64, i64),
last: bool,
terminal_marker: bool,
ends_in_pre_break: bool,
state: &State,
span: Span,
) -> 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 = p[&Parameter::Pdfprotrudechars].width() > 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 last {
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 last {
material.push(TextNode::NamedGlue(
p[&Parameter::Parfillskip].glue(),
Parameter::Parfillskip,
));
}
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)?;
}
let shrinking = material.iter().map(width).sum::<i64>() > target;
let mut b = super::boxes::hpack(
material,
super::boxes::PackSpec::To(
i32::try_from(target).map_err(|_| "native line width overflow")?,
),
span,
state,
)?;
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::MathChar(_)
| TextNode::Indent(_)
| TextNode::Rule(_)
);
if let TextNode::Glue(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: &State,
final_widow: Parameter,
steps: &mut usize,
step_limit: usize,
trace: &mut super::paragraph_trace::Tracer<'_>,
cache: Option<&LineBreakCache>,
) -> Result<NativeParagraph, String> {
b.finish_text(true, state)?;
if b.nodes.last().is_some_and(|n| {
matches!(
n,
TextNode::Glue(_) | TextNode::NamedGlue(_, _) | 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();
for n in &b.nodes {
if let TextNode::Glue(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 work = 0;
let mut missing_glyphs = Vec::new();
let mut result = None;
let mut selected_pass = 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,
)?;
}
trace.pass(pass, parameters[&Parameter::Pretolerance].width() >= 0)?;
if let Some(path) = break_cache::solve(
&b.nodes,
&parameters,
state,
shape,
pass,
&mut work,
b.previous_lines,
trace,
cache,
)? {
result = Some(path);
selected_pass = pass;
break;
}
}
let path = result.ok_or("native paragraph has no legal break sequence")?;
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;
for (i, (point, bad)) in path.iter().enumerate() {
let material = line_material(
&b.nodes,
start,
point.end,
post,
point.pre_break,
true,
point.zero_tail,
);
let dimensions = geometry(&parameters, 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 (line, line_box, adjustments, shrinking) = pack(
&material,
&parameters,
dimensions,
i + 1 == path.len(),
terminal_marker,
ends_in_pre_break,
state,
b.span,
)?;
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() {
// TeX post_line_break: all applicable terms add, including both
// club and widow for a two-line paragraph. Never penalize the end.
let get = |p| parameters[&p].width() as i64;
let penalty = get(Parameter::Interlinepenalty)
+ if i == 0 {
get(Parameter::Clubpenalty)
} else {
0
}
+ if i + 2 == path.len() {
get(final_widow)
} else {
0
}
+ if disc_break {
get(Parameter::Brokenpenalty)
} 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;
while !has_post(&b.nodes, post) && start < b.nodes.len() && discardable(&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 (mut start, mut i) = (0, 0);
let mut edits = Vec::new();
let mut word_font = None;
while i <= nodes.len() {
let word_node=nodes.get(i).is_some_and(|n|matches!(n,TextNode::Glyph{original,..} if original.chars().all(|c| state.case_code(super::CaseCode::Lower,c) != 0)))||nodes.get(i).is_some_and(|n|matches!(n,TextNode::Kern{explicit: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 > 63 {
false
} else {
letters += n;
true
}
})
.collect();
if start > 0
&& nodes[..start]
.iter()
.rev()
.find(|n| match n {
TextNode::Language(_)
| TextNode::Output(_)
| TextNode::Kern {
explicit: false, ..
} => false,
TextNode::Glyph { original, .. } => original
.chars()
.next()
.is_some_and(|c| state.case_code(super::CaseCode::Lower, c) != 0),
_ => true,
})
.is_some_and(|n| {
matches!(
n,
TextNode::Glue(_) | TextNode::NamedGlue(_, _) | TextNode::Leaders(_)
)
})
&& !word.is_empty()
&& (state.parameter(Parameter::Uchyph).width() > 0
|| word
.chars()
.next()
.is_some_and(|c| state.case_code(super::CaseCode::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::Adjustment(_)
| TextNode::Insertion(_)
| TextNode::Mark(_)
| TextNode::Output(_)
| TextNode::Glue(_)
| TextNode::NamedGlue(_, _)
| TextNode::Leaders(_)
| TextNode::Penalty(_)
| TextNode::AccentKern(_)
| TextNode::AutoKern(_)
| TextNode::Kern { explicit: true, .. }
)
})
{
let normalized: String = word
.chars()
.map(|c| {
char::from_u32(state.case_code(super::CaseCode::Lower, c))
.expect("nonzero case mapping")
})
.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() > 63 {
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(())
}