Execute ICU locale line breaks in native XeTeX paragraphs

This commit is contained in:
gloamxun committed 2026-11-26 12:46:30 +08:00
1 parent 4e16531a62
commit 048478c346
12 files changed
+238 -29

No files matched your search

@@ -2650,6 +2650,13 @@ impl Executor {
fn filename_with_quoting(
&mut self,
files: &mut impl SourceProvider,
) -> Result<(String, bool), Error> {
self.scan_filename(files, false)
}
fn scan_filename(
&mut self,
files: &mut impl SourceProvider,
allow_empty: bool,
) -> Result<(String, bool), Error> {
let first = self.expanded_non_space(files)?;
let mut used_quotes = false;
@@ -2694,7 +2701,7 @@ impl Executor {
return self.fail("unclosed quote in filename");
}
}
if name.is_empty() {
if name.is_empty() && !allow_empty {
return self.fail("empty filename");
}
self.decode_filename(name).map(|name| (name, used_quotes))
@@ -3264,6 +3271,7 @@ impl Executor {
Primitive::XeTeXglyphname => "XeTeXglyphname".into(),
Primitive::XeTeXinputencoding => "XeTeXinputencoding".into(),
Primitive::XeTeXdefaultencoding => "XeTeXdefaultencoding".into(),
Primitive::XeTeXlinebreaklocale => "XeTeXlinebreaklocale".into(),
Primitive::XeTeXcharclass => "XeTeXcharclass".into(),
Primitive::XeTeXinterchartoks => "XeTeXinterchartoks".into(),
Primitive::BeginL => "beginL".into(),
@@ -52,6 +52,14 @@ impl Executor {
self.scan_xdv_image(token, primitive == XeTeXpdffile, files)?
}
XeTeXglyph => self.append_opentype_glyph(token, files)?,
XeTeXlinebreaklocale => {
let (name, _) = self.scan_filename(files, true)?;
let stem = name.rsplit('/').next().unwrap_or_default();
let stem = stem.rsplit_once('.').map_or(stem, |(stem, _)| stem);
// This extension changes the locale directly. Glue and penalty
// still use ordinary scoped TeX assignments.
self.state.xe_line_break_locale = (!stem.is_empty()).then(|| stem.to_owned());
}
_ => return Ok(false),
}
Ok(true)
@@ -434,6 +434,11 @@ impl Executor {
self.reads.insert(Dependency::Parameter(Parameter::XeTeXinterwordspaceshaping));
if !self.restricted() {
self.reads.insert(Dependency::Parameter(Parameter::XeTeXdashbreakstate));
self.reads.insert(Dependency::XeLineBreakLocale);
if self.state.xe_line_break_locale.is_some() {
self.reads.insert(Dependency::Parameter(Parameter::XeTeXlinebreakskip));
self.reads.insert(Dependency::Parameter(Parameter::XeTeXlinebreakpenalty));
}
}
}
return self.paragraph.as_mut().unwrap()
@@ -8,9 +8,9 @@ use std::{
sync::{Arc, Mutex, OnceLock, Weak},
};
const SCHEMA: u32 = 75;
const COMPATIBLE_SCHEMAS: [u32; 42] = [
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, SCHEMA,
const SCHEMA: u32 = 76;
const COMPATIBLE_SCHEMAS: [u32; 43] = [
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, SCHEMA,
];
const ENGINE: &str = concat!("texrra-native/", env!("CARGO_PKG_VERSION"));
@@ -477,6 +477,7 @@ pub enum Dependency {
},
InputStream(u8),
XeDefaultInputEncoding,
XeLineBreakLocale,
InputPosition(usize),
OutputStream(u8),
ParagraphToken,
@@ -383,15 +383,55 @@ impl Builder {
joined_sources.extend(sources.into_iter().map(|(at, source)| (at + offset, source)));
sources = joined_sources;
}
let replaced = previous.is_some();
if previous.is_some() {
self.nodes.pop();
}
let actual_text = xetex && state.parameter(Parameter::XeTeXgenerateactualtext).width() > 0;
if xetex && !self.restricted
&& let Some(locale) = &state.xe_line_break_locale
{
let ends = super::xe_encoding::icu::line_breaks(locale, &text)?;
if !ends.is_empty() {
let glue = state.parameter(Parameter::XeTeXlinebreakskip).glue();
let penalty = state.parameter(Parameter::XeTeXlinebreakpenalty).width();
let use_skip = !glue.canonical_zero;
let mut sources = sources.into_iter().peekable();
let mut start = 0;
for end in ends.into_iter().chain(std::iter::once(text.len())) {
if start != 0 {
if penalty != 0 || !use_skip {
self.nodes.push(TextNode::Penalty(penalty));
}
if use_skip {
self.nodes.push(TextNode::NamedGlue(glue, Parameter::XeTeXlinebreakskip));
}
}
let mut origins = Vec::new();
while let Some((offset, source)) = sources.next_if(|(offset, _)| *offset < end) {
origins.push((offset - start, source));
}
self.shape_opentype(font, text[start..end].to_owned(), origins, use_glyph_metrics, actual_text)?;
start = end;
}
return Ok(());
}
}
self.shape_opentype(font, text, sources, use_glyph_metrics, actual_text)
}
fn shape_opentype(
&mut self,
font: &Arc<OpenTypeFont>,
text: String,
sources: Vec<(usize, PaintSource)>,
use_glyph_metrics: bool,
actual_text: bool,
) -> Result<(), String> {
let mut shaped = font.shape_mapped(text, sources, use_glyph_metrics)?;
shaped.actual_text = xetex && state.parameter(Parameter::XeTeXgenerateactualtext).width() > 0;
shaped.actual_text = actual_text;
self.font_steps = self.font_steps.checked_add(shaped.glyphs.len())
.filter(|steps| *steps <= self.font_step_limit)
.ok_or("native OpenType shaping step limit exceeded")?;
if replaced {
self.nodes.pop();
}
self.nodes.push(TextNode::OpenType(Arc::new(shaped)));
Ok(())
}
@@ -128,6 +128,8 @@ pub enum Parameter {
XeTeXhyphenatablelength,
XeTeXgenerateactualtext,
XeTeXinterwordspaceshaping,
XeTeXlinebreakskip,
XeTeXlinebreakpenalty,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
pub enum ParameterValue {
@@ -160,7 +162,7 @@ impl Parameter {
)
}
pub(super) const XETEX: [Self; 8] = [
pub(super) const XETEX: [Self; 10] = [
Self::XeTeXuseglyphmetrics,
Self::XeTeXdashbreakstate,
Self::Suppressfontnotfounderror,
@@ -169,6 +171,8 @@ impl Parameter {
Self::XeTeXhyphenatablelength,
Self::XeTeXgenerateactualtext,
Self::XeTeXinterwordspaceshaping,
Self::XeTeXlinebreakskip,
Self::XeTeXlinebreakpenalty,
];
pub const ALL: &'static [Self] = &[
@@ -295,6 +299,8 @@ impl Parameter {
Self::XeTeXhyphenatablelength,
Self::XeTeXgenerateactualtext,
Self::XeTeXinterwordspaceshaping,
Self::XeTeXlinebreakskip,
Self::XeTeXlinebreakpenalty,
];
pub fn name(self) -> String {
match self {
@@ -306,6 +312,8 @@ impl Parameter {
Self::XeTeXhyphenatablelength => "XeTeXhyphenatablelength".into(),
Self::XeTeXgenerateactualtext => "XeTeXgenerateactualtext".into(),
Self::XeTeXinterwordspaceshaping => "XeTeXinterwordspaceshaping".into(),
Self::XeTeXlinebreakskip => "XeTeXlinebreakskip".into(),
Self::XeTeXlinebreakpenalty => "XeTeXlinebreakpenalty".into(),
_ => format!("{self:?}").to_ascii_lowercase(),
}
}
@@ -353,7 +361,8 @@ impl Parameter {
| Self::Splittopskip
| Self::Topskip
| Self::Lineskip
| Self::Tabskip => Some(RegisterKind::Skip),
| Self::Tabskip
| Self::XeTeXlinebreakskip => Some(RegisterKind::Skip),
_ => None,
}
}
@@ -394,6 +394,7 @@ pub enum Primitive {
XeTeXglyphname,
XeTeXfirstfontchar,
XeTeXlastfontchar,
XeTeXlinebreaklocale,
}
impl Primitive {
@@ -716,6 +717,8 @@ pub struct State {
input_profile: super::InputProfile,
#[serde(default)]
pub(super) xe_default_encoding: super::xe_encoding::Encoding,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub(super) xe_line_break_locale: Option<String>,
pub endlinechar: i32,
pub newlinechar: i32,
pub escapechar: i32,
@@ -932,6 +935,7 @@ impl Default for State {
initex: false,
input_profile: super::InputProfile::default(),
xe_default_encoding: super::xe_encoding::Encoding::Auto,
xe_line_break_locale: None,
endlinechar: 13,
newlinechar: -1,
escapechar: 92,
@@ -1746,6 +1750,7 @@ impl State {
("XeTeXpdfpagecount", Primitive::XeTeXpdfpagecount),
("XeTeXinputencoding", Primitive::XeTeXinputencoding),
("XeTeXdefaultencoding", Primitive::XeTeXdefaultencoding),
("XeTeXlinebreaklocale", Primitive::XeTeXlinebreaklocale),
("XeTeXcharclass", Primitive::XeTeXcharclass),
("XeTeXinterchartoks", Primitive::XeTeXinterchartoks),
] {
@@ -1,7 +1,7 @@
//! XeTeX physical input encodings. Decoded units retain their source bytes.
use std::sync::Arc;
mod icu;
pub(super) mod icu;
#[derive(Clone, Debug, Default, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
pub(super) enum Encoding {
@@ -1,4 +1,4 @@
//! The ICU converter used by XeTeX for non-built-in encoding names.
//! ICU4C services used by XeTeX input and line breaking.
use super::{Character, utf16_character};
use libloading::Library;
use std::{
@@ -34,6 +34,20 @@ fn library() -> Result<&'static Icu, String> {
}
fn load() -> Option<Icu> {
let ((open, close, to_unicode), library) = load_symbols(|lib, suffix| {
// Load all functions from the same ICU installation and ABI version.
unsafe {
Some((
*lib.get::<Open>(format!("ucnv_open{suffix}").as_bytes()).ok()?,
*lib.get::<Close>(format!("ucnv_close{suffix}").as_bytes()).ok()?,
*lib.get::<ToUnicode>(format!("ucnv_toUnicode{suffix}").as_bytes()).ok()?,
))
}
})?;
Some(Icu { open, close, to_unicode, _library: library })
}
fn load_symbols<T>(symbols: impl Fn(&Library, &str) -> Option<T>) -> Option<(T, Library)> {
#[cfg(target_os = "windows")]
let unversioned = ["icu.dll", "icuuc.dll"];
#[cfg(target_os = "macos")]
@@ -67,22 +81,8 @@ fn load() -> Option<Icu> {
for suffix in
std::iter::once(String::new()).chain(versions.clone().map(|v| format!("_{v}")))
{
// ICU4C ships these declarations as stable C ABI. All three must
// come from this same library and use the same export suffix.
let symbols = unsafe {
(
lib.get::<Open>(format!("ucnv_open{suffix}").as_bytes()),
lib.get::<Close>(format!("ucnv_close{suffix}").as_bytes()),
lib.get::<ToUnicode>(format!("ucnv_toUnicode{suffix}").as_bytes()),
)
};
if let (Ok(open), Ok(close), Ok(to_unicode)) = symbols {
return Some(Icu {
open: *open,
close: *close,
to_unicode: *to_unicode,
_library: lib,
});
if let Some(functions) = symbols(&lib, &suffix) {
return Some((functions, lib));
}
}
}
@@ -190,3 +190,100 @@ pub(super) fn decode(name: &str, data: &[u8], base: usize) -> Result<Vec<Charact
}
Ok(chars)
}
type BreakOpen = unsafe extern "C" fn(i32, *const c_char, *const u16, i32, *mut i32) -> *mut c_void;
type BreakNext = unsafe extern "C" fn(*mut c_void) -> i32;
struct BreakApi {
open: BreakOpen,
next: BreakNext,
close: Close,
_library: Library,
}
impl BreakApi {
fn shared() -> Result<&'static Self, String> {
static BREAKS: OnceLock<Option<BreakApi>> = OnceLock::new();
BREAKS
.get_or_init(|| {
let ((open, next, close), library) = load_symbols(|lib, suffix| unsafe {
Some((
*lib.get::<BreakOpen>(format!("ubrk_open{suffix}").as_bytes()).ok()?,
*lib.get::<BreakNext>(format!("ubrk_next{suffix}").as_bytes()).ok()?,
*lib.get::<Close>(format!("ubrk_close{suffix}").as_bytes()).ok()?,
))
})?;
Some(Self { open, next, close, _library: library })
})
.as_ref()
.ok_or_else(|| "XeTeX locale line breaking requires an ICU4C runtime".into())
}
}
struct BreakIterator<'a> {
api: &'static BreakApi,
handle: std::ptr::NonNull<c_void>,
_text: &'a [u16],
}
impl<'a> BreakIterator<'a> {
fn open(api: &'static BreakApi, locale: &std::ffi::CStr, text: &'a [u16]) -> Option<Self> {
const UBRK_LINE: i32 = 2;
let count = i32::try_from(text.len()).ok()?;
let mut status = 0i32;
// ICU borrows the UTF-16 buffer. The returned guard keeps it alive
// until after ubrk_close and is never shared between jobs.
let handle = std::ptr::NonNull::new(unsafe {
(api.open)(UBRK_LINE, locale.as_ptr(), text.as_ptr(), count, &mut status)
})?;
let iterator = Self { api, handle, _text: text };
(status <= 0).then_some(iterator)
}
fn next(&self) -> i32 {
unsafe { (self.api.next)(self.handle.as_ptr()) }
}
}
impl Drop for BreakIterator<'_> {
fn drop(&mut self) {
unsafe { (self.api.close)(self.handle.as_ptr()) }
}
}
pub(in crate::execution) fn line_breaks(locale: &str, text: &str) -> Result<Vec<usize>, String> {
if text.chars().nth(1).is_none() {
return Ok(Vec::new());
}
let api = BreakApi::shared()?;
let utf16: Vec<_> = text.encode_utf16().collect();
let locale = CString::new(locale.split('\0').next().unwrap_or_default())
.map_err(|_| "invalid XeTeX line break locale")?;
let iterator = BreakIterator::open(api, &locale, &utf16)
.or_else(|| BreakIterator::open(api, c"en_us", &utf16))
.ok_or("ICU could not create the XeTeX line break iterator")?;
let mut offsets = Vec::new();
let mut chars = text.char_indices();
let mut units = 0;
loop {
let at = iterator.next();
if at == -1 || at as usize == utf16.len() {
break;
}
let at = usize::try_from(at).map_err(|_| "invalid ICU line break offset")?;
if at <= units || at > utf16.len() {
return Err("invalid ICU line break offset".into());
}
while let Some((byte, character)) = chars.next() {
units += character.len_utf16();
if units == at {
offsets.push(byte + character.len_utf8());
break;
}
if units > at {
return Err("ICU line break falls within a Unicode scalar".into());
}
}
}
Ok(offsets)
}
+27
View File
@@ -2175,6 +2175,33 @@ PDF,恢复实际 PFB 并反转斜切时复用 1277 步,只替换第二页。
全量编译一致。incremental-receipt.json 的 SHA-256 为
bbc0991b0316e6d76aa58649ec873525f5544ab530d93fe491fc6e16bd00a27d。
### XeTeX Unicode 段落断行
`\XeTeXlinebreaklocale` 决定实际 OpenType 词的 ICU 行断点。XeTeX
先合并同字体的相邻词,再对字符映射后的文本查找边界,并逐段塑形。
边界进入真实水平列表,使用 `\XeTeXlinebreakskip` 的弹性胶与
`\XeTeXlinebreakpenalty` 的罚值。段落装箱按实际节点选断点。
空 locale 关闭断点,受限横盒保留原整词。locale 跨组生效,胶与罚值
按各自作用域取值。运行 locale 断行需要 ICU4C,验收使用 77.1。
Graphite 的字体指定断行与 ICU 打开失败时的参考诊断仍待支持。
[参考 XeTeX 断点入口](https://github.com/TeX-Live/texlive-source/blob/279984fab6eaed8d17e02882f2668ab5caac0f27/texk/web2c/xetexdir/XeTeX_ext.c#L444-L494)
中文、泰文词典及未改动的 fontspec 共 10 页、272 个字形。
盒度量、原始字体和字形位置、提取文本及 144 DPI RGB 光栅均与参考
一致。44 pt 原样中文样例启用 locale 时从一行变为六行,罚值
10000 阻止断行。由原样 xelatex.ini 转储并实际加载 schema76。
同一 schema71 与已收敛生成初态复编原样 ACL,PDF、aux、out、bbl
与上一版逐字节一致。12 项定向回归通过。
三次跨文件变更各复用 66 步、重放两次调用,实际行数为
6、1、6,只更新第二页。字形来源与命中保持可追溯。从对应 aux 初态
独立全量得到相同的 PDF、SVG、来源映射和实际 aux。
回执 `target/p3-xetex-line-break-locale/receipt.json` 的 SHA-256 为 `bc8ff52766f4caaf1f6d5586e851918debc01b0e1f45d675df66e38677565488`。
下一入口是 `\XeTeXinputnormalization`。`target/p3-xetex-input-normalization` 保留
同源原版的 NFC、NFD、分组恢复、同一行赋值后的输入、规范化控制序列名、
UTF-16 流和 UTF-8 子文件的输出,以及当前原生未定义诊断。
### XeTeX 字体首尾字符
`\XeTeXfirstfontchar` 和 `\XeTeXlastfontchar` 接入真实字体的整数扫描。
+9
View File
@@ -758,6 +758,15 @@ XDV 链接注释接入后,沿原样 ACL 的第二轮辅助文件和 BibTeX
`target/p3-xdv-annotation/receipt.json`。
[链接注释阶段记录](P2_M1_PROGRESS.md#xdv-链接注释与实际矩形)
#### XeTeX Unicode 段落断行复编
以同一 schema71、真实字体和已收敛辅助文件复编原样 ACL,PDF、
aux、out、bbl 与上一版逐字节相同。另从原样 xelatex.ini 转储 schema76,
加载未改动的 fontspec 并按中文 locale 出页。字形、度量、文本和
光栅与原版一致。原样 ACL 的整页门禁继续保留。
回执 `target/p3-xetex-line-break-locale/receipt.json` 的 SHA-256 为 `bc8ff52766f4caaf1f6d5586e851918debc01b0e1f45d675df66e38677565488`。
[段落断行阶段记录](P2_M1_PROGRESS.md#xetex-unicode-段落断行)
#### XeTeX 字体字符范围复编
同一 schema71、真实字体和已收敛辅助文件原样复编 ACL,其 PDF、