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 if ix_converter.utf8_ix >= text.len() {
320 break;
321 }
322 break_indices.push(ix_converter.utf8_ix as usize);
323 }
324 break_indices
325 }
326 }
327}
328
329#[derive(Clone)]
330struct StringIndexConverter<'a> {
331 text: &'a str,
332 utf8_ix: usize,
333 utf16_ix: usize,
334}
335
336impl<'a> StringIndexConverter<'a> {
337 fn new(text: &'a str) -> Self {
338 Self {
339 text,
340 utf8_ix: 0,
341 utf16_ix: 0,
342 }
343 }
344
345 fn advance_to_utf8_ix(&mut self, utf8_target: usize) {
346 for (ix, c) in self.text[self.utf8_ix..].char_indices() {
347 if self.utf8_ix + ix >= utf8_target {
348 self.utf8_ix += ix;
349 return;
350 }
351 self.utf16_ix += c.len_utf16();
352 }
353 self.utf8_ix = self.text.len();
354 }
355
356 fn advance_to_utf16_ix(&mut self, utf16_target: usize) {
357 for (ix, c) in self.text[self.utf8_ix..].char_indices() {
358 if self.utf16_ix >= utf16_target {
359 self.utf8_ix += ix;
360 return;
361 }
362 self.utf16_ix += c.len_utf16();
363 }
364 self.utf8_ix = self.text.len();
365 }
366}
367
368#[repr(C)]
369pub struct __CFTypesetter(c_void);
370
371pub type CTTypesetterRef = *const __CFTypesetter;
372
373#[link(name = "CoreText", kind = "framework")]
374extern "C" {
375 fn CTTypesetterCreateWithAttributedString(string: CFAttributedStringRef) -> CTTypesetterRef;
376
377 fn CTTypesetterSuggestLineBreak(
378 typesetter: CTTypesetterRef,
379 start_index: CFIndex,
380 width: f64,
381 ) -> CFIndex;
382}
383
384#[cfg(test)]
385mod tests {
386 use crate::MutableAppContext;
387
388 use super::*;
389 use font_kit::properties::{Style, Weight};
390 use platform::FontSystem as _;
391
392 #[crate::test(self, retries = 5)]
393 fn test_layout_str(_: &mut MutableAppContext) {
394 // This is failing intermittently on CI and we don't have time to figure it out
395 let fonts = FontSystem::new();
396 let menlo = fonts.load_family("Menlo").unwrap();
397 let menlo_regular = fonts.select_font(&menlo, &Properties::new()).unwrap();
398 let menlo_italic = fonts
399 .select_font(&menlo, &Properties::new().style(Style::Italic))
400 .unwrap();
401 let menlo_bold = fonts
402 .select_font(&menlo, &Properties::new().weight(Weight::BOLD))
403 .unwrap();
404 assert_ne!(menlo_regular, menlo_italic);
405 assert_ne!(menlo_regular, menlo_bold);
406 assert_ne!(menlo_italic, menlo_bold);
407
408 let line = fonts.layout_line(
409 "hello world",
410 16.0,
411 &[
412 (2, menlo_bold, Default::default()),
413 (4, menlo_italic, Default::default()),
414 (5, menlo_regular, Default::default()),
415 ],
416 );
417 assert_eq!(line.runs.len(), 3);
418 assert_eq!(line.runs[0].font_id, menlo_bold);
419 assert_eq!(line.runs[0].glyphs.len(), 2);
420 assert_eq!(line.runs[1].font_id, menlo_italic);
421 assert_eq!(line.runs[1].glyphs.len(), 4);
422 assert_eq!(line.runs[2].font_id, menlo_regular);
423 assert_eq!(line.runs[2].glyphs.len(), 5);
424 }
425
426 #[test]
427 fn test_glyph_offsets() -> anyhow::Result<()> {
428 let fonts = FontSystem::new();
429 let zapfino = fonts.load_family("Zapfino")?;
430 let zapfino_regular = fonts.select_font(&zapfino, &Properties::new())?;
431 let menlo = fonts.load_family("Menlo")?;
432 let menlo_regular = fonts.select_font(&menlo, &Properties::new())?;
433
434 let text = "This is, mπre πr less, Zapfino!π";
435 let line = fonts.layout_line(
436 text,
437 16.0,
438 &[
439 (9, zapfino_regular, ColorU::default()),
440 (13, menlo_regular, ColorU::default()),
441 (text.len() - 22, zapfino_regular, ColorU::default()),
442 ],
443 );
444 assert_eq!(
445 line.runs
446 .iter()
447 .flat_map(|r| r.glyphs.iter())
448 .map(|g| g.index)
449 .collect::<Vec<_>>(),
450 vec![0, 2, 4, 5, 7, 8, 9, 10, 14, 15, 16, 17, 21, 22, 23, 24, 26, 27, 28, 29, 36, 37],
451 );
452 Ok(())
453 }
454
455 #[test]
456 #[ignore]
457 fn test_rasterize_glyph() {
458 use std::{fs::File, io::BufWriter, path::Path};
459
460 let fonts = FontSystem::new();
461 let font_ids = fonts.load_family("Fira Code").unwrap();
462 let font_id = fonts.select_font(&font_ids, &Default::default()).unwrap();
463 let glyph_id = fonts.glyph_for_char(font_id, 'G').unwrap();
464
465 const VARIANTS: usize = 1;
466 for i in 0..VARIANTS {
467 let variant = i as f32 / VARIANTS as f32;
468 let (bounds, bytes) = fonts
469 .rasterize_glyph(font_id, 16.0, glyph_id, vec2f(variant, variant), 2.)
470 .unwrap();
471
472 let name = format!("/Users/as-cii/Desktop/twog-{}.png", i);
473 let path = Path::new(&name);
474 let file = File::create(path).unwrap();
475 let ref mut w = BufWriter::new(file);
476
477 let mut encoder = png::Encoder::new(w, bounds.width() as u32, bounds.height() as u32);
478 encoder.set_color(png::ColorType::Grayscale);
479 encoder.set_depth(png::BitDepth::Eight);
480 let mut writer = encoder.write_header().unwrap();
481 writer.write_image_data(&bytes).unwrap();
482 }
483 }
484
485 #[test]
486 fn test_layout_line() {
487 let fonts = FontSystem::new();
488 let font_ids = fonts.load_family("Helvetica").unwrap();
489 let font_id = fonts.select_font(&font_ids, &Default::default()).unwrap();
490
491 let line = "one two three four five\n";
492 let wrap_boundaries = fonts.wrap_line(line, font_id, 16., 64.0);
493 assert_eq!(wrap_boundaries, &["one two ".len(), "one two three ".len()]);
494
495 let line = "aaa Ξ±Ξ±Ξ± βββ πππ\n";
496 let wrap_boundaries = fonts.wrap_line(line, font_id, 16., 64.0);
497 assert_eq!(
498 wrap_boundaries,
499 &["aaa Ξ±Ξ±Ξ± ".len(), "aaa Ξ±Ξ±Ξ± βββ ".len(),]
500 );
501 }
502}