text_system.rs

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