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