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