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