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