text_system.rs

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