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