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