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
237 // This block contains a precautionary fix to guard against loading fonts
238 // that might cause panics due to `.unwrap()`s up the chain.
239 {
240 // We use the 'm' character for text measurements in various spots
241 // (e.g., the editor). However, at time of writing some of those usages
242 // will panic if the font has no 'm' glyph.
243 //
244 // Therefore, we check up front that the font has the necessary glyph.
245 let has_m_glyph = font.glyph_for_char('m').is_some();
246
247 // HACK: The 'Segoe Fluent Icons' font does not have an 'm' glyph,
248 // but we need to be able to load it for rendering Windows icons in
249 // the Storybook (on macOS).
250 let is_segoe_fluent_icons = font.full_name() == "Segoe Fluent Icons";
251
252 if !has_m_glyph && !is_segoe_fluent_icons {
253 // I spent far too long trying to track down why a font missing the 'm'
254 // character wasn't loading. This log statement will hopefully save
255 // someone else from suffering the same fate.
256 log::warn!(
257 "font '{}' has no 'm' character and was not loaded",
258 font.full_name()
259 );
260 continue;
261 }
262 }
263
264 // We've seen a number of panics in production caused by calling font.properties()
265 // which unwraps a downcast to CFNumber. This is an attempt to avoid the panic,
266 // and to try and identify the incalcitrant font.
267 let traits = font.native_font().all_traits();
268 if unsafe {
269 !(traits
270 .get(kCTFontSymbolicTrait)
271 .downcast::<CFNumber>()
272 .is_some()
273 && traits
274 .get(kCTFontWidthTrait)
275 .downcast::<CFNumber>()
276 .is_some()
277 && traits
278 .get(kCTFontWeightTrait)
279 .downcast::<CFNumber>()
280 .is_some()
281 && traits
282 .get(kCTFontSlantTrait)
283 .downcast::<CFNumber>()
284 .is_some())
285 } {
286 log::error!(
287 "Failed to read traits for font {:?}",
288 font.postscript_name().unwrap()
289 );
290 continue;
291 }
292
293 let font_id = FontId(self.fonts.len());
294 font_ids.push(font_id);
295 let postscript_name = font.postscript_name().unwrap();
296 self.font_ids_by_postscript_name
297 .insert(postscript_name.clone(), font_id);
298 self.postscript_names_by_font_id
299 .insert(font_id, postscript_name);
300 self.fonts.push(font);
301 }
302 Ok(font_ids)
303 }
304
305 fn advance(&self, font_id: FontId, glyph_id: GlyphId) -> Result<Size<f32>> {
306 Ok(self.fonts[font_id.0].advance(glyph_id.0)?.into())
307 }
308
309 fn glyph_for_char(&self, font_id: FontId, ch: char) -> Option<GlyphId> {
310 self.fonts[font_id.0].glyph_for_char(ch).map(GlyphId)
311 }
312
313 fn id_for_native_font(&mut self, requested_font: CTFont) -> FontId {
314 let postscript_name = requested_font.postscript_name();
315 if let Some(font_id) = self.font_ids_by_postscript_name.get(&postscript_name) {
316 *font_id
317 } else {
318 let font_id = FontId(self.fonts.len());
319 self.font_ids_by_postscript_name
320 .insert(postscript_name.clone(), font_id);
321 self.postscript_names_by_font_id
322 .insert(font_id, postscript_name);
323 self.fonts
324 .push(font_kit::font::Font::from_core_graphics_font(
325 requested_font.copy_to_CGFont(),
326 ));
327 font_id
328 }
329 }
330
331 fn is_emoji(&self, font_id: FontId) -> bool {
332 self.postscript_names_by_font_id
333 .get(&font_id)
334 .map_or(false, |postscript_name| {
335 postscript_name == "AppleColorEmoji"
336 })
337 }
338
339 fn raster_bounds(&self, params: &RenderGlyphParams) -> Result<Bounds<DevicePixels>> {
340 let font = &self.fonts[params.font_id.0];
341 let scale = Transform2F::from_scale(params.scale_factor);
342 Ok(font
343 .raster_bounds(
344 params.glyph_id.0,
345 params.font_size.into(),
346 scale,
347 HintingOptions::None,
348 font_kit::canvas::RasterizationOptions::GrayscaleAa,
349 )?
350 .into())
351 }
352
353 fn rasterize_glyph(
354 &self,
355 params: &RenderGlyphParams,
356 glyph_bounds: Bounds<DevicePixels>,
357 ) -> Result<(Size<DevicePixels>, Vec<u8>)> {
358 if glyph_bounds.size.width.0 == 0 || glyph_bounds.size.height.0 == 0 {
359 Err(anyhow!("glyph bounds are empty"))
360 } else {
361 // Add an extra pixel when the subpixel variant isn't zero to make room for anti-aliasing.
362 let mut bitmap_size = glyph_bounds.size;
363 if params.subpixel_variant.x > 0 {
364 bitmap_size.width += DevicePixels(1);
365 }
366 if params.subpixel_variant.y > 0 {
367 bitmap_size.height += DevicePixels(1);
368 }
369 let bitmap_size = bitmap_size;
370
371 let mut bytes;
372 let cx;
373 if params.is_emoji {
374 bytes = vec![0; bitmap_size.width.0 as usize * 4 * bitmap_size.height.0 as usize];
375 cx = CGContext::create_bitmap_context(
376 Some(bytes.as_mut_ptr() as *mut _),
377 bitmap_size.width.0 as usize,
378 bitmap_size.height.0 as usize,
379 8,
380 bitmap_size.width.0 as usize * 4,
381 &CGColorSpace::create_device_rgb(),
382 kCGImageAlphaPremultipliedLast,
383 );
384 } else {
385 bytes = vec![0; bitmap_size.width.0 as usize * bitmap_size.height.0 as usize];
386 cx = CGContext::create_bitmap_context(
387 Some(bytes.as_mut_ptr() as *mut _),
388 bitmap_size.width.0 as usize,
389 bitmap_size.height.0 as usize,
390 8,
391 bitmap_size.width.0 as usize,
392 &CGColorSpace::create_device_gray(),
393 kCGImageAlphaOnly,
394 );
395 }
396
397 // Move the origin to bottom left and account for scaling, this
398 // makes drawing text consistent with the font-kit's raster_bounds.
399 cx.translate(
400 -glyph_bounds.origin.x.0 as CGFloat,
401 (glyph_bounds.origin.y.0 + glyph_bounds.size.height.0) as CGFloat,
402 );
403 cx.scale(
404 params.scale_factor as CGFloat,
405 params.scale_factor as CGFloat,
406 );
407
408 let subpixel_shift = params
409 .subpixel_variant
410 .map(|v| v as f32 / SUBPIXEL_VARIANTS as f32);
411 cx.set_allows_font_subpixel_positioning(true);
412 cx.set_should_subpixel_position_fonts(true);
413 cx.set_allows_font_subpixel_quantization(false);
414 cx.set_should_subpixel_quantize_fonts(false);
415 self.fonts[params.font_id.0]
416 .native_font()
417 .clone_with_font_size(f32::from(params.font_size) as CGFloat)
418 .draw_glyphs(
419 &[params.glyph_id.0 as CGGlyph],
420 &[CGPoint::new(
421 (subpixel_shift.x / params.scale_factor) as CGFloat,
422 (subpixel_shift.y / params.scale_factor) as CGFloat,
423 )],
424 cx,
425 );
426
427 if params.is_emoji {
428 // Convert from RGBA with premultiplied alpha to RGBA with straight alpha.
429 for pixel in bytes.chunks_exact_mut(4) {
430 let a = pixel[3] as f32 / 255.;
431 pixel[0] = (pixel[0] as f32 / a) as u8;
432 pixel[1] = (pixel[1] as f32 / a) as u8;
433 pixel[2] = (pixel[2] as f32 / a) as u8;
434 }
435 }
436
437 Ok((bitmap_size, bytes))
438 }
439 }
440
441 fn layout_line(&mut self, text: &str, font_size: Pixels, font_runs: &[FontRun]) -> LineLayout {
442 // Construct the attributed string, converting UTF8 ranges to UTF16 ranges.
443 let mut string = CFMutableAttributedString::new();
444 {
445 string.replace_str(&CFString::new(text), CFRange::init(0, 0));
446 let utf16_line_len = string.char_len() as usize;
447
448 let mut ix_converter = StringIndexConverter::new(text);
449 for run in font_runs {
450 let utf8_end = ix_converter.utf8_ix + run.len;
451 let utf16_start = ix_converter.utf16_ix;
452
453 if utf16_start >= utf16_line_len {
454 break;
455 }
456
457 ix_converter.advance_to_utf8_ix(utf8_end);
458 let utf16_end = cmp::min(ix_converter.utf16_ix, utf16_line_len);
459
460 let cf_range =
461 CFRange::init(utf16_start as isize, (utf16_end - utf16_start) as isize);
462
463 let font: &FontKitFont = &self.fonts[run.font_id.0];
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 fn wrap_line(
525 &self,
526 text: &str,
527 font_id: FontId,
528 font_size: Pixels,
529 width: Pixels,
530 ) -> Vec<usize> {
531 let mut string = CFMutableAttributedString::new();
532 string.replace_str(&CFString::new(text), CFRange::init(0, 0));
533 let cf_range = CFRange::init(0, text.encode_utf16().count() as isize);
534 let font = &self.fonts[font_id.0];
535 unsafe {
536 string.set_attribute(
537 cf_range,
538 kCTFontAttributeName,
539 &font.native_font().clone_with_font_size(font_size.into()),
540 );
541
542 let typesetter = CTTypesetterCreateWithAttributedString(string.as_concrete_TypeRef());
543 let mut ix_converter = StringIndexConverter::new(text);
544 let mut break_indices = Vec::new();
545 while ix_converter.utf8_ix < text.len() {
546 let utf16_len = CTTypesetterSuggestLineBreak(
547 typesetter,
548 ix_converter.utf16_ix as isize,
549 width.into(),
550 ) as usize;
551 ix_converter.advance_to_utf16_ix(ix_converter.utf16_ix + utf16_len);
552 if ix_converter.utf8_ix >= text.len() {
553 break;
554 }
555 break_indices.push(ix_converter.utf8_ix);
556 }
557 break_indices
558 }
559 }
560}
561
562#[derive(Clone)]
563struct StringIndexConverter<'a> {
564 text: &'a str,
565 utf8_ix: usize,
566 utf16_ix: usize,
567}
568
569impl<'a> StringIndexConverter<'a> {
570 fn new(text: &'a str) -> Self {
571 Self {
572 text,
573 utf8_ix: 0,
574 utf16_ix: 0,
575 }
576 }
577
578 fn advance_to_utf8_ix(&mut self, utf8_target: usize) {
579 for (ix, c) in self.text[self.utf8_ix..].char_indices() {
580 if self.utf8_ix + ix >= utf8_target {
581 self.utf8_ix += ix;
582 return;
583 }
584 self.utf16_ix += c.len_utf16();
585 }
586 self.utf8_ix = self.text.len();
587 }
588
589 fn advance_to_utf16_ix(&mut self, utf16_target: usize) {
590 for (ix, c) in self.text[self.utf8_ix..].char_indices() {
591 if self.utf16_ix >= utf16_target {
592 self.utf8_ix += ix;
593 return;
594 }
595 self.utf16_ix += c.len_utf16();
596 }
597 self.utf8_ix = self.text.len();
598 }
599}
600
601#[repr(C)]
602pub(crate) struct __CFTypesetter(c_void);
603
604type CTTypesetterRef = *const __CFTypesetter;
605
606#[link(name = "CoreText", kind = "framework")]
607extern "C" {
608 fn CTTypesetterCreateWithAttributedString(string: CFAttributedStringRef) -> CTTypesetterRef;
609
610 fn CTTypesetterSuggestLineBreak(
611 typesetter: CTTypesetterRef,
612 start_index: CFIndex,
613 width: f64,
614 ) -> CFIndex;
615}
616
617impl From<Metrics> for FontMetrics {
618 fn from(metrics: Metrics) -> Self {
619 FontMetrics {
620 units_per_em: metrics.units_per_em,
621 ascent: metrics.ascent,
622 descent: metrics.descent,
623 line_gap: metrics.line_gap,
624 underline_position: metrics.underline_position,
625 underline_thickness: metrics.underline_thickness,
626 cap_height: metrics.cap_height,
627 x_height: metrics.x_height,
628 bounding_box: metrics.bounding_box.into(),
629 }
630 }
631}
632
633impl From<RectF> for Bounds<f32> {
634 fn from(rect: RectF) -> 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<RectI> for Bounds<DevicePixels> {
643 fn from(rect: RectI) -> Self {
644 Bounds {
645 origin: point(DevicePixels(rect.origin_x()), DevicePixels(rect.origin_y())),
646 size: size(DevicePixels(rect.width()), DevicePixels(rect.height())),
647 }
648 }
649}
650
651impl From<Vector2I> for Size<DevicePixels> {
652 fn from(value: Vector2I) -> Self {
653 size(value.x().into(), value.y().into())
654 }
655}
656
657impl From<RectI> for Bounds<i32> {
658 fn from(rect: RectI) -> Self {
659 Bounds {
660 origin: point(rect.origin_x(), rect.origin_y()),
661 size: size(rect.width(), rect.height()),
662 }
663 }
664}
665
666impl From<Point<u32>> for Vector2I {
667 fn from(size: Point<u32>) -> Self {
668 Vector2I::new(size.x as i32, size.y as i32)
669 }
670}
671
672impl From<Vector2F> for Size<f32> {
673 fn from(vec: Vector2F) -> Self {
674 size(vec.x(), vec.y())
675 }
676}
677
678impl From<FontWeight> for FontkitWeight {
679 fn from(value: FontWeight) -> Self {
680 FontkitWeight(value.0)
681 }
682}
683
684impl From<FontStyle> for FontkitStyle {
685 fn from(style: FontStyle) -> Self {
686 match style {
687 FontStyle::Normal => FontkitStyle::Normal,
688 FontStyle::Italic => FontkitStyle::Italic,
689 FontStyle::Oblique => FontkitStyle::Oblique,
690 }
691 }
692}
693
694// Some fonts may have no attributest despite `core_text` requiring them (and panicking).
695// This is the same version as `core_text` has without `expect` calls.
696mod lenient_font_attributes {
697 use core_foundation::{
698 base::{CFRetain, CFType, TCFType},
699 string::{CFString, CFStringRef},
700 };
701 use core_text::font_descriptor::{
702 kCTFontFamilyNameAttribute, CTFontDescriptor, CTFontDescriptorCopyAttribute,
703 };
704
705 pub fn family_name(descriptor: &CTFontDescriptor) -> Option<String> {
706 unsafe { get_string_attribute(descriptor, kCTFontFamilyNameAttribute) }
707 }
708
709 fn get_string_attribute(
710 descriptor: &CTFontDescriptor,
711 attribute: CFStringRef,
712 ) -> Option<String> {
713 unsafe {
714 let value = CTFontDescriptorCopyAttribute(descriptor.as_concrete_TypeRef(), attribute);
715 if value.is_null() {
716 return None;
717 }
718
719 let value = CFType::wrap_under_create_rule(value);
720 assert!(value.instance_of::<CFString>());
721 let s = wrap_under_get_rule(value.as_CFTypeRef() as CFStringRef);
722 Some(s.to_string())
723 }
724 }
725
726 unsafe fn wrap_under_get_rule(reference: CFStringRef) -> CFString {
727 assert!(!reference.is_null(), "Attempted to create a NULL object.");
728 let reference = CFRetain(reference as *const ::std::os::raw::c_void) as CFStringRef;
729 TCFType::wrap_under_create_rule(reference)
730 }
731}
732
733#[cfg(test)]
734mod tests {
735 use crate::{font, px, FontRun, GlyphId, MacTextSystem, PlatformTextSystem};
736
737 #[test]
738 fn test_wrap_line() {
739 let fonts = MacTextSystem::new();
740 let font_id = fonts.font_id(&font("Helvetica")).unwrap();
741
742 let line = "one two three four five\n";
743 let wrap_boundaries = fonts.wrap_line(line, font_id, px(16.), px(64.0));
744 assert_eq!(wrap_boundaries, &["one two ".len(), "one two three ".len()]);
745
746 let line = "aaa ααα ✋✋✋ 🎉🎉🎉\n";
747 let wrap_boundaries = fonts.wrap_line(line, font_id, px(16.), px(64.0));
748 assert_eq!(
749 wrap_boundaries,
750 &["aaa ααα ".len(), "aaa ααα ✋✋✋ ".len(),]
751 );
752 }
753
754 #[test]
755 fn test_layout_line_bom_char() {
756 let fonts = MacTextSystem::new();
757 let font_id = fonts.font_id(&font("Helvetica")).unwrap();
758 let line = "\u{feff}";
759 let mut style = FontRun {
760 font_id,
761 len: line.len(),
762 };
763
764 let layout = fonts.layout_line(line, px(16.), &[style]);
765 assert_eq!(layout.len, line.len());
766 assert!(layout.runs.is_empty());
767
768 let line = "a\u{feff}b";
769 style.len = line.len();
770 let layout = fonts.layout_line(line, px(16.), &[style]);
771 assert_eq!(layout.len, line.len());
772 assert_eq!(layout.runs.len(), 1);
773 assert_eq!(layout.runs[0].glyphs.len(), 2);
774 assert_eq!(layout.runs[0].glyphs[0].id, GlyphId(68u32)); // a
775 // There's no glyph for \u{feff}
776 assert_eq!(layout.runs[0].glyphs[1].id, GlyphId(69u32)); // b
777 }
778}