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 utf16_start = string.char_len(); // insert at end of string
454                ix_converter.advance_to_utf8_ix(ix_converter.utf8_ix + run.len);
455
456                // note: replace_str may silently ignore codepoints it dislikes (e.g., BOM at start of string)
457                string.replace_str(&CFString::new(text), CFRange::init(utf16_start, 0));
458                if needs_zwnj {
459                    let zwnjs_pos = string.char_len();
460                    self.zwnjs_scratch_space.push(zwnjs_pos as usize);
461                    string.replace_str(
462                        &CFString::from_static_string(ZWNJ_STR),
463                        CFRange::init(zwnjs_pos, 0),
464                    );
465                }
466                let utf16_end = string.char_len();
467
468                let cf_range = CFRange::init(utf16_start, utf16_end - utf16_start);
469                let font = &self.fonts[run.font_id.0];
470
471                let font_metrics = font.metrics();
472                let font_scale = font_size.0 / font_metrics.units_per_em as f32;
473                max_ascent = max_ascent.max(font_metrics.ascent * font_scale);
474                max_descent = max_descent.max(-font_metrics.descent * font_scale);
475
476                unsafe {
477                    string.set_attribute(
478                        cf_range,
479                        kCTFontAttributeName,
480                        &font.native_font().clone_with_font_size(font_size.into()),
481                    );
482                }
483            }
484        }
485        // Retrieve the glyphs from the shaped line, converting UTF16 offsets to UTF8 offsets.
486        let line = CTLine::new_with_attributed_string(string.as_concrete_TypeRef());
487        let glyph_runs = line.glyph_runs();
488        let mut runs = <Vec<ShapedRun>>::with_capacity(glyph_runs.len() as usize);
489        let mut ix_converter = StringIndexConverter::new(text);
490        for run in glyph_runs.into_iter() {
491            let attributes = run.attributes().unwrap();
492            let font = unsafe {
493                attributes
494                    .get(kCTFontAttributeName)
495                    .downcast::<CTFont>()
496                    .unwrap()
497            };
498            let font_id = self.id_for_native_font(font);
499
500            let mut glyphs = match runs.last_mut() {
501                Some(run) if run.font_id == font_id => &mut run.glyphs,
502                _ => {
503                    runs.push(ShapedRun {
504                        font_id,
505                        glyphs: Vec::with_capacity(run.glyph_count().try_into().unwrap_or(0)),
506                    });
507                    &mut runs.last_mut().unwrap().glyphs
508                }
509            };
510            for ((&glyph_id, position), &glyph_utf16_ix) in run
511                .glyphs()
512                .iter()
513                .zip(run.positions().iter())
514                .zip(run.string_indices().iter())
515            {
516                let mut glyph_utf16_ix = usize::try_from(glyph_utf16_ix).unwrap();
517                let r = self
518                    .zwnjs_scratch_space
519                    .binary_search_by(|&it| it.cmp(&glyph_utf16_ix));
520                match r {
521                    // this glyph is a ZWNJ, skip it
522                    Ok(_) => continue,
523                    // adjust the index to account for the ZWNJs we've inserted
524                    Err(idx) => glyph_utf16_ix -= idx * ZWNJ_SIZE_16,
525                }
526                if ix_converter.utf16_ix > glyph_utf16_ix {
527                    // We cannot reuse current index converter, as it can only seek forward. Restart the search.
528                    ix_converter = StringIndexConverter::new(text);
529                }
530                ix_converter.advance_to_utf16_ix(glyph_utf16_ix);
531                glyphs.push(ShapedGlyph {
532                    id: GlyphId(glyph_id as u32),
533                    position: point(position.x as f32, position.y as f32).map(px),
534                    index: ix_converter.utf8_ix,
535                    is_emoji: self.is_emoji(font_id),
536                });
537            }
538        }
539        let typographic_bounds = line.get_typographic_bounds();
540        LineLayout {
541            runs,
542            font_size,
543            width: typographic_bounds.width.into(),
544            ascent: max_ascent.into(),
545            descent: max_descent.into(),
546            len: text.len(),
547        }
548    }
549}
550
551#[derive(Debug, Clone)]
552struct StringIndexConverter<'a> {
553    text: &'a str,
554    /// Index in UTF-8 bytes
555    utf8_ix: usize,
556    /// Index in UTF-16 code units
557    utf16_ix: usize,
558}
559
560impl<'a> StringIndexConverter<'a> {
561    const fn new(text: &'a str) -> Self {
562        Self {
563            text,
564            utf8_ix: 0,
565            utf16_ix: 0,
566        }
567    }
568
569    fn advance_to_utf8_ix(&mut self, utf8_target: usize) {
570        for (ix, c) in self.text[self.utf8_ix..].char_indices() {
571            if self.utf8_ix + ix >= utf8_target {
572                self.utf8_ix += ix;
573                return;
574            }
575            self.utf16_ix += c.len_utf16();
576        }
577        self.utf8_ix = self.text.len();
578    }
579
580    fn advance_to_utf16_ix(&mut self, utf16_target: usize) {
581        for (ix, c) in self.text[self.utf8_ix..].char_indices() {
582            if self.utf16_ix >= utf16_target {
583                self.utf8_ix += ix;
584                return;
585            }
586            self.utf16_ix += c.len_utf16();
587        }
588        self.utf8_ix = self.text.len();
589    }
590}
591
592impl From<Metrics> for FontMetrics {
593    fn from(metrics: Metrics) -> Self {
594        FontMetrics {
595            units_per_em: metrics.units_per_em,
596            ascent: metrics.ascent,
597            descent: metrics.descent,
598            line_gap: metrics.line_gap,
599            underline_position: metrics.underline_position,
600            underline_thickness: metrics.underline_thickness,
601            cap_height: metrics.cap_height,
602            x_height: metrics.x_height,
603            bounding_box: metrics.bounding_box.into(),
604        }
605    }
606}
607
608impl From<RectF> for Bounds<f32> {
609    fn from(rect: RectF) -> Self {
610        Bounds {
611            origin: point(rect.origin_x(), rect.origin_y()),
612            size: size(rect.width(), rect.height()),
613        }
614    }
615}
616
617impl From<RectI> for Bounds<DevicePixels> {
618    fn from(rect: RectI) -> Self {
619        Bounds {
620            origin: point(DevicePixels(rect.origin_x()), DevicePixels(rect.origin_y())),
621            size: size(DevicePixels(rect.width()), DevicePixels(rect.height())),
622        }
623    }
624}
625
626impl From<Vector2I> for Size<DevicePixels> {
627    fn from(value: Vector2I) -> Self {
628        size(value.x().into(), value.y().into())
629    }
630}
631
632impl From<RectI> for Bounds<i32> {
633    fn from(rect: RectI) -> Self {
634        Bounds {
635            origin: point(rect.origin_x(), rect.origin_y()),
636            size: size(rect.width(), rect.height()),
637        }
638    }
639}
640
641impl From<Point<u32>> for Vector2I {
642    fn from(size: Point<u32>) -> Self {
643        Vector2I::new(size.x as i32, size.y as i32)
644    }
645}
646
647impl From<Vector2F> for Size<f32> {
648    fn from(vec: Vector2F) -> Self {
649        size(vec.x(), vec.y())
650    }
651}
652
653impl From<FontWeight> for FontkitWeight {
654    fn from(value: FontWeight) -> Self {
655        FontkitWeight(value.0)
656    }
657}
658
659impl From<FontStyle> for FontkitStyle {
660    fn from(style: FontStyle) -> Self {
661        match style {
662            FontStyle::Normal => FontkitStyle::Normal,
663            FontStyle::Italic => FontkitStyle::Italic,
664            FontStyle::Oblique => FontkitStyle::Oblique,
665        }
666    }
667}
668
669// Some fonts may have no attributes despite `core_text` requiring them (and panicking).
670// This is the same version as `core_text` has without `expect` calls.
671mod lenient_font_attributes {
672    use core_foundation::{
673        base::{CFRetain, CFType, TCFType},
674        string::{CFString, CFStringRef},
675    };
676    use core_text::font_descriptor::{
677        CTFontDescriptor, CTFontDescriptorCopyAttribute, kCTFontFamilyNameAttribute,
678    };
679
680    pub fn family_name(descriptor: &CTFontDescriptor) -> Option<String> {
681        unsafe { get_string_attribute(descriptor, kCTFontFamilyNameAttribute) }
682    }
683
684    fn get_string_attribute(
685        descriptor: &CTFontDescriptor,
686        attribute: CFStringRef,
687    ) -> Option<String> {
688        unsafe {
689            let value = CTFontDescriptorCopyAttribute(descriptor.as_concrete_TypeRef(), attribute);
690            if value.is_null() {
691                return None;
692            }
693
694            let value = CFType::wrap_under_create_rule(value);
695            assert!(value.instance_of::<CFString>());
696            let s = wrap_under_get_rule(value.as_CFTypeRef() as CFStringRef);
697            Some(s.to_string())
698        }
699    }
700
701    unsafe fn wrap_under_get_rule(reference: CFStringRef) -> CFString {
702        unsafe {
703            assert!(!reference.is_null(), "Attempted to create a NULL object.");
704            let reference = CFRetain(reference as *const ::std::os::raw::c_void) as CFStringRef;
705            TCFType::wrap_under_create_rule(reference)
706        }
707    }
708}
709
710#[cfg(test)]
711mod tests {
712    use crate::{FontRun, GlyphId, MacTextSystem, PlatformTextSystem, font, px};
713
714    #[test]
715    fn test_layout_line_bom_char() {
716        let fonts = MacTextSystem::new();
717        let font_id = fonts.font_id(&font("Helvetica")).unwrap();
718        let line = "\u{feff}";
719        let mut style = FontRun {
720            font_id,
721            len: line.len(),
722        };
723
724        let layout = fonts.layout_line(line, px(16.), &[style]);
725        assert_eq!(layout.len, line.len());
726        assert!(layout.runs.is_empty());
727
728        let line = "a\u{feff}b";
729        style.len = line.len();
730        let layout = fonts.layout_line(line, px(16.), &[style]);
731        assert_eq!(layout.len, line.len());
732        assert_eq!(layout.runs.len(), 1);
733        assert_eq!(layout.runs[0].glyphs.len(), 2);
734        assert_eq!(layout.runs[0].glyphs[0].id, GlyphId(68u32)); // a
735        // There's no glyph for \u{feff}
736        assert_eq!(layout.runs[0].glyphs[1].id, GlyphId(69u32)); // b
737
738        let line = "\u{feff}ab";
739        let font_runs = &[
740            FontRun {
741                len: "\u{feff}".len(),
742                font_id,
743            },
744            FontRun {
745                len: "ab".len(),
746                font_id,
747            },
748        ];
749        let layout = fonts.layout_line(line, px(16.), font_runs);
750        assert_eq!(layout.len, line.len());
751        assert_eq!(layout.runs.len(), 1);
752        assert_eq!(layout.runs[0].glyphs.len(), 2);
753        // There's no glyph for \u{feff}
754        assert_eq!(layout.runs[0].glyphs[0].id, GlyphId(68u32)); // a
755        assert_eq!(layout.runs[0].glyphs[1].id, GlyphId(69u32)); // b
756    }
757
758    #[test]
759    fn test_layout_line_zwnj_insertion() {
760        let fonts = MacTextSystem::new();
761        let font_id = fonts.font_id(&font("Helvetica")).unwrap();
762
763        let text = "hello world";
764        let font_runs = &[
765            FontRun { font_id, len: 5 }, // "hello"
766            FontRun { font_id, len: 6 }, // " world"
767        ];
768
769        let layout = fonts.layout_line(text, px(16.), font_runs);
770        assert_eq!(layout.len, text.len());
771
772        for run in &layout.runs {
773            for glyph in &run.glyphs {
774                assert!(
775                    glyph.index < text.len(),
776                    "Glyph index {} is out of bounds for text length {}",
777                    glyph.index,
778                    text.len()
779                );
780            }
781        }
782
783        // Test with different font runs - should not insert ZWNJ
784        let font_id2 = fonts.font_id(&font("Times")).unwrap_or(font_id);
785        let font_runs_different = &[
786            FontRun { font_id, len: 5 }, // "hello"
787            // " world"
788            FontRun {
789                font_id: font_id2,
790                len: 6,
791            },
792        ];
793
794        let layout2 = fonts.layout_line(text, px(16.), font_runs_different);
795        assert_eq!(layout2.len, text.len());
796
797        for run in &layout2.runs {
798            for glyph in &run.glyphs {
799                assert!(
800                    glyph.index < text.len(),
801                    "Glyph index {} is out of bounds for text length {}",
802                    glyph.index,
803                    text.len()
804                );
805            }
806        }
807    }
808
809    #[test]
810    fn test_layout_line_zwnj_edge_cases() {
811        let fonts = MacTextSystem::new();
812        let font_id = fonts.font_id(&font("Helvetica")).unwrap();
813
814        let text = "hello";
815        let font_runs = &[FontRun { font_id, len: 5 }];
816        let layout = fonts.layout_line(text, px(16.), font_runs);
817        assert_eq!(layout.len, text.len());
818
819        let text = "abc";
820        let font_runs = &[
821            FontRun { font_id, len: 1 }, // "a"
822            FontRun { font_id, len: 1 }, // "b"
823            FontRun { font_id, len: 1 }, // "c"
824        ];
825        let layout = fonts.layout_line(text, px(16.), font_runs);
826        assert_eq!(layout.len, text.len());
827
828        for run in &layout.runs {
829            for glyph in &run.glyphs {
830                assert!(
831                    glyph.index < text.len(),
832                    "Glyph index {} is out of bounds for text length {}",
833                    glyph.index,
834                    text.len()
835                );
836            }
837        }
838
839        // Test with empty text
840        let text = "";
841        let font_runs = &[];
842        let layout = fonts.layout_line(text, px(16.), font_runs);
843        assert_eq!(layout.len, 0);
844        assert!(layout.runs.is_empty());
845    }
846}