text_system.rs

  1use crate::{
  2    point, px, size, Bounds, DevicePixels, Font, FontFeatures, FontId, FontMetrics, FontRun,
  3    FontStyle, FontWeight, GlyphId, LineLayout, Pixels, PlatformTextSystem, Point,
  4    RenderGlyphParams, Result, ShapedGlyph, ShapedRun, SharedString, Size, SUBPIXEL_VARIANTS,
  5};
  6use anyhow::anyhow;
  7use cocoa::appkit::{CGFloat, CGPoint};
  8use collections::{BTreeSet, HashMap};
  9use core_foundation::{
 10    array::CFIndex,
 11    attributed_string::{CFAttributedStringRef, CFMutableAttributedString},
 12    base::{CFRange, TCFType},
 13    string::CFString,
 14};
 15use core_graphics::{
 16    base::{kCGImageAlphaPremultipliedLast, CGGlyph},
 17    color_space::CGColorSpace,
 18    context::CGContext,
 19};
 20use core_text::{font::CTFont, line::CTLine, string_attributes::kCTFontAttributeName};
 21use font_kit::{
 22    font::Font as FontKitFont,
 23    handle::Handle,
 24    hinting::HintingOptions,
 25    metrics::Metrics,
 26    properties::{Style as FontkitStyle, Weight as FontkitWeight},
 27    source::SystemSource,
 28    sources::mem::MemSource,
 29};
 30use parking_lot::{RwLock, RwLockUpgradableReadGuard};
 31use pathfinder_geometry::{
 32    rect::{RectF, RectI},
 33    transform2d::Transform2F,
 34    vector::{Vector2F, Vector2I},
 35};
 36use smallvec::SmallVec;
 37use std::{char, cmp, convert::TryFrom, ffi::c_void, sync::Arc};
 38
 39use super::open_type;
 40
 41#[allow(non_upper_case_globals)]
 42const kCGImageAlphaOnly: u32 = 7;
 43
 44pub(crate) struct MacTextSystem(RwLock<MacTextSystemState>);
 45
 46struct MacTextSystemState {
 47    memory_source: MemSource,
 48    system_source: SystemSource,
 49    fonts: Vec<FontKitFont>,
 50    font_selections: HashMap<Font, FontId>,
 51    font_ids_by_postscript_name: HashMap<String, FontId>,
 52    font_ids_by_family_name: HashMap<SharedString, SmallVec<[FontId; 4]>>,
 53    postscript_names_by_font_id: HashMap<FontId, String>,
 54}
 55
 56impl MacTextSystem {
 57    pub(crate) fn new() -> Self {
 58        Self(RwLock::new(MacTextSystemState {
 59            memory_source: MemSource::empty(),
 60            system_source: SystemSource::new(),
 61            fonts: Vec::new(),
 62            font_selections: HashMap::default(),
 63            font_ids_by_postscript_name: HashMap::default(),
 64            font_ids_by_family_name: HashMap::default(),
 65            postscript_names_by_font_id: HashMap::default(),
 66        }))
 67    }
 68}
 69
 70impl Default for MacTextSystem {
 71    fn default() -> Self {
 72        Self::new()
 73    }
 74}
 75
 76impl PlatformTextSystem for MacTextSystem {
 77    fn add_fonts(&self, fonts: &[Arc<Vec<u8>>]) -> Result<()> {
 78        self.0.write().add_fonts(fonts)
 79    }
 80
 81    fn all_font_names(&self) -> Vec<String> {
 82        let collection = core_text::font_collection::create_for_all_families();
 83        let Some(descriptors) = collection.get_descriptors() else {
 84            return Vec::new();
 85        };
 86        let mut names = BTreeSet::new();
 87        for descriptor in descriptors.into_iter() {
 88            names.extend(lenient_font_attributes::family_name(&descriptor));
 89        }
 90        if let Ok(fonts_in_memory) = self.0.read().memory_source.all_families() {
 91            names.extend(fonts_in_memory);
 92        }
 93        names.into_iter().collect()
 94    }
 95
 96    fn all_font_families(&self) -> Vec<String> {
 97        self.0
 98            .read()
 99            .system_source
100            .all_families()
101            .expect("core text should never return an error")
102    }
103
104    fn font_id(&self, font: &Font) -> Result<FontId> {
105        let lock = self.0.upgradable_read();
106        if let Some(font_id) = lock.font_selections.get(font) {
107            Ok(*font_id)
108        } else {
109            let mut lock = RwLockUpgradableReadGuard::upgrade(lock);
110            let candidates = if let Some(font_ids) = lock.font_ids_by_family_name.get(&font.family)
111            {
112                font_ids.as_slice()
113            } else {
114                let font_ids = lock.load_family(&font.family, font.features)?;
115                lock.font_ids_by_family_name
116                    .insert(font.family.clone(), font_ids);
117                lock.font_ids_by_family_name[&font.family].as_ref()
118            };
119
120            let candidate_properties = candidates
121                .iter()
122                .map(|font_id| lock.fonts[font_id.0].properties())
123                .collect::<SmallVec<[_; 4]>>();
124
125            let ix = font_kit::matching::find_best_match(
126                &candidate_properties,
127                &font_kit::properties::Properties {
128                    style: font.style.into(),
129                    weight: font.weight.into(),
130                    stretch: Default::default(),
131                },
132            )?;
133
134            let font_id = candidates[ix];
135            lock.font_selections.insert(font.clone(), font_id);
136            Ok(font_id)
137        }
138    }
139
140    fn font_metrics(&self, font_id: FontId) -> FontMetrics {
141        self.0.read().fonts[font_id.0].metrics().into()
142    }
143
144    fn typographic_bounds(&self, font_id: FontId, glyph_id: GlyphId) -> Result<Bounds<f32>> {
145        Ok(self.0.read().fonts[font_id.0]
146            .typographic_bounds(glyph_id.0)?
147            .into())
148    }
149
150    fn advance(&self, font_id: FontId, glyph_id: GlyphId) -> Result<Size<f32>> {
151        self.0.read().advance(font_id, glyph_id)
152    }
153
154    fn glyph_for_char(&self, font_id: FontId, ch: char) -> Option<GlyphId> {
155        self.0.read().glyph_for_char(font_id, ch)
156    }
157
158    fn glyph_raster_bounds(&self, params: &RenderGlyphParams) -> Result<Bounds<DevicePixels>> {
159        self.0.read().raster_bounds(params)
160    }
161
162    fn rasterize_glyph(
163        &self,
164        glyph_id: &RenderGlyphParams,
165        raster_bounds: Bounds<DevicePixels>,
166    ) -> Result<(Size<DevicePixels>, Vec<u8>)> {
167        self.0.read().rasterize_glyph(glyph_id, raster_bounds)
168    }
169
170    fn layout_line(&self, text: &str, font_size: Pixels, font_runs: &[FontRun]) -> LineLayout {
171        self.0.write().layout_line(text, font_size, font_runs)
172    }
173
174    fn wrap_line(
175        &self,
176        text: &str,
177        font_id: FontId,
178        font_size: Pixels,
179        width: Pixels,
180    ) -> Vec<usize> {
181        self.0.read().wrap_line(text, font_id, font_size, width)
182    }
183}
184
185impl MacTextSystemState {
186    fn add_fonts(&mut self, fonts: &[Arc<Vec<u8>>]) -> Result<()> {
187        self.memory_source.add_fonts(
188            fonts
189                .iter()
190                .map(|bytes| Handle::from_memory(bytes.clone(), 0)),
191        )?;
192        Ok(())
193    }
194
195    fn load_family(
196        &mut self,
197        name: &SharedString,
198        features: FontFeatures,
199    ) -> Result<SmallVec<[FontId; 4]>> {
200        let mut font_ids = SmallVec::new();
201        let family = self
202            .memory_source
203            .select_family_by_name(name.as_ref())
204            .or_else(|_| self.system_source.select_family_by_name(name.as_ref()))?;
205        for font in family.fonts() {
206            let mut font = font.load()?;
207            open_type::apply_features(&mut font, features);
208            let Some(_) = font.glyph_for_char('m') else {
209                continue;
210            };
211            let font_id = FontId(self.fonts.len());
212            font_ids.push(font_id);
213            let postscript_name = font.postscript_name().unwrap();
214            self.font_ids_by_postscript_name
215                .insert(postscript_name.clone(), font_id);
216            self.postscript_names_by_font_id
217                .insert(font_id, postscript_name);
218            self.fonts.push(font);
219        }
220        Ok(font_ids)
221    }
222
223    fn advance(&self, font_id: FontId, glyph_id: GlyphId) -> Result<Size<f32>> {
224        Ok(self.fonts[font_id.0].advance(glyph_id.0)?.into())
225    }
226
227    fn glyph_for_char(&self, font_id: FontId, ch: char) -> Option<GlyphId> {
228        self.fonts[font_id.0].glyph_for_char(ch).map(GlyphId)
229    }
230
231    fn id_for_native_font(&mut self, requested_font: CTFont) -> FontId {
232        let postscript_name = requested_font.postscript_name();
233        if let Some(font_id) = self.font_ids_by_postscript_name.get(&postscript_name) {
234            *font_id
235        } else {
236            let font_id = FontId(self.fonts.len());
237            self.font_ids_by_postscript_name
238                .insert(postscript_name.clone(), font_id);
239            self.postscript_names_by_font_id
240                .insert(font_id, postscript_name);
241            self.fonts
242                .push(font_kit::font::Font::from_core_graphics_font(
243                    requested_font.copy_to_CGFont(),
244                ));
245            font_id
246        }
247    }
248
249    fn is_emoji(&self, font_id: FontId) -> bool {
250        self.postscript_names_by_font_id
251            .get(&font_id)
252            .map_or(false, |postscript_name| {
253                postscript_name == "AppleColorEmoji"
254            })
255    }
256
257    fn raster_bounds(&self, params: &RenderGlyphParams) -> Result<Bounds<DevicePixels>> {
258        let font = &self.fonts[params.font_id.0];
259        let scale = Transform2F::from_scale(params.scale_factor);
260        Ok(font
261            .raster_bounds(
262                params.glyph_id.0,
263                params.font_size.into(),
264                scale,
265                HintingOptions::None,
266                font_kit::canvas::RasterizationOptions::GrayscaleAa,
267            )?
268            .into())
269    }
270
271    fn rasterize_glyph(
272        &self,
273        params: &RenderGlyphParams,
274        glyph_bounds: Bounds<DevicePixels>,
275    ) -> Result<(Size<DevicePixels>, Vec<u8>)> {
276        if glyph_bounds.size.width.0 == 0 || glyph_bounds.size.height.0 == 0 {
277            Err(anyhow!("glyph bounds are empty"))
278        } else {
279            // Add an extra pixel when the subpixel variant isn't zero to make room for anti-aliasing.
280            let mut bitmap_size = glyph_bounds.size;
281            if params.subpixel_variant.x > 0 {
282                bitmap_size.width += DevicePixels(1);
283            }
284            if params.subpixel_variant.y > 0 {
285                bitmap_size.height += DevicePixels(1);
286            }
287            let bitmap_size = bitmap_size;
288
289            let mut bytes;
290            let cx;
291            if params.is_emoji {
292                bytes = vec![0; bitmap_size.width.0 as usize * 4 * bitmap_size.height.0 as usize];
293                cx = CGContext::create_bitmap_context(
294                    Some(bytes.as_mut_ptr() as *mut _),
295                    bitmap_size.width.0 as usize,
296                    bitmap_size.height.0 as usize,
297                    8,
298                    bitmap_size.width.0 as usize * 4,
299                    &CGColorSpace::create_device_rgb(),
300                    kCGImageAlphaPremultipliedLast,
301                );
302            } else {
303                bytes = vec![0; bitmap_size.width.0 as usize * bitmap_size.height.0 as usize];
304                cx = CGContext::create_bitmap_context(
305                    Some(bytes.as_mut_ptr() as *mut _),
306                    bitmap_size.width.0 as usize,
307                    bitmap_size.height.0 as usize,
308                    8,
309                    bitmap_size.width.0 as usize,
310                    &CGColorSpace::create_device_gray(),
311                    kCGImageAlphaOnly,
312                );
313            }
314
315            // Move the origin to bottom left and account for scaling, this
316            // makes drawing text consistent with the font-kit's raster_bounds.
317            cx.translate(
318                -glyph_bounds.origin.x.0 as CGFloat,
319                (glyph_bounds.origin.y.0 + glyph_bounds.size.height.0) as CGFloat,
320            );
321            cx.scale(
322                params.scale_factor as CGFloat,
323                params.scale_factor as CGFloat,
324            );
325
326            let subpixel_shift = params
327                .subpixel_variant
328                .map(|v| v as f32 / SUBPIXEL_VARIANTS as f32);
329            cx.set_allows_font_subpixel_positioning(true);
330            cx.set_should_subpixel_position_fonts(true);
331            cx.set_allows_font_subpixel_quantization(false);
332            cx.set_should_subpixel_quantize_fonts(false);
333            self.fonts[params.font_id.0]
334                .native_font()
335                .clone_with_font_size(f32::from(params.font_size) as CGFloat)
336                .draw_glyphs(
337                    &[params.glyph_id.0 as CGGlyph],
338                    &[CGPoint::new(
339                        (subpixel_shift.x / params.scale_factor) as CGFloat,
340                        (subpixel_shift.y / params.scale_factor) as CGFloat,
341                    )],
342                    cx,
343                );
344
345            if params.is_emoji {
346                // Convert from RGBA with premultiplied alpha to BGRA with straight alpha.
347                for pixel in bytes.chunks_exact_mut(4) {
348                    pixel.swap(0, 2);
349                    let a = pixel[3] as f32 / 255.;
350                    pixel[0] = (pixel[0] as f32 / a) as u8;
351                    pixel[1] = (pixel[1] as f32 / a) as u8;
352                    pixel[2] = (pixel[2] as f32 / a) as u8;
353                }
354            }
355
356            Ok((bitmap_size, bytes))
357        }
358    }
359
360    fn layout_line(&mut self, text: &str, font_size: Pixels, font_runs: &[FontRun]) -> LineLayout {
361        // Construct the attributed string, converting UTF8 ranges to UTF16 ranges.
362        let mut string = CFMutableAttributedString::new();
363        {
364            string.replace_str(&CFString::new(text), CFRange::init(0, 0));
365            let utf16_line_len = string.char_len() as usize;
366
367            let mut ix_converter = StringIndexConverter::new(text);
368            for run in font_runs {
369                let utf8_end = ix_converter.utf8_ix + run.len;
370                let utf16_start = ix_converter.utf16_ix;
371
372                if utf16_start >= utf16_line_len {
373                    break;
374                }
375
376                ix_converter.advance_to_utf8_ix(utf8_end);
377                let utf16_end = cmp::min(ix_converter.utf16_ix, utf16_line_len);
378
379                let cf_range =
380                    CFRange::init(utf16_start as isize, (utf16_end - utf16_start) as isize);
381
382                let font: &FontKitFont = &self.fonts[run.font_id.0];
383                unsafe {
384                    string.set_attribute(
385                        cf_range,
386                        kCTFontAttributeName,
387                        &font.native_font().clone_with_font_size(font_size.into()),
388                    );
389                }
390
391                if utf16_end == utf16_line_len {
392                    break;
393                }
394            }
395        }
396
397        // Retrieve the glyphs from the shaped line, converting UTF16 offsets to UTF8 offsets.
398        let line = CTLine::new_with_attributed_string(string.as_concrete_TypeRef());
399
400        let mut runs = Vec::new();
401        for run in line.glyph_runs().into_iter() {
402            let attributes = run.attributes().unwrap();
403            let font = unsafe {
404                attributes
405                    .get(kCTFontAttributeName)
406                    .downcast::<CTFont>()
407                    .unwrap()
408            };
409            let font_id = self.id_for_native_font(font);
410
411            let mut ix_converter = StringIndexConverter::new(text);
412            let mut glyphs = SmallVec::new();
413            for ((glyph_id, position), glyph_utf16_ix) in run
414                .glyphs()
415                .iter()
416                .zip(run.positions().iter())
417                .zip(run.string_indices().iter())
418            {
419                let glyph_utf16_ix = usize::try_from(*glyph_utf16_ix).unwrap();
420                ix_converter.advance_to_utf16_ix(glyph_utf16_ix);
421                glyphs.push(ShapedGlyph {
422                    id: GlyphId(*glyph_id as u32),
423                    position: point(position.x as f32, position.y as f32).map(px),
424                    index: ix_converter.utf8_ix,
425                    is_emoji: self.is_emoji(font_id),
426                });
427            }
428
429            runs.push(ShapedRun { font_id, glyphs })
430        }
431
432        let typographic_bounds = line.get_typographic_bounds();
433        LineLayout {
434            runs,
435            font_size,
436            width: typographic_bounds.width.into(),
437            ascent: typographic_bounds.ascent.into(),
438            descent: typographic_bounds.descent.into(),
439            len: text.len(),
440        }
441    }
442
443    fn wrap_line(
444        &self,
445        text: &str,
446        font_id: FontId,
447        font_size: Pixels,
448        width: Pixels,
449    ) -> Vec<usize> {
450        let mut string = CFMutableAttributedString::new();
451        string.replace_str(&CFString::new(text), CFRange::init(0, 0));
452        let cf_range = CFRange::init(0, text.encode_utf16().count() as isize);
453        let font = &self.fonts[font_id.0];
454        unsafe {
455            string.set_attribute(
456                cf_range,
457                kCTFontAttributeName,
458                &font.native_font().clone_with_font_size(font_size.into()),
459            );
460
461            let typesetter = CTTypesetterCreateWithAttributedString(string.as_concrete_TypeRef());
462            let mut ix_converter = StringIndexConverter::new(text);
463            let mut break_indices = Vec::new();
464            while ix_converter.utf8_ix < text.len() {
465                let utf16_len = CTTypesetterSuggestLineBreak(
466                    typesetter,
467                    ix_converter.utf16_ix as isize,
468                    width.into(),
469                ) as usize;
470                ix_converter.advance_to_utf16_ix(ix_converter.utf16_ix + utf16_len);
471                if ix_converter.utf8_ix >= text.len() {
472                    break;
473                }
474                break_indices.push(ix_converter.utf8_ix);
475            }
476            break_indices
477        }
478    }
479}
480
481#[derive(Clone)]
482struct StringIndexConverter<'a> {
483    text: &'a str,
484    utf8_ix: usize,
485    utf16_ix: usize,
486}
487
488impl<'a> StringIndexConverter<'a> {
489    fn new(text: &'a str) -> Self {
490        Self {
491            text,
492            utf8_ix: 0,
493            utf16_ix: 0,
494        }
495    }
496
497    fn advance_to_utf8_ix(&mut self, utf8_target: usize) {
498        for (ix, c) in self.text[self.utf8_ix..].char_indices() {
499            if self.utf8_ix + ix >= utf8_target {
500                self.utf8_ix += ix;
501                return;
502            }
503            self.utf16_ix += c.len_utf16();
504        }
505        self.utf8_ix = self.text.len();
506    }
507
508    fn advance_to_utf16_ix(&mut self, utf16_target: usize) {
509        for (ix, c) in self.text[self.utf8_ix..].char_indices() {
510            if self.utf16_ix >= utf16_target {
511                self.utf8_ix += ix;
512                return;
513            }
514            self.utf16_ix += c.len_utf16();
515        }
516        self.utf8_ix = self.text.len();
517    }
518}
519
520#[repr(C)]
521pub(crate) struct __CFTypesetter(c_void);
522
523type CTTypesetterRef = *const __CFTypesetter;
524
525#[link(name = "CoreText", kind = "framework")]
526extern "C" {
527    fn CTTypesetterCreateWithAttributedString(string: CFAttributedStringRef) -> CTTypesetterRef;
528
529    fn CTTypesetterSuggestLineBreak(
530        typesetter: CTTypesetterRef,
531        start_index: CFIndex,
532        width: f64,
533    ) -> CFIndex;
534}
535
536impl From<Metrics> for FontMetrics {
537    fn from(metrics: Metrics) -> Self {
538        FontMetrics {
539            units_per_em: metrics.units_per_em,
540            ascent: metrics.ascent,
541            descent: metrics.descent,
542            line_gap: metrics.line_gap,
543            underline_position: metrics.underline_position,
544            underline_thickness: metrics.underline_thickness,
545            cap_height: metrics.cap_height,
546            x_height: metrics.x_height,
547            bounding_box: metrics.bounding_box.into(),
548        }
549    }
550}
551
552impl From<RectF> for Bounds<f32> {
553    fn from(rect: RectF) -> Self {
554        Bounds {
555            origin: point(rect.origin_x(), rect.origin_y()),
556            size: size(rect.width(), rect.height()),
557        }
558    }
559}
560
561impl From<RectI> for Bounds<DevicePixels> {
562    fn from(rect: RectI) -> Self {
563        Bounds {
564            origin: point(DevicePixels(rect.origin_x()), DevicePixels(rect.origin_y())),
565            size: size(DevicePixels(rect.width()), DevicePixels(rect.height())),
566        }
567    }
568}
569
570impl From<Vector2I> for Size<DevicePixels> {
571    fn from(value: Vector2I) -> Self {
572        size(value.x().into(), value.y().into())
573    }
574}
575
576impl From<RectI> for Bounds<i32> {
577    fn from(rect: RectI) -> Self {
578        Bounds {
579            origin: point(rect.origin_x(), rect.origin_y()),
580            size: size(rect.width(), rect.height()),
581        }
582    }
583}
584
585impl From<Point<u32>> for Vector2I {
586    fn from(size: Point<u32>) -> Self {
587        Vector2I::new(size.x as i32, size.y as i32)
588    }
589}
590
591impl From<Vector2F> for Size<f32> {
592    fn from(vec: Vector2F) -> Self {
593        size(vec.x(), vec.y())
594    }
595}
596
597impl From<FontWeight> for FontkitWeight {
598    fn from(value: FontWeight) -> Self {
599        FontkitWeight(value.0)
600    }
601}
602
603impl From<FontStyle> for FontkitStyle {
604    fn from(style: FontStyle) -> Self {
605        match style {
606            FontStyle::Normal => FontkitStyle::Normal,
607            FontStyle::Italic => FontkitStyle::Italic,
608            FontStyle::Oblique => FontkitStyle::Oblique,
609        }
610    }
611}
612
613// Some fonts may have no attributest despite `core_text` requiring them (and panicking).
614// This is the same version as `core_text` has without `expect` calls.
615mod lenient_font_attributes {
616    use core_foundation::{
617        base::{CFRetain, CFType, TCFType},
618        string::{CFString, CFStringRef},
619    };
620    use core_text::font_descriptor::{
621        kCTFontFamilyNameAttribute, CTFontDescriptor, CTFontDescriptorCopyAttribute,
622    };
623
624    pub fn family_name(descriptor: &CTFontDescriptor) -> Option<String> {
625        unsafe { get_string_attribute(descriptor, kCTFontFamilyNameAttribute) }
626    }
627
628    fn get_string_attribute(
629        descriptor: &CTFontDescriptor,
630        attribute: CFStringRef,
631    ) -> Option<String> {
632        unsafe {
633            let value = CTFontDescriptorCopyAttribute(descriptor.as_concrete_TypeRef(), attribute);
634            if value.is_null() {
635                return None;
636            }
637
638            let value = CFType::wrap_under_create_rule(value);
639            assert!(value.instance_of::<CFString>());
640            let s = wrap_under_get_rule(value.as_CFTypeRef() as CFStringRef);
641            Some(s.to_string())
642        }
643    }
644
645    unsafe fn wrap_under_get_rule(reference: CFStringRef) -> CFString {
646        assert!(!reference.is_null(), "Attempted to create a NULL object.");
647        let reference = CFRetain(reference as *const ::std::os::raw::c_void) as CFStringRef;
648        TCFType::wrap_under_create_rule(reference)
649    }
650}
651
652#[cfg(test)]
653mod tests {
654    use crate::{font, px, FontRun, GlyphId, MacTextSystem, PlatformTextSystem};
655
656    #[test]
657    fn test_wrap_line() {
658        let fonts = MacTextSystem::new();
659        let font_id = fonts.font_id(&font("Helvetica")).unwrap();
660
661        let line = "one two three four five\n";
662        let wrap_boundaries = fonts.wrap_line(line, font_id, px(16.), px(64.0));
663        assert_eq!(wrap_boundaries, &["one two ".len(), "one two three ".len()]);
664
665        let line = "aaa ααα ✋✋✋ 🎉🎉🎉\n";
666        let wrap_boundaries = fonts.wrap_line(line, font_id, px(16.), px(64.0));
667        assert_eq!(
668            wrap_boundaries,
669            &["aaa ααα ".len(), "aaa ααα ✋✋✋ ".len(),]
670        );
671    }
672
673    #[test]
674    fn test_layout_line_bom_char() {
675        let fonts = MacTextSystem::new();
676        let font_id = fonts.font_id(&font("Helvetica")).unwrap();
677        let line = "\u{feff}";
678        let mut style = FontRun {
679            font_id,
680            len: line.len(),
681        };
682
683        let layout = fonts.layout_line(line, px(16.), &[style]);
684        assert_eq!(layout.len, line.len());
685        assert!(layout.runs.is_empty());
686
687        let line = "a\u{feff}b";
688        style.len = line.len();
689        let layout = fonts.layout_line(line, px(16.), &[style]);
690        assert_eq!(layout.len, line.len());
691        assert_eq!(layout.runs.len(), 1);
692        assert_eq!(layout.runs[0].glyphs.len(), 2);
693        assert_eq!(layout.runs[0].glyphs[0].id, GlyphId(68u32)); // a
694                                                                 // There's no glyph for \u{feff}
695        assert_eq!(layout.runs[0].glyphs[1].id, GlyphId(69u32)); // b
696    }
697}