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(); // from previous loop
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((n_zwnjs, 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    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}