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        let mut bounds: Bounds<DevicePixels> = 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        // Add 3% of font size as padding, clamped between 1 and 5 pixels
373        // to avoid clipping of anti-aliased edges.
374        let pad =
375            ((params.font_size.as_f32() * 0.03 * params.scale_factor).ceil() as i32).clamp(1, 5);
376        bounds.origin.x -= DevicePixels(pad);
377        bounds.size.width += DevicePixels(pad);
378
379        Ok(bounds)
380    }
381
382    fn rasterize_glyph(
383        &self,
384        params: &RenderGlyphParams,
385        glyph_bounds: Bounds<DevicePixels>,
386    ) -> Result<(Size<DevicePixels>, Vec<u8>)> {
387        if glyph_bounds.size.width.0 == 0 || glyph_bounds.size.height.0 == 0 {
388            anyhow::bail!("glyph bounds are empty");
389        } else {
390            // Add an extra pixel when the subpixel variant isn't zero to make room for anti-aliasing.
391            let mut bitmap_size = glyph_bounds.size;
392            if params.subpixel_variant.x > 0 {
393                bitmap_size.width += DevicePixels(1);
394            }
395            if params.subpixel_variant.y > 0 {
396                bitmap_size.height += DevicePixels(1);
397            }
398            let bitmap_size = bitmap_size;
399
400            let mut bytes;
401            let cx;
402            if params.is_emoji {
403                bytes = vec![0; bitmap_size.width.0 as usize * 4 * 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 * 4,
410                    &CGColorSpace::create_device_rgb(),
411                    kCGImageAlphaPremultipliedLast,
412                );
413            } else {
414                bytes = vec![0; bitmap_size.width.0 as usize * bitmap_size.height.0 as usize];
415                cx = CGContext::create_bitmap_context(
416                    Some(bytes.as_mut_ptr() as *mut _),
417                    bitmap_size.width.0 as usize,
418                    bitmap_size.height.0 as usize,
419                    8,
420                    bitmap_size.width.0 as usize,
421                    &CGColorSpace::create_device_gray(),
422                    kCGImageAlphaOnly,
423                );
424            }
425
426            // Move the origin to bottom left and account for scaling, this
427            // makes drawing text consistent with the font-kit's raster_bounds.
428            cx.translate(
429                -glyph_bounds.origin.x.0 as CGFloat,
430                (glyph_bounds.origin.y.0 + glyph_bounds.size.height.0) as CGFloat,
431            );
432            cx.scale(
433                params.scale_factor as CGFloat,
434                params.scale_factor as CGFloat,
435            );
436
437            let subpixel_shift = params
438                .subpixel_variant
439                .map(|v| v as f32 / SUBPIXEL_VARIANTS_X as f32);
440            cx.set_text_drawing_mode(CGTextDrawingMode::CGTextFill);
441            cx.set_gray_fill_color(0.0, 1.0);
442            cx.set_allows_antialiasing(true);
443            cx.set_should_antialias(true);
444            cx.set_allows_font_subpixel_positioning(true);
445            cx.set_should_subpixel_position_fonts(true);
446            cx.set_allows_font_subpixel_quantization(false);
447            cx.set_should_subpixel_quantize_fonts(false);
448            self.fonts[params.font_id.0]
449                .native_font()
450                .clone_with_font_size(f32::from(params.font_size) as CGFloat)
451                .draw_glyphs(
452                    &[params.glyph_id.0 as CGGlyph],
453                    &[CGPoint::new(
454                        (subpixel_shift.x / params.scale_factor) as CGFloat,
455                        (subpixel_shift.y / params.scale_factor) as CGFloat,
456                    )],
457                    cx,
458                );
459
460            if params.is_emoji {
461                // Convert from RGBA with premultiplied alpha to BGRA with straight alpha.
462                for pixel in bytes.chunks_exact_mut(4) {
463                    swap_rgba_pa_to_bgra(pixel);
464                }
465            }
466
467            Ok((bitmap_size, bytes))
468        }
469    }
470
471    fn layout_line(&mut self, text: &str, font_size: Pixels, font_runs: &[FontRun]) -> LineLayout {
472        // Construct the attributed string, converting UTF8 ranges to UTF16 ranges.
473        let mut string = CFMutableAttributedString::new();
474        let mut max_ascent = 0.0f32;
475        let mut max_descent = 0.0f32;
476
477        {
478            let mut text = text;
479            let mut break_ligature = true;
480            for run in font_runs {
481                let text_run;
482                (text_run, text) = text.split_at(run.len);
483
484                let utf16_start = string.char_len(); // insert at end of string
485                // note: replace_str may silently ignore codepoints it dislikes (e.g., BOM at start of string)
486                string.replace_str(&CFString::new(text_run), CFRange::init(utf16_start, 0));
487                let utf16_end = string.char_len();
488
489                let length = utf16_end - utf16_start;
490                let cf_range = CFRange::init(utf16_start, length);
491                let font = &self.fonts[run.font_id.0];
492
493                let font_metrics = font.metrics();
494                let font_scale = f32::from(font_size) / font_metrics.units_per_em as f32;
495                max_ascent = max_ascent.max(font_metrics.ascent * font_scale);
496                max_descent = max_descent.max(-font_metrics.descent * font_scale);
497
498                let font_size = if break_ligature {
499                    px(f32::from(font_size).next_up())
500                } else {
501                    font_size
502                };
503                unsafe {
504                    string.set_attribute(
505                        cf_range,
506                        kCTFontAttributeName,
507                        &font.native_font().clone_with_font_size(font_size.into()),
508                    );
509                }
510                break_ligature = !break_ligature;
511            }
512        }
513        // Retrieve the glyphs from the shaped line, converting UTF16 offsets to UTF8 offsets.
514        let line = CTLine::new_with_attributed_string(string.as_concrete_TypeRef());
515        let glyph_runs = line.glyph_runs();
516        let mut runs = <Vec<ShapedRun>>::with_capacity(glyph_runs.len() as usize);
517        let mut ix_converter = StringIndexConverter::new(text);
518        for run in glyph_runs.into_iter() {
519            let attributes = run.attributes().unwrap();
520            let font = unsafe {
521                attributes
522                    .get(kCTFontAttributeName)
523                    .downcast::<CTFont>()
524                    .unwrap()
525            };
526            let font_id = self.id_for_native_font(font);
527
528            let glyphs = match runs.last_mut() {
529                Some(run) if run.font_id == font_id => &mut run.glyphs,
530                _ => {
531                    runs.push(ShapedRun {
532                        font_id,
533                        glyphs: Vec::with_capacity(run.glyph_count().try_into().unwrap_or(0)),
534                    });
535                    &mut runs.last_mut().unwrap().glyphs
536                }
537            };
538            for ((&glyph_id, position), &glyph_utf16_ix) in run
539                .glyphs()
540                .iter()
541                .zip(run.positions().iter())
542                .zip(run.string_indices().iter())
543            {
544                let glyph_utf16_ix = usize::try_from(glyph_utf16_ix).unwrap();
545                if ix_converter.utf16_ix > glyph_utf16_ix {
546                    // We cannot reuse current index converter, as it can only seek forward. Restart the search.
547                    ix_converter = StringIndexConverter::new(text);
548                }
549                ix_converter.advance_to_utf16_ix(glyph_utf16_ix);
550                glyphs.push(ShapedGlyph {
551                    id: GlyphId(glyph_id as u32),
552                    position: point(position.x as f32, position.y as f32).map(px),
553                    index: ix_converter.utf8_ix,
554                    is_emoji: self.is_emoji(font_id),
555                });
556            }
557        }
558        let typographic_bounds = line.get_typographic_bounds();
559        LineLayout {
560            runs,
561            font_size,
562            width: typographic_bounds.width.into(),
563            ascent: max_ascent.into(),
564            descent: max_descent.into(),
565            len: text.len(),
566        }
567    }
568}
569
570#[derive(Debug, Clone)]
571struct StringIndexConverter<'a> {
572    text: &'a str,
573    /// Index in UTF-8 bytes
574    utf8_ix: usize,
575    /// Index in UTF-16 code units
576    utf16_ix: usize,
577}
578
579impl<'a> StringIndexConverter<'a> {
580    fn new(text: &'a str) -> Self {
581        Self {
582            text,
583            utf8_ix: 0,
584            utf16_ix: 0,
585        }
586    }
587
588    fn advance_to_utf16_ix(&mut self, utf16_target: usize) {
589        for (ix, c) in self.text[self.utf8_ix..].char_indices() {
590            if self.utf16_ix >= utf16_target {
591                self.utf8_ix += ix;
592                return;
593            }
594            self.utf16_ix += c.len_utf16();
595        }
596        self.utf8_ix = self.text.len();
597    }
598}
599
600fn font_kit_metrics_to_metrics(metrics: Metrics) -> FontMetrics {
601    FontMetrics {
602        units_per_em: metrics.units_per_em,
603        ascent: metrics.ascent,
604        descent: metrics.descent,
605        line_gap: metrics.line_gap,
606        underline_position: metrics.underline_position,
607        underline_thickness: metrics.underline_thickness,
608        cap_height: metrics.cap_height,
609        x_height: metrics.x_height,
610        bounding_box: bounds_from_rect(metrics.bounding_box),
611    }
612}
613
614fn bounds_from_rect(rect: RectF) -> Bounds<f32> {
615    Bounds {
616        origin: point(rect.origin_x(), rect.origin_y()),
617        size: size(rect.width(), rect.height()),
618    }
619}
620
621fn bounds_from_rect_i(rect: RectI) -> Bounds<DevicePixels> {
622    Bounds {
623        origin: point(DevicePixels(rect.origin_x()), DevicePixels(rect.origin_y())),
624        size: size(DevicePixels(rect.width()), DevicePixels(rect.height())),
625    }
626}
627
628// impl From<Vector2I> for Size<DevicePixels> {
629//     fn from(value: Vector2I) -> Self {
630//         size(value.x().into(), value.y().into())
631//     }
632// }
633
634// impl From<RectI> for Bounds<i32> {
635//     fn from(rect: RectI) -> Self {
636//         Bounds {
637//             origin: point(rect.origin_x(), rect.origin_y()),
638//             size: size(rect.width(), rect.height()),
639//         }
640//     }
641// }
642
643// impl From<Point<u32>> for Vector2I {
644//     fn from(size: Point<u32>) -> Self {
645//         Vector2I::new(size.x as i32, size.y as i32)
646//     }
647// }
648
649fn size_from_vector2f(vec: Vector2F) -> Size<f32> {
650    size(vec.x(), vec.y())
651}
652
653fn fontkit_weight(value: FontWeight) -> FontkitWeight {
654    FontkitWeight(value.0)
655}
656
657fn fontkit_style(style: FontStyle) -> FontkitStyle {
658    match style {
659        FontStyle::Normal => FontkitStyle::Normal,
660        FontStyle::Italic => FontkitStyle::Italic,
661        FontStyle::Oblique => FontkitStyle::Oblique,
662    }
663}
664
665// Some fonts may have no attributes despite `core_text` requiring them (and panicking).
666// This is the same version as `core_text` has without `expect` calls.
667mod lenient_font_attributes {
668    use core_foundation::{
669        base::{CFRetain, CFType, TCFType},
670        string::{CFString, CFStringRef},
671    };
672    use core_text::font_descriptor::{
673        CTFontDescriptor, CTFontDescriptorCopyAttribute, kCTFontFamilyNameAttribute,
674    };
675
676    pub fn family_name(descriptor: &CTFontDescriptor) -> Option<String> {
677        unsafe { get_string_attribute(descriptor, kCTFontFamilyNameAttribute) }
678    }
679
680    fn get_string_attribute(
681        descriptor: &CTFontDescriptor,
682        attribute: CFStringRef,
683    ) -> Option<String> {
684        unsafe {
685            let value = CTFontDescriptorCopyAttribute(descriptor.as_concrete_TypeRef(), attribute);
686            if value.is_null() {
687                return None;
688            }
689
690            let value = CFType::wrap_under_create_rule(value);
691            assert!(value.instance_of::<CFString>());
692            let s = wrap_under_get_rule(value.as_CFTypeRef() as CFStringRef);
693            Some(s.to_string())
694        }
695    }
696
697    unsafe fn wrap_under_get_rule(reference: CFStringRef) -> CFString {
698        unsafe {
699            assert!(!reference.is_null(), "Attempted to create a NULL object.");
700            let reference = CFRetain(reference as *const ::std::os::raw::c_void) as CFStringRef;
701            TCFType::wrap_under_create_rule(reference)
702        }
703    }
704}
705
706#[cfg(test)]
707mod tests {
708    use crate::MacTextSystem;
709    use gpui::{FontRun, GlyphId, PlatformTextSystem, font, px};
710
711    #[test]
712    fn test_layout_line_bom_char() {
713        let fonts = MacTextSystem::new();
714        let font_id = fonts.font_id(&font("Helvetica")).unwrap();
715        let line = "\u{feff}";
716        let mut style = FontRun {
717            font_id,
718            len: line.len(),
719        };
720
721        let layout = fonts.layout_line(line, px(16.), &[style]);
722        assert_eq!(layout.len, line.len());
723        assert!(layout.runs.is_empty());
724
725        let line = "a\u{feff}b";
726        style.len = line.len();
727        let layout = fonts.layout_line(line, px(16.), &[style]);
728        assert_eq!(layout.len, line.len());
729        assert_eq!(layout.runs.len(), 1);
730        assert_eq!(layout.runs[0].glyphs.len(), 2);
731        assert_eq!(layout.runs[0].glyphs[0].id, GlyphId(68u32)); // a
732        // There's no glyph for \u{feff}
733        assert_eq!(layout.runs[0].glyphs[1].id, GlyphId(69u32)); // b
734
735        let line = "\u{feff}ab";
736        let font_runs = &[
737            FontRun {
738                len: "\u{feff}".len(),
739                font_id,
740            },
741            FontRun {
742                len: "ab".len(),
743                font_id,
744            },
745        ];
746        let layout = fonts.layout_line(line, px(16.), font_runs);
747        assert_eq!(layout.len, line.len());
748        assert_eq!(layout.runs.len(), 1);
749        assert_eq!(layout.runs[0].glyphs.len(), 2);
750        // There's no glyph for \u{feff}
751        assert_eq!(layout.runs[0].glyphs[0].id, GlyphId(68u32)); // a
752        assert_eq!(layout.runs[0].glyphs[1].id, GlyphId(69u32)); // b
753    }
754
755    #[test]
756    fn test_layout_line_zwnj_insertion() {
757        let fonts = MacTextSystem::new();
758        let font_id = fonts.font_id(&font("Helvetica")).unwrap();
759
760        let text = "hello world";
761        let font_runs = &[
762            FontRun { font_id, len: 5 }, // "hello"
763            FontRun { font_id, len: 6 }, // " world"
764        ];
765
766        let layout = fonts.layout_line(text, px(16.), font_runs);
767        assert_eq!(layout.len, text.len());
768
769        for run in &layout.runs {
770            for glyph in &run.glyphs {
771                assert!(
772                    glyph.index < text.len(),
773                    "Glyph index {} is out of bounds for text length {}",
774                    glyph.index,
775                    text.len()
776                );
777            }
778        }
779
780        // Test with different font runs - should not insert ZWNJ
781        let font_id2 = fonts.font_id(&font("Times")).unwrap_or(font_id);
782        let font_runs_different = &[
783            FontRun { font_id, len: 5 }, // "hello"
784            // " world"
785            FontRun {
786                font_id: font_id2,
787                len: 6,
788            },
789        ];
790
791        let layout2 = fonts.layout_line(text, px(16.), font_runs_different);
792        assert_eq!(layout2.len, text.len());
793
794        for run in &layout2.runs {
795            for glyph in &run.glyphs {
796                assert!(
797                    glyph.index < text.len(),
798                    "Glyph index {} is out of bounds for text length {}",
799                    glyph.index,
800                    text.len()
801                );
802            }
803        }
804    }
805
806    #[test]
807    fn test_layout_line_zwnj_edge_cases() {
808        let fonts = MacTextSystem::new();
809        let font_id = fonts.font_id(&font("Helvetica")).unwrap();
810
811        let text = "hello";
812        let font_runs = &[FontRun { font_id, len: 5 }];
813        let layout = fonts.layout_line(text, px(16.), font_runs);
814        assert_eq!(layout.len, text.len());
815
816        let text = "abc";
817        let font_runs = &[
818            FontRun { font_id, len: 1 }, // "a"
819            FontRun { font_id, len: 1 }, // "b"
820            FontRun { font_id, len: 1 }, // "c"
821        ];
822        let layout = fonts.layout_line(text, px(16.), font_runs);
823        assert_eq!(layout.len, text.len());
824
825        for run in &layout.runs {
826            for glyph in &run.glyphs {
827                assert!(
828                    glyph.index < text.len(),
829                    "Glyph index {} is out of bounds for text length {}",
830                    glyph.index,
831                    text.len()
832                );
833            }
834        }
835
836        // Test with empty text
837        let text = "";
838        let font_runs = &[];
839        let layout = fonts.layout_line(text, px(16.), font_runs);
840        assert_eq!(layout.len, 0);
841        assert!(layout.runs.is_empty());
842    }
843}