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