text_system.rs

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