diff --git a/src/rust/Cargo.toml b/src/rust/Cargo.toml index 3b78f303a..38fe6a633 100644 --- a/src/rust/Cargo.toml +++ b/src/rust/Cargo.toml @@ -4,11 +4,11 @@ edition = "2021" rust-version = "1.87.0" [dependencies] -harfrust = { version = "0.13.3", features = ["experimental_font_api"], optional = true } +harfrust = { version = "0.14.0", optional = true } # harfrust = { git = "https://github.com/harfbuzz/harfrust", optional = true } -read-fonts = "0.43.*" -skrifa = { version = "0.46.*", optional = true } -smallvec = "1.*" +read-fonts = { version = "0.45.*", optional = true } +skrifa = { version = "0.48.*", optional = true, default-features = false, features = ["std"] } +smallvec = { version = "1.*", optional = true } [lib] name = "harfbuzz_rust" @@ -17,10 +17,14 @@ crate-type = ["staticlib"] [features] default = ["paint", "draw", "hb-allocator"] -font = ["dep:skrifa"] -shape = ["dep:harfrust"] -paint = [] -draw = [] +# Core font functions require only read-fonts. +font = ["read-fonts"] +shape = ["dep:harfrust", "dep:smallvec"] +read-fonts = ["dep:read-fonts"] +# Skrifa also provides bitmap and COLR extents without drawing or painting. +skrifa = ["read-fonts", "dep:skrifa"] +paint = ["skrifa"] +draw = ["skrifa"] hb-allocator = [] [profile.release] diff --git a/src/rust/font.rs b/src/rust/font.rs index 3aa3f1007..5f0b3f285 100644 --- a/src/rust/font.rs +++ b/src/rust/font.rs @@ -1,25 +1,32 @@ -use super::hb::*; +use super::{hb::*, HbBlob}; use std::collections::HashMap; use std::ffi::c_void; -use std::mem::transmute; +use std::marker::PhantomData; use std::ptr::null_mut; use std::sync::atomic::{AtomicPtr, AtomicU32, Ordering}; -use std::sync::Mutex; +use std::sync::{Arc, Mutex}; +use read_fonts::model::{ + metrics::{GlyphExtents, LineExtents, Scale, ScaledGlyphMetrics}, + Blob, Font, NormalizedCoord, +}; +use read_fonts::types::{BoundingBox as FontBounds, F48Dot16, GlyphId}; +use read_fonts::TableProvider; + +#[cfg(feature = "skrifa")] +use read_fonts::FontRef; + +#[cfg(feature = "skrifa")] use skrifa::bitmap::{BitmapFormat, BitmapGlyph, BitmapStrikes, Origin}; -use skrifa::charmap::Charmap; -use skrifa::charmap::MapVariant::{UseDefault, Variant}; +#[cfg(feature = "skrifa")] use skrifa::color::ColorGlyphCollection; -use skrifa::font::FontRef; -use skrifa::instance::{Location, NormalizedCoord, Size}; -use skrifa::metrics::GlyphMetrics; -use skrifa::raw::tables::vmtx::Vmtx; -use skrifa::raw::tables::vorg::Vorg; -use skrifa::raw::tables::vvar::Vvar; -use skrifa::raw::TableProvider; +#[cfg(feature = "skrifa")] +use skrifa::instance::Size; +#[cfg(feature = "skrifa")] +use skrifa::MetadataProvider; +#[cfg(feature = "draw")] use skrifa::OutlineGlyphCollection; -use skrifa::{GlyphId, GlyphNames, MetadataProvider}; #[cfg(feature = "draw")] use skrifa::outline::{pen::OutlinePen, DrawSettings}; @@ -34,84 +41,69 @@ use skrifa::{ // A struct for storing your “fontations” data #[repr(C)] -struct FontationsData<'a> { - face_blob: *mut hb_blob_t, +struct FontationsData { + #[cfg(feature = "paint")] + face_blob: Arc, font: *mut hb_font_t, - font_ref: FontRef<'a>, - char_map: Charmap<'a>, - outline_glyphs: OutlineGlyphCollection<'a>, - color_glyphs: ColorGlyphCollection<'a>, - cbdt_strikes: Option>, - sbix_strikes: Option>, - glyph_names: GlyphNames<'a>, - size: Size, - vert_metrics: Option>, - vert_origin: Option>, - vert_vars: Option>, + #[cfg(feature = "skrifa")] + skrifa: SkrifaData<'static>, // Mutex for the below mutex: Mutex<()>, serial: AtomicU32, x_mult: f32, y_mult: f32, - location: Location, - glyph_metrics: Option>, + instance: Font, } -impl FontationsData<'_> { +#[cfg(feature = "skrifa")] +struct SkrifaData<'a> { + #[cfg(feature = "draw")] + outline_glyphs: OutlineGlyphCollection<'a>, + color_glyphs: ColorGlyphCollection<'a>, + cbdt_strikes: Option>, + sbix_strikes: Option>, + size: Size, +} + +impl FontationsData { unsafe fn from_hb_font(font: *mut hb_font_t) -> Option { let face_index = hb_face_get_index(hb_font_get_face(font)); - let face_blob = hb_face_reference_blob(hb_font_get_face(font)); - let blob_length = hb_blob_get_length(face_blob); - let blob_data: *const u8 = hb_blob_get_data(face_blob, null_mut()).cast(); - if blob_data.is_null() { - return None; - } - let face_data = std::slice::from_raw_parts(blob_data, blob_length as usize); + let face_blob = Arc::new(HbBlob(hb_face_reference_blob(hb_font_get_face(font)))); + let instance = Font::new(Blob::Shared(face_blob.clone()), face_index)?; - let font_ref = FontRef::from_index(face_data, face_index); - let font_ref = match font_ref { - Ok(f) => f, - Err(_) => return None, + #[cfg(feature = "skrifa")] + let skrifa = { + let blob_length = hb_blob_get_length(face_blob.0); + let blob_data: *const u8 = hb_blob_get_data(face_blob.0, null_mut()).cast(); + if blob_data.is_null() { + return None; + } + // The instance owns the blob for the lifetime of these collections. + let face_data = std::slice::from_raw_parts(blob_data, blob_length as usize); + let font_ref = FontRef::from_index(face_data, face_index).ok()?; + + SkrifaData { + #[cfg(feature = "draw")] + outline_glyphs: font_ref.outline_glyphs(), + color_glyphs: font_ref.color_glyphs(), + cbdt_strikes: BitmapStrikes::with_format(&font_ref, BitmapFormat::Cbdt), + sbix_strikes: BitmapStrikes::with_format(&font_ref, BitmapFormat::Sbix), + size: Size::new(hb_face_get_upem(hb_font_get_face(font)) as f32), + } }; - let char_map = Charmap::new(&font_ref); - - let outline_glyphs = font_ref.outline_glyphs(); - - let color_glyphs = font_ref.color_glyphs(); - - let cbdt_strikes = BitmapStrikes::with_format(&font_ref, BitmapFormat::Cbdt); - let sbix_strikes = BitmapStrikes::with_format(&font_ref, BitmapFormat::Sbix); - - let glyph_names = font_ref.glyph_names(); - - let upem = hb_face_get_upem(hb_font_get_face(font)); - - let vert_metrics = font_ref.vmtx().ok(); - let vert_origin = font_ref.vorg().ok(); - let vert_vars = font_ref.vvar().ok(); - let mut data = FontationsData { + #[cfg(feature = "paint")] face_blob, font, - font_ref, - char_map, - outline_glyphs, - color_glyphs, - cbdt_strikes, - sbix_strikes, - glyph_names, - size: Size::new(upem as f32), - vert_metrics, - vert_origin, - vert_vars, + #[cfg(feature = "skrifa")] + skrifa, mutex: Mutex::new(()), x_mult: 1.0, y_mult: 1.0, serial: AtomicU32::new(u32::MAX), - location: Location::default(), - glyph_metrics: None, + instance, }; data.check_for_updates(); @@ -142,49 +134,262 @@ impl FontationsData<'_> { } else { std::slice::from_raw_parts(coords, num_coords as usize) }; - let all_zeros = coords.iter().all(|&x| x == 0); - // if all zeros, use Location::default() - // otherwise, use the provided coords. - // This currently doesn't seem to have a perf effect on fontations, but it's a good idea to - // check if the coords are all zeros before creating a Location. - self.location = if all_zeros { - Location::default() - } else { - let mut location = Location::new(num_coords as usize); - let coords_mut = location.coords_mut(); - coords_mut - .iter_mut() - .zip(coords.iter().map(|v| NormalizedCoord::from_bits(*v as i16))) - .for_each(|(dest, source)| *dest = source); - location - }; - - let location = transmute::<&Location, &Location>(&self.location); - self.glyph_metrics = Some(self.font_ref.glyph_metrics(self.size, location)); + let current_coords = self.instance.normalized_coords(); + let axis_count = self + .instance + .tables() + .fvar() + .map(|fvar| fvar.axis_count() as usize) + .unwrap_or(0); + // Match the builder's padding and truncation, including its empty + // representation of an all-default location. + if (0..axis_count).any(|i| { + current_coords + .get(i) + .copied() + .unwrap_or(NormalizedCoord::ZERO) + != NormalizedCoord::from_bits(coords.get(i).copied().unwrap_or(0) as i16) + }) { + self.instance = self + .instance + .instance_builder() + .normalized_coords(coords.iter().map(|v| NormalizedCoord::from_bits(*v as i16))) + .build(); + } self.serial.store(font_serial, Ordering::Release); } fn check_for_updates(&mut self) { unsafe { self._check_for_updates() } } -} -extern "C" fn _hb_fontations_data_destroy(font_data: *mut c_void) { - let data = unsafe { Box::from_raw(font_data as *mut FontationsData) }; + fn scale(&self) -> FontationsScale { + FontationsScale { + x_mult: self.x_mult, + y_mult: self.y_mult, + } + } - unsafe { - hb_blob_destroy(data.face_blob); + fn glyph_metrics(&self) -> ScaledGlyphMetrics<'_, 'static, FontationsScale> { + self.instance.glyph_metrics().scaled(self.scale()) } } -fn struct_at_offset(first: *const T, index: u32, stride: u32) -> T { - unsafe { *((first as *const u8).offset((index * stride) as isize) as *const T) } +extern "C" fn _hb_fontations_data_destroy(font_data: *mut c_void) { + let _data = unsafe { Box::from_raw(font_data as *mut FontationsData) }; } -fn struct_at_offset_mut(first: *mut T, index: u32, stride: u32) -> &'static mut T { - unsafe { &mut *((first as *mut u8).offset((index * stride) as isize) as *mut T) } +#[derive(Clone, Copy)] +struct FontationsScale { + x_mult: f32, + y_mult: f32, } +impl Scale for FontationsScale { + // Keep intermediate sums wide when combining HarfBuzz callback results. + type Value = i64; + + fn add(a: i64, b: i64) -> i64 { + a.saturating_add(b) + } + + fn sub(a: i64, b: i64) -> i64 { + a.saturating_sub(b) + } + + fn half(value: i64) -> i64 { + value >> 1 + } + + fn scale_x(&self, value: F48Dot16) -> i64 { + round_to_position(value.to_f32() * self.x_mult) as i64 + } + + fn scale_y(&self, value: F48Dot16) -> i64 { + round_to_position(value.to_f32() * self.y_mult) as i64 + } + + fn scale_glyph_extents(&self, extents: GlyphExtents) -> GlyphExtents { + let x_bearing = self.scale_x(extents.x_bearing); + let y_bearing = self.scale_y(extents.y_bearing); + GlyphExtents { + x_bearing, + y_bearing, + width: self.scale_x(extents.x_bearing.saturating_add(extents.width)) - x_bearing, + height: y_bearing - self.scale_y(extents.y_bearing.saturating_sub(extents.height)), + } + } + + fn scale_rect(&self, bounds: FontBounds) -> FontBounds { + FontBounds { + x_min: self.scale_x(bounds.x_min), + y_min: self.scale_y(bounds.y_min), + x_max: self.scale_x(bounds.x_max), + y_max: self.scale_y(bounds.y_max), + } + } +} + +fn hb_position(value: i64) -> hb_position_t { + value.clamp(hb_position_t::MIN as i64, hb_position_t::MAX as i64) as hb_position_t +} + +#[inline] +fn round_to_position(value: f32) -> hb_position_t { + // Bias in f64 so values just below a half-integer do not round up. + let value = f64::from(value); + (value + 0.5f64.copysign(value)) as hb_position_t +} + +fn font_line_extents(font: *mut hb_font_t) -> LineExtents { + let mut extents: hb_font_extents_t = unsafe { std::mem::zeroed() }; + unsafe { + hb_font_get_extents_for_direction(font, hb_direction_t_HB_DIRECTION_LTR, &mut extents); + } + LineExtents { + ascender: extents.ascender as i64, + descender: extents.descender as i64, + } +} + +// SAFETY: The selected slot must be readable for a T. Alignment is not required. +unsafe fn struct_at_offset(first: *const T, index: u32, stride: u32) -> T { + first + .cast::() + .add(index as usize * stride as usize) + .cast::() + .read_unaligned() +} + +// SAFETY: The selected slot must be writable for a T. Alignment is not required. +unsafe fn write_struct_at_offset(first: *mut T, index: u32, stride: u32, value: T) { + first + .cast::() + .add(index as usize * stride as usize) + .cast::() + .write_unaligned(value); +} + +// Constructed only by with_strided_glyphs: outputs are aligned, disjoint, +// and exclusively borrowed for 'a, and cannot alias the input slots. +struct StridedGlyphs<'a> { + index: u32, + count: u32, + first_glyph: *const hb_codepoint_t, + glyph_stride: u32, + first_value: *mut hb_position_t, + value_stride: u32, + lifetime: PhantomData<&'a mut hb_position_t>, +} + +impl<'a> Iterator for StridedGlyphs<'a> { + type Item = (GlyphId, &'a mut hb_position_t); + + fn next(&mut self) -> Option { + if self.index == self.count { + return None; + } + let i = self.index; + self.index += 1; + unsafe { + Some(( + GlyphId::new(struct_at_offset(self.first_glyph, i, self.glyph_stride)), + &mut *self + .first_value + .cast::() + .add(i as usize * self.value_stride as usize) + .cast::(), + )) + } + } +} + +// Conservatively check the used slots, allowing disjoint interleaved fields. +fn strided_slots_overlap( + count: u32, + first_a: *const T, + stride_a: u32, + first_b: *const U, + stride_b: u32, +) -> bool { + if count == 0 { + return false; + } + let end_a = + first_a as usize + (count - 1) as usize * stride_a as usize + std::mem::size_of::(); + let end_b = + first_b as usize + (count - 1) as usize * stride_b as usize + std::mem::size_of::(); + if end_a <= first_b as usize || end_b <= first_a as usize { + return false; + } + if stride_a == stride_b && stride_a != 0 { + let gap = (first_a as usize).abs_diff(first_b as usize) % stride_a as usize; + let (size_low, size_high) = if first_a as usize <= first_b as usize { + (std::mem::size_of::(), std::mem::size_of::()) + } else { + (std::mem::size_of::(), std::mem::size_of::()) + }; + // Both gaps must fit the fields, including across record boundaries. + if gap >= size_low && stride_a as usize - gap >= size_high { + return false; + } + } + true +} + +// SAFETY: All input/output slots must be readable/writable for this call. +// The callback must access these buffers only through the supplied iterator. +unsafe fn with_strided_glyphs( + count: u32, + first_glyph: *const hb_codepoint_t, + glyph_stride: u32, + first_value: *mut hb_position_t, + value_stride: u32, + mut batch: impl for<'a> FnMut(StridedGlyphs<'a>), +) { + if count == 0 { + return; + } + let disjoint = + !strided_slots_overlap(count, first_glyph, glyph_stride, first_value, value_stride); + if disjoint + && first_value.is_aligned() + && (count == 1 + || (value_stride as usize >= std::mem::size_of::() + && (value_stride as usize).is_multiple_of(std::mem::align_of::()))) + { + batch(StridedGlyphs { + index: 0, + count, + first_glyph, + glyph_stride, + first_value, + value_stride, + lifetime: PhantomData, + }); + } else { + // Unaligned or overlapping slots cannot yield simultaneous &mut + // references. Use one stack output at a time and scatter it back. + for i in 0..count { + let mut value = 0; + batch(StridedGlyphs { + index: 0, + count: 1, + first_glyph: first_glyph + .cast::() + .add(i as usize * glyph_stride as usize) + .cast(), + glyph_stride: 0, + first_value: &mut value, + value_stride: 0, + lifetime: PhantomData, + }); + write_struct_at_offset(first_value, i, value_stride, value); + } + } +} + +#[cfg(feature = "skrifa")] fn bitmap_size(font: *mut hb_font_t) -> Size { let mut x_ppem = 0; let mut y_ppem = 0; @@ -197,6 +402,7 @@ fn bitmap_size(font: *mut hb_font_t) -> Size { } } +#[cfg(feature = "skrifa")] fn bitmap_glyph_extents( data: &FontationsData, bitmap_glyph: &BitmapGlyph, @@ -211,7 +417,7 @@ fn bitmap_glyph_extents( return None; } - let upem = data.size.ppem()?; + let upem = data.skrifa.size.ppem()?; let x_scale = upem / bitmap_glyph.ppem_x; let y_scale = upem / bitmap_glyph.ppem_y; @@ -250,15 +456,15 @@ extern "C" fn _hb_fontations_get_nominal_glyphs( _user_data: *mut ::std::os::raw::c_void, ) -> ::std::os::raw::c_uint { let data = unsafe { &*(font_data as *const FontationsData) }; - let char_map = &data.char_map; + let char_map = data.instance.charmap(); for i in 0..count { - let unicode = struct_at_offset(first_unicode, i, unicode_stride); - let Some(glyph) = char_map.map(unicode) else { + let unicode = unsafe { struct_at_offset(first_unicode, i, unicode_stride) }; + let Some(glyph) = char_map.map_unicode(unicode) else { return i; }; let glyph_id = glyph.to_u32() as hb_codepoint_t; - *struct_at_offset_mut(first_glyph, i, glyph_stride) = glyph_id; + unsafe { write_struct_at_offset(first_glyph, i, glyph_stride, glyph_id) }; } count @@ -273,21 +479,16 @@ extern "C" fn _hb_fontations_get_variation_glyph( ) -> hb_bool_t { let data = unsafe { &*(font_data as *const FontationsData) }; - let char_map = &data.char_map; - - match char_map.map_variant(unicode, variation_selector) { - Some(Variant(glyph_id)) => { + match data + .instance + .charmap() + .map_unicode_variant(unicode, variation_selector) + { + Some(glyph_id) => { unsafe { *glyph = glyph_id.to_u32() as hb_codepoint_t }; true as hb_bool_t } - Some(UseDefault) => match char_map.map(unicode) { - Some(glyph_id) => { - unsafe { *glyph = glyph_id.to_u32() as hb_codepoint_t }; - true as hb_bool_t - } - None => false as hb_bool_t, - }, - _ => false as hb_bool_t, + None => false as hb_bool_t, } } @@ -304,14 +505,21 @@ extern "C" fn _hb_fontations_get_glyph_h_advances( let data = unsafe { &mut *(font_data as *mut FontationsData) }; data.check_for_updates(); - let glyph_metrics = &data.glyph_metrics.as_ref().unwrap(); - - for i in 0..count { - let glyph = struct_at_offset(first_glyph, i, glyph_stride); - let glyph_id = GlyphId::new(glyph); - let advance = glyph_metrics.advance_width(glyph_id).unwrap_or_default(); - let scaled = (advance * data.x_mult).round() as hb_position_t; - *struct_at_offset_mut(first_advance, i, advance_stride) = scaled; + unsafe { + with_strided_glyphs( + count, + first_glyph, + glyph_stride, + first_advance, + advance_stride, + |glyphs| { + data.instance.glyph_metrics().h_advance_batched( + // Skrifa rounded advances to design units before applying our scale. + |advance| round_to_position(advance.to_i32() as f32 * data.x_mult), + glyphs, + ); + }, + ); } } @@ -328,135 +536,102 @@ extern "C" fn _hb_fontations_get_glyph_v_advances( let data = unsafe { &mut *(font_data as *mut FontationsData) }; data.check_for_updates(); - if let Some(vert_metrics) = &data.vert_metrics { - let vert_vars = &data.vert_vars; - for i in 0..count { - let glyph = struct_at_offset(first_glyph, i, glyph_stride); - let glyph_id = GlyphId::new(glyph); - let mut advance = vert_metrics.advance(glyph_id).unwrap_or_default() as f32; - if let Some(vert_vars) = vert_vars { - let coords = data.location.coords(); - if !coords.is_empty() { - advance += vert_vars - .advance_height_delta(glyph_id, coords) - .unwrap_or_default() - .to_f32(); - } - } - let scaled = ((advance * data.y_mult).round() as hb_position_t).saturating_neg(); - *struct_at_offset_mut(first_advance, i, advance_stride) = scaled; - } - } else { - let mut font_extents = unsafe { std::mem::zeroed() }; - unsafe { - hb_font_get_extents_for_direction( - font, - hb_direction_t_HB_DIRECTION_LTR, - &mut font_extents, - ); - } - let advance = font_extents - .ascender - .saturating_sub(font_extents.descender) - .saturating_neg(); - - for i in 0..count { - *struct_at_offset_mut(first_advance, i, advance_stride) = advance; - } + let line = font_line_extents(font); + unsafe { + with_strided_glyphs( + count, + first_glyph, + glyph_stride, + first_advance, + advance_stride, + |glyphs| { + data.glyph_metrics() + .with_line_extents(Some(line)) + .v_advance_batched(|advance| hb_position(advance).saturating_neg(), glyphs); + }, + ); } } -extern "C" fn _hb_fontations_get_glyph_v_origin( +extern "C" fn _hb_fontations_get_glyph_v_origins( font: *mut hb_font_t, font_data: *mut ::std::os::raw::c_void, - glyph: hb_codepoint_t, - x: *mut hb_position_t, - y: *mut hb_position_t, + count: ::std::os::raw::c_uint, + first_glyph: *const hb_codepoint_t, + glyph_stride: ::std::os::raw::c_uint, + first_x: *mut hb_position_t, + x_stride: ::std::os::raw::c_uint, + first_y: *mut hb_position_t, + y_stride: ::std::os::raw::c_uint, _user_data: *mut ::std::os::raw::c_void, ) -> hb_bool_t { + // Preserve scalar write order for aliased buffers, while batching disjoint + // glyph and position fields in the same interleaved records. + if (count > 1 && (x_stride as usize) < std::mem::size_of::()) + || strided_slots_overlap(count, first_glyph, glyph_stride, first_x, x_stride) + || strided_slots_overlap(count, first_glyph, glyph_stride, first_y, y_stride) + || strided_slots_overlap(count, first_x, x_stride, first_y, y_stride) + { + for i in 0..count { + let glyph = unsafe { struct_at_offset(first_glyph, i, glyph_stride) }; + let (mut x, mut y) = (0, 0); + _hb_fontations_get_glyph_v_origins( + font, font_data, 1, &glyph, 0, &mut x, 0, &mut y, 0, _user_data, + ); + unsafe { + write_struct_at_offset(first_x, i, x_stride, x); + write_struct_at_offset(first_y, i, y_stride, y); + } + } + return true as hb_bool_t; + } + let data = unsafe { &mut *(font_data as *mut FontationsData) }; data.check_for_updates(); unsafe { - *x = hb_font_get_glyph_h_advance(font, glyph) / 2; + hb_font_get_glyph_h_advances(font, count, first_glyph, glyph_stride, first_x, x_stride); + for i in 0..count { + let x = struct_at_offset(first_x, i, x_stride) / 2; + write_struct_at_offset(first_x, i, x_stride, x); + } } - let vert_origin = &data.vert_origin; - if let Some(vert_origin) = vert_origin { - let glyph_id = GlyphId::new(glyph); - - let mut y_origin = vert_origin.vertical_origin_y(glyph_id) as f32; - let vert_vars = &data.vert_vars; - if let Some(vert_vars) = vert_vars { - let coords = data.location.coords(); - if !coords.is_empty() { - y_origin += vert_vars - .v_org_delta(glyph_id, coords) - .unwrap_or_default() - .to_f32(); - } + let line = font_line_extents(font); + let extents = |glyph: GlyphId| { + let mut extents: hb_glyph_extents_t = unsafe { std::mem::zeroed() }; + if unsafe { hb_font_get_glyph_extents(font, glyph.to_u32(), &mut extents) } == 0 { + return None; } - - unsafe { - *y = (y_origin * data.y_mult).round() as hb_position_t; - } - - return true as hb_bool_t; - } - - let mut extents: hb_glyph_extents_t = unsafe { std::mem::zeroed() }; - if unsafe { hb_font_get_glyph_extents(font, glyph, &mut extents) != 0 } { - if let Some(vert_metrics) = &data.vert_metrics { - let glyph = GlyphId::new(glyph); - let mut tsb: f32 = vert_metrics.side_bearing(glyph).unwrap_or_default() as f32; - if let Some(vert_vars) = &data.vert_vars { - let coords = data.location.coords(); - if !coords.is_empty() { - tsb += vert_vars - .tsb_delta(glyph, coords) - .unwrap_or_default() - .to_f32(); - } - } - unsafe { - *y = extents - .y_bearing - .saturating_add((tsb * data.y_mult).round() as hb_position_t); - } - return true as hb_bool_t; - } - - let mut font_extents: hb_font_extents_t = unsafe { std::mem::zeroed() }; - unsafe { - hb_font_get_extents_for_direction( - font, - hb_direction_t_HB_DIRECTION_LTR, - &mut font_extents, - ); - } - let advance = font_extents.ascender as i64 - font_extents.descender as i64; - let diff = advance + extents.height as i64; - unsafe { - *y = (extents.y_bearing as i64 + (diff >> 1)) - .clamp(hb_position_t::MIN as i64, hb_position_t::MAX as i64) - as hb_position_t; - } - return true as hb_bool_t; - } - - let mut font_extents: hb_font_extents_t = unsafe { std::mem::zeroed() }; + Some(GlyphExtents { + x_bearing: extents.x_bearing as i64, + y_bearing: extents.y_bearing as i64, + width: extents.width as i64, + height: -(extents.height as i64), + }) + }; + let metrics = data + .glyph_metrics() + .with_line_extents(Some(line)) + .with_glyph_extents(Some(&extents)); unsafe { - hb_font_get_extents_for_direction(font, hb_direction_t_HB_DIRECTION_LTR, &mut font_extents); - } - unsafe { - *y = font_extents.ascender; + with_strided_glyphs( + count, + first_glyph, + glyph_stride, + first_y, + y_stride, + |glyphs| { + metrics.v_origin_y_batched(hb_position, glyphs); + }, + ); } true as hb_bool_t } extern "C" fn _hb_fontations_get_glyph_extents( - font: *mut hb_font_t, + _font: *mut hb_font_t, font_data: *mut ::std::os::raw::c_void, glyph: hb_codepoint_t, extents: *mut hb_glyph_extents_t, @@ -467,51 +642,62 @@ extern "C" fn _hb_fontations_get_glyph_extents( let glyph_id = GlyphId::new(glyph); - let size = bitmap_size(font); - let bitmap_glyph = data - .sbix_strikes - .as_ref() - .and_then(|strikes| strikes.glyph_for_size(size, glyph_id)) - .or_else(|| { - data.cbdt_strikes - .as_ref() - .and_then(|strikes| strikes.glyph_for_size(size, glyph_id)) - }); - if let Some(bitmap_glyph) = bitmap_glyph { - let Some(bitmap_extents) = bitmap_glyph_extents(data, &bitmap_glyph) else { - return false as hb_bool_t; - }; - unsafe { *extents = bitmap_extents }; - return true as hb_bool_t; + #[cfg(feature = "skrifa")] + { + let skrifa = &data.skrifa; + let bitmap_glyph = skrifa + .sbix_strikes + .as_ref() + .and_then(|strikes| strikes.glyph_for_size(bitmap_size(_font), glyph_id)) + .or_else(|| { + skrifa + .cbdt_strikes + .as_ref() + .and_then(|strikes| strikes.glyph_for_size(bitmap_size(_font), glyph_id)) + }); + if let Some(bitmap_glyph) = bitmap_glyph { + let Some(bitmap_extents) = bitmap_glyph_extents(data, &bitmap_glyph) else { + return false as hb_bool_t; + }; + unsafe { *extents = bitmap_extents }; + return true as hb_bool_t; + } + + if let Some(color_glyph) = skrifa.color_glyphs.get(glyph_id) { + let Some(glyph_extents) = + color_glyph.bounding_box(data.instance.normalized_coords(), skrifa.size) + else { + return false as hb_bool_t; + }; + + let x_bearing = round_to_position(glyph_extents.x_min * data.x_mult); + let width = + round_to_position(glyph_extents.x_max * data.x_mult).saturating_sub(x_bearing); + let y_bearing = round_to_position(glyph_extents.y_max * data.y_mult); + let height = + round_to_position(glyph_extents.y_min * data.y_mult).saturating_sub(y_bearing); + + unsafe { + *extents = hb_glyph_extents_t { + x_bearing, + y_bearing, + width, + height, + }; + } + return true as hb_bool_t; + } } - let color_glyphs = &data.color_glyphs; - let glyph_extents = if let Some(color_glyph) = color_glyphs.get(glyph_id) { - let Some(glyph_extents) = color_glyph.bounding_box(&data.location, data.size) else { - return false as hb_bool_t; - }; - glyph_extents - } else { - let glyph_metrics = &data.glyph_metrics.as_ref().unwrap(); - let Some(glyph_extents) = glyph_metrics.bounds(glyph_id) else { - return false as hb_bool_t; - }; - glyph_extents + let Some(glyph_extents) = data.glyph_metrics().extents(glyph_id) else { + return false as hb_bool_t; }; - - let x_bearing = (glyph_extents.x_min * data.x_mult).round() as hb_position_t; - let width = - ((glyph_extents.x_max * data.x_mult).round() as hb_position_t).saturating_sub(x_bearing); - let y_bearing = (glyph_extents.y_max * data.y_mult).round() as hb_position_t; - let height = - ((glyph_extents.y_min * data.y_mult).round() as hb_position_t).saturating_sub(y_bearing); - unsafe { *extents = hb_glyph_extents_t { - x_bearing, - y_bearing, - width, - height, + x_bearing: hb_position(glyph_extents.x_bearing), + y_bearing: hb_position(glyph_extents.y_bearing), + width: hb_position(glyph_extents.width), + height: hb_position(-glyph_extents.height), }; } @@ -527,15 +713,17 @@ extern "C" fn _hb_fontations_get_font_h_extents( let data = unsafe { &mut *(font_data as *mut FontationsData) }; data.check_for_updates(); - let font_ref = &data.font_ref; - let size = &data.size; - let location = &data.location; - let metrics = font_ref.metrics(*size, location); + let line = data + .instance + .metrics() + .scaled(data.scale()) + .h_line() + .unwrap_or_default(); unsafe { - (*extents).ascender = (metrics.ascent * data.y_mult).round() as hb_position_t; - (*extents).descender = (metrics.descent * data.y_mult).round() as hb_position_t; - (*extents).line_gap = (metrics.leading * data.y_mult).round() as hb_position_t; + (*extents).ascender = hb_position(line.ascender); + (*extents).descender = hb_position(line.descender); + (*extents).line_gap = hb_position(line.line_gap); } true as hb_bool_t @@ -621,9 +809,9 @@ extern "C" fn _hb_fontations_draw_glyph_or_fail( let data = unsafe { &mut *(font_data as *mut FontationsData) }; data.check_for_updates(); - let size = &data.size; - let location = &data.location; - let outline_glyphs = &data.outline_glyphs; + let size = &data.skrifa.size; + let location = data.instance.normalized_coords(); + let outline_glyphs = &data.skrifa.outline_glyphs; let glyph_id = GlyphId::new(glyph); let Some(outline_glyph) = outline_glyphs.get(glyph_id) else { @@ -1032,15 +1220,16 @@ fn paint_bitmap_glyph( paint_funcs: *mut hb_paint_funcs_t, paint_data: *mut ::std::os::raw::c_void, ) -> hb_bool_t { - let size = bitmap_size(font); let bitmap_glyph = data + .skrifa .cbdt_strikes .as_ref() - .and_then(|strikes| strikes.glyph_for_size(size, glyph_id)) + .and_then(|strikes| strikes.glyph_for_size(bitmap_size(font), glyph_id)) .or_else(|| { - data.sbix_strikes + data.skrifa + .sbix_strikes .as_ref() - .and_then(|strikes| strikes.glyph_for_size(size, glyph_id)) + .and_then(|strikes| strikes.glyph_for_size(bitmap_size(font), glyph_id)) }); let Some(bitmap_glyph) = bitmap_glyph else { return false as hb_bool_t; @@ -1060,7 +1249,7 @@ fn paint_bitmap_glyph( let Ok(image_length) = image.len().try_into() else { return false as hb_bool_t; }; - let face_blob = unsafe { hb_blob_reference(data.face_blob) }; + let face_blob = unsafe { hb_blob_reference(data.face_blob.0) }; let blob = unsafe { hb_blob_create_or_fail( image.as_ptr().cast(), @@ -1104,16 +1293,15 @@ extern "C" fn _hb_fontations_paint_glyph_or_fail( let data = unsafe { &mut *(font_data as *mut FontationsData) }; data.check_for_updates(); - let font_ref = &data.font_ref; - let location = &data.location; - let color_glyphs = &data.color_glyphs; + let location = data.instance.normalized_coords(); + let color_glyphs = &data.skrifa.color_glyphs; let glyph_id = GlyphId::new(glyph); let Some(color_glyph) = color_glyphs.get(glyph_id) else { return paint_bitmap_glyph(font, data, glyph_id, paint_funcs, paint_data); }; - let cpal = font_ref.cpal(); + let cpal = data.instance.tables().cpal(); let color_records = if let Ok(cpal) = cpal { let num_entries = cpal.num_palette_entries().into(); let color_records = cpal.color_records_array(); @@ -1177,7 +1365,7 @@ extern "C" fn _hb_fontations_glyph_name( ) -> hb_bool_t { let data = unsafe { &mut *(font_data as *mut FontationsData) }; - if let Some(glyph_name) = data.glyph_names.get(GlyphId::new(glyph)) { + if let Some(glyph_name) = data.instance.glyph_name(GlyphId::new(glyph)) { if size == 0 { return true as hb_bool_t; } @@ -1221,18 +1409,13 @@ extern "C" fn _hb_fontations_glyph_from_name( }; let face = unsafe { hb_font_get_face(font) }; - let mut user_data_ptr: *mut c_void; - - loop { - user_data_ptr = - unsafe { hb_face_get_user_data(face, std::ptr::addr_of_mut!(GLYPH_FROM_NAMES_KEY)) }; - if !user_data_ptr.is_null() { - break; - } + let mut user_data_ptr = + unsafe { hb_face_get_user_data(face, std::ptr::addr_of_mut!(GLYPH_FROM_NAMES_KEY)) }; + if user_data_ptr.is_null() { // Build the HashMap from glyph names to IDs let mut map = HashMap::new(); - for (glyph_id, glyph_name) in data.glyph_names.iter() { + for (glyph_id, glyph_name) in data.instance.glyph_names() { map.insert(glyph_name.to_string(), glyph_id.to_u32()); } @@ -1245,18 +1428,24 @@ extern "C" fn _hb_fontations_glyph_from_name( std::ptr::addr_of_mut!(GLYPH_FROM_NAMES_KEY), ptr, Some(_hb_glyph_from_names_destroy), - true as hb_bool_t, + false as hb_bool_t, ) }; if success != false as hb_bool_t { user_data_ptr = ptr; - break; + } else { + // Another reader may have published first. Never replace its map: + // readers keep using it until the face is destroyed. + _hb_glyph_from_names_destroy(ptr); + user_data_ptr = unsafe { + hb_face_get_user_data(face, std::ptr::addr_of_mut!(GLYPH_FROM_NAMES_KEY)) + }; + if user_data_ptr.is_null() { + // Publication failed without a winner (for example, on OOM). + return false as hb_bool_t; + } } - - // We failed to set user data — reclaim the pointer to avoid leaking - _hb_glyph_from_names_destroy(ptr); - // Try again in next loop iteration } let glyph_from_names = unsafe { &*(user_data_ptr as *const HashMap) }; @@ -1307,9 +1496,9 @@ fn _hb_fontations_font_funcs_get() -> *mut hb_font_funcs_t { null_mut(), None, ); - hb_font_funcs_set_glyph_v_origin_func( + hb_font_funcs_set_glyph_v_origins_func( ffuncs, - Some(_hb_fontations_get_glyph_v_origin), + Some(_hb_fontations_get_glyph_v_origins), null_mut(), None, ); diff --git a/src/rust/lib.rs b/src/rust/lib.rs index 71df5a50c..6c7a93735 100644 --- a/src/rust/lib.rs +++ b/src/rust/lib.rs @@ -7,6 +7,36 @@ mod font; #[cfg(feature = "shape")] mod shape; +#[cfg(any(feature = "font", feature = "shape"))] +struct HbBlob(*mut hb_blob_t); + +#[cfg(any(feature = "font", feature = "shape"))] +impl Drop for HbBlob { + fn drop(&mut self) { + unsafe { + hb_blob_destroy(self.0); + } + } +} + +#[cfg(any(feature = "font", feature = "shape"))] +impl AsRef<[u8]> for HbBlob { + fn as_ref(&self) -> &[u8] { + let mut length = 0; + let data = unsafe { hb_blob_get_data(self.0, &mut length) }; + if data.is_null() { + &[] + } else { + unsafe { std::slice::from_raw_parts(data.cast(), length as usize) } + } + } +} + +#[cfg(any(feature = "font", feature = "shape"))] +unsafe impl Send for HbBlob {} +#[cfg(any(feature = "font", feature = "shape"))] +unsafe impl Sync for HbBlob {} + #[cfg(feature = "hb-allocator")] use std::alloc::{GlobalAlloc, Layout}; #[cfg(feature = "hb-allocator")] diff --git a/src/rust/shape.rs b/src/rust/shape.rs index fa81c25c2..ad8f05e86 100644 --- a/src/rust/shape.rs +++ b/src/rust/shape.rs @@ -2,7 +2,7 @@ // C enum becomes i32 on some systems (eg. Windows). #![allow(clippy::unnecessary_cast)] -use super::hb::*; +use super::{hb::*, HbBlob}; use std::ffi::c_void; use std::mem::{align_of, offset_of, size_of}; @@ -10,12 +10,10 @@ use std::ptr::null_mut; use std::sync::Arc; use harfrust::{ - font::{ - AdvanceWidthBatch, BuiltinFontFuncs, Font, FontBlob, FontFuncs, FontInstance, - FontTableFunction, NominalGlyphBatch, - }, - GlyphExtents, GlyphFlags as HRGlyphFlags, GlyphId, GlyphInfo as HRGlyphInfo, - GlyphPosition as HRGlyphPosition, NormalizedCoord, ShapeOptions, Tag, + font::{Blob, Font, NormalizedCoord, TableFunction}, + Advances, FontFuncs, GlyphExtents, GlyphFlags as HRGlyphFlags, GlyphId, + GlyphInfo as HRGlyphInfo, GlyphPosition as HRGlyphPosition, NominalGlyphs, ShapeOptions, + ShaperFont, Tag, }; use smallvec::SmallVec; @@ -72,38 +70,13 @@ impl HbFace { unsafe impl Send for HbFace {} unsafe impl Sync for HbFace {} -struct HbBlob(*mut hb_blob_t); - -impl Drop for HbBlob { - fn drop(&mut self) { - unsafe { - hb_blob_destroy(self.0); - } - } -} - -impl AsRef<[u8]> for HbBlob { - fn as_ref(&self) -> &[u8] { - let mut length = 0; - let data = unsafe { hb_blob_get_data(self.0, &mut length) }; - if data.is_null() { - &[] - } else { - unsafe { std::slice::from_raw_parts(data.cast(), length as usize) } - } - } -} - -unsafe impl Send for HbBlob {} -unsafe impl Sync for HbBlob {} - #[unsafe(no_mangle)] pub unsafe extern "C" fn _hb_harfrust_shaper_face_data_create_rs( face: *mut hb_face_t, ) -> *mut c_void { let face_index = hb_face_get_index(face); let hb_face = HbFace::new(face); - let table_fn = FontTableFunction::new(Arc::new(move |tag| { + let table_fn = TableFunction::new(Arc::new(move |tag| { let blob = hb_face.reference_table(tag); if blob.is_null() { return None; @@ -114,12 +87,12 @@ pub unsafe extern "C" fn _hb_harfrust_shaper_face_data_create_rs( } return None; } - Some(FontBlob::Shared(Arc::new(HbBlob(blob)))) + Some(Blob::Shared(Arc::new(HbBlob(blob)))) })); let font = match Font::new(table_fn, face_index) { - Ok(font) => font, - Err(_) => return null_mut(), + Some(font) => font, + None => return null_mut(), }; let hr_face_data = Box::new(HBHarfRustFaceData { font }); @@ -134,7 +107,7 @@ pub unsafe extern "C" fn _hb_harfrust_shaper_face_data_destroy_rs(data: *mut c_v } pub struct HBHarfRustFontData { - instance: FontInstance, + instance: Font, x_scale: i32, y_scale: i32, ptem: Option, @@ -145,7 +118,7 @@ struct HBHarfBuzzFontFuncs { } impl FontFuncs for HBHarfBuzzFontFuncs { - fn nominal_glyph(&mut self, _: &BuiltinFontFuncs, c: u32) -> Option { + fn nominal_glyph(&self, _: &ShaperFont, c: u32) -> Option { let mut glyph = 0; if unsafe { hb_font_get_nominal_glyph(self.font, c, &mut glyph) } != 0 { Some(GlyphId::new(glyph)) @@ -154,7 +127,7 @@ impl FontFuncs for HBHarfBuzzFontFuncs { } } - fn variant_glyph(&mut self, _: &BuiltinFontFuncs, c: u32, vs: u32) -> Option { + fn variation_glyph(&self, _: &ShaperFont, c: u32, vs: u32) -> Option { let mut glyph = 0; if unsafe { hb_font_get_variation_glyph(self.font, c, vs, &mut glyph) } != 0 { Some(GlyphId::new(glyph)) @@ -163,11 +136,11 @@ impl FontFuncs for HBHarfBuzzFontFuncs { } } - fn advance_width(&mut self, _: &BuiltinFontFuncs, glyph: GlyphId) -> i32 { + fn glyph_h_advance(&self, _: &ShaperFont, glyph: GlyphId) -> i32 { unsafe { hb_font_get_glyph_h_advance(self.font, glyph.to_u32()) } } - fn populate_advance_widths(&mut self, _: &BuiltinFontFuncs, batch: AdvanceWidthBatch<'_>) { + fn glyph_h_advances(&self, _: &ShaperFont, batch: Advances<'_>) { let raw = batch.into_raw(); unsafe { hb_font_get_glyph_h_advances( @@ -181,11 +154,7 @@ impl FontFuncs for HBHarfBuzzFontFuncs { } } - fn populate_nominal_glyphs( - &mut self, - _: &BuiltinFontFuncs, - batch: NominalGlyphBatch<'_>, - ) -> usize { + fn nominal_glyphs(&self, _: &ShaperFont, batch: NominalGlyphs<'_>) -> usize { let raw = batch.into_raw(); unsafe { hb_font_get_nominal_glyphs( @@ -199,11 +168,11 @@ impl FontFuncs for HBHarfBuzzFontFuncs { } } - fn advance_height(&mut self, _: &BuiltinFontFuncs, glyph: GlyphId) -> i32 { + fn glyph_v_advance(&self, _: &ShaperFont, glyph: GlyphId) -> i32 { unsafe { hb_font_get_glyph_v_advance(self.font, glyph.to_u32()) } } - fn vertical_origin(&mut self, _: &BuiltinFontFuncs, glyph: GlyphId) -> (i32, i32) { + fn glyph_v_origin(&self, _: &ShaperFont, glyph: GlyphId) -> (i32, i32) { let mut x = 0; let mut y = 0; unsafe { @@ -212,7 +181,7 @@ impl FontFuncs for HBHarfBuzzFontFuncs { (x, y) } - fn extents(&mut self, _: &BuiltinFontFuncs, glyph: GlyphId) -> Option { + fn glyph_extents(&self, _: &ShaperFont, glyph: GlyphId) -> Option { let mut extents = hb_glyph_extents_t { x_bearing: 0, y_bearing: 0, @@ -232,7 +201,7 @@ impl FontFuncs for HBHarfBuzzFontFuncs { } } -fn font_to_instance(font: *mut hb_font_t, font_ref: &Font) -> FontInstance { +fn font_to_instance(font: *mut hb_font_t, font_ref: &Font) -> Font { let mut num_coords: u32 = 0; let coords = unsafe { hb_font_get_var_coords_normalized(font, &mut num_coords) }; let coords = if coords.is_null() { @@ -241,7 +210,8 @@ fn font_to_instance(font: *mut hb_font_t, font_ref: &Font) -> FontInstance { unsafe { std::slice::from_raw_parts(coords, num_coords as usize) } }; let coords = coords.iter().map(|&v| NormalizedCoord::from_bits(v as i16)); - FontInstance::builder(font_ref) + font_ref + .instance_builder() .normalized_coords(coords) .build() } @@ -290,13 +260,13 @@ fn hb_language_to_hr_language(language: hb_language_t) -> Option *mut c_void { - let hr_buffer = Box::new(harfrust::UnicodeBuffer::new()); + let hr_buffer = Box::new(harfrust::Buffer::new()); Box::into_raw(hr_buffer) as *mut c_void } #[unsafe(no_mangle)] pub unsafe extern "C" fn _hb_harfrust_buffer_destroy_rs(data: *mut c_void) { - let data = data as *mut harfrust::UnicodeBuffer; + let data = data as *mut harfrust::Buffer; let _hr_buffer = Box::from_raw(data); } @@ -377,41 +347,41 @@ pub unsafe extern "C" fn _hb_harfrust_shape_rs( num_features: u32, ) -> hb_bool_t { let font_data = font_data as *const HBHarfRustFontData; - let hr_buffer_box = hr_buffer_box as *mut harfrust::UnicodeBuffer; - let mut hr_buffer_box = Box::from_raw(hr_buffer_box); - let mut hr_buffer = *hr_buffer_box; + let hr_buffer = &mut *(hr_buffer_box as *mut harfrust::Buffer); + hr_buffer.clear(); let shape_plan = (shape_plan as *const harfrust::ShapePlan).as_ref(); // Set buffer properties let cluster_level = hb_buffer_get_cluster_level(buffer); let cluster_level = match cluster_level { hb_buffer_cluster_level_t_HB_BUFFER_CLUSTER_LEVEL_MONOTONE_GRAPHEMES => { - harfrust::BufferClusterLevel::MonotoneGraphemes + harfrust::ClusterLevel::MonotoneGraphemes } hb_buffer_cluster_level_t_HB_BUFFER_CLUSTER_LEVEL_MONOTONE_CHARACTERS => { - harfrust::BufferClusterLevel::MonotoneCharacters + harfrust::ClusterLevel::MonotoneCharacters } hb_buffer_cluster_level_t_HB_BUFFER_CLUSTER_LEVEL_CHARACTERS => { - harfrust::BufferClusterLevel::Characters + harfrust::ClusterLevel::Characters } hb_buffer_cluster_level_t_HB_BUFFER_CLUSTER_LEVEL_GRAPHEMES => { - harfrust::BufferClusterLevel::Graphemes + harfrust::ClusterLevel::Graphemes } - _ => harfrust::BufferClusterLevel::default(), + _ => harfrust::ClusterLevel::MonotoneGraphemes, }; hr_buffer.set_cluster_level(cluster_level); let flags = hb_buffer_get_flags(buffer); hr_buffer.set_flags(harfrust::BufferFlags::from_bits_truncate(flags as u32)); let not_found_variation_selector_glyph = hb_buffer_get_not_found_variation_selector_glyph(buffer); - if not_found_variation_selector_glyph != u32::MAX { - hr_buffer.set_not_found_variation_selector_glyph(not_found_variation_selector_glyph); - } + hr_buffer.set_not_found_variation_selector_glyph( + (not_found_variation_selector_glyph != u32::MAX) + .then_some(not_found_variation_selector_glyph), + ); if let Some(plan) = shape_plan { // Language is only used to build the plan; shaping with an explicit // plan reads its cached segment properties instead of buffer language. - hr_buffer.set_script(plan.script().unwrap_or(harfrust::script::UNKNOWN)); + hr_buffer.set_script(Some(plan.script().unwrap_or(harfrust::Script::UNKNOWN))); hr_buffer.set_direction(plan.direction()); } else { // Convert segment properties when shaping without a cached plan. @@ -419,7 +389,7 @@ pub unsafe extern "C" fn _hb_harfrust_shape_rs( let language = hb_buffer_get_language(buffer); let direction = hb_buffer_get_direction(buffer); let script = harfrust::Script::from_iso15924_tag(Tag::from_u32(script as u32)) - .unwrap_or(harfrust::script::UNKNOWN); + .unwrap_or(harfrust::Script::UNKNOWN); let language = hb_language_to_hr_language(language); let direction = match direction { hb_direction_t_HB_DIRECTION_LTR => harfrust::Direction::LeftToRight, @@ -428,9 +398,9 @@ pub unsafe extern "C" fn _hb_harfrust_shape_rs( hb_direction_t_HB_DIRECTION_BTT => harfrust::Direction::BottomToTop, _ => harfrust::Direction::Invalid, }; - hr_buffer.set_script(script); + hr_buffer.set_script(Some(script)); if let Some(lang) = language { - hr_buffer.set_language(lang); + hr_buffer.set_language(Some(lang)); } hr_buffer.set_direction(direction); } @@ -449,20 +419,25 @@ pub unsafe extern "C" fn _hb_harfrust_shape_rs( hr_buffer.set_post_context_codepoints(post_context); let features = hb_feature_to_hr_feature(features, num_features); - let mut font_funcs = HBHarfBuzzFontFuncs { font }; + let font_funcs = HBHarfBuzzFontFuncs { font }; + let shaper_font = ShaperFont::new(&(*font_data).instance) + .with_scale_separate((*font_data).x_scale, (*font_data).y_scale) + .with_font_funcs(Some(&font_funcs)); let options = ShapeOptions::new() .plan(shape_plan) - .scale_separate(Some(((*font_data).x_scale, (*font_data).y_scale))) .point_size((*font_data).ptem) - .features(&features) - .font_funcs(Some(&mut font_funcs)); - let glyphs = harfrust::shape(&(*font_data).instance, hr_buffer, options); + .features(&features); + if harfrust::shape(&shaper_font, hr_buffer, options).is_err() + || !hr_buffer.allocation_successful() + { + return false as hb_bool_t; + } hb_buffer_set_content_type( buffer, hb_buffer_content_type_t_HB_BUFFER_CONTENT_TYPE_GLYPHS, ); - let count = glyphs.len(); + let count = hr_buffer.len(); hb_buffer_set_length(buffer, count as u32); let mut count_out: u32 = 0; let infos = hb_buffer_get_glyph_infos(buffer, &mut count_out); @@ -471,12 +446,14 @@ pub unsafe extern "C" fn _hb_harfrust_shape_rs( return false as hb_bool_t; } - std::ptr::copy_nonoverlapping(glyphs.glyph_infos().as_ptr().cast(), infos, count); - std::ptr::copy_nonoverlapping(glyphs.glyph_positions().as_ptr().cast(), positions, count); + std::ptr::copy_nonoverlapping(hr_buffer.glyph_infos().as_ptr().cast(), infos, count); + std::ptr::copy_nonoverlapping( + hr_buffer.glyph_positions().as_ptr().cast(), + positions, + count, + ); - let hr_buffer = glyphs.clear(); - *hr_buffer_box = hr_buffer; // Move the buffer back into the box - let _ = Box::into_raw(hr_buffer_box); // Prevent double free + hr_buffer.clear(); true as hb_bool_t } diff --git a/test/api/test-font.c b/test/api/test-font.c index e8087574e..9f2a5cb84 100644 --- a/test/api/test-font.c +++ b/test/api/test-font.c @@ -26,6 +26,10 @@ #include "hb-test.h" +#ifdef HAVE_FONTATIONS +#include +#endif + /* Unit tests for hb-font.h */ @@ -712,6 +716,397 @@ test_synthetic_glyph_extents_overflow (void) hb_font_funcs_destroy (ffuncs); } +#ifdef HAVE_FONTATIONS +typedef struct { + hb_font_t *font; + GMutex mutex; + GCond cond; + unsigned waiting; + hb_bool_t start; + char name[128]; +} fontations_name_test_t; + +static gpointer +fontations_name_thread (gpointer user_data) +{ + fontations_name_test_t *data = user_data; + g_mutex_lock (&data->mutex); + data->waiting++; + g_cond_broadcast (&data->cond); + while (!data->start) + g_cond_wait (&data->cond, &data->mutex); + g_mutex_unlock (&data->mutex); + + for (unsigned i = 0; i < 100; i++) + { + hb_codepoint_t glyph = HB_CODEPOINT_INVALID; + g_assert_true (hb_font_get_glyph_from_name (data->font, data->name, -1, &glyph)); + g_assert_cmpuint (glyph, ==, 1); + g_assert_false (hb_font_get_glyph_from_name (data->font, "nonexistent-glyph", -1, &glyph)); + } + return NULL; +} + +static void +test_fontations_glyph_from_name_threads (void) +{ + for (unsigned run = 0; run < 8; run++) + { + hb_face_t *face = hb_test_open_font_file ("fonts/NotoSans-Bold.ttf"); + fontations_name_test_t data = {0}; + data.font = hb_font_create (face); + hb_fontations_font_set_funcs (data.font); + hb_font_make_immutable (data.font); + g_assert_true (hb_font_get_glyph_name (data.font, 1, data.name, sizeof (data.name))); + g_mutex_init (&data.mutex); + g_cond_init (&data.cond); + + GThread *threads[8]; + for (unsigned i = 0; i < G_N_ELEMENTS (threads); i++) + threads[i] = g_thread_new ("fontations-names", fontations_name_thread, &data); + g_mutex_lock (&data.mutex); + while (data.waiting != G_N_ELEMENTS (threads)) + g_cond_wait (&data.cond, &data.mutex); + data.start = true; + g_cond_broadcast (&data.cond); + g_mutex_unlock (&data.mutex); + for (unsigned i = 0; i < G_N_ELEMENTS (threads); i++) + g_thread_join (threads[i]); + + g_cond_clear (&data.cond); + g_mutex_clear (&data.mutex); + hb_font_destroy (data.font); + hb_face_destroy (face); + } +} + +static void +test_fontations_scale_changes (void) +{ + const char *fonts[] = { + "fonts/Roboto-Variable.abc.ttf", + "fonts/SourceSerifVariable-Roman-VVAR.abc.ttf", + "fonts/Roboto-Regular.abc.ttf", + }; + const struct { + int values[3]; + unsigned count; + } locations[] = { + {{0, 0, 0}, 0}, {{0, 0, 0}, 3}, + {{9830, 0, 0}, 1}, {{9830, 0, 0}, 3}, + {{9830, 16384, 0}, 2}, {{9830, 16384, 16384}, 3}, + {{0, 0, 16384}, 3}, {{0, 0, 0}, 0}, + }; + const int scales[][2] = {{2048, 4096}, {-1234, -5678}, {0, 0}, {1234, 5678}}; + + for (unsigned f = 0; f < G_N_ELEMENTS (fonts); f++) + { + hb_face_t *face = hb_test_open_font_file (fonts[f]); + hb_font_t *font = hb_font_create (face); + hb_font_t *reference = hb_font_create (face); + hb_fontations_font_set_funcs (font); + + for (unsigned c = 0; c < G_N_ELEMENTS (locations); c++) + { + hb_font_set_var_coords_normalized (font, locations[c].values, locations[c].count); + hb_font_set_var_coords_normalized (reference, locations[c].values, locations[c].count); + for (unsigned s = 0; s < G_N_ELEMENTS (scales); s++) + { + hb_font_set_scale (font, scales[s][0], scales[s][1]); + hb_font_set_scale (reference, scales[s][0], scales[s][1]); + /* Compare the reused instance against a freshly initialized one. */ + hb_fontations_font_set_funcs (reference); + for (hb_codepoint_t glyph = 0; glyph < hb_face_get_glyph_count (face); glyph++) + { + g_assert_cmpint (hb_font_get_glyph_h_advance (font, glyph), ==, + hb_font_get_glyph_h_advance (reference, glyph)); + g_assert_cmpint (hb_font_get_glyph_v_advance (font, glyph), ==, + hb_font_get_glyph_v_advance (reference, glyph)); + } + } + } + + hb_font_destroy (reference); + hb_font_destroy (font); + hb_face_destroy (face); + } +} + +static void +test_fontations_strides (void) +{ + hb_face_t *face = hb_test_open_font_file ("fonts/Roboto-Regular.abc.ttf"); + hb_font_t *font = hb_font_create (face); + hb_fontations_font_set_funcs (font); + const hb_codepoint_t unicodes[] = {'a', 'b', 'c'}; + hb_codepoint_t ids[3]; + uint8_t unicode_bytes[16], glyph_bytes[16], advance_bytes[16]; + memset (unicode_bytes, 0xA5, sizeof (unicode_bytes)); + memset (glyph_bytes, 0xA5, sizeof (glyph_bytes)); + for (unsigned i = 0; i < G_N_ELEMENTS (unicodes); i++) + { + memcpy (unicode_bytes + 1 + 5 * i, &unicodes[i], sizeof (unicodes[i])); + g_assert_true (hb_font_get_nominal_glyph (font, unicodes[i], &ids[i])); + } + g_assert_cmpuint (hb_font_get_nominal_glyphs (font, 3, + (const hb_codepoint_t *) (unicode_bytes + 1), 5, + (hb_codepoint_t *) (glyph_bytes + 1), 5), ==, 3); + for (unsigned i = 0; i < 3; i++) + { + hb_codepoint_t glyph; + memcpy (&glyph, glyph_bytes + 1 + 5 * i, sizeof (glyph)); + g_assert_cmpuint (glyph, ==, ids[i]); + g_assert_cmpuint (glyph_bytes[5 * i + 5], ==, 0xA5); + } + g_assert_cmpuint (glyph_bytes[0], ==, 0xA5); + + /* hb-ot-normalize maps codepoint to var1.u32 in the same glyph-info array. */ + hb_glyph_info_t infos[3] = {0}; + for (unsigned i = 0; i < G_N_ELEMENTS (infos); i++) + { + infos[i].codepoint = unicodes[i]; + infos[i].mask = 123456; + infos[i].cluster = i; + infos[i].var1.u32 = HB_CODEPOINT_INVALID; + infos[i].var2.u32 = 123456; + } + g_assert_cmpuint (hb_font_get_nominal_glyphs (font, G_N_ELEMENTS (infos), + &infos[0].codepoint, sizeof (infos[0]), + &infos[0].var1.u32, sizeof (infos[0])), ==, G_N_ELEMENTS (infos)); + for (unsigned i = 0; i < G_N_ELEMENTS (infos); i++) + { + g_assert_cmpuint (infos[i].codepoint, ==, unicodes[i]); + g_assert_cmpuint (infos[i].var1.u32, ==, ids[i]); + g_assert_cmpuint (infos[i].mask, ==, 123456); + g_assert_cmpuint (infos[i].cluster, ==, i); + g_assert_cmpuint (infos[i].var2.u32, ==, 123456); + } + + void (*get_advances[])(hb_font_t *, unsigned, const hb_codepoint_t *, unsigned, + hb_position_t *, unsigned) = { + hb_font_get_glyph_h_advances, hb_font_get_glyph_v_advances, + }; + for (unsigned axis = 0; axis < G_N_ELEMENTS (get_advances); axis++) + { + hb_position_t expected[3]; + get_advances[axis] (font, 3, ids, sizeof (ids[0]), expected, sizeof (expected[0])); + memset (advance_bytes, 0xA5, sizeof (advance_bytes)); + get_advances[axis] (font, 3, (const hb_codepoint_t *) (glyph_bytes + 1), 5, + (hb_position_t *) (advance_bytes + 1), 5); + for (unsigned i = 0; i < 3; i++) + { + hb_position_t advance; + memcpy (&advance, advance_bytes + 1 + 5 * i, sizeof (advance)); + g_assert_cmpint (advance, ==, expected[i]); + g_assert_cmpuint (advance_bytes[5 * i + 5], ==, 0xA5); + } + g_assert_cmpuint (advance_bytes[0], ==, 0xA5); + + hb_position_t last = 0; + get_advances[axis] (font, 3, ids, sizeof (ids[0]), &last, 0); + g_assert_cmpint (last, ==, expected[2]); + + hb_codepoint_t in_place[3]; + memcpy (in_place, ids, sizeof (ids)); + get_advances[axis] (font, 3, in_place, sizeof (in_place[0]), + (hb_position_t *) in_place, sizeof (in_place[0])); + for (unsigned i = 0; i < 3; i++) + g_assert_cmpint ((hb_position_t) in_place[i], ==, expected[i]); + } + + struct { + hb_codepoint_t glyph; + hb_position_t h_advance, v_advance, x, y, padding; + } records[3]; + for (unsigned i = 0; i < G_N_ELEMENTS (records); i++) + { + records[i].glyph = ids[i]; + records[i].h_advance = records[i].v_advance = records[i].x = records[i].y = 0; + records[i].padding = 123456; + } + hb_font_get_glyph_h_advances (font, G_N_ELEMENTS (records), + &records[0].glyph, sizeof (records[0]), + &records[0].h_advance, sizeof (records[0])); + hb_font_get_glyph_v_advances (font, G_N_ELEMENTS (records), + &records[0].glyph, sizeof (records[0]), + &records[0].v_advance, sizeof (records[0])); + g_assert_true (hb_font_get_glyph_v_origins (font, G_N_ELEMENTS (records), + &records[0].glyph, sizeof (records[0]), + &records[0].x, sizeof (records[0]), + &records[0].y, sizeof (records[0]))); + for (unsigned i = 0; i < G_N_ELEMENTS (records); i++) + { + hb_position_t x, y; + g_assert_cmpuint (records[i].glyph, ==, ids[i]); + g_assert_cmpint (records[i].h_advance, ==, hb_font_get_glyph_h_advance (font, ids[i])); + g_assert_cmpint (records[i].v_advance, ==, hb_font_get_glyph_v_advance (font, ids[i])); + g_assert_true (hb_font_get_glyph_v_origin (font, ids[i], &x, &y)); + g_assert_cmpint (records[i].x, ==, x); + g_assert_cmpint (records[i].y, ==, y); + g_assert_cmpint (records[i].padding, ==, 123456); + } + hb_font_destroy (font); + hb_face_destroy (face); +} + +static void +test_fontations_v_origins (void) +{ + const char *fonts[] = { + "fonts/Roboto-Regular.abc.ttf", + "fonts/Roboto-Variable.abc.ttf", + "fonts/SourceSerifVariable-Roman-VVAR.abc.ttf", + "fonts/AdobeVFPrototype.abc.otf", + "../shape/data/in-house/fonts/NotoSansCJK-VF.abc.ttf", + "../shape/data/in-house/fonts/NotoSansCJK-VF.abc.otf", + }; + const int coords[] = {0, 16384, -16384, 0}; + const hb_codepoint_t glyphs[] = {0, 1, 2, 3, HB_CODEPOINT_INVALID}; + for (unsigned f = 0; f < G_N_ELEMENTS (fonts); f++) + { + hb_face_t *face = hb_test_open_font_file (fonts[f]); + hb_font_t *font = hb_font_create (face); + hb_fontations_font_set_funcs (font); + int upem = hb_face_get_upem (face); + for (int sign = 1; sign >= -1; sign -= 2) + { + hb_font_set_scale (font, sign * upem * 2, sign * upem * 3); + for (unsigned c = 0; c < G_N_ELEMENTS (coords); c++) + { + hb_font_set_var_coords_normalized (font, &coords[c], 1); + hb_position_t expected_x[G_N_ELEMENTS (glyphs)], expected_y[G_N_ELEMENTS (glyphs)]; + for (unsigned i = 0; i < G_N_ELEMENTS (glyphs); i++) + g_assert_true (hb_font_get_glyph_v_origin (font, glyphs[i], &expected_x[i], &expected_y[i])); + + hb_position_t origins[4 * G_N_ELEMENTS (glyphs)]; + for (unsigned i = 0; i < G_N_ELEMENTS (origins); i++) + origins[i] = 123456; + g_assert_true (hb_font_get_glyph_v_origins (font, G_N_ELEMENTS (glyphs), + glyphs, sizeof (glyphs[0]), + origins, 4 * sizeof (origins[0]), + origins + 1, 4 * sizeof (origins[0]))); + for (unsigned i = 0; i < G_N_ELEMENTS (glyphs); i++) + { + g_assert_cmpint (origins[4 * i], ==, expected_x[i]); + g_assert_cmpint (origins[4 * i + 1], ==, expected_y[i]); + g_assert_cmpint (origins[4 * i + 2], ==, 123456); + g_assert_cmpint (origins[4 * i + 3], ==, 123456); + } + + hb_position_t last_x = 0, last_y = 0; + g_assert_true (hb_font_get_glyph_v_origins (font, G_N_ELEMENTS (glyphs), + glyphs, sizeof (glyphs[0]), &last_x, 0, &last_y, 0)); + g_assert_cmpint (last_x, ==, expected_x[G_N_ELEMENTS (glyphs) - 1]); + g_assert_cmpint (last_y, ==, expected_y[G_N_ELEMENTS (glyphs) - 1]); + + hb_codepoint_t in_place[G_N_ELEMENTS (glyphs)]; + memcpy (in_place, glyphs, sizeof (glyphs)); + g_assert_true (hb_font_get_glyph_v_origins (font, G_N_ELEMENTS (glyphs), + in_place, sizeof (in_place[0]), + (hb_position_t *) in_place, sizeof (in_place[0]), + origins, sizeof (origins[0]))); + for (unsigned i = 0; i < G_N_ELEMENTS (glyphs); i++) + { + g_assert_cmpint ((hb_position_t) in_place[i], ==, expected_x[i]); + g_assert_cmpint (origins[i], ==, expected_y[i]); + } + + uint8_t x_bytes[1 + 5 * G_N_ELEMENTS (glyphs)], y_bytes[sizeof (x_bytes)]; + memset (x_bytes, 0xA5, sizeof (x_bytes)); + memset (y_bytes, 0xA5, sizeof (y_bytes)); + g_assert_true (hb_font_get_glyph_v_origins (font, G_N_ELEMENTS (glyphs), + glyphs, sizeof (glyphs[0]), + (hb_position_t *) (x_bytes + 1), 5, + (hb_position_t *) (y_bytes + 1), 5)); + for (unsigned i = 0; i < G_N_ELEMENTS (glyphs); i++) + { + hb_position_t x, y; + memcpy (&x, x_bytes + 1 + 5 * i, sizeof (x)); + memcpy (&y, y_bytes + 1 + 5 * i, sizeof (y)); + g_assert_cmpint (x, ==, expected_x[i]); + g_assert_cmpint (y, ==, expected_y[i]); + g_assert_cmpuint (x_bytes[5 * i + 5], ==, 0xA5); + g_assert_cmpuint (y_bytes[5 * i + 5], ==, 0xA5); + } + g_assert_true (hb_font_get_glyph_v_origins (font, 0, NULL, 0, NULL, 0, NULL, 0)); + } + } + hb_font_destroy (font); + hb_face_destroy (face); + } +} + +static void +test_fontations_advances (void) +{ + const char *fonts[] = { + "fonts/Roboto-Variable.abc.ttf", + "fonts/SourceSerifVariable-Roman-VVAR.abc.ttf", + "fonts/SourceSansVariable-Roman-nohvar-41,C1.ttf", + }; + const int coords[] = {0, 16384, -16384, 0}; + const struct { + hb_codepoint_t glyph; + hb_codepoint_t padding[2]; + } glyphs[] = {{1, {0}}, {2, {0}}, {3, {0}}, {HB_CODEPOINT_INVALID, {0}}}; + + for (unsigned f = 0; f < G_N_ELEMENTS (fonts); f++) + { + hb_face_t *face = hb_test_open_font_file (fonts[f]); + hb_font_t *font = hb_font_create (face); + hb_font_t *reference = hb_font_create (face); + int upem = hb_face_get_upem (face); + hb_fontations_font_set_funcs (font); + + for (int sign = 1; sign >= -1; sign -= 2) + { + hb_font_set_scale (font, sign * upem * 2, sign * upem * 3); + hb_font_set_scale (reference, sign * upem * 2, sign * upem * 3); + + for (unsigned c = 0; c < G_N_ELEMENTS (coords); c++) + { + hb_font_set_var_coords_normalized (font, &coords[c], 1); + hb_font_set_var_coords_normalized (reference, &coords[c], 1); + + hb_position_t h_advances[2 * G_N_ELEMENTS (glyphs)]; + hb_position_t v_advances[2 * G_N_ELEMENTS (glyphs)]; + for (unsigned i = 0; i < G_N_ELEMENTS (h_advances); i++) + h_advances[i] = v_advances[i] = 123456; + + hb_font_get_glyph_h_advances (font, G_N_ELEMENTS (glyphs), + &glyphs[0].glyph, sizeof (glyphs[0]), + h_advances, 2 * sizeof (h_advances[0])); + hb_font_get_glyph_v_advances (font, G_N_ELEMENTS (glyphs), + &glyphs[0].glyph, sizeof (glyphs[0]), + v_advances, 2 * sizeof (v_advances[0])); + + for (unsigned i = 0; i < G_N_ELEMENTS (glyphs); i++) + { + hb_codepoint_t glyph = glyphs[i].glyph; + g_assert_cmpint (h_advances[2 * i], ==, hb_font_get_glyph_h_advance (font, glyph)); + g_assert_cmpint (v_advances[2 * i], ==, hb_font_get_glyph_v_advance (font, glyph)); + /* OT can apply variation deltas even to invalid glyph IDs. */ + if (glyph < hb_face_get_glyph_count (face)) + { + g_assert_cmpint (h_advances[2 * i], ==, hb_font_get_glyph_h_advance (reference, glyph)); + g_assert_cmpint (v_advances[2 * i], ==, hb_font_get_glyph_v_advance (reference, glyph)); + } + g_assert_cmpint (h_advances[2 * i + 1], ==, 123456); + g_assert_cmpint (v_advances[2 * i + 1], ==, 123456); + } + + hb_font_get_glyph_h_advances (font, 0, NULL, 0, NULL, 0); + hb_font_get_glyph_v_advances (font, 0, NULL, 0, NULL, 0); + } + } + + hb_font_destroy (reference); + hb_font_destroy (font); + hb_face_destroy (face); + } +} +#endif + int main (int argc, char **argv) { @@ -730,6 +1125,13 @@ main (int argc, char **argv) hb_test_add (test_font_empty); hb_test_add (test_font_properties); hb_test_add (test_synthetic_glyph_extents_overflow); +#ifdef HAVE_FONTATIONS + hb_test_add (test_fontations_glyph_from_name_threads); + hb_test_add (test_fontations_scale_changes); + hb_test_add (test_fontations_strides); + hb_test_add (test_fontations_v_origins); + hb_test_add (test_fontations_advances); +#endif return hb_test_run(); } diff --git a/test/shape/data/in-house/tests/vertical.tests b/test/shape/data/in-house/tests/vertical.tests index 7dd50d503..cf57f17ed 100644 --- a/test/shape/data/in-house/tests/vertical.tests +++ b/test/shape/data/in-house/tests/vertical.tests @@ -7,8 +7,7 @@ @font-funcs=ot,ft,fontations ../fonts/NotoSansCJK-VF.abc.ttf;--direction=t;U+0041,U+0042;[gid1=0@-287,-880+0,-1000|gid2=1@-316,-880+0,-1000] ../fonts/NotoSerifHK-subset.ttf;--direction=t;U+0041,U+0042;[gid1=0@-353,-880+0,-1000|gid2=1@-327,-880+0,-1000] -# glyf+gvar+vmtx; TODO: fontations needs more work https://github.com/harfbuzz/harfbuzz/issues/5388 -@font-funcs=ot,ft +# glyf+gvar+vmtx ../fonts/NotoSansCJK-VF.abc.ttf;--direction=t --variations wght=700;U+0041,U+0042;[gid1=0@-320,-880+0,-1000|gid2=1@-340,-880+0,-1000] ../fonts/NotoSerifHK-subset.ttf;--direction=t --variations wght=700;U+0041,U+0042;[gid1=0@-373,-880+0,-1000|gid2=1@-354,-880+0,-1000] @font-funcs=ot,ft,fontations