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