1#![expect(unsafe_code)]
6
7use std::os::raw::{c_char, c_int, c_uint, c_void};
8use std::sync::LazyLock;
9use std::{char, ptr};
10
11use app_units::Au;
12use euclid::default::Point2D;
13use harfbuzz_sys::{
16 HB_BUFFER_CLUSTER_LEVEL_MONOTONE_CHARACTERS, HB_DIRECTION_LTR, HB_DIRECTION_RTL,
17 HB_MEMORY_MODE_READONLY, HB_OT_LAYOUT_BASELINE_TAG_HANGING,
18 HB_OT_LAYOUT_BASELINE_TAG_IDEO_EMBOX_BOTTOM_OR_LEFT, HB_OT_LAYOUT_BASELINE_TAG_ROMAN,
19 hb_blob_create, hb_blob_t, hb_bool_t, hb_buffer_add_utf8, hb_buffer_create, hb_buffer_destroy,
20 hb_buffer_get_glyph_infos, hb_buffer_get_glyph_positions, hb_buffer_get_length,
21 hb_buffer_set_cluster_level, hb_buffer_set_direction, hb_buffer_set_script, hb_buffer_t,
22 hb_codepoint_t, hb_face_create_for_tables, hb_face_destroy, hb_face_t, hb_feature_t,
23 hb_font_create, hb_font_destroy, hb_font_funcs_create, hb_font_funcs_set_glyph_h_advance_func,
24 hb_font_funcs_set_nominal_glyph_func, hb_font_funcs_t, hb_font_set_funcs, hb_font_set_ppem,
25 hb_font_set_scale, hb_font_set_variations, hb_font_t, hb_glyph_info_t, hb_glyph_position_t,
26 hb_ot_layout_get_baseline, hb_position_t, hb_script_from_iso15924_tag, hb_shape, hb_tag_t,
27 hb_variation_t,
28};
29use num_traits::Zero;
30use read_fonts::types::Tag;
31
32use super::{GlyphShapingResult, ShapedGlyph, unicode_script_to_iso15924_tag};
33use crate::platform::font::FontTable;
34use crate::{
35 BASE, Font, FontBaseline, FontTableMethods, GlyphId, GlyphStore, KERN, LIGA, ShapingFlags,
36 ShapingOptions, fixed_to_float, float_to_fixed,
37};
38
39const HB_OT_TAG_DEFAULT_SCRIPT: hb_tag_t = u32::from_be_bytes(Tag::new(b"DFLT").to_be_bytes());
40const HB_OT_TAG_DEFAULT_LANGUAGE: hb_tag_t = u32::from_be_bytes(Tag::new(b"dflt").to_be_bytes());
41
42pub(crate) struct HarfbuzzGlyphShapingResult {
43 count: usize,
44 buffer: *mut hb_buffer_t,
45 glyph_infos: *mut hb_glyph_info_t,
46 pos_infos: *mut hb_glyph_position_t,
47}
48
49impl HarfbuzzGlyphShapingResult {
50 unsafe fn new(buffer: *mut hb_buffer_t) -> HarfbuzzGlyphShapingResult {
58 let mut glyph_count = 0;
59 let glyph_infos = unsafe { hb_buffer_get_glyph_infos(buffer, &mut glyph_count) };
60 assert!(!glyph_infos.is_null());
61 let mut pos_count = 0;
62 let pos_infos = unsafe { hb_buffer_get_glyph_positions(buffer, &mut pos_count) };
63 assert!(!pos_infos.is_null());
64 assert_eq!(glyph_count, pos_count);
65
66 HarfbuzzGlyphShapingResult {
67 count: glyph_count as usize,
68 buffer,
69 glyph_infos,
70 pos_infos,
71 }
72 }
73}
74
75impl Drop for HarfbuzzGlyphShapingResult {
76 fn drop(&mut self) {
77 unsafe { hb_buffer_destroy(self.buffer) }
78 }
79}
80
81struct ShapedGlyphIterator<'a> {
82 shaped_glyph_data: &'a HarfbuzzGlyphShapingResult,
83 current_glyph_offset: usize,
84 y_position: Au,
85}
86
87impl<'a> Iterator for ShapedGlyphIterator<'a> {
88 type Item = ShapedGlyph;
89
90 fn next(&mut self) -> Option<Self::Item> {
91 if self.current_glyph_offset >= self.shaped_glyph_data.count {
92 return None;
93 }
94
95 unsafe {
96 let glyph_info_i = self
97 .shaped_glyph_data
98 .glyph_infos
99 .add(self.current_glyph_offset);
100 let pos_info_i = self
101 .shaped_glyph_data
102 .pos_infos
103 .add(self.current_glyph_offset);
104 let x_offset = Shaper::fixed_to_float((*pos_info_i).x_offset);
105 let y_offset = Shaper::fixed_to_float((*pos_info_i).y_offset);
106 let x_advance = Shaper::fixed_to_float((*pos_info_i).x_advance);
107 let y_advance = Shaper::fixed_to_float((*pos_info_i).y_advance);
108
109 let x_offset = Au::from_f64_px(x_offset);
110 let y_offset = Au::from_f64_px(y_offset);
111 let x_advance = Au::from_f64_px(x_advance);
112 let y_advance = Au::from_f64_px(y_advance);
113
114 let offset = if x_offset.is_zero() && y_offset.is_zero() && y_advance.is_zero() {
115 None
116 } else {
117 if y_advance > Au::zero() {
119 self.y_position -= y_advance;
120 }
121
122 Some(Point2D::new(x_offset, self.y_position - y_offset))
123 };
124
125 self.current_glyph_offset += 1;
126 Some(ShapedGlyph {
127 glyph_id: (*glyph_info_i).codepoint as GlyphId,
128 string_byte_offset: (*glyph_info_i).cluster as usize,
129 advance: x_advance,
130 offset,
131 })
132 }
133 }
134}
135
136impl GlyphShapingResult for HarfbuzzGlyphShapingResult {
137 #[inline]
138 fn len(&self) -> usize {
139 self.count
140 }
141
142 fn iter(&self) -> impl Iterator<Item = ShapedGlyph> {
143 ShapedGlyphIterator {
144 shaped_glyph_data: self,
145 current_glyph_offset: 0,
146 y_position: Au::zero(),
147 }
148 }
149
150 fn is_rtl(&self) -> bool {
151 unsafe {
152 let first_glyph_info = self.glyph_infos.add(0);
153 let last_glyph_info = self.glyph_infos.add(self.count - 1);
154 (*last_glyph_info).cluster < (*first_glyph_info).cluster
155 }
156 }
157}
158
159#[derive(Debug)]
160pub(crate) struct Shaper {
161 hb_face: *mut hb_face_t,
162 hb_font: *mut hb_font_t,
163 font: *const Font,
164}
165
166unsafe impl Sync for Shaper {}
170unsafe impl Send for Shaper {}
171
172impl Drop for Shaper {
173 fn drop(&mut self) {
174 unsafe {
175 assert!(!self.hb_face.is_null());
176 hb_face_destroy(self.hb_face);
177
178 assert!(!self.hb_font.is_null());
179 hb_font_destroy(self.hb_font);
180 }
181 }
182}
183
184impl Shaper {
185 pub(crate) fn new(font: &Font) -> Shaper {
186 unsafe {
187 let hb_face: *mut hb_face_t = hb_face_create_for_tables(
188 Some(font_table_func),
189 font as *const Font as *mut c_void,
190 None,
191 );
192 let hb_font: *mut hb_font_t = hb_font_create(hb_face);
193
194 let pt_size = font.descriptor.pt_size.to_f64_px();
196 hb_font_set_ppem(hb_font, pt_size as c_uint, pt_size as c_uint);
197
198 hb_font_set_scale(
200 hb_font,
201 Shaper::float_to_fixed(pt_size) as c_int,
202 Shaper::float_to_fixed(pt_size) as c_int,
203 );
204
205 hb_font_set_funcs(
207 hb_font,
208 HB_FONT_FUNCS.0,
209 font as *const Font as *mut c_void,
210 None,
211 );
212
213 if servo_config::pref!(layout_variable_fonts_enabled) {
214 let variations = &font.variations();
215 if !variations.is_empty() {
216 let variations: Vec<_> = variations
217 .iter()
218 .map(|variation| hb_variation_t {
219 tag: variation.tag,
220
221 value: variation.value,
222 })
223 .collect();
224
225 hb_font_set_variations(hb_font, variations.as_ptr(), variations.len() as u32);
226 }
227 }
228
229 Shaper {
230 hb_face,
231 hb_font,
232 font,
233 }
234 }
235 }
236
237 fn shaped_glyph_data(
239 &self,
240 text: &str,
241 options: &ShapingOptions,
242 ) -> HarfbuzzGlyphShapingResult {
243 unsafe {
244 let hb_buffer: *mut hb_buffer_t = hb_buffer_create();
245 hb_buffer_set_cluster_level(hb_buffer, HB_BUFFER_CLUSTER_LEVEL_MONOTONE_CHARACTERS);
246 hb_buffer_set_direction(
247 hb_buffer,
248 if options.flags.contains(ShapingFlags::RTL_FLAG) {
249 HB_DIRECTION_RTL
250 } else {
251 HB_DIRECTION_LTR
252 },
253 );
254
255 let script =
256 hb_script_from_iso15924_tag(unicode_script_to_iso15924_tag(options.script));
257 hb_buffer_set_script(hb_buffer, script);
258
259 hb_buffer_add_utf8(
260 hb_buffer,
261 text.as_ptr() as *const c_char,
262 text.len() as c_int,
263 0,
264 text.len() as c_int,
265 );
266
267 let mut features = Vec::new();
268 if options
269 .flags
270 .contains(ShapingFlags::IGNORE_LIGATURES_SHAPING_FLAG)
271 {
272 features.push(hb_feature_t {
273 tag: u32::from_be_bytes(LIGA.to_be_bytes()),
274 value: 0,
275 start: 0,
276 end: hb_buffer_get_length(hb_buffer),
277 })
278 }
279 if options
280 .flags
281 .contains(ShapingFlags::DISABLE_KERNING_SHAPING_FLAG)
282 {
283 features.push(hb_feature_t {
284 tag: u32::from_be_bytes(KERN.to_be_bytes()),
285 value: 0,
286 start: 0,
287 end: hb_buffer_get_length(hb_buffer),
288 })
289 }
290
291 hb_shape(
292 self.hb_font,
293 hb_buffer,
294 features.as_mut_ptr(),
295 features.len() as u32,
296 );
297
298 HarfbuzzGlyphShapingResult::new(hb_buffer)
299 }
300 }
301
302 pub(crate) fn shape_text(
303 &self,
304 font: &Font,
305 text: &str,
306 options: &ShapingOptions,
307 ) -> GlyphStore {
308 GlyphStore::with_shaped_glyph_data(
309 font,
310 text,
311 options,
312 &self.shaped_glyph_data(text, options),
313 )
314 }
315
316 pub(crate) fn baseline(&self) -> Option<FontBaseline> {
317 unsafe { (*self.font).table_for_tag(BASE)? };
318
319 let mut hanging_baseline = 0;
320 let mut alphabetic_baseline = 0;
321 let mut ideographic_baseline = 0;
322
323 unsafe {
324 hb_ot_layout_get_baseline(
325 self.hb_font,
326 HB_OT_LAYOUT_BASELINE_TAG_ROMAN,
327 HB_DIRECTION_LTR,
328 HB_OT_TAG_DEFAULT_SCRIPT,
329 HB_OT_TAG_DEFAULT_LANGUAGE,
330 &mut alphabetic_baseline as *mut _,
331 );
332
333 hb_ot_layout_get_baseline(
334 self.hb_font,
335 HB_OT_LAYOUT_BASELINE_TAG_HANGING,
336 HB_DIRECTION_LTR,
337 HB_OT_TAG_DEFAULT_SCRIPT,
338 HB_OT_TAG_DEFAULT_LANGUAGE,
339 &mut hanging_baseline as *mut _,
340 );
341
342 hb_ot_layout_get_baseline(
343 self.hb_font,
344 HB_OT_LAYOUT_BASELINE_TAG_IDEO_EMBOX_BOTTOM_OR_LEFT,
345 HB_DIRECTION_LTR,
346 HB_OT_TAG_DEFAULT_SCRIPT,
347 HB_OT_TAG_DEFAULT_LANGUAGE,
348 &mut ideographic_baseline as *mut _,
349 );
350 }
351
352 Some(FontBaseline {
353 ideographic_baseline: Shaper::fixed_to_float(ideographic_baseline) as f32,
354 alphabetic_baseline: Shaper::fixed_to_float(alphabetic_baseline) as f32,
355 hanging_baseline: Shaper::fixed_to_float(hanging_baseline) as f32,
356 })
357 }
358
359 fn float_to_fixed(f: f64) -> i32 {
360 float_to_fixed(16, f)
361 }
362
363 fn fixed_to_float(i: hb_position_t) -> f64 {
364 fixed_to_float(16, i)
365 }
366}
367
368struct FontFuncs(*mut hb_font_funcs_t);
370
371unsafe impl Sync for FontFuncs {}
372unsafe impl Send for FontFuncs {}
373
374static HB_FONT_FUNCS: LazyLock<FontFuncs> = LazyLock::new(|| unsafe {
375 let hb_funcs = hb_font_funcs_create();
376 hb_font_funcs_set_nominal_glyph_func(hb_funcs, Some(glyph_func), ptr::null_mut(), None);
377 hb_font_funcs_set_glyph_h_advance_func(
378 hb_funcs,
379 Some(glyph_h_advance_func),
380 ptr::null_mut(),
381 None,
382 );
383
384 FontFuncs(hb_funcs)
385});
386
387extern "C" fn glyph_func(
388 _: *mut hb_font_t,
389 font_data: *mut c_void,
390 unicode: hb_codepoint_t,
391 glyph: *mut hb_codepoint_t,
392 _: *mut c_void,
393) -> hb_bool_t {
394 let font: *const Font = font_data as *const Font;
395 assert!(!font.is_null());
396
397 match unsafe { (*font).glyph_index(char::from_u32(unicode).unwrap()) } {
398 Some(g) => {
399 unsafe { *glyph = g as hb_codepoint_t };
400 true as hb_bool_t
401 },
402 None => false as hb_bool_t,
403 }
404}
405
406extern "C" fn glyph_h_advance_func(
407 _: *mut hb_font_t,
408 font_data: *mut c_void,
409 glyph: hb_codepoint_t,
410 _: *mut c_void,
411) -> hb_position_t {
412 let font: *mut Font = font_data as *mut Font;
413 assert!(!font.is_null());
414
415 let advance = unsafe { (*font).glyph_h_advance(glyph as GlyphId) };
416 Shaper::float_to_fixed(advance)
417}
418
419extern "C" fn font_table_func(
421 _: *mut hb_face_t,
422 tag: hb_tag_t,
423 user_data: *mut c_void,
424) -> *mut hb_blob_t {
425 let font = user_data as *const Font;
427 assert!(!font.is_null());
428
429 let Some(font_table) = (unsafe { (*font).table_for_tag(Tag::from_u32(tag)) }) else {
431 return ptr::null_mut();
432 };
433
434 let font_table_ptr = Box::into_raw(Box::new(font_table));
438
439 let buf = unsafe { (*font_table_ptr).buffer() };
440 let blob = unsafe {
442 hb_blob_create(
443 buf.as_ptr() as *const c_char,
444 buf.len() as c_uint,
445 HB_MEMORY_MODE_READONLY,
446 font_table_ptr as *mut c_void,
447 Some(destroy_blob_func),
448 )
449 };
450
451 assert!(!blob.is_null());
452 blob
453}
454
455extern "C" fn destroy_blob_func(font_table_ptr: *mut c_void) {
456 unsafe {
457 drop(Box::from_raw(font_table_ptr as *mut FontTable));
458 }
459}