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