text_system.rs

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