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