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