Fit native paragraph endings using preceding line glue

This commit is contained in:
gloamxun committed 2026-11-28 11:50:07 +08:00
1 parent e72104eab3
commit 11fd66713b
10 files changed
+247 -23

No files matched your search

@@ -16,9 +16,9 @@ use std::{
sync::{Arc, Mutex, OnceLock, Weak},
};
const SCHEMA: u32 = 97;
const COMPATIBLE_SCHEMAS: [u32; 63] = [
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, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 91, 92, 93, 94, 95, 96, SCHEMA,
const SCHEMA: u32 = 98;
const COMPATIBLE_SCHEMAS: [u32; 64] = [
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, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 91, 92, 93, 94, 95, 96, 97, SCHEMA,
];
const ENGINE: &str = concat!("texrra-native/", env!("CARGO_PKG_VERSION"));
@@ -208,6 +208,9 @@ impl FormatImage {
Parameter::Pdfptexuseunderscore,
]);
}
if image.schema < 98 {
image.state.restore_legacy_last_line_fit();
}
let pdf_objects = image.state.pdf_objects.as_deref();
let mut numbered_images = 0;
for (index, saved) in image.pdf_images.iter().enumerate() {
+3 -1
View File
@@ -85,7 +85,9 @@ pub use math::{
pub use math_code::MathCode;
pub use page_builder::{NativePageState, PageTrace, PageTraceReport};
pub use paragraph::{LineBreakCache, LineBreakWork, NativeParagraph, ParagraphMode, TextNode};
pub use paragraph_trace::{ParagraphBreakKind, ParagraphTrace, ParagraphTraceReport};
pub use paragraph_trace::{
ParagraphBreakKind, ParagraphLineFitTrace, ParagraphTrace, ParagraphTraceReport,
};
pub use parameters::{Parameter, ParameterValue};
pub(crate) use registers::print_scaled;
pub use registers::{Flex, Glue, Register, RegisterKind, RegisterValue};
+109 -14
View File
@@ -664,6 +664,36 @@ struct Break {
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,
@@ -674,6 +704,7 @@ struct Active {
fitness: u8,
hyphen: bool,
cost: i64,
fit_widths: FitWidths,
path: Vec<(Break, i32)>,
}
fn geometry(
@@ -806,11 +837,27 @@ fn break_lines(
work: &mut usize,
previous_lines: usize,
trace: &mut super::paragraph_trace::Tracer,
) -> Result<Option<Vec<(Break, i32)>>, String> {
) -> 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;
@@ -923,6 +970,7 @@ fn break_lines(
fitness: 1,
hyphen: false,
cost: 0,
fit_widths: FitWidths::default(),
path: Vec::new(),
}];
let last_special_line = if !shape.is_empty() {
@@ -1007,7 +1055,22 @@ fn break_lines(
shortfall
};
let infinite = stretch[1..].iter().any(|n| *n != 0);
let bad = if delta >= 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 {
@@ -1024,7 +1087,8 @@ fn break_lines(
&& index + 1 == total
&& added.is_empty();
if bad <= threshold as i32 || forced_artificial {
let fitness = if delta < 0 && bad > 12 {
let shrinking = delta < 0 || fit_adjustment < 0;
let fitness = if shrinking && bad > 12 {
0
} else if bad <= 12 {
1
@@ -1101,6 +1165,21 @@ fn break_lines(
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);
@@ -1140,6 +1219,11 @@ fn break_lines(
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);
@@ -1191,13 +1275,25 @@ fn break_lines(
if !accepted {
return Ok(None);
}
Ok(Some(chosen.path.clone()))
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),
keep_par_fill: bool,
par_fill: Option<Glue>,
terminal_marker: bool,
ends_in_pre_break: bool,
direction_stack: &[super::direction::Region],
@@ -1217,7 +1313,7 @@ fn pack(
}
let right_end = nodes.len() - usize::from(terminal_marker);
material.extend_from_slice(&nodes[..right_end]);
if keep_par_fill {
if par_fill.is_some() {
material.push(TextNode::Penalty(10000));
}
if enabled
@@ -1226,11 +1322,8 @@ fn pack(
material.push(kern);
}
material.extend_from_slice(&nodes[right_end..]);
if keep_par_fill {
material.push(TextNode::NamedGlue(
p[&Parameter::Parfillskip].glue(),
Parameter::Parfillskip,
));
if let Some(fill) = par_fill {
material.push(TextNode::NamedGlue(fill, Parameter::Parfillskip));
}
super::direction::close(&mut material, direction_stack);
material.push(TextNode::NamedGlue(
@@ -1412,7 +1505,8 @@ pub(super) fn finish(
Err(String::from("native paragraph has no legal break sequence"))
})();
*records = trace.into_records();
let (path, selected_pass) = search?;
let (breaks, selected_pass) = search?;
let path = &breaks.lines;
let mut start = 0;
let mut post = None;
let mut lines = Vec::new();
@@ -1447,7 +1541,8 @@ pub(super) fn finish(
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 keep_par_fill = i + 1 == path.len() && (i == 0 || !material.is_empty());
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);
@@ -1456,7 +1551,7 @@ pub(super) fn finish(
&material,
&parameters,
dimensions,
keep_par_fill,
par_fill,
terminal_marker,
ends_in_pre_break,
&direction_stack,
@@ -42,7 +42,7 @@ struct CacheState {
work: LineBreakWork,
}
type Path = Option<Vec<(Break, i32)>>;
type Path = Option<LineBreaks>;
struct Entry {
hash: u64,
@@ -10,6 +10,13 @@ pub enum ParagraphBreakKind {
Math,
End,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct ParagraphLineFitTrace {
pub shortfall: i64,
/// Available glue on a candidate line, or the signed adjustment on the final line.
pub glue: i64,
pub final_line: bool,
}
#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub enum ParagraphTrace {
Pass {
@@ -36,6 +43,8 @@ pub enum ParagraphTrace {
hyphenated: bool,
demerits: i64,
previous: usize,
#[serde(default, skip_serializing_if = "Option::is_none")]
last_line_fit: Option<ParagraphLineFitTrace>,
},
/// The actual chosen final active node; intentionally no invented log line.
Selection {
@@ -93,11 +102,22 @@ impl ParagraphTrace {
hyphenated,
demerits,
previous,
last_line_fit,
..
} => Some(format!(
"@@{serial}: line {line}.{fitness}{} t={demerits} -> @@{previous}",
if *hyphenated { "-" } else { "" }
)),
} => {
let fit = last_line_fit.map_or_else(String::new, |fit| {
let value = if fit.final_line { 'a' } else { 'g' };
format!(
" s={} {value}={}",
super::registers::print_scaled_wide(fit.shortfall),
super::registers::print_scaled_wide(fit.glue),
)
});
Some(format!(
"@@{serial}: line {line}.{fitness}{} t={demerits}{fit} -> @@{previous}",
if *hyphenated { "-" } else { "" }
))
}
Self::Selection { .. } => None,
}
}
@@ -144,6 +144,7 @@ pub enum Parameter {
Pdfsuppressptexinfo,
Pdfptexuseunderscore,
Ignoreprimitiveerror,
Lastlinefit,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
pub enum ParameterValue {
@@ -342,6 +343,7 @@ impl Parameter {
Self::XeTeXlinebreakskip,
Self::XeTeXlinebreakpenalty,
Self::XeTeXinputnormalization,
Self::Lastlinefit,
];
pub fn name(self) -> String {
match self {
@@ -1292,6 +1292,7 @@ impl Default for State {
| Parameter::Savingvdiscards
| Parameter::Ignoreprimitiveerror
| Parameter::TeXXeTstate
| Parameter::Lastlinefit
) || Parameter::XETEX.contains(p) {
continue;
}
@@ -1543,6 +1544,7 @@ impl State {
Parameter::Tracingassigns,
Parameter::Savingvdiscards,
Parameter::Ignoreprimitiveerror,
Parameter::Lastlinefit,
] {
self.commands.insert(
CommandName::Control(parameter.name()),
@@ -1793,6 +1795,15 @@ impl State {
}
}
pub(super) fn restore_legacy_last_line_fit(&mut self) {
if self.profile == Profile::EtexBootstrap {
let parameter = Parameter::Lastlinefit;
self.commands
.entry(CommandName::Control(parameter.name()))
.or_insert(Meaning::Parameter(parameter));
}
}
pub fn is_initex(&self) -> bool {
self.initex
}
@@ -87,6 +87,47 @@ fn paragraph_fill_is_discarded_after_a_break_that_consumes_the_tail() {
));
}
#[test]
fn last_line_fit_reuses_the_selected_fill_only_for_the_same_parameter() {
use std::sync::Arc;
let cache = Arc::new(LineBreakCache::default());
let compile = |factor, cached| {
let mut executor = Executor::new(State::initex().with_etex(), Limits::default());
if cached {
executor = executor.with_line_break_cache(cache.clone());
}
executor.run(
SourceFile {
name: "fitted.tex".into(),
data: format!(r"{SETUP}\hsize=50pt\pretolerance=10000
\lastlinefit={factor}\noindent
\hbox to20pt{{A\hfil}}\hskip4pt plus12pt\hbox to20pt{{B\hfil}}%
\penalty-10000
\hbox to12pt{{C\hfil}}\hskip4pt plus12pt\hbox to12pt{{D\hfil}}\par\end")
.into_bytes(),
},
&mut FontFiles,
).unwrap()
};
for (factor, width) in [(1000, 16), (500, 19), (1000, 16)] {
let live = compile(factor, true);
let full = compile(factor, false);
let (live, full) = (paragraphs(&live)[0], paragraphs(&full)[0]);
assert_eq!(live, full);
assert_eq!(live.parameters[&Parameter::Parfillskip].glue().stretch.amount, 65536);
let BoxContent::Horizontal(nodes) = &live.line_boxes[1].content else {
panic!("expected the fitted final line");
};
assert!(nodes.iter().any(|node| matches!(node,
TextNode::NamedGlue(fill, Parameter::Parfillskip)
if fill.width == width * 65536 && fill.stretch.amount == 0
)));
}
let work = cache.work();
assert_eq!((work.solved_passes, work.reused_passes), (2, 1));
}
#[test]
fn native_parameters_have_scopes_and_par_end_timing() {
let e = run(