text_system.rs

  1use crate::{
  2    point, px, size, Bounds, DevicePixels, Font, FontFeatures, FontId, FontMetrics, FontRun,
  3    FontStyle, FontWeight, GlyphId, LineLayout, Pixels, PlatformTextSystem, Point,
  4    RenderGlyphParams, Result, ShapedGlyph, ShapedRun, SharedString, Size, SUBPIXEL_VARIANTS,
  5};
  6use anyhow::anyhow;
  7use cocoa::appkit::{CGFloat, CGPoint};
  8use collections::HashMap;
  9use core_foundation::{
 10    array::CFIndex,
 11    attributed_string::{CFAttributedStringRef, CFMutableAttributedString},
 12    base::{CFRange, TCFType},
 13    string::CFString,
 14};
 15use core_graphics::{
 16    base::{kCGImageAlphaPremultipliedLast, CGGlyph},
 17    color_space::CGColorSpace,
 18    context::CGContext,
 19};
 20use core_text::{font::CTFont, line::CTLine, string_attributes::kCTFontAttributeName};
 21use font_kit::{
 22    font::Font as FontKitFont,
 23    handle::Handle,
 24    hinting::HintingOptions,
 25    metrics::Metrics,
 26    properties::{Style as FontkitStyle, Weight as FontkitWeight},
 27    source::SystemSource,
 28    sources::mem::MemSource,
 29};
 30use parking_lot::{RwLock, RwLockUpgradableReadGuard};
 31use pathfinder_geometry::{
 32    rect::{RectF, RectI},
 33    transform2d::Transform2F,
 34    vector::{Vector2F, Vector2I},
 35};
 36use smallvec::SmallVec;
 37use std::{char, cmp, convert::TryFrom, ffi::c_void, sync::Arc};
 38
 39use super::open_type;
 40
 41#[allow(non_upper_case_globals)]
 42const kCGImageAlphaOnly: u32 = 7;
 43
 44pub struct MacTextSystem(RwLock<MacTextSystemState>);
 45
 46struct MacTextSystemState {
 47    memory_source: MemSource,
 48    system_source: SystemSource,
 49    fonts: Vec<FontKitFont>,
 50    font_selections: HashMap<Font, FontId>,
 51    font_ids_by_postscript_name: HashMap<String, FontId>,
 52    font_ids_by_family_name: HashMap<SharedString, SmallVec<[FontId; 4]>>,
 53    postscript_names_by_font_id: HashMap<FontId, String>,
 54}
 55
 56impl MacTextSystem {
 57    pub fn new() -> Self {
 58        Self(RwLock::new(MacTextSystemState {
 59            memory_source: MemSource::empty(),
 60            system_source: SystemSource::new(),
 61            fonts: Vec::new(),
 62            font_selections: HashMap::default(),
 63            font_ids_by_postscript_name: HashMap::default(),
 64            font_ids_by_family_name: HashMap::default(),
 65            postscript_names_by_font_id: HashMap::default(),
 66        }))
 67    }
 68}
 69
 70impl Default for MacTextSystem {
 71    fn default() -> Self {
 72        Self::new()
 73    }
 74}
 75
 76impl PlatformTextSystem for MacTextSystem {
 77    fn add_fonts(&self, fonts: &[Arc<Vec<u8>>]) -> Result<()> {
 78        self.0.write().add_fonts(fonts)
 79    }
 80
 81    fn all_font_families(&self) -> Vec<String> {
 82        self.0
 83            .read()
 84            .system_source
 85            .all_families()
 86            .expect("core text should never return an error")
 87    }
 88
 89    fn font_id(&self, font: &Font) -> Result<FontId> {
 90        let lock = self.0.upgradable_read();
 91        if let Some(font_id) = lock.font_selections.get(font) {
 92            Ok(*font_id)
 93        } else {
 94            let mut lock = RwLockUpgradableReadGuard::upgrade(lock);
 95            let candidates = if let Some(font_ids) = lock.font_ids_by_family_name.get(&font.family)
 96            {
 97                font_ids.as_slice()
 98            } else {
 99                let font_ids = lock.load_family(&font.family, font.features)?;
100                lock.font_ids_by_family_name
101                    .insert(font.family.clone(), font_ids);
102                lock.font_ids_by_family_name[&font.family].as_ref()
103            };
104
105            let candidate_properties = candidates
106                .iter()
107                .map(|font_id| lock.fonts[font_id.0].properties())
108                .collect::<SmallVec<[_; 4]>>();
109
110            let ix = font_kit::matching::find_best_match(
111                &candidate_properties,
112                &font_kit::properties::Properties {
113                    style: font.style.into(),
114                    weight: font.weight.into(),
115                    stretch: Default::default(),
116                },
117            )?;
118
119            Ok(candidates[ix])
120        }
121    }
122
123    fn font_metrics(&self, font_id: FontId) -> FontMetrics {
124        self.0.read().fonts[font_id.0].metrics().into()
125    }
126
127    fn typographic_bounds(&self, font_id: FontId, glyph_id: GlyphId) -> Result<Bounds<f32>> {
128        Ok(self.0.read().fonts[font_id.0]
129            .typographic_bounds(glyph_id.into())?
130            .into())
131    }
132
133    fn advance(&self, font_id: FontId, glyph_id: GlyphId) -> Result<Size<f32>> {
134        self.0.read().advance(font_id, glyph_id)
135    }
136
137    fn glyph_for_char(&self, font_id: FontId, ch: char) -> Option<GlyphId> {
138        self.0.read().glyph_for_char(font_id, ch)
139    }
140
141    fn glyph_raster_bounds(&self, params: &RenderGlyphParams) -> Result<Bounds<DevicePixels>> {
142        self.0.read().raster_bounds(params)
143    }
144
145    fn rasterize_glyph(
146        &self,
147        glyph_id: &RenderGlyphParams,
148    ) -> Result<(Size<DevicePixels>, Vec<u8>)> {
149        self.0.read().rasterize_glyph(glyph_id)
150    }
151
152    fn layout_line(&self, text: &str, font_size: Pixels, font_runs: &[FontRun]) -> LineLayout {
153        self.0.write().layout_line(text, font_size, font_runs)
154    }
155
156    fn wrap_line(
157        &self,
158        text: &str,
159        font_id: FontId,
160        font_size: Pixels,
161        width: Pixels,
162    ) -> Vec<usize> {
163        self.0.read().wrap_line(text, font_id, font_size, width)
164    }
165}
166
167impl MacTextSystemState {
168    fn add_fonts(&mut self, fonts: &[Arc<Vec<u8>>]) -> Result<()> {
169        self.memory_source.add_fonts(
170            fonts
171                .iter()
172                .map(|bytes| Handle::from_memory(bytes.clone(), 0)),
173        )?;
174        Ok(())
175    }
176
177    fn load_family(
178        &mut self,
179        name: &SharedString,
180        features: FontFeatures,
181    ) -> Result<SmallVec<[FontId; 4]>> {
182        let mut font_ids = SmallVec::new();
183        let family = self
184            .memory_source
185            .select_family_by_name(name.as_ref())
186            .or_else(|_| self.system_source.select_family_by_name(name.as_ref()))?;
187        for font in family.fonts() {
188            let mut font = font.load()?;
189            open_type::apply_features(&mut font, features);
190            let font_id = FontId(self.fonts.len());
191            font_ids.push(font_id);
192            let postscript_name = font.postscript_name().unwrap();
193            self.font_ids_by_postscript_name
194                .insert(postscript_name.clone(), font_id);
195            self.postscript_names_by_font_id
196                .insert(font_id, postscript_name);
197            self.fonts.push(font);
198        }
199        Ok(font_ids)
200    }
201
202    fn advance(&self, font_id: FontId, glyph_id: GlyphId) -> Result<Size<f32>> {
203        Ok(self.fonts[font_id.0].advance(glyph_id.into())?.into())
204    }
205
206    fn glyph_for_char(&self, font_id: FontId, ch: char) -> Option<GlyphId> {
207        self.fonts[font_id.0].glyph_for_char(ch).map(Into::into)
208    }
209
210    fn id_for_native_font(&mut self, requested_font: CTFont) -> FontId {
211        let postscript_name = requested_font.postscript_name();
212        if let Some(font_id) = self.font_ids_by_postscript_name.get(&postscript_name) {
213            *font_id
214        } else {
215            let font_id = FontId(self.fonts.len());
216            self.font_ids_by_postscript_name
217                .insert(postscript_name.clone(), font_id);
218            self.postscript_names_by_font_id
219                .insert(font_id, postscript_name);
220            self.fonts
221                .push(font_kit::font::Font::from_core_graphics_font(
222                    requested_font.copy_to_CGFont(),
223                ));
224            font_id
225        }
226    }
227
228    fn is_emoji(&self, font_id: FontId) -> bool {
229        self.postscript_names_by_font_id
230            .get(&font_id)
231            .map_or(false, |postscript_name| {
232                postscript_name == "AppleColorEmoji"
233            })
234    }
235
236    fn raster_bounds(&self, params: &RenderGlyphParams) -> Result<Bounds<DevicePixels>> {
237        let font = &self.fonts[params.font_id.0];
238        let scale = Transform2F::from_scale(params.scale_factor);
239        Ok(font
240            .raster_bounds(
241                params.glyph_id.into(),
242                params.font_size.into(),
243                scale,
244                HintingOptions::None,
245                font_kit::canvas::RasterizationOptions::GrayscaleAa,
246            )?
247            .into())
248    }
249
250    fn rasterize_glyph(&self, params: &RenderGlyphParams) -> Result<(Size<DevicePixels>, Vec<u8>)> {
251        let glyph_bounds = self.raster_bounds(params)?;
252        if glyph_bounds.size.width.0 == 0 || glyph_bounds.size.height.0 == 0 {
253            Err(anyhow!("glyph bounds are empty"))
254        } else {
255            // Add an extra pixel when the subpixel variant isn't zero to make room for anti-aliasing.
256            let mut bitmap_size = glyph_bounds.size;
257            if params.subpixel_variant.x > 0 {
258                bitmap_size.width += DevicePixels(1);
259            }
260            if params.subpixel_variant.y > 0 {
261                bitmap_size.height += DevicePixels(1);
262            }
263
264            let mut bytes;
265            let cx;
266            if params.is_emoji {
267                bytes = vec![0; bitmap_size.width.0 as usize * 4 * bitmap_size.height.0 as usize];
268                cx = CGContext::create_bitmap_context(
269                    Some(bytes.as_mut_ptr() as *mut _),
270                    bitmap_size.width.0 as usize,
271                    bitmap_size.height.0 as usize,
272                    8,
273                    bitmap_size.width.0 as usize * 4,
274                    &CGColorSpace::create_device_rgb(),
275                    kCGImageAlphaPremultipliedLast,
276                );
277            } else {
278                bytes = vec![0; bitmap_size.width.0 as usize * bitmap_size.height.0 as usize];
279                cx = CGContext::create_bitmap_context(
280                    Some(bytes.as_mut_ptr() as *mut _),
281                    bitmap_size.width.0 as usize,
282                    bitmap_size.height.0 as usize,
283                    8,
284                    bitmap_size.width.0 as usize,
285                    &CGColorSpace::create_device_gray(),
286                    kCGImageAlphaOnly,
287                );
288            }
289
290            // Move the origin to bottom left and account for scaling, this
291            // makes drawing text consistent with the font-kit's raster_bounds.
292            cx.translate(
293                -glyph_bounds.origin.x.0 as CGFloat,
294                (glyph_bounds.origin.y.0 + glyph_bounds.size.height.0) as CGFloat,
295            );
296            cx.scale(
297                params.scale_factor as CGFloat,
298                params.scale_factor as CGFloat,
299            );
300
301            let subpixel_shift = params
302                .subpixel_variant
303                .map(|v| v as f32 / SUBPIXEL_VARIANTS as f32);
304            cx.set_allows_font_subpixel_positioning(true);
305            cx.set_should_subpixel_position_fonts(true);
306            cx.set_allows_font_subpixel_quantization(false);
307            cx.set_should_subpixel_quantize_fonts(false);
308            self.fonts[params.font_id.0]
309                .native_font()
310                .clone_with_font_size(f32::from(params.font_size) as CGFloat)
311                .draw_glyphs(
312                    &[u32::from(params.glyph_id) as CGGlyph],
313                    &[CGPoint::new(
314                        (subpixel_shift.x / params.scale_factor) as CGFloat,
315                        (subpixel_shift.y / params.scale_factor) as CGFloat,
316                    )],
317                    cx,
318                );
319
320            if params.is_emoji {
321                // Convert from RGBA with premultiplied alpha to BGRA with straight alpha.
322                for pixel in bytes.chunks_exact_mut(4) {
323                    pixel.swap(0, 2);
324                    let a = pixel[3] as f32 / 255.;
325                    pixel[0] = (pixel[0] as f32 / a) as u8;
326                    pixel[1] = (pixel[1] as f32 / a) as u8;
327                    pixel[2] = (pixel[2] as f32 / a) as u8;
328                }
329            }
330
331            Ok((bitmap_size.into(), bytes))
332        }
333    }
334
335    fn layout_line(&mut self, text: &str, font_size: Pixels, font_runs: &[FontRun]) -> LineLayout {
336        // Construct the attributed string, converting UTF8 ranges to UTF16 ranges.
337        let mut string = CFMutableAttributedString::new();
338        {
339            string.replace_str(&CFString::new(text), CFRange::init(0, 0));
340            let utf16_line_len = string.char_len() as usize;
341
342            let mut ix_converter = StringIndexConverter::new(text);
343            for run in font_runs {
344                let utf8_end = ix_converter.utf8_ix + run.len;
345                let utf16_start = ix_converter.utf16_ix;
346
347                if utf16_start >= utf16_line_len {
348                    break;
349                }
350
351                ix_converter.advance_to_utf8_ix(utf8_end);
352                let utf16_end = cmp::min(ix_converter.utf16_ix, utf16_line_len);
353
354                let cf_range =
355                    CFRange::init(utf16_start as isize, (utf16_end - utf16_start) as isize);
356
357                let font: &FontKitFont = &self.fonts[run.font_id.0];
358                unsafe {
359                    string.set_attribute(
360                        cf_range,
361                        kCTFontAttributeName,
362                        &font.native_font().clone_with_font_size(font_size.into()),
363                    );
364                }
365
366                if utf16_end == utf16_line_len {
367                    break;
368                }
369            }
370        }
371
372        // Retrieve the glyphs from the shaped line, converting UTF16 offsets to UTF8 offsets.
373        let line = CTLine::new_with_attributed_string(string.as_concrete_TypeRef());
374
375        let mut runs = Vec::new();
376        for run in line.glyph_runs().into_iter() {
377            let attributes = run.attributes().unwrap();
378            let font = unsafe {
379                attributes
380                    .get(kCTFontAttributeName)
381                    .downcast::<CTFont>()
382                    .unwrap()
383            };
384            let font_id = self.id_for_native_font(font);
385
386            let mut ix_converter = StringIndexConverter::new(text);
387            let mut glyphs = SmallVec::new();
388            for ((glyph_id, position), glyph_utf16_ix) in run
389                .glyphs()
390                .iter()
391                .zip(run.positions().iter())
392                .zip(run.string_indices().iter())
393            {
394                let glyph_utf16_ix = usize::try_from(*glyph_utf16_ix).unwrap();
395                ix_converter.advance_to_utf16_ix(glyph_utf16_ix);
396                glyphs.push(ShapedGlyph {
397                    id: (*glyph_id).into(),
398                    position: point(position.x as f32, position.y as f32).map(px),
399                    index: ix_converter.utf8_ix,
400                    is_emoji: self.is_emoji(font_id),
401                });
402            }
403
404            runs.push(ShapedRun { font_id, glyphs })
405        }
406
407        let typographic_bounds = line.get_typographic_bounds();
408        LineLayout {
409            width: typographic_bounds.width.into(),
410            ascent: typographic_bounds.ascent.into(),
411            descent: typographic_bounds.descent.into(),
412            runs,
413            font_size,
414        }
415    }
416
417    fn wrap_line(
418        &self,
419        text: &str,
420        font_id: FontId,
421        font_size: Pixels,
422        width: Pixels,
423    ) -> Vec<usize> {
424        let mut string = CFMutableAttributedString::new();
425        string.replace_str(&CFString::new(text), CFRange::init(0, 0));
426        let cf_range = CFRange::init(0, text.encode_utf16().count() as isize);
427        let font = &self.fonts[font_id.0];
428        unsafe {
429            string.set_attribute(
430                cf_range,
431                kCTFontAttributeName,
432                &font.native_font().clone_with_font_size(font_size.into()),
433            );
434
435            let typesetter = CTTypesetterCreateWithAttributedString(string.as_concrete_TypeRef());
436            let mut ix_converter = StringIndexConverter::new(text);
437            let mut break_indices = Vec::new();
438            while ix_converter.utf8_ix < text.len() {
439                let utf16_len = CTTypesetterSuggestLineBreak(
440                    typesetter,
441                    ix_converter.utf16_ix as isize,
442                    width.into(),
443                ) as usize;
444                ix_converter.advance_to_utf16_ix(ix_converter.utf16_ix + utf16_len);
445                if ix_converter.utf8_ix >= text.len() {
446                    break;
447                }
448                break_indices.push(ix_converter.utf8_ix as usize);
449            }
450            break_indices
451        }
452    }
453}
454
455#[derive(Clone)]
456struct StringIndexConverter<'a> {
457    text: &'a str,
458    utf8_ix: usize,
459    utf16_ix: usize,
460}
461
462impl<'a> StringIndexConverter<'a> {
463    fn new(text: &'a str) -> Self {
464        Self {
465            text,
466            utf8_ix: 0,
467            utf16_ix: 0,
468        }
469    }
470
471    fn advance_to_utf8_ix(&mut self, utf8_target: usize) {
472        for (ix, c) in self.text[self.utf8_ix..].char_indices() {
473            if self.utf8_ix + ix >= utf8_target {
474                self.utf8_ix += ix;
475                return;
476            }
477            self.utf16_ix += c.len_utf16();
478        }
479        self.utf8_ix = self.text.len();
480    }
481
482    fn advance_to_utf16_ix(&mut self, utf16_target: usize) {
483        for (ix, c) in self.text[self.utf8_ix..].char_indices() {
484            if self.utf16_ix >= utf16_target {
485                self.utf8_ix += ix;
486                return;
487            }
488            self.utf16_ix += c.len_utf16();
489        }
490        self.utf8_ix = self.text.len();
491    }
492}
493
494#[repr(C)]
495pub struct __CFTypesetter(c_void);
496
497pub type CTTypesetterRef = *const __CFTypesetter;
498
499#[link(name = "CoreText", kind = "framework")]
500extern "C" {
501    fn CTTypesetterCreateWithAttributedString(string: CFAttributedStringRef) -> CTTypesetterRef;
502
503    fn CTTypesetterSuggestLineBreak(
504        typesetter: CTTypesetterRef,
505        start_index: CFIndex,
506        width: f64,
507    ) -> CFIndex;
508}
509
510impl From<Metrics> for FontMetrics {
511    fn from(metrics: Metrics) -> Self {
512        FontMetrics {
513            units_per_em: metrics.units_per_em,
514            ascent: metrics.ascent,
515            descent: metrics.descent,
516            line_gap: metrics.line_gap,
517            underline_position: metrics.underline_position,
518            underline_thickness: metrics.underline_thickness,
519            cap_height: metrics.cap_height,
520            x_height: metrics.x_height,
521            bounding_box: metrics.bounding_box.into(),
522        }
523    }
524}
525
526impl From<RectF> for Bounds<f32> {
527    fn from(rect: RectF) -> Self {
528        Bounds {
529            origin: point(rect.origin_x(), rect.origin_y()),
530            size: size(rect.width(), rect.height()),
531        }
532    }
533}
534
535impl From<RectI> for Bounds<DevicePixels> {
536    fn from(rect: RectI) -> Self {
537        Bounds {
538            origin: point(DevicePixels(rect.origin_x()), DevicePixels(rect.origin_y())),
539            size: size(DevicePixels(rect.width()), DevicePixels(rect.height())),
540        }
541    }
542}
543
544impl From<Vector2I> for Size<DevicePixels> {
545    fn from(value: Vector2I) -> Self {
546        size(value.x().into(), value.y().into())
547    }
548}
549
550impl From<RectI> for Bounds<i32> {
551    fn from(rect: RectI) -> Self {
552        Bounds {
553            origin: point(rect.origin_x(), rect.origin_y()),
554            size: size(rect.width(), rect.height()),
555        }
556    }
557}
558
559impl From<Point<u32>> for Vector2I {
560    fn from(size: Point<u32>) -> Self {
561        Vector2I::new(size.x as i32, size.y as i32)
562    }
563}
564
565impl From<Vector2F> for Size<f32> {
566    fn from(vec: Vector2F) -> Self {
567        size(vec.x(), vec.y())
568    }
569}
570
571impl From<FontWeight> for FontkitWeight {
572    fn from(value: FontWeight) -> Self {
573        FontkitWeight(value.0)
574    }
575}
576
577impl From<FontStyle> for FontkitStyle {
578    fn from(style: FontStyle) -> Self {
579        match style {
580            FontStyle::Normal => FontkitStyle::Normal,
581            FontStyle::Italic => FontkitStyle::Italic,
582            FontStyle::Oblique => FontkitStyle::Oblique,
583        }
584    }
585}
586
587// #[cfg(test)]
588// mod tests {
589//     use super::*;
590//     use crate::AppContext;
591//     use font_kit::properties::{Style, Weight};
592//     use platform::FontSystem as _;
593
594//     #[crate::test(self, retries = 5)]
595//     fn test_layout_str(_: &mut AppContext) {
596//         // This is failing intermittently on CI and we don't have time to figure it out
597//         let fonts = FontSystem::new();
598//         let menlo = fonts.load_family("Menlo", &Default::default()).unwrap();
599//         let menlo_regular = RunStyle {
600//             font_id: fonts.select_font(&menlo, &Properties::new()).unwrap(),
601//             color: Default::default(),
602//             underline: Default::default(),
603//         };
604//         let menlo_italic = RunStyle {
605//             font_id: fonts
606//                 .select_font(&menlo, Properties::new().style(Style::Italic))
607//                 .unwrap(),
608//             color: Default::default(),
609//             underline: Default::default(),
610//         };
611//         let menlo_bold = RunStyle {
612//             font_id: fonts
613//                 .select_font(&menlo, Properties::new().weight(Weight::BOLD))
614//                 .unwrap(),
615//             color: Default::default(),
616//             underline: Default::default(),
617//         };
618//         assert_ne!(menlo_regular, menlo_italic);
619//         assert_ne!(menlo_regular, menlo_bold);
620//         assert_ne!(menlo_italic, menlo_bold);
621
622//         let line = fonts.layout_line(
623//             "hello world",
624//             16.0,
625//             &[(2, menlo_bold), (4, menlo_italic), (5, menlo_regular)],
626//         );
627//         assert_eq!(line.runs.len(), 3);
628//         assert_eq!(line.runs[0].font_id, menlo_bold.font_id);
629//         assert_eq!(line.runs[0].glyphs.len(), 2);
630//         assert_eq!(line.runs[1].font_id, menlo_italic.font_id);
631//         assert_eq!(line.runs[1].glyphs.len(), 4);
632//         assert_eq!(line.runs[2].font_id, menlo_regular.font_id);
633//         assert_eq!(line.runs[2].glyphs.len(), 5);
634//     }
635
636//     #[test]
637//     fn test_glyph_offsets() -> crate::Result<()> {
638//         let fonts = FontSystem::new();
639//         let zapfino = fonts.load_family("Zapfino", &Default::default())?;
640//         let zapfino_regular = RunStyle {
641//             font_id: fonts.select_font(&zapfino, &Properties::new())?,
642//             color: Default::default(),
643//             underline: Default::default(),
644//         };
645//         let menlo = fonts.load_family("Menlo", &Default::default())?;
646//         let menlo_regular = RunStyle {
647//             font_id: fonts.select_font(&menlo, &Properties::new())?,
648//             color: Default::default(),
649//             underline: Default::default(),
650//         };
651
652//         let text = "This is, m𐍈re 𐍈r less, Zapfino!𐍈";
653//         let line = fonts.layout_line(
654//             text,
655//             16.0,
656//             &[
657//                 (9, zapfino_regular),
658//                 (13, menlo_regular),
659//                 (text.len() - 22, zapfino_regular),
660//             ],
661//         );
662//         assert_eq!(
663//             line.runs
664//                 .iter()
665//                 .flat_map(|r| r.glyphs.iter())
666//                 .map(|g| g.index)
667//                 .collect::<Vec<_>>(),
668//             vec![0, 2, 4, 5, 7, 8, 9, 10, 14, 15, 16, 17, 21, 22, 23, 24, 26, 27, 28, 29, 36, 37],
669//         );
670//         Ok(())
671//     }
672
673//     #[test]
674//     #[ignore]
675//     fn test_rasterize_glyph() {
676//         use std::{fs::File, io::BufWriter, path::Path};
677
678//         let fonts = FontSystem::new();
679//         let font_ids = fonts.load_family("Fira Code", &Default::default()).unwrap();
680//         let font_id = fonts.select_font(&font_ids, &Default::default()).unwrap();
681//         let glyph_id = fonts.glyph_for_char(font_id, 'G').unwrap();
682
683//         const VARIANTS: usize = 1;
684//         for i in 0..VARIANTS {
685//             let variant = i as f32 / VARIANTS as f32;
686//             let (bounds, bytes) = fonts
687//                 .rasterize_glyph(
688//                     font_id,
689//                     16.0,
690//                     glyph_id,
691//                     vec2f(variant, variant),
692//                     2.,
693//                     RasterizationOptions::Alpha,
694//                 )
695//                 .unwrap();
696
697//             let name = format!("/Users/as-cii/Desktop/twog-{}.png", i);
698//             let path = Path::new(&name);
699//             let file = File::create(path).unwrap();
700//             let w = &mut BufWriter::new(file);
701
702//             let mut encoder = png::Encoder::new(w, bounds.width() as u32, bounds.height() as u32);
703//             encoder.set_color(png::ColorType::Grayscale);
704//             encoder.set_depth(png::BitDepth::Eight);
705//             let mut writer = encoder.write_header().unwrap();
706//             writer.write_image_data(&bytes).unwrap();
707//         }
708//     }
709
710//     #[test]
711//     fn test_wrap_line() {
712//         let fonts = FontSystem::new();
713//         let font_ids = fonts.load_family("Helvetica", &Default::default()).unwrap();
714//         let font_id = fonts.select_font(&font_ids, &Default::default()).unwrap();
715
716//         let line = "one two three four five\n";
717//         let wrap_boundaries = fonts.wrap_line(line, font_id, 16., 64.0);
718//         assert_eq!(wrap_boundaries, &["one two ".len(), "one two three ".len()]);
719
720//         let line = "aaa Ξ±Ξ±Ξ± βœ‹βœ‹βœ‹ πŸŽ‰πŸŽ‰πŸŽ‰\n";
721//         let wrap_boundaries = fonts.wrap_line(line, font_id, 16., 64.0);
722//         assert_eq!(
723//             wrap_boundaries,
724//             &["aaa Ξ±Ξ±Ξ± ".len(), "aaa Ξ±Ξ±Ξ± βœ‹βœ‹βœ‹ ".len(),]
725//         );
726//     }
727
728//     #[test]
729//     fn test_layout_line_bom_char() {
730//         let fonts = FontSystem::new();
731//         let font_ids = fonts.load_family("Helvetica", &Default::default()).unwrap();
732//         let style = RunStyle {
733//             font_id: fonts.select_font(&font_ids, &Default::default()).unwrap(),
734//             color: Default::default(),
735//             underline: Default::default(),
736//         };
737
738//         let line = "\u{feff}";
739//         let layout = fonts.layout_line(line, 16., &[(line.len(), style)]);
740//         assert_eq!(layout.len, line.len());
741//         assert!(layout.runs.is_empty());
742
743//         let line = "a\u{feff}b";
744//         let layout = fonts.layout_line(line, 16., &[(line.len(), style)]);
745//         assert_eq!(layout.len, line.len());
746//         assert_eq!(layout.runs.len(), 1);
747//         assert_eq!(layout.runs[0].glyphs.len(), 2);
748//         assert_eq!(layout.runs[0].glyphs[0].id, 68); // a
749//                                                      // There's no glyph for \u{feff}
750//         assert_eq!(layout.runs[0].glyphs[1].id, 69); // b
751//     }
752// }