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