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