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 len: text.len(),
415 }
416 }
417
418 fn wrap_line(
419 &self,
420 text: &str,
421 font_id: FontId,
422 font_size: Pixels,
423 width: Pixels,
424 ) -> Vec<usize> {
425 let mut string = CFMutableAttributedString::new();
426 string.replace_str(&CFString::new(text), CFRange::init(0, 0));
427 let cf_range = CFRange::init(0, text.encode_utf16().count() as isize);
428 let font = &self.fonts[font_id.0];
429 unsafe {
430 string.set_attribute(
431 cf_range,
432 kCTFontAttributeName,
433 &font.native_font().clone_with_font_size(font_size.into()),
434 );
435
436 let typesetter = CTTypesetterCreateWithAttributedString(string.as_concrete_TypeRef());
437 let mut ix_converter = StringIndexConverter::new(text);
438 let mut break_indices = Vec::new();
439 while ix_converter.utf8_ix < text.len() {
440 let utf16_len = CTTypesetterSuggestLineBreak(
441 typesetter,
442 ix_converter.utf16_ix as isize,
443 width.into(),
444 ) as usize;
445 ix_converter.advance_to_utf16_ix(ix_converter.utf16_ix + utf16_len);
446 if ix_converter.utf8_ix >= text.len() {
447 break;
448 }
449 break_indices.push(ix_converter.utf8_ix as usize);
450 }
451 break_indices
452 }
453 }
454}
455
456#[derive(Clone)]
457struct StringIndexConverter<'a> {
458 text: &'a str,
459 utf8_ix: usize,
460 utf16_ix: usize,
461}
462
463impl<'a> StringIndexConverter<'a> {
464 fn new(text: &'a str) -> Self {
465 Self {
466 text,
467 utf8_ix: 0,
468 utf16_ix: 0,
469 }
470 }
471
472 fn advance_to_utf8_ix(&mut self, utf8_target: usize) {
473 for (ix, c) in self.text[self.utf8_ix..].char_indices() {
474 if self.utf8_ix + ix >= utf8_target {
475 self.utf8_ix += ix;
476 return;
477 }
478 self.utf16_ix += c.len_utf16();
479 }
480 self.utf8_ix = self.text.len();
481 }
482
483 fn advance_to_utf16_ix(&mut self, utf16_target: usize) {
484 for (ix, c) in self.text[self.utf8_ix..].char_indices() {
485 if self.utf16_ix >= utf16_target {
486 self.utf8_ix += ix;
487 return;
488 }
489 self.utf16_ix += c.len_utf16();
490 }
491 self.utf8_ix = self.text.len();
492 }
493}
494
495#[repr(C)]
496pub struct __CFTypesetter(c_void);
497
498pub type CTTypesetterRef = *const __CFTypesetter;
499
500#[link(name = "CoreText", kind = "framework")]
501extern "C" {
502 fn CTTypesetterCreateWithAttributedString(string: CFAttributedStringRef) -> CTTypesetterRef;
503
504 fn CTTypesetterSuggestLineBreak(
505 typesetter: CTTypesetterRef,
506 start_index: CFIndex,
507 width: f64,
508 ) -> CFIndex;
509}
510
511impl From<Metrics> for FontMetrics {
512 fn from(metrics: Metrics) -> Self {
513 FontMetrics {
514 units_per_em: metrics.units_per_em,
515 ascent: metrics.ascent,
516 descent: metrics.descent,
517 line_gap: metrics.line_gap,
518 underline_position: metrics.underline_position,
519 underline_thickness: metrics.underline_thickness,
520 cap_height: metrics.cap_height,
521 x_height: metrics.x_height,
522 bounding_box: metrics.bounding_box.into(),
523 }
524 }
525}
526
527impl From<RectF> for Bounds<f32> {
528 fn from(rect: RectF) -> Self {
529 Bounds {
530 origin: point(rect.origin_x(), rect.origin_y()),
531 size: size(rect.width(), rect.height()),
532 }
533 }
534}
535
536impl From<RectI> for Bounds<DevicePixels> {
537 fn from(rect: RectI) -> Self {
538 Bounds {
539 origin: point(DevicePixels(rect.origin_x()), DevicePixels(rect.origin_y())),
540 size: size(DevicePixels(rect.width()), DevicePixels(rect.height())),
541 }
542 }
543}
544
545impl From<Vector2I> for Size<DevicePixels> {
546 fn from(value: Vector2I) -> Self {
547 size(value.x().into(), value.y().into())
548 }
549}
550
551impl From<RectI> for Bounds<i32> {
552 fn from(rect: RectI) -> Self {
553 Bounds {
554 origin: point(rect.origin_x(), rect.origin_y()),
555 size: size(rect.width(), rect.height()),
556 }
557 }
558}
559
560impl From<Point<u32>> for Vector2I {
561 fn from(size: Point<u32>) -> Self {
562 Vector2I::new(size.x as i32, size.y as i32)
563 }
564}
565
566impl From<Vector2F> for Size<f32> {
567 fn from(vec: Vector2F) -> Self {
568 size(vec.x(), vec.y())
569 }
570}
571
572impl From<FontWeight> for FontkitWeight {
573 fn from(value: FontWeight) -> Self {
574 FontkitWeight(value.0)
575 }
576}
577
578impl From<FontStyle> for FontkitStyle {
579 fn from(style: FontStyle) -> Self {
580 match style {
581 FontStyle::Normal => FontkitStyle::Normal,
582 FontStyle::Italic => FontkitStyle::Italic,
583 FontStyle::Oblique => FontkitStyle::Oblique,
584 }
585 }
586}
587
588// #[cfg(test)]
589// mod tests {
590// use super::*;
591// use crate::AppContext;
592// use font_kit::properties::{Style, Weight};
593// use platform::FontSystem as _;
594
595// #[crate::test(self, retries = 5)]
596// fn test_layout_str(_: &mut AppContext) {
597// // This is failing intermittently on CI and we don't have time to figure it out
598// let fonts = FontSystem::new();
599// let menlo = fonts.load_family("Menlo", &Default::default()).unwrap();
600// let menlo_regular = RunStyle {
601// font_id: fonts.select_font(&menlo, &Properties::new()).unwrap(),
602// color: Default::default(),
603// underline: Default::default(),
604// };
605// let menlo_italic = RunStyle {
606// font_id: fonts
607// .select_font(&menlo, Properties::new().style(Style::Italic))
608// .unwrap(),
609// color: Default::default(),
610// underline: Default::default(),
611// };
612// let menlo_bold = RunStyle {
613// font_id: fonts
614// .select_font(&menlo, Properties::new().weight(Weight::BOLD))
615// .unwrap(),
616// color: Default::default(),
617// underline: Default::default(),
618// };
619// assert_ne!(menlo_regular, menlo_italic);
620// assert_ne!(menlo_regular, menlo_bold);
621// assert_ne!(menlo_italic, menlo_bold);
622
623// let line = fonts.layout_line(
624// "hello world",
625// 16.0,
626// &[(2, menlo_bold), (4, menlo_italic), (5, menlo_regular)],
627// );
628// assert_eq!(line.runs.len(), 3);
629// assert_eq!(line.runs[0].font_id, menlo_bold.font_id);
630// assert_eq!(line.runs[0].glyphs.len(), 2);
631// assert_eq!(line.runs[1].font_id, menlo_italic.font_id);
632// assert_eq!(line.runs[1].glyphs.len(), 4);
633// assert_eq!(line.runs[2].font_id, menlo_regular.font_id);
634// assert_eq!(line.runs[2].glyphs.len(), 5);
635// }
636
637// #[test]
638// fn test_glyph_offsets() -> crate::Result<()> {
639// let fonts = FontSystem::new();
640// let zapfino = fonts.load_family("Zapfino", &Default::default())?;
641// let zapfino_regular = RunStyle {
642// font_id: fonts.select_font(&zapfino, &Properties::new())?,
643// color: Default::default(),
644// underline: Default::default(),
645// };
646// let menlo = fonts.load_family("Menlo", &Default::default())?;
647// let menlo_regular = RunStyle {
648// font_id: fonts.select_font(&menlo, &Properties::new())?,
649// color: Default::default(),
650// underline: Default::default(),
651// };
652
653// let text = "This is, mπre πr less, Zapfino!π";
654// let line = fonts.layout_line(
655// text,
656// 16.0,
657// &[
658// (9, zapfino_regular),
659// (13, menlo_regular),
660// (text.len() - 22, zapfino_regular),
661// ],
662// );
663// assert_eq!(
664// line.runs
665// .iter()
666// .flat_map(|r| r.glyphs.iter())
667// .map(|g| g.index)
668// .collect::<Vec<_>>(),
669// vec![0, 2, 4, 5, 7, 8, 9, 10, 14, 15, 16, 17, 21, 22, 23, 24, 26, 27, 28, 29, 36, 37],
670// );
671// Ok(())
672// }
673
674// #[test]
675// #[ignore]
676// fn test_rasterize_glyph() {
677// use std::{fs::File, io::BufWriter, path::Path};
678
679// let fonts = FontSystem::new();
680// let font_ids = fonts.load_family("Fira Code", &Default::default()).unwrap();
681// let font_id = fonts.select_font(&font_ids, &Default::default()).unwrap();
682// let glyph_id = fonts.glyph_for_char(font_id, 'G').unwrap();
683
684// const VARIANTS: usize = 1;
685// for i in 0..VARIANTS {
686// let variant = i as f32 / VARIANTS as f32;
687// let (bounds, bytes) = fonts
688// .rasterize_glyph(
689// font_id,
690// 16.0,
691// glyph_id,
692// vec2f(variant, variant),
693// 2.,
694// RasterizationOptions::Alpha,
695// )
696// .unwrap();
697
698// let name = format!("/Users/as-cii/Desktop/twog-{}.png", i);
699// let path = Path::new(&name);
700// let file = File::create(path).unwrap();
701// let w = &mut BufWriter::new(file);
702
703// let mut encoder = png::Encoder::new(w, bounds.width() as u32, bounds.height() as u32);
704// encoder.set_color(png::ColorType::Grayscale);
705// encoder.set_depth(png::BitDepth::Eight);
706// let mut writer = encoder.write_header().unwrap();
707// writer.write_image_data(&bytes).unwrap();
708// }
709// }
710
711// #[test]
712// fn test_wrap_line() {
713// let fonts = FontSystem::new();
714// let font_ids = fonts.load_family("Helvetica", &Default::default()).unwrap();
715// let font_id = fonts.select_font(&font_ids, &Default::default()).unwrap();
716
717// let line = "one two three four five\n";
718// let wrap_boundaries = fonts.wrap_line(line, font_id, 16., 64.0);
719// assert_eq!(wrap_boundaries, &["one two ".len(), "one two three ".len()]);
720
721// let line = "aaa Ξ±Ξ±Ξ± βββ πππ\n";
722// let wrap_boundaries = fonts.wrap_line(line, font_id, 16., 64.0);
723// assert_eq!(
724// wrap_boundaries,
725// &["aaa Ξ±Ξ±Ξ± ".len(), "aaa Ξ±Ξ±Ξ± βββ ".len(),]
726// );
727// }
728
729// #[test]
730// fn test_layout_line_bom_char() {
731// let fonts = FontSystem::new();
732// let font_ids = fonts.load_family("Helvetica", &Default::default()).unwrap();
733// let style = RunStyle {
734// font_id: fonts.select_font(&font_ids, &Default::default()).unwrap(),
735// color: Default::default(),
736// underline: Default::default(),
737// };
738
739// let line = "\u{feff}";
740// let layout = fonts.layout_line(line, 16., &[(line.len(), style)]);
741// assert_eq!(layout.len, line.len());
742// assert!(layout.runs.is_empty());
743
744// let line = "a\u{feff}b";
745// let layout = fonts.layout_line(line, 16., &[(line.len(), style)]);
746// assert_eq!(layout.len, line.len());
747// assert_eq!(layout.runs.len(), 1);
748// assert_eq!(layout.runs[0].glyphs.len(), 2);
749// assert_eq!(layout.runs[0].glyphs[0].id, 68); // a
750// // There's no glyph for \u{feff}
751// assert_eq!(layout.runs[0].glyphs[1].id, 69); // b
752// }
753// }