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