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