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