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