1use crate::{
2 color::ColorU,
3 fonts::{FontId, GlyphId, Metrics, Properties},
4 geometry::{
5 rect::{RectF, RectI},
6 transform2d::Transform2F,
7 vector::{vec2f, vec2i, Vector2F},
8 },
9 platform,
10 text_layout::{Glyph, LineLayout, Run},
11};
12use cocoa::appkit::{CGFloat, CGPoint};
13use core_foundation::{
14 array::CFIndex,
15 attributed_string::{CFAttributedStringRef, CFMutableAttributedString},
16 base::{CFRange, TCFType},
17 number::CFNumber,
18 string::CFString,
19};
20use core_graphics::{
21 base::CGGlyph, color_space::CGColorSpace, context::CGContext, geometry::CGAffineTransform,
22};
23use core_text::{line::CTLine, string_attributes::kCTFontAttributeName};
24use font_kit::{canvas::RasterizationOptions, hinting::HintingOptions, source::SystemSource};
25use parking_lot::RwLock;
26use std::{cell::RefCell, char, convert::TryFrom, ffi::c_void};
27
28#[allow(non_upper_case_globals)]
29const kCGImageAlphaOnly: u32 = 7;
30
31pub struct FontSystem(RwLock<FontSystemState>);
32
33struct FontSystemState {
34 source: SystemSource,
35 fonts: Vec<font_kit::font::Font>,
36}
37
38impl FontSystem {
39 pub fn new() -> Self {
40 Self(RwLock::new(FontSystemState {
41 source: SystemSource::new(),
42 fonts: Vec::new(),
43 }))
44 }
45}
46
47impl platform::FontSystem for FontSystem {
48 fn load_family(&self, name: &str) -> anyhow::Result<Vec<FontId>> {
49 self.0.write().load_family(name)
50 }
51
52 fn select_font(&self, font_ids: &[FontId], properties: &Properties) -> anyhow::Result<FontId> {
53 self.0.read().select_font(font_ids, properties)
54 }
55
56 fn font_metrics(&self, font_id: FontId) -> Metrics {
57 self.0.read().font_metrics(font_id)
58 }
59
60 fn typographic_bounds(&self, font_id: FontId, glyph_id: GlyphId) -> anyhow::Result<RectF> {
61 self.0.read().typographic_bounds(font_id, glyph_id)
62 }
63
64 fn glyph_for_char(&self, font_id: FontId, ch: char) -> Option<GlyphId> {
65 self.0.read().glyph_for_char(font_id, ch)
66 }
67
68 fn rasterize_glyph(
69 &self,
70 font_id: FontId,
71 font_size: f32,
72 glyph_id: GlyphId,
73 subpixel_shift: Vector2F,
74 scale_factor: f32,
75 ) -> Option<(RectI, Vec<u8>)> {
76 self.0
77 .read()
78 .rasterize_glyph(font_id, font_size, glyph_id, subpixel_shift, scale_factor)
79 }
80
81 fn layout_line(
82 &self,
83 text: &str,
84 font_size: f32,
85 runs: &[(usize, FontId, ColorU)],
86 ) -> LineLayout {
87 self.0.read().layout_line(text, font_size, runs)
88 }
89
90 fn wrap_line(&self, text: &str, font_id: FontId, font_size: f32, width: f32) -> Vec<usize> {
91 self.0.read().wrap_line(text, font_id, font_size, width)
92 }
93}
94
95impl FontSystemState {
96 fn load_family(&mut self, name: &str) -> anyhow::Result<Vec<FontId>> {
97 let mut font_ids = Vec::new();
98 for font in self.source.select_family_by_name(name)?.fonts() {
99 let font = font.load()?;
100 font_ids.push(FontId(self.fonts.len()));
101 self.fonts.push(font);
102 }
103 Ok(font_ids)
104 }
105
106 fn select_font(&self, font_ids: &[FontId], properties: &Properties) -> anyhow::Result<FontId> {
107 let candidates = font_ids
108 .iter()
109 .map(|font_id| self.fonts[font_id.0].properties())
110 .collect::<Vec<_>>();
111 let idx = font_kit::matching::find_best_match(&candidates, properties)?;
112 Ok(font_ids[idx])
113 }
114
115 fn font_metrics(&self, font_id: FontId) -> Metrics {
116 self.fonts[font_id.0].metrics()
117 }
118
119 fn typographic_bounds(&self, font_id: FontId, glyph_id: GlyphId) -> anyhow::Result<RectF> {
120 Ok(self.fonts[font_id.0].typographic_bounds(glyph_id)?)
121 }
122
123 fn glyph_for_char(&self, font_id: FontId, ch: char) -> Option<GlyphId> {
124 self.fonts[font_id.0].glyph_for_char(ch)
125 }
126
127 fn rasterize_glyph(
128 &self,
129 font_id: FontId,
130 font_size: f32,
131 glyph_id: GlyphId,
132 subpixel_shift: Vector2F,
133 scale_factor: f32,
134 ) -> Option<(RectI, Vec<u8>)> {
135 let font = &self.fonts[font_id.0];
136 let scale = Transform2F::from_scale(scale_factor);
137 let bounds = font
138 .raster_bounds(
139 glyph_id,
140 font_size,
141 scale,
142 HintingOptions::None,
143 RasterizationOptions::GrayscaleAa,
144 )
145 .ok()?;
146
147 if bounds.width() == 0 || bounds.height() == 0 {
148 None
149 } else {
150 // Make room for subpixel variants.
151 let bounds = RectI::new(bounds.origin(), bounds.size() + vec2i(1, 1));
152 let mut pixels = vec![0; bounds.width() as usize * bounds.height() as usize];
153 let cx = CGContext::create_bitmap_context(
154 Some(pixels.as_mut_ptr() as *mut _),
155 bounds.width() as usize,
156 bounds.height() as usize,
157 8,
158 bounds.width() as usize,
159 &CGColorSpace::create_device_gray(),
160 kCGImageAlphaOnly,
161 );
162
163 // Move the origin to bottom left and account for scaling, this
164 // makes drawing text consistent with the font-kit's raster_bounds.
165 cx.translate(0.0, bounds.height() as CGFloat);
166 let transform = scale.translate(-bounds.origin().to_f32());
167 cx.set_text_matrix(&CGAffineTransform {
168 a: transform.matrix.m11() as CGFloat,
169 b: -transform.matrix.m21() as CGFloat,
170 c: -transform.matrix.m12() as CGFloat,
171 d: transform.matrix.m22() as CGFloat,
172 tx: transform.vector.x() as CGFloat,
173 ty: -transform.vector.y() as CGFloat,
174 });
175
176 cx.set_font(&font.native_font().copy_to_CGFont());
177 cx.set_font_size(font_size as CGFloat);
178 cx.show_glyphs_at_positions(
179 &[glyph_id as CGGlyph],
180 &[CGPoint::new(
181 (subpixel_shift.x() / scale_factor) as CGFloat,
182 (subpixel_shift.y() / scale_factor) as CGFloat,
183 )],
184 );
185
186 Some((bounds, pixels))
187 }
188 }
189
190 fn layout_line(
191 &self,
192 text: &str,
193 font_size: f32,
194 runs: &[(usize, FontId, ColorU)],
195 ) -> LineLayout {
196 let font_id_attr_name = CFString::from_static_string("zed_font_id");
197
198 // Construct the attributed string, converting UTF8 ranges to UTF16 ranges.
199 let mut string = CFMutableAttributedString::new();
200 {
201 string.replace_str(&CFString::new(text), CFRange::init(0, 0));
202
203 let last_run: RefCell<Option<(usize, FontId)>> = Default::default();
204 let font_runs = runs
205 .iter()
206 .filter_map(|(len, font_id, _)| {
207 let mut last_run = last_run.borrow_mut();
208 if let Some((last_len, last_font_id)) = last_run.as_mut() {
209 if font_id == last_font_id {
210 *last_len += *len;
211 None
212 } else {
213 let result = (*last_len, *last_font_id);
214 *last_len = *len;
215 *last_font_id = *font_id;
216 Some(result)
217 }
218 } else {
219 *last_run = Some((*len, *font_id));
220 None
221 }
222 })
223 .chain(std::iter::from_fn(|| last_run.borrow_mut().take()));
224
225 let mut ix_converter = StringIndexConverter::new(text);
226 for (run_len, font_id) in font_runs {
227 let utf8_end = ix_converter.utf8_ix + run_len;
228 let utf16_start = ix_converter.utf16_ix;
229 ix_converter.advance_to_utf8_ix(utf8_end);
230
231 let cf_range = CFRange::init(
232 utf16_start as isize,
233 (ix_converter.utf16_ix - utf16_start) as isize,
234 );
235 let font = &self.fonts[font_id.0];
236 unsafe {
237 string.set_attribute(
238 cf_range,
239 kCTFontAttributeName,
240 &font.native_font().clone_with_font_size(font_size as f64),
241 );
242 string.set_attribute(
243 cf_range,
244 font_id_attr_name.as_concrete_TypeRef(),
245 &CFNumber::from(font_id.0 as i64),
246 );
247 }
248 }
249 }
250
251 // Retrieve the glyphs from the shaped line, converting UTF16 offsets to UTF8 offsets.
252 let line = CTLine::new_with_attributed_string(string.as_concrete_TypeRef());
253
254 let mut runs = Vec::new();
255 for run in line.glyph_runs().into_iter() {
256 let font_id = FontId(
257 run.attributes()
258 .unwrap()
259 .get(&font_id_attr_name)
260 .downcast::<CFNumber>()
261 .unwrap()
262 .to_i64()
263 .unwrap() as usize,
264 );
265
266 let mut ix_converter = StringIndexConverter::new(text);
267 let mut glyphs = Vec::new();
268 for ((glyph_id, position), glyph_utf16_ix) in run
269 .glyphs()
270 .iter()
271 .zip(run.positions().iter())
272 .zip(run.string_indices().iter())
273 {
274 let glyph_utf16_ix = usize::try_from(*glyph_utf16_ix).unwrap();
275 ix_converter.advance_to_utf16_ix(glyph_utf16_ix);
276 glyphs.push(Glyph {
277 id: *glyph_id as GlyphId,
278 position: vec2f(position.x as f32, position.y as f32),
279 index: ix_converter.utf8_ix,
280 });
281 }
282
283 runs.push(Run { font_id, glyphs })
284 }
285
286 let typographic_bounds = line.get_typographic_bounds();
287 LineLayout {
288 width: typographic_bounds.width as f32,
289 ascent: typographic_bounds.ascent as f32,
290 descent: typographic_bounds.descent as f32,
291 runs,
292 font_size,
293 len: text.len(),
294 }
295 }
296
297 fn wrap_line(&self, text: &str, font_id: FontId, font_size: f32, width: f32) -> Vec<usize> {
298 let mut string = CFMutableAttributedString::new();
299 string.replace_str(&CFString::new(text), CFRange::init(0, 0));
300 let cf_range = CFRange::init(0 as isize, text.encode_utf16().count() as isize);
301 let font = &self.fonts[font_id.0];
302 unsafe {
303 string.set_attribute(
304 cf_range,
305 kCTFontAttributeName,
306 &font.native_font().clone_with_font_size(font_size as f64),
307 );
308
309 let typesetter = CTTypesetterCreateWithAttributedString(string.as_concrete_TypeRef());
310 let mut ix_converter = StringIndexConverter::new(text);
311 let mut break_indices = Vec::new();
312 while ix_converter.utf8_ix < text.len() {
313 let utf16_len = CTTypesetterSuggestLineBreak(
314 typesetter,
315 ix_converter.utf16_ix as isize,
316 width as f64,
317 ) as usize;
318 ix_converter.advance_to_utf16_ix(ix_converter.utf16_ix + utf16_len);
319 break_indices.push(ix_converter.utf8_ix as usize);
320 }
321 break_indices
322 }
323 }
324}
325
326#[derive(Clone)]
327struct StringIndexConverter<'a> {
328 text: &'a str,
329 utf8_ix: usize,
330 utf16_ix: usize,
331}
332
333impl<'a> StringIndexConverter<'a> {
334 fn new(text: &'a str) -> Self {
335 Self {
336 text,
337 utf8_ix: 0,
338 utf16_ix: 0,
339 }
340 }
341
342 fn advance_to_utf8_ix(&mut self, utf8_target: usize) {
343 for (ix, c) in self.text[self.utf8_ix..].char_indices() {
344 if self.utf8_ix + ix >= utf8_target {
345 self.utf8_ix += ix;
346 return;
347 }
348 self.utf16_ix += c.len_utf16();
349 }
350 self.utf8_ix = self.text.len();
351 }
352
353 fn advance_to_utf16_ix(&mut self, utf16_target: usize) {
354 for (ix, c) in self.text[self.utf8_ix..].char_indices() {
355 if self.utf16_ix >= utf16_target {
356 self.utf8_ix += ix;
357 return;
358 }
359 self.utf16_ix += c.len_utf16();
360 }
361 self.utf8_ix = self.text.len();
362 }
363}
364
365#[repr(C)]
366pub struct __CFTypesetter(c_void);
367
368pub type CTTypesetterRef = *const __CFTypesetter;
369
370#[link(name = "CoreText", kind = "framework")]
371extern "C" {
372 fn CTTypesetterCreateWithAttributedString(string: CFAttributedStringRef) -> CTTypesetterRef;
373
374 fn CTTypesetterSuggestLineBreak(
375 typesetter: CTTypesetterRef,
376 start_index: CFIndex,
377 width: f64,
378 ) -> CFIndex;
379}
380
381#[cfg(test)]
382mod tests {
383 use crate::MutableAppContext;
384
385 use super::*;
386 use font_kit::properties::{Style, Weight};
387 use platform::FontSystem as _;
388
389 #[crate::test(self, retries = 5)]
390 fn test_layout_str(_: &mut MutableAppContext) {
391 // This is failing intermittently on CI and we don't have time to figure it out
392 let fonts = FontSystem::new();
393 let menlo = fonts.load_family("Menlo").unwrap();
394 let menlo_regular = fonts.select_font(&menlo, &Properties::new()).unwrap();
395 let menlo_italic = fonts
396 .select_font(&menlo, &Properties::new().style(Style::Italic))
397 .unwrap();
398 let menlo_bold = fonts
399 .select_font(&menlo, &Properties::new().weight(Weight::BOLD))
400 .unwrap();
401 assert_ne!(menlo_regular, menlo_italic);
402 assert_ne!(menlo_regular, menlo_bold);
403 assert_ne!(menlo_italic, menlo_bold);
404
405 let line = fonts.layout_line(
406 "hello world",
407 16.0,
408 &[
409 (2, menlo_bold, Default::default()),
410 (4, menlo_italic, Default::default()),
411 (5, menlo_regular, Default::default()),
412 ],
413 );
414 assert_eq!(line.runs.len(), 3);
415 assert_eq!(line.runs[0].font_id, menlo_bold);
416 assert_eq!(line.runs[0].glyphs.len(), 2);
417 assert_eq!(line.runs[1].font_id, menlo_italic);
418 assert_eq!(line.runs[1].glyphs.len(), 4);
419 assert_eq!(line.runs[2].font_id, menlo_regular);
420 assert_eq!(line.runs[2].glyphs.len(), 5);
421 }
422
423 #[test]
424 fn test_glyph_offsets() -> anyhow::Result<()> {
425 let fonts = FontSystem::new();
426 let zapfino = fonts.load_family("Zapfino")?;
427 let zapfino_regular = fonts.select_font(&zapfino, &Properties::new())?;
428 let menlo = fonts.load_family("Menlo")?;
429 let menlo_regular = fonts.select_font(&menlo, &Properties::new())?;
430
431 let text = "This is, mπre πr less, Zapfino!π";
432 let line = fonts.layout_line(
433 text,
434 16.0,
435 &[
436 (9, zapfino_regular, ColorU::default()),
437 (13, menlo_regular, ColorU::default()),
438 (text.len() - 22, zapfino_regular, ColorU::default()),
439 ],
440 );
441 assert_eq!(
442 line.runs
443 .iter()
444 .flat_map(|r| r.glyphs.iter())
445 .map(|g| g.index)
446 .collect::<Vec<_>>(),
447 vec![0, 2, 4, 5, 7, 8, 9, 10, 14, 15, 16, 17, 21, 22, 23, 24, 26, 27, 28, 29, 36, 37],
448 );
449 Ok(())
450 }
451
452 #[test]
453 #[ignore]
454 fn test_rasterize_glyph() {
455 use std::{fs::File, io::BufWriter, path::Path};
456
457 let fonts = FontSystem::new();
458 let font_ids = fonts.load_family("Fira Code").unwrap();
459 let font_id = fonts.select_font(&font_ids, &Default::default()).unwrap();
460 let glyph_id = fonts.glyph_for_char(font_id, 'G').unwrap();
461
462 const VARIANTS: usize = 1;
463 for i in 0..VARIANTS {
464 let variant = i as f32 / VARIANTS as f32;
465 let (bounds, bytes) = fonts
466 .rasterize_glyph(font_id, 16.0, glyph_id, vec2f(variant, variant), 2.)
467 .unwrap();
468
469 let name = format!("/Users/as-cii/Desktop/twog-{}.png", i);
470 let path = Path::new(&name);
471 let file = File::create(path).unwrap();
472 let ref mut w = BufWriter::new(file);
473
474 let mut encoder = png::Encoder::new(w, bounds.width() as u32, bounds.height() as u32);
475 encoder.set_color(png::ColorType::Grayscale);
476 encoder.set_depth(png::BitDepth::Eight);
477 let mut writer = encoder.write_header().unwrap();
478 writer.write_image_data(&bytes).unwrap();
479 }
480 }
481
482 #[test]
483 fn test_layout_line() {
484 let fonts = FontSystem::new();
485 let font_ids = fonts.load_family("Helvetica").unwrap();
486 let font_id = fonts.select_font(&font_ids, &Default::default()).unwrap();
487
488 let line = "one two three four five";
489 let wrap_boundaries = fonts.wrap_line(line, font_id, 16., 64.0);
490 assert_eq!(
491 wrap_boundaries,
492 &["one two ".len(), "one two three ".len(), line.len()]
493 );
494
495 let line = "aaa Ξ±Ξ±Ξ± βββ πππ";
496 let wrap_boundaries = fonts.wrap_line(line, font_id, 16., 64.0);
497 assert_eq!(
498 wrap_boundaries,
499 &[
500 "aaa Ξ±Ξ±Ξ± ".len(),
501 "aaa Ξ±Ξ±Ξ± βββ ".len(),
502 "aaa Ξ±Ξ±Ξ± βββ πππ".len(),
503 ]
504 );
505 }
506}