Shape native XeTeX Graphite fonts with actual feature settings

This commit is contained in:
gloamxun committed 2026-11-26 13:27:16 +08:00
1 parent 76df2d6832
commit eb0afccc03
9 files changed
+744 -39

No files matched your search

@@ -1107,6 +1107,9 @@ impl Executor {
let name = self.xetex_glyph_name(files)?;
self.print_tokens(&name, token)?;
}
p @ (XeTeXfeaturename | XeTeXselectorname) => {
self.scan_xetex_graphite_label(p, files)?;
}
Etexrevision => self.print_tokens(".6", token)?,
Csname => {
let name = self.csname(files)?;
@@ -3267,6 +3270,8 @@ impl Executor {
Primitive::XeTeXglyph => "XeTeXglyph".into(),
Primitive::XeTeXglyphbounds => "XeTeXglyphbounds".into(),
Primitive::XeTeXglyphname => "XeTeXglyphname".into(),
Primitive::XeTeXfeaturename => "XeTeXfeaturename".into(),
Primitive::XeTeXselectorname => "XeTeXselectorname".into(),
Primitive::XeTeXinputencoding => "XeTeXinputencoding".into(),
Primitive::XeTeXdefaultencoding => "XeTeXdefaultencoding".into(),
Primitive::XeTeXlinebreaklocale => "XeTeXlinebreaklocale".into(),
@@ -167,6 +167,27 @@ impl Executor {
Ok((id, slot))
}
pub(super) fn scan_xetex_graphite_label(
&mut self, command: Primitive, files: &mut impl SourceProvider,
) -> Result<(), Error> {
let id = self.font_identifier(files)?;
let instance = self.state.fonts.font(id).map_err(|error| self.error(error, self.current))?;
let graphite = match instance.opentype() {
Some(font) => font.graphite_features().map_err(|error| self.error(error, self.current))?.is_some(),
None => false,
};
if !graphite {
return self.fail("XeTeX feature label requires a Graphite font");
}
self.integer(files)?;
if command == Primitive::XeTeXselectorname {
self.integer(files)?;
}
// XeTeX passes its current convert code to grprintfontname. The
// legacy switch handles codes 8 and 9, so these queries emit no tokens.
Ok(())
}
pub(super) fn xetex_font_query(
&mut self,
command: Primitive,
@@ -205,10 +226,55 @@ impl Executor {
};
return Ok(range[usize::from(command == XeTeXlastfontchar)] as i32);
}
let font = font.cloned();
let graphite = match &font {
Some(font) => font.graphite_features().map_err(|error| self.error(error, self.current))?,
None => None,
};
if command == XeTeXfonttype {
return Ok(if font.is_some() { 2 } else { 0 });
return Ok(if graphite.is_some() { 3 } else if font.is_some() { 2 } else { 0 });
}
let Some(font) = font.cloned() else {
if command == XeTeXcountfeatures {
return Ok(graphite.map_or(0, |catalog| catalog.len() as i32));
}
if matches!(command, XeTeXfeaturecode | XeTeXfindfeaturebyname | XeTeXisexclusivefeature
| XeTeXcountselectors | XeTeXselectorcode | XeTeXfindselectorbyname | XeTeXisdefaultselector)
{
let catalog = graphite.ok_or_else(|| self.error("XeTeX feature query requires a Graphite font", self.current))?;
if command == XeTeXfindfeaturebyname {
let name = self.filename(files)?;
return Ok(catalog.iter().find(|feature| feature.name.starts_with(&name)).map_or(-1, |feature| feature.id as i32));
}
let first = self.integer(files)?;
if command == XeTeXfeaturecode {
return Ok(catalog.get(first as usize).map_or(0, |feature| feature.id as i32));
}
if command == XeTeXisexclusivefeature {
return Ok(1);
}
let feature = catalog.iter().find(|feature| feature.id == first as u32);
if command == XeTeXcountselectors {
return Ok(feature.map_or(0, |feature| feature.values.len() as i32));
}
if command == XeTeXfindselectorbyname {
let name = self.filename(files)?;
return Ok(feature.and_then(|feature| feature.values.iter().find(|(_, label)| label.starts_with(&name)))
.map_or(-1, |(value, _)| i32::from(*value as i16)));
}
let second = self.integer(files)?;
if command == XeTeXisdefaultselector {
return Ok(i32::from(feature.is_some_and(|feature| i32::from(feature.default) == second)));
}
return Ok(feature.and_then(|feature| feature.values.get(second as usize))
.map_or(0, |(value, _)| i32::from(*value as i16)));
}
if graphite.is_some() && command != XeTeXcountglyphs {
if command == XeTeXOTcountscripts {
return Ok(0);
}
return self.fail("XeTeX OpenType layout query requires an OpenType layout font");
}
let Some(font) = font else {
return match command {
XeTeXcountglyphs | XeTeXOTcountscripts => Ok(0),
_ => self.fail("XeTeX OpenType layout query requires a native OpenType font"),
@@ -762,7 +762,18 @@ impl Executor {
self.state.fonts.load_tfm(files, &file, &from, size, name.clone(), defaults, false)
};
match font {
Ok(font) => self.define_traced(name, Meaning::Font(font), global, files),
Ok(font) => {
let instance = self.state.fonts.font(font).map_err(|error| self.error(error, self.current))?;
if let Some(native) = instance.opentype() {
for option in native.ignored_graphite_options().map_err(|error| self.error(error, self.current))? {
files.observe_diagnostic(
WriteDestination::Log,
&format!("\nUnknown feature `{option}' in font `{file}'.\n"),
).map_err(|error| self.error(error, self.current))?;
}
}
self.define_traced(name, Meaning::Font(font), global, files)
}
Err(FontLoadError::Rejected(_) | FontLoadError::Missing(_)) if suppress => Ok(()),
Err(error) => Err(self.error(error.message(), self.current)),
}
@@ -8,9 +8,9 @@ use std::{
sync::{Arc, Mutex, OnceLock, Weak},
};
const SCHEMA: u32 = 77;
const COMPATIBLE_SCHEMAS: [u32; 44] = [
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, SCHEMA,
const SCHEMA: u32 = 78;
const COMPATIBLE_SCHEMAS: [u32; 45] = [
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, SCHEMA,
];
const ENGINE: &str = concat!("texrra-native/", env!("CARGO_PKG_VERSION"));
+31 -1
View File
@@ -395,10 +395,20 @@ pub enum Primitive {
XeTeXfirstfontchar,
XeTeXlastfontchar,
XeTeXlinebreaklocale,
XeTeXcountfeatures,
XeTeXfeaturecode,
XeTeXfindfeaturebyname,
XeTeXisexclusivefeature,
XeTeXcountselectors,
XeTeXselectorcode,
XeTeXfindselectorbyname,
XeTeXisdefaultselector,
XeTeXfeaturename,
XeTeXselectorname,
}
impl Primitive {
const XETEX_FONT_QUERIES: [Self; 12] = [
const XETEX_FONT_QUERIES: [Self; 20] = [
Self::XeTeXfonttype,
Self::XeTeXcountglyphs,
Self::XeTeXcharglyph,
@@ -411,6 +421,14 @@ impl Primitive {
Self::XeTeXOTlanguagetag,
Self::XeTeXOTcountfeatures,
Self::XeTeXOTfeaturetag,
Self::XeTeXcountfeatures,
Self::XeTeXfeaturecode,
Self::XeTeXfindfeaturebyname,
Self::XeTeXisexclusivefeature,
Self::XeTeXcountselectors,
Self::XeTeXselectorcode,
Self::XeTeXfindselectorbyname,
Self::XeTeXisdefaultselector,
];
pub(super) fn xetex_font_query_name(self) -> Option<&'static str> {
@@ -427,6 +445,14 @@ impl Primitive {
Self::XeTeXOTlanguagetag => "XeTeXOTlanguagetag",
Self::XeTeXOTcountfeatures => "XeTeXOTcountfeatures",
Self::XeTeXOTfeaturetag => "XeTeXOTfeaturetag",
Self::XeTeXcountfeatures => "XeTeXcountfeatures",
Self::XeTeXfeaturecode => "XeTeXfeaturecode",
Self::XeTeXfindfeaturebyname => "XeTeXfindfeaturebyname",
Self::XeTeXisexclusivefeature => "XeTeXisexclusivefeature",
Self::XeTeXcountselectors => "XeTeXcountselectors",
Self::XeTeXselectorcode => "XeTeXselectorcode",
Self::XeTeXfindselectorbyname => "XeTeXfindselectorbyname",
Self::XeTeXisdefaultselector => "XeTeXisdefaultselector",
_ => return None,
})
}
@@ -482,6 +508,8 @@ impl Primitive {
| Pdftexrevision
| XeTeXrevision
| XeTeXglyphname
| XeTeXfeaturename
| XeTeXselectorname
| Pdfstrcmp
| Pdfmatch
| Pdflastmatch
@@ -1747,6 +1775,8 @@ impl State {
("XeTeXglyph", Primitive::XeTeXglyph),
("XeTeXglyphbounds", Primitive::XeTeXglyphbounds),
("XeTeXglyphname", Primitive::XeTeXglyphname),
("XeTeXfeaturename", Primitive::XeTeXfeaturename),
("XeTeXselectorname", Primitive::XeTeXselectorname),
("XeTeXpdfpagecount", Primitive::XeTeXpdfpagecount),
("XeTeXinputencoding", Primitive::XeTeXinputencoding),
("XeTeXdefaultencoding", Primitive::XeTeXdefaultencoding),
+103 -31
View File
@@ -19,6 +19,7 @@ use unicode_bidi::BidiInfo;
mod character_range;
mod font_info;
mod graphite;
mod tags;
pub(crate) use font_info::LayoutTags;
mod math_layout;
@@ -28,6 +29,8 @@ pub(crate) use math_layout::{MathConstants, ScriptSide, Stretch, accent_attachme
pub(crate) struct Request {
pub file: String,
pub index: u32,
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
graphite: bool,
features: Vec<String>,
script: Option<String>,
language: Option<String>,
@@ -108,7 +111,10 @@ impl Request {
}
pub(crate) fn with_options(file: &str, index: u32, options: &str) -> Result<Self, String> {
let options = options.strip_prefix("/OT").unwrap_or(options);
let (graphite, options) = match options.strip_prefix("/GR") {
Some(options) => (true, options),
None => (false, options.strip_prefix("/OT").or_else(|| options.strip_prefix("/ICU")).unwrap_or(options)),
};
let features = if options.is_empty() {
""
} else {
@@ -119,6 +125,7 @@ impl Request {
let mut request = Self {
file: file.to_owned(),
index,
graphite,
features: Vec::new(),
script: None,
language: None,
@@ -166,9 +173,11 @@ impl Request {
} else if let Some(value) = feature.strip_prefix("color=") {
request.color = Some(read_color(value)?);
} else {
feature
.parse::<Feature>()
.map_err(|_| format!("unsupported OpenType font option: {feature}"))?;
if !graphite {
feature
.parse::<Feature>()
.map_err(|_| format!("unsupported OpenType font option: {feature}"))?;
}
request.features.push(feature.to_owned());
}
}
@@ -233,6 +242,7 @@ impl<'a> NamedRequest<'a> {
for part in parts {
match part {
"OT" | "ICU" => options.push_str("/OT"),
"GR" => options.push_str("/GR"),
"B" => style.bold = true,
"I" => style.italic = true,
"BI" | "IB" => style = crate::resources::FontStyle { bold: true, italic: true },
@@ -267,6 +277,8 @@ pub struct OpenTypeFont {
mapping: Option<Arc<FontMapping>>,
#[serde(skip)]
character_range: OnceLock<Result<[u32; 2], String>>,
#[serde(skip)]
graphite: OnceLock<Result<Option<Arc<graphite::Font>>, String>>,
}
impl PartialEq for OpenTypeFont {
@@ -362,6 +374,7 @@ impl OpenTypeFont {
request,
mapping,
character_range: OnceLock::new(),
graphite: OnceLock::new(),
});
// The unmapped space can itself undergo OpenType substitution.
// XeTeX adds tracking to its glue even for a single shaped glyph.
@@ -393,6 +406,31 @@ impl OpenTypeFont {
})
}
fn graphite_font(&self) -> Result<Option<&graphite::Font>, String> {
if !self.request.graphite {
return Ok(None);
}
self.graphite.get_or_init(|| {
let face = self.face()?;
if face.raw_face().table(Tag::from_bytes(b"Silf")).is_none() {
return Ok(None);
}
let (_, language) = tags::segment_properties(None, self.request.language.as_deref());
graphite::Font::new(
self.resource.data.clone(), self.request.index, face.units_per_em(),
&self.request.features, language.as_ref(),
).map(|font| font.map(Arc::new))
}).as_ref().map(|font| font.as_deref()).map_err(Clone::clone)
}
pub(crate) fn graphite_features(&self) -> Result<Option<&[graphite::FontFeature]>, String> {
Ok(self.graphite_font()?.map(|font| font.catalog.as_slice()))
}
pub(crate) fn ignored_graphite_options(&self) -> Result<&[String], String> {
Ok(self.graphite_font()?.map_or(&[], |font| font.ignored_options.as_slice()))
}
pub(crate) fn character_range(&self) -> Result<[u32; 2], String> {
self.character_range
.get_or_init(|| character_range::of(&self.face()?))
@@ -524,10 +562,12 @@ impl OpenTypeFont {
) -> Result<OpenTypeRun, String> {
let face = Face::from_slice(&self.resource.data, self.request.index)
.ok_or("invalid OpenType shaping face")?;
let graphite = self.graphite_font()?;
let features: Vec<_> = self
.request
.features
.iter()
.filter(|option| !self.request.graphite || option.starts_with(['+', '-']))
.map(|option| {
let mut feature = option.parse::<Feature>()?;
if option.starts_with('+') && option.contains('=') {
@@ -557,45 +597,48 @@ impl OpenTypeFont {
for paragraph in &bidi.paragraphs {
let (levels, runs) = bidi.visual_runs(paragraph, paragraph.range.clone());
for range in runs {
let mut buffer = UnicodeBuffer::new();
buffer.push_str(&text[range.clone()]);
buffer.set_direction(if levels[range.start].is_rtl() {
Direction::RightToLeft
let text = &text[range.clone()];
let rtl = levels[range.start].is_rtl();
let graphite_glyphs = match graphite {
Some(font) => font.shape(text, rtl, script, language.as_ref())?,
None => None,
};
let shaped = if let Some(glyphs) = graphite_glyphs {
ShapedGlyphs::Graphite(glyphs)
} else {
Direction::LeftToRight
});
if let Some(script) = script {
buffer.set_script(script);
}
if let Some(language) = &language {
buffer.set_language(language.clone());
}
buffer.guess_segment_properties();
let shaped = rustybuzz::shape(&face, &features, buffer);
let mut starts: Vec<_> = shaped
.glyph_infos()
.iter()
.map(|info| range.start + info.cluster as usize)
.collect();
let mut buffer = UnicodeBuffer::new();
buffer.push_str(text);
buffer.set_direction(if rtl { Direction::RightToLeft } else { Direction::LeftToRight });
if let Some(script) = script {
buffer.set_script(script);
}
if let Some(language) = &language {
buffer.set_language(language.clone());
}
buffer.guess_segment_properties();
ShapedGlyphs::OpenType(rustybuzz::shape(&face, &features, buffer))
};
let mut starts: Vec<_> = shaped.iter()
.map(|glyph| range.start + glyph.cluster).collect();
starts.push(range.end);
starts.sort_unstable();
starts.dedup();
let mut x = 0;
let mut y = 0;
let mut previous = usize::MAX;
for (info, pos) in shaped.glyph_infos().iter().zip(shaped.glyph_positions()) {
let cluster = range.start + info.cluster as usize;
for glyph in shaped.iter() {
let cluster = range.start + glyph.cluster;
let end = starts[starts.partition_point(|at| *at <= cluster)];
let next_x = x + i64::from(pos.x_advance);
let next_y = y + i64::from(pos.y_advance);
if tracking != 0 && points_to_sp(points(i64::from(pos.x_advance))) == 0 {
let next_x = x + i64::from(glyph.x_advance);
let next_y = y + i64::from(glyph.y_advance);
if tracking != 0 && points_to_sp(points(i64::from(glyph.x_advance))) == 0 {
tracking -= letter_space;
}
let x_position = |x, y| point_position_to_sp(x_origin + f64::from(horizontal(x, y)));
let glyph_y = y + i64::from(pos.y_offset);
let glyph_y = y + i64::from(glyph.y_offset);
glyphs.push(OpenTypeGlyph {
id: info.glyph_id as u16,
x: x_position(x + i64::from(pos.x_offset), glyph_y) + tracking,
id: glyph.id,
x: x_position(x + i64::from(glyph.x_offset), glyph_y) + tracking,
y: point_position_to_sp(y_origin + f64::from(points(-glyph_y))),
advance: x_position(next_x, next_y) - x_position(x, y),
cluster: cluster..end,
@@ -628,6 +671,35 @@ impl OpenTypeFont {
}
}
enum ShapedGlyphs {
OpenType(rustybuzz::GlyphBuffer),
Graphite(Vec<graphite::Glyph>),
}
impl ShapedGlyphs {
fn iter(&self) -> impl Iterator<Item = graphite::Glyph> + '_ {
let length = match self {
Self::OpenType(run) => run.len(),
Self::Graphite(glyphs) => glyphs.len(),
};
(0..length).map(|index| match self {
Self::OpenType(run) => {
let info = &run.glyph_infos()[index];
let position = &run.glyph_positions()[index];
graphite::Glyph {
id: info.glyph_id as u16,
cluster: info.cluster as usize,
x_advance: position.x_advance,
y_advance: position.y_advance,
x_offset: position.x_offset,
y_offset: position.y_offset,
}
}
Self::Graphite(glyphs) => glyphs[index],
})
}
}
// FreeType's unscaled control box includes off-curve points. In particular
// it can be larger than the tight bounds of a CFF cubic outline.
#[derive(Default)]
@@ -0,0 +1,476 @@
//! HarfBuzz's Graphite2 shaper, using the native font's exact resource bytes.
use libloading::Library;
use rustybuzz::{
Feature, Language, Script,
ttf_parser::{RawFace, Tag},
};
use std::{
ffi::{c_char, c_void},
ptr::{NonNull, null_mut},
sync::{Arc, Mutex, OnceLock},
};
type Handle = *mut c_void;
type Destroy = unsafe extern "C" fn(Handle);
macro_rules! api {
($name:ident { $($routine:ident: $signature:ty),* $(,)? }) => {
struct $name {
$($routine: $signature,)*
_library: Library,
}
impl $name {
fn load(names: &[&str]) -> Option<Self> {
for name in names {
#[cfg(target_os = "windows")]
let loaded = unsafe {
// LOAD_LIBRARY_SEARCH_DEFAULT_DIRS excludes the project directory.
libloading::os::windows::Library::load_with_flags(name, 0x0000_1000)
.map(Library::from)
};
#[cfg(not(target_os = "windows"))]
let loaded = unsafe { Library::new(name) };
let Ok(library) = loaded else { continue };
// All functions and their backing handle come from one library.
if let Some(api) = (|| {
$(let $routine = unsafe { *library.get::<$signature>(stringify!($routine).as_bytes()).ok()? };)*
Some(Self { $($routine,)* _library: library })
})() {
return Some(api);
}
}
None
}
}
};
}
#[repr(C)]
struct GlyphInfo {
codepoint: u32,
mask: u32,
cluster: u32,
reserved: [u32; 2],
}
#[repr(C)]
struct Position {
x_advance: i32,
y_advance: i32,
x_offset: i32,
y_offset: i32,
reserved: u32,
}
#[repr(C)]
struct HbFeature {
tag: u32,
value: u32,
start: u32,
end: u32,
}
api!(HarfBuzz {
hb_blob_create: unsafe extern "C" fn(*const c_char, u32, i32, Handle, Option<Destroy>) -> Handle,
hb_blob_destroy: Destroy,
hb_face_create: unsafe extern "C" fn(Handle, u32) -> Handle,
hb_face_destroy: Destroy,
hb_font_create: unsafe extern "C" fn(Handle) -> Handle,
hb_font_destroy: Destroy,
hb_font_set_scale: unsafe extern "C" fn(Handle, i32, i32),
hb_ot_font_set_funcs: unsafe extern "C" fn(Handle),
hb_font_make_immutable: unsafe extern "C" fn(Handle),
hb_graphite2_face_get_gr_face: unsafe extern "C" fn(Handle) -> Handle,
hb_buffer_create: unsafe extern "C" fn() -> Handle,
hb_buffer_destroy: Destroy,
hb_buffer_add_utf16: unsafe extern "C" fn(Handle, *const u16, i32, u32, i32),
hb_buffer_set_direction: unsafe extern "C" fn(Handle, i32),
hb_buffer_set_script: unsafe extern "C" fn(Handle, u32),
hb_language_from_string: unsafe extern "C" fn(*const c_char, i32) -> Handle,
hb_buffer_set_language: unsafe extern "C" fn(Handle, Handle),
hb_buffer_guess_segment_properties: unsafe extern "C" fn(Handle),
hb_shape_full: unsafe extern "C" fn(Handle, Handle, *const HbFeature, u32, *const *const c_char) -> i32,
hb_buffer_get_glyph_infos: unsafe extern "C" fn(Handle, *mut u32) -> *const GlyphInfo,
hb_buffer_get_glyph_positions: unsafe extern "C" fn(Handle, *mut u32) -> *const Position,
});
#[repr(C)]
struct FaceOps {
size: usize,
get_table: unsafe extern "C" fn(*const c_void, u32, *mut usize) -> *const c_void,
release_table: Option<unsafe extern "C" fn(*const c_void, *const c_void)>,
}
api!(Graphite {
gr_make_face_with_ops: unsafe extern "C" fn(*const c_void, *const FaceOps, u32) -> Handle,
gr_face_destroy: Destroy,
gr_face_n_fref: unsafe extern "C" fn(Handle) -> u16,
gr_face_fref: unsafe extern "C" fn(Handle, u16) -> Handle,
gr_fref_id: unsafe extern "C" fn(Handle) -> u32,
gr_fref_n_values: unsafe extern "C" fn(Handle) -> u16,
gr_fref_value: unsafe extern "C" fn(Handle, u16) -> i16,
gr_fref_label: unsafe extern "C" fn(Handle, *mut u16, i32, *mut u32) -> Handle,
gr_fref_value_label: unsafe extern "C" fn(Handle, u16, *mut u16, i32, *mut u32) -> Handle,
gr_label_destroy: Destroy,
gr_face_featureval_for_lang: unsafe extern "C" fn(Handle, u32) -> Handle,
gr_fref_feature_value: unsafe extern "C" fn(Handle, Handle) -> u16,
gr_featureval_destroy: Destroy,
});
fn harfbuzz() -> Result<&'static HarfBuzz, String> {
#[cfg(target_os = "windows")]
let names = ["libharfbuzz-0.dll", "harfbuzz.dll"];
#[cfg(target_os = "macos")]
let names = ["libharfbuzz.0.dylib", "libharfbuzz.dylib"];
#[cfg(not(any(target_os = "windows", target_os = "macos")))]
let names = ["libharfbuzz.so.0", "libharfbuzz.so"];
static API: OnceLock<Option<HarfBuzz>> = OnceLock::new();
API.get_or_init(|| HarfBuzz::load(&names))
.as_ref()
.ok_or_else(|| {
"XeTeX Graphite fonts require a HarfBuzz runtime with Graphite2 support".into()
})
}
fn graphite() -> Result<&'static Graphite, String> {
#[cfg(target_os = "windows")]
let names = ["libgraphite2-3.dll", "libgraphite2.dll", "graphite2.dll"];
#[cfg(target_os = "macos")]
let names = ["libgraphite2.3.dylib", "libgraphite2.dylib"];
#[cfg(not(any(target_os = "windows", target_os = "macos")))]
let names = ["libgraphite2.so.3", "libgraphite2.so"];
static API: OnceLock<Option<Graphite>> = OnceLock::new();
API.get_or_init(|| Graphite::load(&names))
.as_ref()
.ok_or_else(|| "XeTeX Graphite fonts require a Graphite2 runtime".into())
}
struct Owned {
pointer: NonNull<c_void>,
destroy: Destroy,
}
impl Owned {
fn new(pointer: Handle, destroy: Destroy) -> Option<Self> {
Some(Self {
pointer: NonNull::new(pointer)?,
destroy,
})
}
fn ptr(&self) -> Handle {
self.pointer.as_ptr()
}
}
impl Drop for Owned {
fn drop(&mut self) {
// The associated library stays loaded for the lifetime of its API table.
unsafe { (self.destroy)(self.ptr()) }
}
}
#[derive(Clone, Copy)]
pub(super) struct Glyph {
pub id: u16,
pub cluster: usize,
pub x_advance: i32,
pub y_advance: i32,
pub x_offset: i32,
pub y_offset: i32,
}
struct LiveFont {
font: Owned,
// hb_blob_create borrows the bytes. Drop the HarfBuzz owner first.
_bytes: Arc<Vec<u8>>,
}
// HarfBuzz owns no thread-local state in this font. Rust only accesses the
// mutable Graphite state while holding the per-font mutex.
unsafe impl Send for LiveFont {}
#[derive(Debug)]
pub(crate) struct FontFeature {
pub id: u32,
pub name: String,
pub values: Vec<(u16, String)>,
pub default: u16,
}
pub(super) struct Font {
live: Mutex<LiveFont>,
pub(crate) catalog: Vec<FontFeature>,
features: Vec<HbFeature>,
pub(super) ignored_options: Vec<String>,
}
impl std::fmt::Debug for Font {
fn fmt(&self, format: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
format
.debug_struct("GraphiteFont")
.field("features", &self.catalog.len())
.finish()
}
}
impl Font {
pub(super) fn new(
bytes: Arc<Vec<u8>>,
index: u32,
units: u16,
options: &[String],
language: Option<&Language>,
) -> Result<Option<Self>, String> {
let api = harfbuzz()?;
let length = u32::try_from(bytes.len()).map_err(|_| "Graphite font is too large")?;
// The blob owns a reference to the face data through LiveFont, and
// HarfBuzz retains its own references from the font to face to blob.
let font = unsafe {
let blob = Owned::new(
(api.hb_blob_create)(bytes.as_ptr().cast(), length, 1, null_mut(), None),
api.hb_blob_destroy,
)
.ok_or("HarfBuzz could not open the Graphite font data")?;
let face = Owned::new((api.hb_face_create)(blob.ptr(), index), api.hb_face_destroy)
.ok_or("HarfBuzz could not create the Graphite face")?;
let gr_face = (api.hb_graphite2_face_get_gr_face)(face.ptr());
if gr_face.is_null() {
return Ok(None);
}
let font = Owned::new((api.hb_font_create)(face.ptr()), api.hb_font_destroy)
.ok_or("HarfBuzz could not create the Graphite font")?;
(api.hb_font_set_scale)(font.ptr(), i32::from(units), i32::from(units));
(api.hb_ot_font_set_funcs)(font.ptr());
(api.hb_font_make_immutable)(font.ptr());
font
};
let catalog = catalog(graphite()?, &bytes, index, language)?;
let mut features = Vec::new();
let mut ignored_options = Vec::new();
for option in options {
if let Some((tag, value)) = feature_option(option, &catalog) {
features.push(HbFeature {
tag,
value,
start: 0,
end: u32::MAX,
});
} else {
ignored_options.push(option.clone());
}
}
Ok(Some(Self {
live: Mutex::new(LiveFont {
font,
_bytes: bytes,
}),
catalog,
features,
ignored_options,
}))
}
pub(super) fn shape(
&self,
text: &str,
rtl: bool,
script: Option<Script>,
language: Option<&Language>,
) -> Result<Option<Vec<Glyph>>, String> {
let api = harfbuzz()?;
let mut utf16 = Vec::new();
let mut offsets = Vec::new();
for (index, character) in text.char_indices() {
let mut units = [0; 2];
let units = character.encode_utf16(&mut units);
utf16.extend_from_slice(units);
offsets.push(Some(index));
if units.len() == 2 {
offsets.push(None);
}
}
let length = i32::try_from(utf16.len()).map_err(|_| "Graphite text run is too long")?;
let count = u32::try_from(self.features.len()).map_err(|_| "too many Graphite features")?;
let live = self
.live
.lock()
.map_err(|_| "Graphite font is unavailable")?;
// The buffer and its returned arrays are local to this shaping call.
// The live font and its bytes remain valid until the buffer drops.
unsafe {
let buffer = Owned::new((api.hb_buffer_create)(), api.hb_buffer_destroy)
.ok_or("HarfBuzz could not create a Graphite shaping buffer")?;
(api.hb_buffer_add_utf16)(buffer.ptr(), utf16.as_ptr(), length, 0, length);
(api.hb_buffer_set_direction)(buffer.ptr(), if rtl { 5 } else { 4 });
if let Some(script) = script {
(api.hb_buffer_set_script)(buffer.ptr(), script.tag().0);
}
if let Some(language) = language {
let text = language.as_str();
let len = i32::try_from(text.len()).map_err(|_| "invalid Graphite language")?;
let language = (api.hb_language_from_string)(text.as_ptr().cast(), len);
(api.hb_buffer_set_language)(buffer.ptr(), language);
}
(api.hb_buffer_guess_segment_properties)(buffer.ptr());
let shapers = [c"graphite2".as_ptr(), std::ptr::null()];
if (api.hb_shape_full)(
live.font.ptr(),
buffer.ptr(),
self.features.as_ptr(),
count,
shapers.as_ptr(),
) == 0
{
return Ok(None);
}
let (mut infos_count, mut positions_count) = (0, 0);
let infos = (api.hb_buffer_get_glyph_infos)(buffer.ptr(), &mut infos_count);
let positions = (api.hb_buffer_get_glyph_positions)(buffer.ptr(), &mut positions_count);
if infos_count == 0 && positions_count == 0 {
return Ok(Some(Vec::new()));
}
if infos_count != positions_count || infos.is_null() || positions.is_null() {
return Err("HarfBuzz returned incomplete Graphite glyph positions".into());
}
let infos = std::slice::from_raw_parts(infos, infos_count as usize);
let positions = std::slice::from_raw_parts(positions, positions_count as usize);
infos
.iter()
.zip(positions)
.map(|(info, position)| {
Ok(Glyph {
id: u16::try_from(info.codepoint)
.map_err(|_| "invalid Graphite glyph ID")?,
cluster: offsets
.get(info.cluster as usize)
.copied()
.flatten()
.ok_or("invalid Graphite UTF-16 cluster")?,
x_advance: position.x_advance,
y_advance: position.y_advance,
x_offset: position.x_offset,
y_offset: position.y_offset,
})
})
.collect::<Result<Vec<_>, String>>()
.map(Some)
}
}
}
unsafe extern "C" fn font_table(
face: *const c_void,
tag: u32,
length: *mut usize,
) -> *const c_void {
// Graphite calls this only while the borrowed face and its bytes are alive.
let face = unsafe { &*face.cast::<RawFace<'_>>() };
let Some(table) = face.table(Tag(tag)) else {
return std::ptr::null();
};
unsafe { *length = table.len() };
table.as_ptr().cast()
}
fn catalog(
api: &Graphite,
bytes: &[u8],
index: u32,
language: Option<&Language>,
) -> Result<Vec<FontFeature>, String> {
let tables = RawFace::parse(bytes, index).map_err(|_| "invalid Graphite feature face")?;
let ops = FaceOps {
size: std::mem::size_of::<FaceOps>(),
get_table: font_table,
release_table: None,
};
// Create the metadata face in the Graphite library that will read it.
// HarfBuzz may have been built with a separate copy of Graphite2.
let face = Owned::new(
unsafe { (api.gr_make_face_with_ops)(std::ptr::from_ref(&tables).cast(), &ops, 0) },
api.gr_face_destroy,
)
.ok_or("Graphite could not open the font features")?;
let tag = language.map_or(0, |language| {
Tag::from_bytes_lossy(language.as_str().as_bytes()).0
});
// Feature references belong to the face. Values and labels belong to the caller.
unsafe {
let values = Owned::new(
(api.gr_face_featureval_for_lang)(face.ptr(), tag),
api.gr_featureval_destroy,
)
.ok_or("Graphite could not read the font feature defaults")?;
(0..(api.gr_face_n_fref)(face.ptr()))
.map(|index| {
let feature = (api.gr_face_fref)(face.ptr(), index);
if feature.is_null() {
return Err("Graphite returned an invalid font feature".into());
}
let name = read_label(api, |language, length| {
(api.gr_fref_label)(feature, language, 1, length)
})?;
let options = (0..(api.gr_fref_n_values)(feature))
.map(|index| {
let label = read_label(api, |language, length| {
(api.gr_fref_value_label)(feature, index, language, 1, length)
})?;
Ok(((api.gr_fref_value)(feature, index) as u16, label))
})
.collect::<Result<_, String>>()?;
Ok(FontFeature {
id: (api.gr_fref_id)(feature),
name,
values: options,
default: (api.gr_fref_feature_value)(feature, values.ptr()),
})
})
.collect()
}
}
fn read_label(
api: &Graphite,
label: impl FnOnce(*mut u16, *mut u32) -> Handle,
) -> Result<String, String> {
let mut language = 0x0409;
let mut length = 0;
let Some(label) = Owned::new(label(&mut language, &mut length), api.gr_label_destroy) else {
return Ok(String::new());
};
// Graphite returns exactly length bytes and may include the terminal NUL.
let bytes = unsafe { std::slice::from_raw_parts(label.ptr().cast::<u8>(), length as usize) };
let label = bytes.strip_suffix(&[0]).unwrap_or(bytes);
String::from_utf8(label.to_owned()).map_err(|_| "invalid Graphite font feature label".into())
}
pub(super) fn feature_option(option: &str, catalog: &[FontFeature]) -> Option<(u32, u32)> {
if let Some((name, value)) = option.split_once('=') {
if let (Ok(id), Ok(value)) = (
name.trim_end().parse::<u32>(),
value.trim_end().parse::<u32>(),
) {
return Some((id, value));
}
if let Some(feature) = catalog
.iter()
.find(|feature| feature.name.starts_with(name))
&& let Some(&(value, _)) = feature
.values
.iter()
.find(|(_, label)| label.starts_with(value.trim_start()))
{
return Some((feature.id, u32::from(value)));
}
}
if !option.starts_with(['+', '-']) {
return None;
}
let mut parsed = option.parse::<Feature>().ok()?;
if option.starts_with('+') && option.contains('=') {
parsed.value = parsed.value.saturating_add(1);
}
Some((parsed.tag.0, parsed.value))
}
+37 -1
View File
@@ -2175,6 +2175,42 @@ PDF,恢复实际 PFB 并反转斜切时复用 1277 步,只替换第二页。
全量编译一致。incremental-receipt.json 的 SHA-256 为
bbc0991b0316e6d76aa58649ec873525f5544ab530d93fe491fc6e16bd00a27d。
### XeTeX Graphite 字体造型与特性
文件和系统名的 `/GR` 选择器进入实际字体实例。HarfBuzz 的 Graphite2
shaper 使用版本化字体字节,原生内核使用返回的 glyph、advance、offset
及 UTF-16 cluster 完成真实列表、断行、PDF、SVG 和来源定位。特性按
字体标签、数字 ID 与正负标签实际选择,字体类型及特性/选择器整数查询
读取同一字体。运行 Graphite 字体需要带 Graphite2 的 HarfBuzz 以及
Graphite2 运行库,已在 Fedora WSL 用 14.1.0 和 1.3.14 验证。
当前参考的 `G` locale 仍以 ICU 断行。实际 HarfBuzz 版本已使 XeTeX
使用的旧字体接口返回空值,原版 `G` 与 `en_us` 的 XDV 逐字节一致。
名称展开命令按参考输出空串,真实字体标签继续用于特性查找和选择。
保留原版未指定语言时查询默认选择器的崩溃记录,原生读取该字体默认值。
[参考 XeTeX 断点入口](https://github.com/TeX-Live/texlive-source/blob/279984fab6eaed8d17e02882f2668ab5caac0f27/texk/web2c/xetexdir/XeTeX_ext.c#L444-L485)
[HarfBuzz 旧字体接口](https://github.com/harfbuzz/harfbuzz/blob/14.1.0/src/hb-graphite2.cc#L184-L200)
Padauk 5.100、Awami Nastaliq 3.400 与真实 fontspec 共 10 页、
370 个字形及 25 项查询。字形、原始位置、文字和 144 DPI
RGB 光栅与参考一致,覆盖缅文、乌尔都语的 RTL 与 ActualText。
原样 xelatex.ini 转储并加载 schema78。原样 ACL 旧 schema71 的 PDF、
aux、out、bbl 与上一版逐字节一致。
[SIL Padauk 5.100](https://github.com/silnrsi/font-padauk/releases/tag/v5.100)
[SIL Awami Nastaliq 3.400](https://github.com/silnrsi/font-awami/releases/tag/v3.400)
三次跨文件改变实际字体特性,各复用 66 步,只更新第二页。
字形命中、PDF、SVG、来源映射和实际 aux 与相同生成初态的独立全量一致。
原样 xeCJK 和 CTeX 辅助包加载同一输入,用真实 Droid Sans 编译中英混排、
公式和表格。与参考的一页文字、aux 和 144 DPI 灰度光栅一致。两端均有
当前格式版本早于包建议版本的诊断。证据在
`target/p3-xecjk-first-consumer`。
原样 ACL 的设备差异仍保留为下一入口。同一编译结果的 98 个像素差
集中于 Algorithms,词框提取还有边栏 004 的顺序差,与原始字形坐标
的等价证据并存。差异范围见 `target/p3-acl-pdf-device-differential/receipt.json`。
回执 `target/p3-xetex-graphite/receipt.json` 的 SHA-256 为 `351698744d2da3462f26042e3af40bfbdd17a3909009a2abce6317f41aa5d1fc`。
### XeTeX 物理输入行的 Unicode 规范化
`\XeTeXinputnormalization` 接入有作用域的整数状态。物理输入行先按
@@ -2206,7 +2242,7 @@ schema77。原语与真实 fontspec 的 3 页、40 个字形、85
下一入口为 Graphite 字体造型与断行。`target/p3-xetex-graphite` 保存 SIL
Padauk 5.100 原样字体、许可、三页原版 XDV/PDF 和当前原生诊断。
同一字体的 Graphite/OpenType 类型查询分别为 3 和 2,词宽分别为
6312192 和 6275328 sp,`G` locale 进入实际字体断行。
6312192 和 6275328 sp。随后核对当前参考运行库,`G` locale 实际由 ICU 断行。
[SIL Padauk 5.100](https://github.com/silnrsi/font-padauk/releases/tag/v5.100)
### XeTeX Unicode 段落断行
+9
View File
@@ -758,6 +758,15 @@ XDV 链接注释接入后,沿原样 ACL 的第二轮辅助文件和 BibTeX
`target/p3-xdv-annotation/receipt.json`。
[链接注释阶段记录](P2_M1_PROGRESS.md#xdv-链接注释与实际矩形)
#### XeTeX Graphite 字体复编
真实 xelatex.ini 生成 schema78 后加载未修改的 fontspec,使用实际
Padauk 5.100 字体。Renderer=Graphite 和按名称设置的字体特性进入
真实出页,字号、字形、盒查询和光栅与 XeTeX 一致。原样 ACL 以旧
schema71 和已收敛辅助文件复编,PDF、aux、out、bbl 与前版逐字节一致。
回执 `target/p3-xetex-graphite/receipt.json` 的 SHA-256 为 `351698744d2da3462f26042e3af40bfbdd17a3909009a2abce6317f41aa5d1fc`。
[Graphite 阶段记录](P2_M1_PROGRESS.md#xetex-graphite-字体造型与特性)
#### XeTeX Unicode 物理输入规范化复编
真实 xelatex.ini 转储后加载 schema77,以未改动 fontspec 读取实际