text_system.rs

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