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