Skip to main content

fonts/shapers/
harfbuzz.rs

1/* This Source Code Form is subject to the terms of the Mozilla Public
2 * License, v. 2.0. If a copy of the MPL was not distributed with this
3 * file, You can obtain one at https://mozilla.org/MPL/2.0/. */
4
5#![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;
13// Eventually we would like the shaper to be pluggable, as many operating systems have their own
14// shapers. For now, however, HarfBuzz is a hard dependency.
15use 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_set_cluster_level,
21    hb_buffer_set_direction, hb_buffer_set_language, 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_create_sub_font, hb_font_destroy, hb_font_funcs_create,
24    hb_font_funcs_set_glyph_h_advance_func, hb_font_funcs_set_nominal_glyph_func, hb_font_funcs_t,
25    hb_font_set_funcs, hb_font_set_ppem, hb_font_set_scale, hb_font_set_variations, hb_font_t,
26    hb_glyph_info_t, hb_glyph_position_t, hb_language_from_string, hb_ot_layout_get_baseline,
27    hb_position_t, hb_script_from_iso15924_tag, hb_shape, hb_tag_t, 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, ShapedText, ShapingFlags, ShapingOptions,
36    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    /// Create a new [`ShapedGlyphData`] from the given HarfBuzz buffer.
51    ///
52    /// # Safety
53    ///
54    /// - Passing an invalid buffer pointer to this function results in undefined behavior.
55    /// - This function takes ownership of the buffer and the ShapedGlyphData destroys the buffer when dropped
56    ///   so the pointer must an owned pointer and must not be used after being passed to this function
57    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                // adjust the pen..
118                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        if self.count == 0 {
152            return false;
153        }
154        // SAFETY: We assume self.glyph_infos is a valid non-zero ptr
155        // to an array of self.count items. We checked self.count != 0
156        // and hence both calculated pointers are within the bounds.
157        unsafe {
158            let first_glyph_info = self.glyph_infos.add(0);
159            let last_glyph_info = self.glyph_infos.add(self.count - 1);
160            (*last_glyph_info).cluster < (*first_glyph_info).cluster
161        }
162    }
163}
164
165#[derive(Debug)]
166pub(crate) struct Shaper {
167    hb_face: *mut hb_face_t,
168    hb_font: *mut hb_font_t,
169    font: *const Font,
170}
171
172// The HarfBuzz API is thread safe as well as our `Font`, so we can make the data
173// structures here as thread-safe as well. This doesn't seem to be documented,
174// but was expressed as one of the original goals of the HarfBuzz API.
175unsafe impl Sync for Shaper {}
176unsafe impl Send for Shaper {}
177
178impl Drop for Shaper {
179    fn drop(&mut self) {
180        unsafe {
181            assert!(!self.hb_face.is_null());
182            hb_face_destroy(self.hb_face);
183
184            assert!(!self.hb_font.is_null());
185            hb_font_destroy(self.hb_font);
186        }
187    }
188}
189
190impl Shaper {
191    pub(crate) fn new(font: &Font) -> Shaper {
192        unsafe {
193            let hb_face: *mut hb_face_t = hb_face_create_for_tables(
194                Some(font_table_func),
195                font as *const Font as *mut c_void,
196                None,
197            );
198            let hb_font: *mut hb_font_t = hb_font_create(hb_face);
199
200            // Set points-per-em. if zero, performs no hinting in that direction.
201            let pt_size = font.descriptor.pt_size.to_f64_px();
202            hb_font_set_ppem(hb_font, pt_size as c_uint, pt_size as c_uint);
203
204            // Set scaling. Note that this takes 16.16 fixed point.
205            hb_font_set_scale(
206                hb_font,
207                Shaper::float_to_fixed(pt_size) as c_int,
208                Shaper::float_to_fixed(pt_size) as c_int,
209            );
210
211            if servo_config::pref!(layout_variable_fonts_enabled) {
212                let variations = &font.variations();
213                if !variations.is_empty() {
214                    let variations: Vec<_> = variations
215                        .iter()
216                        .map(|variation| hb_variation_t {
217                            tag: variation.tag,
218
219                            value: variation.value,
220                        })
221                        .collect();
222
223                    hb_font_set_variations(hb_font, variations.as_ptr(), variations.len() as u32);
224                }
225            }
226
227            // Create a subfont before setting font-funcs so that we can
228            // inherit the default font-funcs for the funcs we don't set.
229            let hb_font = {
230                let sub_font = hb_font_create_sub_font(hb_font);
231                hb_font_destroy(hb_font);
232                sub_font
233            };
234
235            // Now configure the subset of function callbacks that we do implement.
236            hb_font_set_funcs(
237                hb_font,
238                HB_FONT_FUNCS.0,
239                font as *const Font as *mut c_void,
240                None,
241            );
242
243            Shaper {
244                hb_face,
245                hb_font,
246                font,
247            }
248        }
249    }
250
251    /// Calculate the layout metrics associated with the given text with the [`Shaper`]s font.
252    fn shaped_glyph_data(
253        &self,
254        text: &str,
255        options: &ShapingOptions,
256        font_features: &[(Tag, u32)],
257    ) -> HarfbuzzGlyphShapingResult {
258        unsafe {
259            let hb_buffer: *mut hb_buffer_t = hb_buffer_create();
260            hb_buffer_set_cluster_level(hb_buffer, HB_BUFFER_CLUSTER_LEVEL_MONOTONE_CHARACTERS);
261            hb_buffer_set_direction(
262                hb_buffer,
263                if options.flags.contains(ShapingFlags::RTL_FLAG) {
264                    HB_DIRECTION_RTL
265                } else {
266                    HB_DIRECTION_LTR
267                },
268            );
269
270            let script =
271                hb_script_from_iso15924_tag(unicode_script_to_iso15924_tag(options.script));
272            hb_buffer_set_script(hb_buffer, script);
273
274            hb_buffer_add_utf8(
275                hb_buffer,
276                text.as_ptr() as *const c_char,
277                text.len() as c_int,
278                0,
279                text.len() as c_int,
280            );
281
282            let language = options.language;
283            let hb_language = hb_language_from_string(
284                language.as_str().as_ptr() as *const c_char,
285                language.as_str().len() as c_int,
286            );
287            hb_buffer_set_language(hb_buffer, hb_language);
288
289            let mut features: Vec<_> = font_features
290                .iter()
291                .map(|(tag, value)| hb_feature_t {
292                    tag: u32::from_be_bytes(tag.to_be_bytes()),
293                    value: *value,
294                    start: 0,      // HB_FEATURE_GLOBAL_START
295                    end: u32::MAX, // HB_FEATURE_GLOBAL_END
296                })
297                .collect();
298            hb_shape(
299                self.hb_font,
300                hb_buffer,
301                features.as_mut_ptr(),
302                features.len() as u32,
303            );
304
305            HarfbuzzGlyphShapingResult::new(hb_buffer)
306        }
307    }
308
309    pub(crate) fn shape_text(
310        &self,
311        text: &str,
312        options: &ShapingOptions,
313        font_features: &[(Tag, u32)],
314    ) -> ShapedText {
315        ShapedText::with_shaped_glyph_data(
316            text,
317            options,
318            &self.shaped_glyph_data(text, options, font_features),
319        )
320    }
321
322    pub(crate) fn baseline(&self) -> Option<FontBaseline> {
323        unsafe { (*self.font).table_for_tag(BASE)? };
324
325        let mut hanging_baseline = 0;
326        let mut alphabetic_baseline = 0;
327        let mut ideographic_baseline = 0;
328
329        unsafe {
330            hb_ot_layout_get_baseline(
331                self.hb_font,
332                HB_OT_LAYOUT_BASELINE_TAG_ROMAN,
333                HB_DIRECTION_LTR,
334                HB_OT_TAG_DEFAULT_SCRIPT,
335                HB_OT_TAG_DEFAULT_LANGUAGE,
336                &mut alphabetic_baseline as *mut _,
337            );
338
339            hb_ot_layout_get_baseline(
340                self.hb_font,
341                HB_OT_LAYOUT_BASELINE_TAG_HANGING,
342                HB_DIRECTION_LTR,
343                HB_OT_TAG_DEFAULT_SCRIPT,
344                HB_OT_TAG_DEFAULT_LANGUAGE,
345                &mut hanging_baseline as *mut _,
346            );
347
348            hb_ot_layout_get_baseline(
349                self.hb_font,
350                HB_OT_LAYOUT_BASELINE_TAG_IDEO_EMBOX_BOTTOM_OR_LEFT,
351                HB_DIRECTION_LTR,
352                HB_OT_TAG_DEFAULT_SCRIPT,
353                HB_OT_TAG_DEFAULT_LANGUAGE,
354                &mut ideographic_baseline as *mut _,
355            );
356        }
357
358        Some(FontBaseline {
359            ideographic_baseline: Shaper::fixed_to_float(ideographic_baseline) as f32,
360            alphabetic_baseline: Shaper::fixed_to_float(alphabetic_baseline) as f32,
361            hanging_baseline: Shaper::fixed_to_float(hanging_baseline) as f32,
362        })
363    }
364
365    fn float_to_fixed(f: f64) -> i32 {
366        float_to_fixed(16, f)
367    }
368
369    fn fixed_to_float(i: hb_position_t) -> f64 {
370        fixed_to_float(16, i)
371    }
372}
373
374/// Callbacks from Harfbuzz when font map and glyph advance lookup needed.
375struct FontFuncs(*mut hb_font_funcs_t);
376
377unsafe impl Sync for FontFuncs {}
378unsafe impl Send for FontFuncs {}
379
380static HB_FONT_FUNCS: LazyLock<FontFuncs> = LazyLock::new(|| unsafe {
381    let hb_funcs = hb_font_funcs_create();
382    hb_font_funcs_set_nominal_glyph_func(hb_funcs, Some(glyph_func), ptr::null_mut(), None);
383    hb_font_funcs_set_glyph_h_advance_func(
384        hb_funcs,
385        Some(glyph_h_advance_func),
386        ptr::null_mut(),
387        None,
388    );
389
390    FontFuncs(hb_funcs)
391});
392
393extern "C" fn glyph_func(
394    _: *mut hb_font_t,
395    font_data: *mut c_void,
396    unicode: hb_codepoint_t,
397    glyph: *mut hb_codepoint_t,
398    _: *mut c_void,
399) -> hb_bool_t {
400    let font: *const Font = font_data as *const Font;
401    assert!(!font.is_null());
402
403    match unsafe { (*font).glyph_index(char::from_u32(unicode).unwrap()) } {
404        Some(g) => {
405            unsafe { *glyph = g as hb_codepoint_t };
406            true as hb_bool_t
407        },
408        None => false as hb_bool_t,
409    }
410}
411
412extern "C" fn glyph_h_advance_func(
413    _: *mut hb_font_t,
414    font_data: *mut c_void,
415    glyph: hb_codepoint_t,
416    _: *mut c_void,
417) -> hb_position_t {
418    let font: *mut Font = font_data as *mut Font;
419    assert!(!font.is_null());
420
421    let advance = unsafe { (*font).glyph_h_advance(glyph as GlyphId) };
422    Shaper::float_to_fixed(advance)
423}
424
425/// Callback to get a font table out of a font.
426extern "C" fn font_table_func(
427    _: *mut hb_face_t,
428    tag: hb_tag_t,
429    user_data: *mut c_void,
430) -> *mut hb_blob_t {
431    // NB: These asserts have security implications.
432    let font = user_data as *const Font;
433    assert!(!font.is_null());
434
435    // TODO(Issue #197): reuse font table data, which will change the unsound trickery here.
436    let Some(font_table) = (unsafe { (*font).table_for_tag(Tag::from_u32(tag)) }) else {
437        return ptr::null_mut();
438    };
439
440    // `Box::into_raw` intentionally leaks the FontTable so we don't destroy the buffer
441    // while HarfBuzz is using it.  When HarfBuzz is done with the buffer, it will pass
442    // this raw pointer back to `destroy_blob_func` which will deallocate the Box.
443    let font_table_ptr = Box::into_raw(Box::new(font_table));
444
445    let buf = unsafe { (*font_table_ptr).buffer() };
446    // HarfBuzz calls `destroy_blob_func` when the buffer is no longer needed.
447    let blob = unsafe {
448        hb_blob_create(
449            buf.as_ptr() as *const c_char,
450            buf.len() as c_uint,
451            HB_MEMORY_MODE_READONLY,
452            font_table_ptr as *mut c_void,
453            Some(destroy_blob_func),
454        )
455    };
456
457    assert!(!blob.is_null());
458    blob
459}
460
461extern "C" fn destroy_blob_func(font_table_ptr: *mut c_void) {
462    unsafe {
463        drop(Box::from_raw(font_table_ptr as *mut FontTable));
464    }
465}