From 1822ab2d326bf145c7e9d9c089b7091bde86c21d Mon Sep 17 00:00:00 2001 From: GloamXun Date: Sat, 21 Nov 2026 06:00:55 +0800 Subject: [PATCH] Apply native automatic kerns and protrusion at real line edges --- crates/texrra-tex-core/src/execution/boxes.rs | 2 + .../src/execution/diagnostics.rs | 8 +++ .../texrra-tex-core/src/execution/engine.rs | 10 +++ .../src/execution/engine/boxes.rs | 1 + .../src/execution/engine/display.rs | 2 + .../src/execution/engine/hyphenation.rs | 2 +- .../src/execution/engine/list_tail.rs | 4 +- .../src/execution/engine/math.rs | 2 +- .../src/execution/engine/paragraphs.rs | 27 ++++++-- .../src/execution/engine/quantities.rs | 2 + .../src/execution/font_catalog.rs | 69 ++++++++++++++++++- .../src/execution/format_image.rs | 6 +- .../texrra-tex-core/src/execution/ligature.rs | 56 +++++++++++---- .../src/execution/paragraph.rs | 32 ++++++--- .../src/execution/paragraph/break_cache.rs | 4 +- .../src/execution/paragraph/protrusion.rs | 1 + .../src/execution/paragraph_trace.rs | 2 +- .../src/execution/parameters.rs | 4 ++ .../src/execution/reconstitute.rs | 1 + crates/texrra-tex-core/src/execution/state.rs | 4 ++ docs/P2_M1_PROGRESS.md | 24 +++++++ tests/native_generated_files.rs | 33 +++++++++ 22 files changed, 260 insertions(+), 36 deletions(-) diff --git a/crates/texrra-tex-core/src/execution/boxes.rs b/crates/texrra-tex-core/src/execution/boxes.rs index fefa93d..d252d75 100644 --- a/crates/texrra-tex-core/src/execution/boxes.rs +++ b/crates/texrra-tex-core/src/execution/boxes.rs @@ -336,6 +336,7 @@ impl NativeBox { TextNode::Indent(w) | TextNode::MathBoundary { width: w, .. } | TextNode::AccentKern(w) + | TextNode::AutoKern(w) | TextNode::MarginKern { width: w, .. } | TextNode::Kern { width: w, .. } => HorizontalItem::Box(HorizontalBox { width: *w as i64, @@ -618,6 +619,7 @@ pub(super) fn hpack( TextNode::Indent(w) | TextNode::MathBoundary { width: w, .. } | TextNode::AccentKern(w) + | TextNode::AutoKern(w) | TextNode::MarginKern { width: w, .. } | TextNode::Kern { width: w, .. } => width += *w as i64, TextNode::Glue(g) | TextNode::NamedGlue(g, _) => { diff --git a/crates/texrra-tex-core/src/execution/diagnostics.rs b/crates/texrra-tex-core/src/execution/diagnostics.rs index 16a0c79..11415bf 100644 --- a/crates/texrra-tex-core/src/execution/diagnostics.rs +++ b/crates/texrra-tex-core/src/execution/diagnostics.rs @@ -53,6 +53,7 @@ pub enum DiagnosticNode { Output(OutputNode), Unsupported(String), AccentKern(i32), + AutoKern(i32), MarginKern { width: i32, right: bool }, } /// A semantic view, without recursively copying the box's painted contents. @@ -223,6 +224,7 @@ pub(super) fn text_nodes(nodes: &[TextNode]) -> Vec { }, TextNode::Leaders(leader) => leader_node(leader), TextNode::AccentKern(width) => DiagnosticNode::AccentKern(*width), + TextNode::AutoKern(width) => DiagnosticNode::AutoKern(*width), TextNode::MarginKern { width, right, .. } => DiagnosticNode::MarginKern { width: *width, right: *right, @@ -505,6 +507,12 @@ impl Printer<'_> { self.number(i64::from(*width)); self.literal(" (for accent)"); } + DiagnosticNode::AutoKern(width) => { + self.command("kern"); + self.literal(" "); + self.number(i64::from(*width)); + self.literal(r" (for \pdfprependkern/\pdfappendkern)"); + } DiagnosticNode::Kern { width, explicit } => { self.command("kern"); if *explicit { diff --git a/crates/texrra-tex-core/src/execution/engine.rs b/crates/texrra-tex-core/src/execution/engine.rs index cf75140..1209bca 100644 --- a/crates/texrra-tex-core/src/execution/engine.rs +++ b/crates/texrra-tex-core/src/execution/engine.rs @@ -2120,6 +2120,10 @@ impl Executor { self.reads.insert(Dependency::FontResources); Ok(self.state.fonts.expansion_code(font, slot)) } + Meaning::Primitive(p @ (Primitive::Knbccode | Primitive::Knaccode)) => { + let (font, slot) = self.font_character_target(files)?; + Ok(self.state.fonts.auto_kern_code(font, slot, p == Primitive::Knaccode)) + } Meaning::Primitive(p @ (Primitive::Lpcode | Primitive::Rpcode)) => { let (font, slot) = self.font_character_target(files)?; Ok(self.state.fonts.protrusion_code(font, slot, p == Primitive::Rpcode)) @@ -4012,6 +4016,12 @@ impl Executor { let code = self.integer(files)?; self.state.fonts.set_expansion_code(font, slot, code); } + Some(Knbccode | Knaccode) => { + let (font, slot) = self.font_character_target(files)?; + self.optional_equals(files)?; + let code = self.integer(files)?; + self.state.fonts.set_auto_kern_code(font, slot, primitive == Some(Knaccode), code); + } Some(Lpcode | Rpcode) => { let (font, slot) = self.font_character_target(files)?; self.optional_equals(files)?; diff --git a/crates/texrra-tex-core/src/execution/engine/boxes.rs b/crates/texrra-tex-core/src/execution/engine/boxes.rs index 25ed522..7a9f1ff 100644 --- a/crates/texrra-tex-core/src/execution/engine/boxes.rs +++ b/crates/texrra-tex-core/src/execution/engine/boxes.rs @@ -252,6 +252,7 @@ impl Executor { TextNode::Glyph { .. } | TextNode::Kern { .. } | TextNode::AccentKern(_) + | TextNode::AutoKern(_) | TextNode::Box(_) | TextNode::Indent(_) | TextNode::Rule(_) diff --git a/crates/texrra-tex-core/src/execution/engine/display.rs b/crates/texrra-tex-core/src/execution/engine/display.rs index 6d06072..f60f14c 100644 --- a/crates/texrra-tex-core/src/execution/engine/display.rs +++ b/crates/texrra-tex-core/src/execution/engine/display.rs @@ -405,6 +405,8 @@ impl Executor { | Hyphenchar | Lpcode | Rpcode + | Knbccode + | Knaccode | Efcode | Pdffontexpand | Skewchar diff --git a/crates/texrra-tex-core/src/execution/engine/hyphenation.rs b/crates/texrra-tex-core/src/execution/engine/hyphenation.rs index bc223b1..7e0cc51 100644 --- a/crates/texrra-tex-core/src/execution/engine/hyphenation.rs +++ b/crates/texrra-tex-core/src/execution/engine/hyphenation.rs @@ -87,7 +87,7 @@ impl Executor { self.paragraph .as_mut() .unwrap() - .set_language(language) + .set_language(language, &self.state) .map_err(|e| self.error(e, self.current))?; self.reads .insert(Dependency::Parameter(Parameter::Lefthyphenmin)); diff --git a/crates/texrra-tex-core/src/execution/engine/list_tail.rs b/crates/texrra-tex-core/src/execution/engine/list_tail.rs index cc1dec1..5fb5b70 100644 --- a/crates/texrra-tex-core/src/execution/engine/list_tail.rs +++ b/crates/texrra-tex-core/src/execution/engine/list_tail.rs @@ -20,7 +20,9 @@ impl Tail { TextNode::Glue(g) | TextNode::NamedGlue(g, _) | TextNode::Leaders(LeaderGlue { glue: g, .. }) => Self::Glue(*g, false), - TextNode::Kern { width, .. } | TextNode::AccentKern(width) => Self::Kern(*width), + TextNode::Kern { width, .. } | TextNode::AccentKern(width) | TextNode::AutoKern(width) => { + Self::Kern(*width) + } TextNode::Penalty(n) => Self::Penalty(*n), TextNode::MarginKern { .. } => Self::Other(15), TextNode::Glyph { ligature, .. } => Self::Other(if *ligature { 7 } else { 0 }), diff --git a/crates/texrra-tex-core/src/execution/engine/math.rs b/crates/texrra-tex-core/src/execution/engine/math.rs index d34a92e..ddee8f4 100644 --- a/crates/texrra-tex-core/src/execution/engine/math.rs +++ b/crates/texrra-tex-core/src/execution/engine/math.rs @@ -783,7 +783,7 @@ impl Executor { | Delcode | Count | Countdef | Dimen | Dimendef | Skip | Skipdef | Muskip | Muskipdef | Toks | Toksdef | Advance | Multiply | Divide | Read | Readline | Font | Fontdimen | Hyphenchar | Skewchar | Lpcode | Rpcode | Efcode | Pdffontexpand - | Letterspacefont | Textfont | Scriptfont + | Knbccode | Knaccode | Letterspacefont | Textfont | Scriptfont | Scriptscriptfont | Endlinechar | Newlinechar | Escapechar | Globaldefs | Time | Day | Month | Year | BeginGroup | EndGroup | Relax | Message | Errmessage | Endinput | Showbox | Show | Showthe | Discretionary | DiscretionaryHyphen diff --git a/crates/texrra-tex-core/src/execution/engine/paragraphs.rs b/crates/texrra-tex-core/src/execution/engine/paragraphs.rs index bb64d17..de676be 100644 --- a/crates/texrra-tex-core/src/execution/engine/paragraphs.rs +++ b/crates/texrra-tex-core/src/execution/engine/paragraphs.rs @@ -288,14 +288,22 @@ impl Executor { } Ok(()) } + fn track_auto_kern_parameters(&mut self) { + if self.state.fonts.has_auto_kern_codes() { + self.reads.insert(Dependency::Parameter(Parameter::Pdfprependkern)); + self.reads.insert(Dependency::Parameter(Parameter::Pdfappendkern)); + } + } + pub(super) fn finish_text(&mut self, right_boundary: bool) -> Result<(), Error> { + self.track_auto_kern_parameters(); let Some(p) = self.paragraph.as_mut() else { return Ok(()); }; let before = p.font_steps; p.ligature_carry = self.ligature_carry; p.font_step_limit = before.saturating_add(self.limits.steps.saturating_sub(self.steps)); - let result = p.finish_text(right_boundary); + let result = p.finish_text(right_boundary, &self.state); self.ligature_carry = p.ligature_carry; self.steps = self .steps @@ -309,6 +317,7 @@ impl Executor { token: &Token, files: &mut impl SourceProvider, ) -> Result<(), Error> { + self.track_auto_kern_parameters(); let before = self.paragraph.as_ref().map_or(0, |p| p.font_steps); if let Some(p) = self.paragraph.as_mut() { p.ligature_carry = self.ligature_carry; @@ -354,7 +363,7 @@ impl Executor { let language = HyphenationLanguage::from_state(&self.state); let b = self.paragraph.as_mut().unwrap(); if b.current_language.language != language.language { - b.set_language(language) + b.set_language(language, &self.state) .map_err(|e| self.error(e, token.span))?; } for p in [ @@ -597,14 +606,20 @@ impl Executor { hyphen_char = None; } } + let mut pre_break = Vec::new(); + if let Some(c) = hyphen_char { + let kern = FontCatalog::auto_kern_for(&self.state, font); + let before = kern.and_then(|k| k.width(None, Some(c as u8))); + let after = kern.and_then(|k| k.width(Some(c as u8), None)); + pre_break.extend(before.map(TextNode::AutoKern)); + pre_break.push(super::super::paragraph::hyphen_node(&self.state, font, c, origin)); + pre_break.extend(after.map(TextNode::AutoKern)); + } TextNode::Discretionary { font, automatic: false, hyphen_char, - pre_break: hyphen_char - .into_iter() - .map(|c| super::super::paragraph::hyphen_node(&self.state, font, c, origin)) - .collect(), + pre_break, post_break: Vec::new(), replacement_count: 0, } diff --git a/crates/texrra-tex-core/src/execution/engine/quantities.rs b/crates/texrra-tex-core/src/execution/engine/quantities.rs index 423bba1..43a8209 100644 --- a/crates/texrra-tex-core/src/execution/engine/quantities.rs +++ b/crates/texrra-tex-core/src/execution/engine/quantities.rs @@ -230,6 +230,8 @@ impl Executor { | Primitive::Hyphenchar | Primitive::Lpcode | Primitive::Rpcode + | Primitive::Knbccode + | Primitive::Knaccode | Primitive::Efcode | Primitive::Skewchar ) diff --git a/crates/texrra-tex-core/src/execution/font_catalog.rs b/crates/texrra-tex-core/src/execution/font_catalog.rs index 9838a7e..ce35032 100644 --- a/crates/texrra-tex-core/src/execution/font_catalog.rs +++ b/crates/texrra-tex-core/src/execution/font_catalog.rs @@ -1,6 +1,6 @@ //! Job-owned, sized fonts loaded from the host's actual binary resource world. //! This layer has no master-font names, outline aliases or bundled fallbacks. -use super::{CommandName, Flex, FontIntegers, Glue, SourceProvider}; +use super::{CommandName, Flex, FontIntegers, Glue, Parameter, SourceProvider, State}; use crate::{ native_font::{LetterspaceProgram, NativeFont}, resources::{LoadedResource, ResourceKind, ResourceVersion}, @@ -152,6 +152,29 @@ pub(crate) struct PdfFontSettings { pub(crate) omit_builtin_unicode: bool, } +#[derive(Clone, Copy)] +pub(super) struct AutoKern<'a> { + codes: &'a BTreeMap, + quad: i64, + prepend: bool, + append: bool, +} + +impl AutoKern<'_> { + pub(super) fn width(self, left: Option, right: Option) -> Option { + let scaled = |slot: Option, after| { + let code = slot + .and_then(|slot| self.codes.get(&slot)) + .map_or(0, |codes| i32::from(codes[usize::from(after)])); + round_ratio(self.quad, code, 1000) + }; + let after = if self.append { scaled(left, true) } else { 0 }; + let before = if self.prepend { scaled(right, false) } else { 0 }; + let width = after + before; + (width != 0).then_some(width as i32) + } +} + #[derive(Clone, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)] pub struct FontCatalog { fonts: Vec, @@ -161,6 +184,8 @@ pub struct FontCatalog { #[serde(default, skip_serializing_if = "BTreeMap::is_empty")] protrusion: BTreeMap>, #[serde(default, skip_serializing_if = "BTreeMap::is_empty")] + auto_kern: BTreeMap>, + #[serde(default, skip_serializing_if = "BTreeMap::is_empty")] expansion: BTreeMap, #[serde(default, skip_serializing_if = "BTreeMap::is_empty")] expansion_codes: BTreeMap>, @@ -196,6 +221,7 @@ impl FontCatalog { parameter_words: 7, limits, protrusion: BTreeMap::new(), + auto_kern: BTreeMap::new(), expansion: BTreeMap::new(), expansion_codes: BTreeMap::new(), pdf_settings: BTreeMap::new(), @@ -423,6 +449,47 @@ impl FontCatalog { self.protrusion.entry(font).or_default().entry(slot).or_default()[usize::from(right)] = code; } } + pub(super) fn has_auto_kern_codes(&self) -> bool { + !self.auto_kern.is_empty() + } + + pub(super) fn auto_kern_code(&self, font: FontId, slot: u8, after: bool) -> i32 { + self.auto_kern + .get(&font) + .and_then(|codes| codes.get(&slot)) + .map_or(0, |codes| i32::from(codes[usize::from(after)])) + } + + pub(super) fn set_auto_kern_code(&mut self, font: FontId, slot: u8, after: bool, code: i32) { + let side = usize::from(after); + let code = code.clamp(-1000, 1000) as i16; + if code != 0 { + self.auto_kern.entry(font).or_default().entry(slot).or_default()[side] = code; + } else if let Some(table) = self.auto_kern.get_mut(&font) { + if let Some(codes) = table.get_mut(&slot) { + codes[side] = 0; + if *codes == [0; 2] { + table.remove(&slot); + } + } + if table.is_empty() { + self.auto_kern.remove(&font); + } + } + } + + pub(super) fn auto_kern_for(state: &State, font: FontId) -> Option> { + let codes = state.fonts.auto_kern.get(&font)?; + let prepend = state.parameter(Parameter::Pdfprependkern).width() > 0; + let append = state.parameter(Parameter::Pdfappendkern).width() > 0; + (prepend || append).then(|| AutoKern { + codes, + quad: i64::from(state.fonts.font(font).expect("loaded font").quad()), + prepend, + append, + }) + } + pub(super) fn configure_expansion( &mut self, font: FontId, diff --git a/crates/texrra-tex-core/src/execution/format_image.rs b/crates/texrra-tex-core/src/execution/format_image.rs index 7e8c685..ffb44e5 100644 --- a/crates/texrra-tex-core/src/execution/format_image.rs +++ b/crates/texrra-tex-core/src/execution/format_image.rs @@ -8,9 +8,9 @@ use std::{ sync::{Arc, Mutex, OnceLock, Weak}, }; -const SCHEMA: u32 = 49; -const COMPATIBLE_SCHEMAS: [u32; 18] = [ - 27, 28, 31, 32, 33, 34, 35, 36, 37, 38, 39, 43, 44, 45, 46, 47, 48, SCHEMA, +const SCHEMA: u32 = 50; +const COMPATIBLE_SCHEMAS: [u32; 19] = [ + 27, 28, 31, 32, 33, 34, 35, 36, 37, 38, 39, 43, 44, 45, 46, 47, 48, 49, SCHEMA, ]; const ENGINE: &str = concat!("texrra-native/", env!("CARGO_PKG_VERSION")); diff --git a/crates/texrra-tex-core/src/execution/ligature.rs b/crates/texrra-tex-core/src/execution/ligature.rs index f6ef6b2..42a4b9c 100644 --- a/crates/texrra-tex-core/src/execution/ligature.rs +++ b/crates/texrra-tex-core/src/execution/ligature.rs @@ -1,7 +1,7 @@ //! Streaming TFM cursor/ligature-stack execution. A raw input character is //! fetched only after the pending cursor asks for one; inserted ligatures can //! therefore retain or consume components without inventing source characters. -use super::Span; +use super::{Span, font_catalog::AutoKern}; use crate::provenance::{Derivation, PaintSource}; use crate::tfm::{LigKernCommand, TfmMetrics}; use std::collections::VecDeque; @@ -27,6 +27,7 @@ pub(super) struct Glyph { pub(super) enum Output { Glyph(Glyph), Kern(i32), + AutoKern { width: i32, after_wrap: bool }, Missing(Component), } /// TeX's main-loop flags are job globals, including across a missing raw @@ -223,7 +224,7 @@ impl Machine { cursor.stack.push_front(r); } 7 | 11 => { - cursor.wrap(false, &mut out); + cursor.wrap(false, None, &mut out); cursor.left = Some(Right::inserted(replacement).glyph); cursor.left.as_mut().unwrap().source = source; } @@ -257,7 +258,7 @@ impl Machine { if !done { continue; } - cursor.wrap(true, &mut out); + cursor.wrap(true, None, &mut out); if kern != 0 { out.push(Output::Kern( i32::try_from(kern).map_err(|_| "native reconstitute kern overflow")?, @@ -304,6 +305,7 @@ impl Machine { f: &TfmMetrics, c: Component, cancel_left: bool, + auto_kern: Option>, steps: &mut usize, limit: usize, ) -> Result, String> { @@ -318,8 +320,15 @@ impl Machine { right_hit: carry.right, ..Self::default() }; + let prepend = auto_kern.and_then(|kern| kern.width(None, Some(c.slot))); + if let Some(width) = prepend { + out.push(Output::AutoKern { + width, + after_wrap: false, + }); + } self.stack.push_back(Right::raw(c, false)); - if cancel_left || f.boundary_label().is_none() { + if prepend.is_some() || cancel_left || f.boundary_label().is_none() { self.advance(f, &mut out); } } else { @@ -327,13 +336,14 @@ impl Machine { let suppress_match = Some(c.slot) == f.false_boundary_char(); self.stack.push_back(Right::raw(c, suppress_match)); } - self.pump(f, false, steps, limit, &mut out)?; + self.pump(f, false, auto_kern, steps, limit, &mut out)?; Ok(out) } pub fn finish( &mut self, f: &TfmMetrics, right_boundary: bool, + auto_kern: Option>, steps: &mut usize, limit: usize, ) -> Result, String> { @@ -341,10 +351,10 @@ impl Machine { self.boundary = None; } let mut out = Vec::new(); - self.pump(f, true, steps, limit, &mut out)?; + self.pump(f, true, auto_kern, steps, limit, &mut out)?; Ok(out) } - fn wrap(&mut self, right: bool, out: &mut Vec) { + fn wrap(&mut self, right: bool, auto_kern: Option>, out: &mut Vec) { if let Some(mut glyph) = self.left.take() { if glyph.ligature { self.orphan_ligature = false; @@ -354,6 +364,12 @@ impl Machine { glyph.right_boundary = self.right_hit; self.right_hit = false; } + if let Some(width) = auto_kern.and_then(|kern| kern.width(None, Some(glyph.slot))) { + out.push(Output::AutoKern { + width, + after_wrap: false, + }); + } } out.push(Output::Glyph(glyph)); } @@ -378,6 +394,7 @@ impl Machine { &mut self, f: &TfmMetrics, ending: bool, + auto_kern: Option>, steps: &mut usize, limit: usize, out: &mut Vec, @@ -399,14 +416,27 @@ impl Machine { } else { self.boundary }; - let command = right.and_then(|r| f.lig_kern(self.left.as_ref().map(|g| g.slot), r)); + let left = self.left.as_ref().map(|g| g.slot); + // The initial boundary program enters after the automatic kern check. + if left.is_some() + && let Some(width) = auto_kern.and_then(|kern| kern.width(left, right)) + { + self.wrap(true, auto_kern, out); + out.push(Output::AutoKern { + width, + after_wrap: true, + }); + self.advance(f, out); + continue; + } + let command = right.and_then(|r| f.lig_kern(left, r)); match command { None => { - self.wrap(true, out); + self.wrap(true, auto_kern, out); self.advance(f, out); } Some(LigKernCommand::Kern(k)) => { - self.wrap(true, out); + self.wrap(true, auto_kern, out); out.push(Output::Kern( i32::try_from(k).map_err(|_| "native font kern overflow")?, )); @@ -459,7 +489,7 @@ impl Machine { self.stack.push_front(r); } 7 | 11 => { - self.wrap(false, out); + self.wrap(false, auto_kern, out); self.left = Some(Right::inserted(replacement).glyph); self.left.as_mut().unwrap().source = source; } @@ -487,7 +517,7 @@ impl Machine { g.components.extend(r.glyph.components); } else { self.left = Some(g); - self.wrap(true, out); + self.wrap(true, auto_kern, out); self.started = false; continue; } @@ -498,7 +528,7 @@ impl Machine { } } if operation > 4 && operation != 7 { - self.wrap(true, out); + self.wrap(true, auto_kern, out); self.advance(f, out); } } diff --git a/crates/texrra-tex-core/src/execution/paragraph.rs b/crates/texrra-tex-core/src/execution/paragraph.rs index b3c167a..298851b 100644 --- a/crates/texrra-tex-core/src/execution/paragraph.rs +++ b/crates/texrra-tex-core/src/execution/paragraph.rs @@ -75,6 +75,7 @@ pub enum TextNode { }, /// 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)] @@ -161,8 +162,8 @@ impl Builder { )); } } - pub fn set_language(&mut self, language: HyphenationLanguage) -> Result<(), String> { - self.finish_text(true)?; + 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(()) @@ -174,6 +175,7 @@ impl Builder { ) -> Vec { use super::ligature::Output; let mut missing = Vec::new(); + let mut hyphen_break = None; for item in output { match item { Output::Glyph(g) => { @@ -196,6 +198,7 @@ impl Builder { 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, @@ -210,18 +213,27 @@ impl Builder { 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) -> Result<(), String> { + 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, )?; @@ -251,7 +263,7 @@ impl Builder { .as_ref() .is_some_and(|r| r.font.id != font || r.hyphen_char != hyphen_char) { - self.finish_text(true)?; + self.finish_text(true, state)?; } let cancel = self.cancel_boundary; self.cancel_boundary = false; @@ -269,6 +281,7 @@ impl Builder { run.font.metrics(), c, cancel, + FontCatalog::auto_kern_for(state, font), &mut self.font_steps, self.font_step_limit, )?; @@ -289,7 +302,7 @@ impl Builder { }; } pub fn space(&mut self, state: &State) -> Result<(), String> { - self.finish_text(true)?; + self.finish_text(true, state)?; let f = state.fonts.font(state.text_font())?; let g = f.space(); let (space, stretch, shrink, extra) = ( @@ -390,6 +403,7 @@ fn width(n: &TextNode) -> i64 { 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, @@ -1050,7 +1064,7 @@ pub(super) fn finish( trace: &mut super::paragraph_trace::Tracer<'_>, cache: Option<&LineBreakCache>, ) -> Result { - b.finish_text(true)?; + b.finish_text(true, state)?; if b.nodes.last().is_some_and(|n| { matches!( n, @@ -1161,11 +1175,12 @@ pub(super) fn finish( point.zero_tail, ); let dimensions = geometry(¶meters, shape, i + b.previous_lines); - let terminal_marker = point.zero_tail.is_some() - || matches!(b.nodes.get(point.end), Some(TextNode::Penalty(_))); 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, ¶meters, @@ -1354,6 +1369,7 @@ fn add_hyphens( | TextNode::Leaders(_) | TextNode::Penalty(_) | TextNode::AccentKern(_) + | TextNode::AutoKern(_) | TextNode::Kern { explicit: true, .. } ) }) 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 4d8178a..63378af 100644 --- a/crates/texrra-tex-core/src/execution/paragraph/break_cache.rs +++ b/crates/texrra-tex-core/src/execution/paragraph/break_cache.rs @@ -153,7 +153,9 @@ impl BreakNode { | TextNode::NamedGlue(glue, _) | TextNode::Leaders(LeaderGlue { glue, .. }) => Self::Glue(*glue), TextNode::AccentKern(width) => Self::AccentKern(*width), - TextNode::MarginKern { width, .. } => Self::Content(i64::from(*width)), + TextNode::MarginKern { width, .. } | TextNode::AutoKern(width) => { + Self::Content(i64::from(*width)) + } TextNode::Kern { width, explicit } => Self::Kern { width: *width, explicit: *explicit, diff --git a/crates/texrra-tex-core/src/execution/paragraph/protrusion.rs b/crates/texrra-tex-core/src/execution/paragraph/protrusion.rs index 0dfa25b..0e4228a 100644 --- a/crates/texrra-tex-core/src/execution/paragraph/protrusion.rs +++ b/crates/texrra-tex-core/src/execution/paragraph/protrusion.rs @@ -96,6 +96,7 @@ fn skippable(node: &TextNode) -> bool { | TextNode::Penalty(_) | TextNode::Indent(0) | TextNode::AccentKern(0) + | TextNode::AutoKern(_) | TextNode::MathBoundary { width: 0, .. } | TextNode::Kern { explicit: false, .. } | TextNode::Kern { width: 0, .. } => true, diff --git a/crates/texrra-tex-core/src/execution/paragraph_trace.rs b/crates/texrra-tex-core/src/execution/paragraph_trace.rs index 5357c2e..7593d8c 100644 --- a/crates/texrra-tex-core/src/execution/paragraph_trace.rs +++ b/crates/texrra-tex-core/src/execution/paragraph_trace.rs @@ -231,7 +231,7 @@ impl<'a> Tracer<'a> { i += usize::from(*replacement_count); } TextNode::Kern { .. } | TextNode::AccentKern(_) | TextNode::Penalty(_) - | TextNode::MarginKern { .. } => {} + | TextNode::AutoKern(_) | TextNode::MarginKern { .. } => {} } i += 1; } diff --git a/crates/texrra-tex-core/src/execution/parameters.rs b/crates/texrra-tex-core/src/execution/parameters.rs index 518921e..f8beb51 100644 --- a/crates/texrra-tex-core/src/execution/parameters.rs +++ b/crates/texrra-tex-core/src/execution/parameters.rs @@ -114,6 +114,8 @@ pub enum Parameter { Lineskip, Tabskip, Pdfprotrudechars, + Pdfprependkern, + Pdfappendkern, Pdfadjustspacing, Partokencontext, } @@ -233,6 +235,8 @@ impl Parameter { Self::Lineskip, Self::Tabskip, Self::Pdfprotrudechars, + Self::Pdfprependkern, + Self::Pdfappendkern, Self::Pdfadjustspacing, Self::Partokencontext, ]; diff --git a/crates/texrra-tex-core/src/execution/reconstitute.rs b/crates/texrra-tex-core/src/execution/reconstitute.rs index 096e560..c56adf3 100644 --- a/crates/texrra-tex-core/src/execution/reconstitute.rs +++ b/crates/texrra-tex-core/src/execution/reconstitute.rs @@ -28,6 +28,7 @@ fn nodes( right_boundary: g.right_boundary, hyphen_char: None, }, + Output::AutoKern { width, .. } => TextNode::AutoKern(width), Output::Missing(_) => { return Err("unfetched original character during native reconstitution".into()); } diff --git a/crates/texrra-tex-core/src/execution/state.rs b/crates/texrra-tex-core/src/execution/state.rs index e8b7956..fe22fad 100644 --- a/crates/texrra-tex-core/src/execution/state.rs +++ b/crates/texrra-tex-core/src/execution/state.rs @@ -333,6 +333,8 @@ pub enum Primitive { Pdflastmatch, Lpcode, Rpcode, + Knbccode, + Knaccode, Efcode, Pdffontexpand, Pdfobj, @@ -795,6 +797,8 @@ impl Default for State { ("hyphenchar", Hyphenchar), ("lpcode", Lpcode), ("rpcode", Rpcode), + ("knbccode", Knbccode), + ("knaccode", Knaccode), ("efcode", Efcode), ("pdffontexpand", Pdffontexpand), ("fontname", Fontname), diff --git a/docs/P2_M1_PROGRESS.md b/docs/P2_M1_PROGRESS.md index 7c42c07..2887d5e 100644 --- a/docs/P2_M1_PROGRESS.md +++ b/docs/P2_M1_PROGRESS.md @@ -1500,6 +1500,30 @@ LaTeX 后端结构目的地分支。 [TeX Live 实现](https://github.com/TeX-Live/texlive-source/blob/trunk/texk/web2c/pdftexdir/pdftex.web) 与 [pdfTeX 发布记录](https://github.com/TeX-Live/texlive-source/blob/trunk/texk/web2c/pdftexdir/NEWS)。 +### 自动字偶和悬挂标点 + +`\knbccode`、`\knaccode` 使用字体每个字符的实际前后字偶量,受 +`\pdfprependkern` 和 `\pdfappendkern` 控制。使用当时 `\fontdimen`6 按 +千分值取整,非零结果在 TFM 字偶与连字决策前产生独立节点。真实盒、 +段落和显式断字列表接入此节点。断行保留自动字偶,边缘搜索跳过节点 +以选择实际悬挂字符。空断字标记保留在右侧悬挂字偶之后。 + +三份 pdfTeX INITEX 对照的原始列表、词框和 144 dpi 栅格完全一致。 +覆盖正负取值、字体隔离、组内开关、数值扫描、`\lastkern`、连字、 +显式与自动断字及段落两侧悬挂。自动断字按上游在现有自动字偶处分段 +搜索。第一版的空断字标记顺序差异及原样失败保留在 +target/p2-autokern-native。schema50 重载了含真实自动字偶的盒, +同时保留字体表与开关。重载与直接编译的盒宽和栅格一致,旧 schema49 +中已保存的字距字体仍成功发页。 + +第二页字体代码从125改为175后,复用899步,只替换第二页。实际盒宽 +从1143605sp变为1176373sp,PDF、SVG、宽度文件和归一化来源映射与 +独立零复用全量一致。对照回执 SHA-256 +df4a0061c782c22ce469d99e5aa8cafd8febe7226185e1861b42ff05f4c57e38, +续编回执 SHA-256 +616875262bf2aeb58823cd9389a9b10a4097b9576f9867e0ff56a7edd9c7efd7。 +[TeX Live pdfTeX 实现](https://github.com/TeX-Live/texlive-source/blob/trunk/texk/web2c/pdftexdir/pdftex.web) + ### PDF 字面中的矩阵与来源映射 来源映射与 PDF 写入共用设备原点的取整。实际字面中的 `q`、`Q` 和 diff --git a/tests/native_generated_files.rs b/tests/native_generated_files.rs index 61a7a02..870378f 100644 --- a/tests/native_generated_files.rs +++ b/tests/native_generated_files.rs @@ -262,3 +262,36 @@ fn redirected_show_uses_the_open_stream_without_setting_the_cli_error_status() { fs::remove_dir_all(root).unwrap(); fs::remove_dir_all(oracle).unwrap(); } + +#[test] +fn automatic_kerns_preserve_raw_ligature_and_hyphen_margin_order() { + let root = directory(); + let oracle = directory(); + let entry = "automatic-kerns.tex"; + let input = r"\catcode123=1 \catcode125=2 +\pdfoutput=1 +\font\roman=cmr10 \roman \hyphenchar\roman=45 +\pdfprependkern=1 \pdfappendkern=1 \pdfprotrudechars=2 +\knbccode\roman65=80 \knaccode\roman65=150 +\knbccode\roman86=120 \knaccode\roman86=-50 \knbccode\roman12=200 +\knbccode\roman45=95 \knaccode\roman45=105 \rpcode\roman45=100 +\hsize=32pt \parindent=0pt \pretolerance=-1 \tolerance=10000 \exhyphenpenalty=0 +\immediate\openout3=lists.dat \showstream=3 +\showboxbreadth=100 \showboxdepth=10 +\setbox0=\hbox{AV fi AA\-VV} \showbox0 +\setbox1=\vbox{\noindent AA-VV VV\par} \showbox1 +\immediate\closeout3 +\end"; + fs::write(root.join(entry), input).unwrap(); + fs::write(oracle.join(entry), input).unwrap(); + let expected = reference(&oracle, entry); + let actual = native(&root, entry); + assert!(expected.status.success(), "{expected:?}"); + assert!(actual.status.success(), "{actual:?}"); + assert_eq!( + fs::read_to_string(root.join("lists.dat")).unwrap(), + fs::read_to_string(oracle.join("lists.dat")).unwrap() + ); + fs::remove_dir_all(root).unwrap(); + fs::remove_dir_all(oracle).unwrap(); +}