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