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