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