Execute ICU locale line breaks in native XeTeX paragraphs
This commit is contained in:
1 parent
4e16531a62
commit
048478c346
12 files changed
+238
-29
No files matched your search
@@ -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)
|
||||
}
|
||||
Reference in new issue
Block a user