text_system.rs

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