From 11fd66713b26bde7843eb391e07c125ad17ad196 Mon Sep 17 00:00:00 2001 From: GloamXun Date: Sat, 28 Nov 2026 11:50:07 +0800 Subject: [PATCH] Fit native paragraph endings using preceding line glue --- .../src/execution/format_image.rs | 9 +- crates/texrra-tex-core/src/execution/mod.rs | 4 +- .../src/execution/paragraph.rs | 123 ++++++++++++++++-- .../src/execution/paragraph/break_cache.rs | 2 +- .../src/execution/paragraph_trace.rs | 28 +++- .../src/execution/parameters.rs | 2 + crates/texrra-tex-core/src/execution/state.rs | 11 ++ .../tests/execution_paragraphs.rs | 41 ++++++ docs/P2_M1_PROGRESS.md | 35 +++++ docs/PUBLISHER_TEMPLATE_MATRIX.md | 15 +++ 10 files changed, 247 insertions(+), 23 deletions(-) diff --git a/crates/texrra-tex-core/src/execution/format_image.rs b/crates/texrra-tex-core/src/execution/format_image.rs index c3cded3..0fd7210 100644 --- a/crates/texrra-tex-core/src/execution/format_image.rs +++ b/crates/texrra-tex-core/src/execution/format_image.rs @@ -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() { diff --git a/crates/texrra-tex-core/src/execution/mod.rs b/crates/texrra-tex-core/src/execution/mod.rs index b7a33c1..73659fb 100644 --- a/crates/texrra-tex-core/src/execution/mod.rs +++ b/crates/texrra-tex-core/src/execution/mod.rs @@ -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}; diff --git a/crates/texrra-tex-core/src/execution/paragraph.rs b/crates/texrra-tex-core/src/execution/paragraph.rs index b6ca160..6b95811 100644 --- a/crates/texrra-tex-core/src/execution/paragraph.rs +++ b/crates/texrra-tex-core/src/execution/paragraph.rs @@ -664,6 +664,36 @@ struct Break { forced: bool, } #[derive(Clone)] +struct LineBreaks { + lines: Vec<(Break, i32)>, + final_fill: Option, +} +#[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>, String> { +) -> Result, 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::() + == 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, (indent, target): (i64, i64), - keep_par_fill: bool, + par_fill: Option, 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, ¶meters, dimensions, - keep_par_fill, + par_fill, terminal_marker, ends_in_pre_break, &direction_stack, diff --git a/crates/texrra-tex-core/src/execution/paragraph/break_cache.rs b/crates/texrra-tex-core/src/execution/paragraph/break_cache.rs index 7ad8744..a0cc9c4 100644 --- a/crates/texrra-tex-core/src/execution/paragraph/break_cache.rs +++ b/crates/texrra-tex-core/src/execution/paragraph/break_cache.rs @@ -42,7 +42,7 @@ struct CacheState { work: LineBreakWork, } -type Path = Option>; +type Path = Option; struct Entry { hash: u64, diff --git a/crates/texrra-tex-core/src/execution/paragraph_trace.rs b/crates/texrra-tex-core/src/execution/paragraph_trace.rs index 22e05a7..1d552fb 100644 --- a/crates/texrra-tex-core/src/execution/paragraph_trace.rs +++ b/crates/texrra-tex-core/src/execution/paragraph_trace.rs @@ -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, }, /// 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, } } diff --git a/crates/texrra-tex-core/src/execution/parameters.rs b/crates/texrra-tex-core/src/execution/parameters.rs index 0a626cb..d5167e1 100644 --- a/crates/texrra-tex-core/src/execution/parameters.rs +++ b/crates/texrra-tex-core/src/execution/parameters.rs @@ -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 { diff --git a/crates/texrra-tex-core/src/execution/state.rs b/crates/texrra-tex-core/src/execution/state.rs index 2dc7609..020787c 100644 --- a/crates/texrra-tex-core/src/execution/state.rs +++ b/crates/texrra-tex-core/src/execution/state.rs @@ -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 } diff --git a/crates/texrra-tex-core/tests/execution_paragraphs.rs b/crates/texrra-tex-core/tests/execution_paragraphs.rs index 9168546..30ee54c 100644 --- a/crates/texrra-tex-core/tests/execution_paragraphs.rs +++ b/crates/texrra-tex-core/tests/execution_paragraphs.rs @@ -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( diff --git a/docs/P2_M1_PROGRESS.md b/docs/P2_M1_PROGRESS.md index 690120d..c96354a 100644 --- a/docs/P2_M1_PROGRESS.md +++ b/docs/P2_M1_PROGRESS.md @@ -18,6 +18,41 @@ | W6 会话 | 实施中 | 共享库/CLI 与当前原生文字/数学/规则来源进入公共结果;真实 A4 副本九类/27 revision 与独立干净作业页面/PDF/aux/映射一致,新增数学场景独立参考通过;详细失败/捕获重放及宿主/离线/CLI观察已通过;原子项目版本/已知生成初态及TeX流记录已接通;完整副作用/恢复契约、旧来源和性能仍缺 | | W7 总验收 | 未满足 | 原有和新增测试、原样项目、格式与会话门禁全部通过才能结项 | +## 2026-11-28 e-TeX 段落末行调整 + +原生 e-TeX 两种 profile 都执行 `\lastlinefit`。正常断行的候选记录 +有限胶水和宽度差。末行只有 `\parfillskip` 提供无限伸长时, +沿用前一行的伸缩比例计算坏度和适合度,在选定断行后改写该行 +真实填充节点的宽度和伸长量。全局 `\parfillskip` 与其收缩分量保留。 +跟踪日志直接记录上述断行数据,格式镜像保存该整数和控制序列别名。 + +同一 CMR10 源在 pdfTeX、XeTeX 两边各五页。覆盖默认值、完整和半比例、 +收缩、无前行、前一行或末行含无限胶水、背景含无限胶水、非零填充宽度 +及上限。每种 profile 的 109 行断行跟踪、10 个盒列表、37 个词框和 +144 DPI 灰度像素与参考一致。schema98 的两种格式均重载了整数、别名及 +作用域恢复。schema97 加载时补齐原语,保留镜像已有的同名用户宏。 +原样 ACL 多语种项目在既有 schema71 下复编,PDF、布局清单和辅助文件 +与主线复核的输出相同。 + +三页项目把第二页的比例依次从 1000 改为 500、0 和 1000。每次复用 +1,087 步 TeX 执行且只更新第二页。两个新比例重新断行,回到 1000 +时复用原断行,PDF 恢复为首轮字节。三轮使用稳定的辅助文件初态。 +各轮 PDF、页面、SVG、辅助文件及来源映射与同版本独立全量一致。 + +13 项段落和跟踪定向测试通过。双 profile 对照、格式重载及编辑回执见 +`target/p2-etex-last-line-fit`,`receipt.json` 的 SHA-256 为 +`43a1bc5b77c5609607065de676d0826399b9e7545d81e3eb64573b59c66c8d89`。 +[e-TeX 的末行算法](https://github.com/TeX-Live/texlive-source/blob/fb6158926661cb7a7246b3a94a0cb170a9624d5a/texk/web2c/etexdir/etex.ch#L5835-L5962) +· [原样 ACL 复验](PUBLISHER_TEMPLATE_MATRIX.md#2026-11-28-原样-acl-多语种项目复验) + +下一项已复现的断词状态差异在 `target/p2-etex-saved-hyphenation-codes`。 +在两种参考引擎中,为一个语言保存加载 `\patterns` 时的断词代码, +改动实时 `\lccode` 后该语言仍按保存值断词,另一语言使用实时值。 +当前原生在 `\savinghyphcodes` 报未定义。需把实际保存表接入格式镜像、 +按语言识别单词及断词例外,继续验证 XeTeX 的 255 以上字符走实时值。 +固定用例 `codes.tex` 的 SHA-256 为 +`6c649644b3a28324b4ba19390a244e7fa01940abb290ab2c6df9bae013ee1467`。 + ## 2026-11-18:编号、数学分支与出版矩阵 主工作区以冻结的399项源和资源指纹推广通用 `\eqno`、`\leqno` 及数学模式盒赋值。 diff --git a/docs/PUBLISHER_TEMPLATE_MATRIX.md b/docs/PUBLISHER_TEMPLATE_MATRIX.md index 3cdea01..edced7b 100644 --- a/docs/PUBLISHER_TEMPLATE_MATRIX.md +++ b/docs/PUBLISHER_TEMPLATE_MATRIX.md @@ -799,6 +799,21 @@ XDV 链接注释接入后,沿原样 ACL 的第二轮辅助文件和 BibTeX 冻结参考、原版差异回执和实际源、字体及映射指纹。 [设备阶段记录](P2_M1_PROGRESS.md#xdv-的-pdf-文字游标与-type-1-字体度量) +#### 2026-11-28 原样 ACL 多语种项目复验 + +以主线 `e72104e` 复编十份原样项目文件。沿用冻结的 schema71 格式、 +TeX Gyre Termes X、Lohit Devanagari、Noto Sans Arabic 及其他真实字体。 +从空 aux/out 开始执行四轮。第三、四轮 aux 一致,最终 aux、out、bbl +逐字节匹配参考。从原生首轮 aux 另跑真实 BibTeX,生成了相同的 bbl。 + +一页中的 589 个原始字形、119 个提取词及词框、144 DPI 灰度像素、 +版面文本和命名目标均与同一冻结 XeTeX/xdvipdfmx 参考一致,词框偏差为 +0 bp。既有自动断词、塑形和设备差异回执保留。此次覆盖该样稿的 +固定项目和资源版本,完整两种 profile 的同版矩阵仍待统一验收。 + +回执 `target/p3-acl-current-reconcile/receipt.json` 的 SHA-256 为 +`cc86509d0cdeeade07bd90c0801e7c9246f44843cdf3b41419078de6c80b2d48`。 + #### XeTeX Graphite 字体复编 真实 xelatex.ini 生成 schema78 后加载未修改的 fontspec,使用实际