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
227            open_type::apply_features(&mut font, features);
228            let Some(_) = font.glyph_for_char('m') else {
229                continue;
230            };
231            // We've seen a number of panics in production caused by calling font.properties()
232            // which unwraps a downcast to CFNumber. This is an attempt to avoid the panic,
233            // and to try and identify the incalcitrant font.
234            let traits = font.native_font().all_traits();
235            if unsafe {
236                !(traits
237                    .get(kCTFontSymbolicTrait)
238                    .downcast::<CFNumber>()
239                    .is_some()
240                    && traits
241                        .get(kCTFontWidthTrait)
242                        .downcast::<CFNumber>()
243                        .is_some()
244                    && traits
245                        .get(kCTFontWeightTrait)
246                        .downcast::<CFNumber>()
247                        .is_some()
248                    && traits
249                        .get(kCTFontSlantTrait)
250                        .downcast::<CFNumber>()
251                        .is_some())
252            } {
253                log::error!(
254                    "Failed to read traits for font {:?}",
255                    font.postscript_name().unwrap()
256                );
257                continue;
258            }
259
260            let font_id = FontId(self.fonts.len());
261            font_ids.push(font_id);
262            let postscript_name = font.postscript_name().unwrap();
263            self.font_ids_by_postscript_name
264                .insert(postscript_name.clone(), font_id);
265            self.postscript_names_by_font_id
266                .insert(font_id, postscript_name);
267            self.fonts.push(font);
268        }
269        Ok(font_ids)
270    }
271
272    fn advance(&self, font_id: FontId, glyph_id: GlyphId) -> Result<Size<f32>> {
273        Ok(self.fonts[font_id.0].advance(glyph_id.0)?.into())
274    }
275
276    fn glyph_for_char(&self, font_id: FontId, ch: char) -> Option<GlyphId> {
277        self.fonts[font_id.0].glyph_for_char(ch).map(GlyphId)
278    }
279
280    fn id_for_native_font(&mut self, requested_font: CTFont) -> FontId {
281        let postscript_name = requested_font.postscript_name();
282        if let Some(font_id) = self.font_ids_by_postscript_name.get(&postscript_name) {
283            *font_id
284        } else {
285            let font_id = FontId(self.fonts.len());
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
291                .push(font_kit::font::Font::from_core_graphics_font(
292                    requested_font.copy_to_CGFont(),
293                ));
294            font_id
295        }
296    }
297
298    fn is_emoji(&self, font_id: FontId) -> bool {
299        self.postscript_names_by_font_id
300            .get(&font_id)
301            .map_or(false, |postscript_name| {
302                postscript_name == "AppleColorEmoji"
303            })
304    }
305
306    fn raster_bounds(&self, params: &RenderGlyphParams) -> Result<Bounds<DevicePixels>> {
307        let font = &self.fonts[params.font_id.0];
308        let scale = Transform2F::from_scale(params.scale_factor);
309        Ok(font
310            .raster_bounds(
311                params.glyph_id.0,
312                params.font_size.into(),
313                scale,
314                HintingOptions::None,
315                font_kit::canvas::RasterizationOptions::GrayscaleAa,
316            )?
317            .into())
318    }
319
320    fn rasterize_glyph(
321        &self,
322        params: &RenderGlyphParams,
323        glyph_bounds: Bounds<DevicePixels>,
324    ) -> Result<(Size<DevicePixels>, Vec<u8>)> {
325        if glyph_bounds.size.width.0 == 0 || glyph_bounds.size.height.0 == 0 {
326            Err(anyhow!("glyph bounds are empty"))
327        } else {
328            // Add an extra pixel when the subpixel variant isn't zero to make room for anti-aliasing.
329            let mut bitmap_size = glyph_bounds.size;
330            if params.subpixel_variant.x > 0 {
331                bitmap_size.width += DevicePixels(1);
332            }
333            if params.subpixel_variant.y > 0 {
334                bitmap_size.height += DevicePixels(1);
335            }
336            let bitmap_size = bitmap_size;
337
338            let mut bytes;
339            let cx;
340            if params.is_emoji {
341                bytes = vec![0; bitmap_size.width.0 as usize * 4 * bitmap_size.height.0 as usize];
342                cx = CGContext::create_bitmap_context(
343                    Some(bytes.as_mut_ptr() as *mut _),
344                    bitmap_size.width.0 as usize,
345                    bitmap_size.height.0 as usize,
346                    8,
347                    bitmap_size.width.0 as usize * 4,
348                    &CGColorSpace::create_device_rgb(),
349                    kCGImageAlphaPremultipliedLast,
350                );
351            } else {
352                bytes = vec![0; bitmap_size.width.0 as usize * bitmap_size.height.0 as usize];
353                cx = CGContext::create_bitmap_context(
354                    Some(bytes.as_mut_ptr() as *mut _),
355                    bitmap_size.width.0 as usize,
356                    bitmap_size.height.0 as usize,
357                    8,
358                    bitmap_size.width.0 as usize,
359                    &CGColorSpace::create_device_gray(),
360                    kCGImageAlphaOnly,
361                );
362            }
363
364            // Move the origin to bottom left and account for scaling, this
365            // makes drawing text consistent with the font-kit's raster_bounds.
366            cx.translate(
367                -glyph_bounds.origin.x.0 as CGFloat,
368                (glyph_bounds.origin.y.0 + glyph_bounds.size.height.0) as CGFloat,
369            );
370            cx.scale(
371                params.scale_factor as CGFloat,
372                params.scale_factor as CGFloat,
373            );
374
375            let subpixel_shift = params
376                .subpixel_variant
377                .map(|v| v as f32 / SUBPIXEL_VARIANTS as f32);
378            cx.set_allows_font_subpixel_positioning(true);
379            cx.set_should_subpixel_position_fonts(true);
380            cx.set_allows_font_subpixel_quantization(false);
381            cx.set_should_subpixel_quantize_fonts(false);
382            self.fonts[params.font_id.0]
383                .native_font()
384                .clone_with_font_size(f32::from(params.font_size) as CGFloat)
385                .draw_glyphs(
386                    &[params.glyph_id.0 as CGGlyph],
387                    &[CGPoint::new(
388                        (subpixel_shift.x / params.scale_factor) as CGFloat,
389                        (subpixel_shift.y / params.scale_factor) as CGFloat,
390                    )],
391                    cx,
392                );
393
394            if params.is_emoji {
395                // Convert from RGBA with premultiplied alpha to BGRA with straight alpha.
396                for pixel in bytes.chunks_exact_mut(4) {
397                    pixel.swap(0, 2);
398                    let a = pixel[3] as f32 / 255.;
399                    pixel[0] = (pixel[0] as f32 / a) as u8;
400                    pixel[1] = (pixel[1] as f32 / a) as u8;
401                    pixel[2] = (pixel[2] as f32 / a) as u8;
402                }
403            }
404
405            Ok((bitmap_size, bytes))
406        }
407    }
408
409    fn layout_line(&mut self, text: &str, font_size: Pixels, font_runs: &[FontRun]) -> LineLayout {
410        // Construct the attributed string, converting UTF8 ranges to UTF16 ranges.
411        let mut string = CFMutableAttributedString::new();
412        {
413            string.replace_str(&CFString::new(text), CFRange::init(0, 0));
414            let utf16_line_len = string.char_len() as usize;
415
416            let mut ix_converter = StringIndexConverter::new(text);
417            for run in font_runs {
418                let utf8_end = ix_converter.utf8_ix + run.len;
419                let utf16_start = ix_converter.utf16_ix;
420
421                if utf16_start >= utf16_line_len {
422                    break;
423                }
424
425                ix_converter.advance_to_utf8_ix(utf8_end);
426                let utf16_end = cmp::min(ix_converter.utf16_ix, utf16_line_len);
427
428                let cf_range =
429                    CFRange::init(utf16_start as isize, (utf16_end - utf16_start) as isize);
430
431                let font: &FontKitFont = &self.fonts[run.font_id.0];
432                unsafe {
433                    string.set_attribute(
434                        cf_range,
435                        kCTFontAttributeName,
436                        &font.native_font().clone_with_font_size(font_size.into()),
437                    );
438                }
439
440                if utf16_end == utf16_line_len {
441                    break;
442                }
443            }
444        }
445
446        // Retrieve the glyphs from the shaped line, converting UTF16 offsets to UTF8 offsets.
447        let line = CTLine::new_with_attributed_string(string.as_concrete_TypeRef());
448
449        let mut runs = Vec::new();
450        for run in line.glyph_runs().into_iter() {
451            let attributes = run.attributes().unwrap();
452            let font = unsafe {
453                attributes
454                    .get(kCTFontAttributeName)
455                    .downcast::<CTFont>()
456                    .unwrap()
457            };
458            let font_id = self.id_for_native_font(font);
459
460            let mut ix_converter = StringIndexConverter::new(text);
461            let mut glyphs = SmallVec::new();
462            for ((glyph_id, position), glyph_utf16_ix) in run
463                .glyphs()
464                .iter()
465                .zip(run.positions().iter())
466                .zip(run.string_indices().iter())
467            {
468                let glyph_utf16_ix = usize::try_from(*glyph_utf16_ix).unwrap();
469                ix_converter.advance_to_utf16_ix(glyph_utf16_ix);
470                glyphs.push(ShapedGlyph {
471                    id: GlyphId(*glyph_id as u32),
472                    position: point(position.x as f32, position.y as f32).map(px),
473                    index: ix_converter.utf8_ix,
474                    is_emoji: self.is_emoji(font_id),
475                });
476            }
477
478            runs.push(ShapedRun { font_id, glyphs })
479        }
480
481        let typographic_bounds = line.get_typographic_bounds();
482        LineLayout {
483            runs,
484            font_size,
485            width: typographic_bounds.width.into(),
486            ascent: typographic_bounds.ascent.into(),
487            descent: typographic_bounds.descent.into(),
488            len: text.len(),
489        }
490    }
491
492    fn wrap_line(
493        &self,
494        text: &str,
495        font_id: FontId,
496        font_size: Pixels,
497        width: Pixels,
498    ) -> Vec<usize> {
499        let mut string = CFMutableAttributedString::new();
500        string.replace_str(&CFString::new(text), CFRange::init(0, 0));
501        let cf_range = CFRange::init(0, text.encode_utf16().count() as isize);
502        let font = &self.fonts[font_id.0];
503        unsafe {
504            string.set_attribute(
505                cf_range,
506                kCTFontAttributeName,
507                &font.native_font().clone_with_font_size(font_size.into()),
508            );
509
510            let typesetter = CTTypesetterCreateWithAttributedString(string.as_concrete_TypeRef());
511            let mut ix_converter = StringIndexConverter::new(text);
512            let mut break_indices = Vec::new();
513            while ix_converter.utf8_ix < text.len() {
514                let utf16_len = CTTypesetterSuggestLineBreak(
515                    typesetter,
516                    ix_converter.utf16_ix as isize,
517                    width.into(),
518                ) as usize;
519                ix_converter.advance_to_utf16_ix(ix_converter.utf16_ix + utf16_len);
520                if ix_converter.utf8_ix >= text.len() {
521                    break;
522                }
523                break_indices.push(ix_converter.utf8_ix);
524            }
525            break_indices
526        }
527    }
528}
529
530#[derive(Clone)]
531struct StringIndexConverter<'a> {
532    text: &'a str,
533    utf8_ix: usize,
534    utf16_ix: usize,
535}
536
537impl<'a> StringIndexConverter<'a> {
538    fn new(text: &'a str) -> Self {
539        Self {
540            text,
541            utf8_ix: 0,
542            utf16_ix: 0,
543        }
544    }
545
546    fn advance_to_utf8_ix(&mut self, utf8_target: usize) {
547        for (ix, c) in self.text[self.utf8_ix..].char_indices() {
548            if self.utf8_ix + ix >= utf8_target {
549                self.utf8_ix += ix;
550                return;
551            }
552            self.utf16_ix += c.len_utf16();
553        }
554        self.utf8_ix = self.text.len();
555    }
556
557    fn advance_to_utf16_ix(&mut self, utf16_target: usize) {
558        for (ix, c) in self.text[self.utf8_ix..].char_indices() {
559            if self.utf16_ix >= utf16_target {
560                self.utf8_ix += ix;
561                return;
562            }
563            self.utf16_ix += c.len_utf16();
564        }
565        self.utf8_ix = self.text.len();
566    }
567}
568
569#[repr(C)]
570pub(crate) struct __CFTypesetter(c_void);
571
572type CTTypesetterRef = *const __CFTypesetter;
573
574#[link(name = "CoreText", kind = "framework")]
575extern "C" {
576    fn CTTypesetterCreateWithAttributedString(string: CFAttributedStringRef) -> CTTypesetterRef;
577
578    fn CTTypesetterSuggestLineBreak(
579        typesetter: CTTypesetterRef,
580        start_index: CFIndex,
581        width: f64,
582    ) -> CFIndex;
583}
584
585impl From<Metrics> for FontMetrics {
586    fn from(metrics: Metrics) -> Self {
587        FontMetrics {
588            units_per_em: metrics.units_per_em,
589            ascent: metrics.ascent,
590            descent: metrics.descent,
591            line_gap: metrics.line_gap,
592            underline_position: metrics.underline_position,
593            underline_thickness: metrics.underline_thickness,
594            cap_height: metrics.cap_height,
595            x_height: metrics.x_height,
596            bounding_box: metrics.bounding_box.into(),
597        }
598    }
599}
600
601impl From<RectF> for Bounds<f32> {
602    fn from(rect: RectF) -> Self {
603        Bounds {
604            origin: point(rect.origin_x(), rect.origin_y()),
605            size: size(rect.width(), rect.height()),
606        }
607    }
608}
609
610impl From<RectI> for Bounds<DevicePixels> {
611    fn from(rect: RectI) -> Self {
612        Bounds {
613            origin: point(DevicePixels(rect.origin_x()), DevicePixels(rect.origin_y())),
614            size: size(DevicePixels(rect.width()), DevicePixels(rect.height())),
615        }
616    }
617}
618
619impl From<Vector2I> for Size<DevicePixels> {
620    fn from(value: Vector2I) -> Self {
621        size(value.x().into(), value.y().into())
622    }
623}
624
625impl From<RectI> for Bounds<i32> {
626    fn from(rect: RectI) -> Self {
627        Bounds {
628            origin: point(rect.origin_x(), rect.origin_y()),
629            size: size(rect.width(), rect.height()),
630        }
631    }
632}
633
634impl From<Point<u32>> for Vector2I {
635    fn from(size: Point<u32>) -> Self {
636        Vector2I::new(size.x as i32, size.y as i32)
637    }
638}
639
640impl From<Vector2F> for Size<f32> {
641    fn from(vec: Vector2F) -> Self {
642        size(vec.x(), vec.y())
643    }
644}
645
646impl From<FontWeight> for FontkitWeight {
647    fn from(value: FontWeight) -> Self {
648        FontkitWeight(value.0)
649    }
650}
651
652impl From<FontStyle> for FontkitStyle {
653    fn from(style: FontStyle) -> Self {
654        match style {
655            FontStyle::Normal => FontkitStyle::Normal,
656            FontStyle::Italic => FontkitStyle::Italic,
657            FontStyle::Oblique => FontkitStyle::Oblique,
658        }
659    }
660}
661
662// Some fonts may have no attributest despite `core_text` requiring them (and panicking).
663// This is the same version as `core_text` has without `expect` calls.
664mod lenient_font_attributes {
665    use core_foundation::{
666        base::{CFRetain, CFType, TCFType},
667        string::{CFString, CFStringRef},
668    };
669    use core_text::font_descriptor::{
670        kCTFontFamilyNameAttribute, CTFontDescriptor, CTFontDescriptorCopyAttribute,
671    };
672
673    pub fn family_name(descriptor: &CTFontDescriptor) -> Option<String> {
674        unsafe { get_string_attribute(descriptor, kCTFontFamilyNameAttribute) }
675    }
676
677    fn get_string_attribute(
678        descriptor: &CTFontDescriptor,
679        attribute: CFStringRef,
680    ) -> Option<String> {
681        unsafe {
682            let value = CTFontDescriptorCopyAttribute(descriptor.as_concrete_TypeRef(), attribute);
683            if value.is_null() {
684                return None;
685            }
686
687            let value = CFType::wrap_under_create_rule(value);
688            assert!(value.instance_of::<CFString>());
689            let s = wrap_under_get_rule(value.as_CFTypeRef() as CFStringRef);
690            Some(s.to_string())
691        }
692    }
693
694    unsafe fn wrap_under_get_rule(reference: CFStringRef) -> CFString {
695        assert!(!reference.is_null(), "Attempted to create a NULL object.");
696        let reference = CFRetain(reference as *const ::std::os::raw::c_void) as CFStringRef;
697        TCFType::wrap_under_create_rule(reference)
698    }
699}
700
701#[cfg(test)]
702mod tests {
703    use crate::{font, px, FontRun, GlyphId, MacTextSystem, PlatformTextSystem};
704
705    #[test]
706    fn test_wrap_line() {
707        let fonts = MacTextSystem::new();
708        let font_id = fonts.font_id(&font("Helvetica")).unwrap();
709
710        let line = "one two three four five\n";
711        let wrap_boundaries = fonts.wrap_line(line, font_id, px(16.), px(64.0));
712        assert_eq!(wrap_boundaries, &["one two ".len(), "one two three ".len()]);
713
714        let line = "aaa ααα ✋✋✋ 🎉🎉🎉\n";
715        let wrap_boundaries = fonts.wrap_line(line, font_id, px(16.), px(64.0));
716        assert_eq!(
717            wrap_boundaries,
718            &["aaa ααα ".len(), "aaa ααα ✋✋✋ ".len(),]
719        );
720    }
721
722    #[test]
723    fn test_layout_line_bom_char() {
724        let fonts = MacTextSystem::new();
725        let font_id = fonts.font_id(&font("Helvetica")).unwrap();
726        let line = "\u{feff}";
727        let mut style = FontRun {
728            font_id,
729            len: line.len(),
730        };
731
732        let layout = fonts.layout_line(line, px(16.), &[style]);
733        assert_eq!(layout.len, line.len());
734        assert!(layout.runs.is_empty());
735
736        let line = "a\u{feff}b";
737        style.len = line.len();
738        let layout = fonts.layout_line(line, px(16.), &[style]);
739        assert_eq!(layout.len, line.len());
740        assert_eq!(layout.runs.len(), 1);
741        assert_eq!(layout.runs[0].glyphs.len(), 2);
742        assert_eq!(layout.runs[0].glyphs[0].id, GlyphId(68u32)); // a
743                                                                 // There's no glyph for \u{feff}
744        assert_eq!(layout.runs[0].glyphs[1].id, GlyphId(69u32)); // b
745    }
746}