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)
}