1use crate::{
2 Bounds, DevicePixels, Font, FontFeatures, FontId, FontMetrics, FontRun, FontStyle, FontWeight,
3 GlyphId, LineLayout, Pixels, PlatformTextSystem, Point, RenderGlyphParams, SUBPIXEL_VARIANTS,
4 ShapedGlyph, SharedString, Size, point, size,
5};
6use anyhow::{Context as _, Ok, Result, anyhow};
7use collections::HashMap;
8use cosmic_text::{
9 Attrs, AttrsList, CacheKey, Family, Font as CosmicTextFont, FontSystem, ShapeBuffer, ShapeLine,
10 SwashCache,
11};
12
13use itertools::Itertools;
14use parking_lot::RwLock;
15use pathfinder_geometry::{
16 rect::{RectF, RectI},
17 vector::{Vector2F, Vector2I},
18};
19use smallvec::SmallVec;
20use std::{borrow::Cow, sync::Arc};
21
22pub(crate) struct CosmicTextSystem(RwLock<CosmicTextSystemState>);
23
24struct CosmicTextSystemState {
25 swash_cache: SwashCache,
26 font_system: FontSystem,
27 scratch: ShapeBuffer,
28 /// Contains all already loaded fonts, including all faces. Indexed by `FontId`.
29 loaded_fonts_store: Vec<Arc<CosmicTextFont>>,
30 /// Caches the `FontId`s associated with a specific family to avoid iterating the font database
31 /// for every font face in a family.
32 font_ids_by_family_cache: HashMap<SharedString, SmallVec<[FontId; 4]>>,
33 /// The name of each font associated with the given font id
34 postscript_names: HashMap<FontId, String>,
35}
36
37impl CosmicTextSystem {
38 pub(crate) fn new() -> Self {
39 // todo(linux) make font loading non-blocking
40 let mut font_system = FontSystem::new();
41
42 Self(RwLock::new(CosmicTextSystemState {
43 font_system,
44 swash_cache: SwashCache::new(),
45 scratch: ShapeBuffer::default(),
46 loaded_fonts_store: Vec::new(),
47 font_ids_by_family_cache: HashMap::default(),
48 postscript_names: HashMap::default(),
49 }))
50 }
51}
52
53impl Default for CosmicTextSystem {
54 fn default() -> Self {
55 Self::new()
56 }
57}
58
59impl PlatformTextSystem for CosmicTextSystem {
60 fn add_fonts(&self, fonts: Vec<Cow<'static, [u8]>>) -> Result<()> {
61 self.0.write().add_fonts(fonts)
62 }
63
64 fn all_font_names(&self) -> Vec<String> {
65 let mut result = self
66 .0
67 .read()
68 .font_system
69 .db()
70 .faces()
71 .filter_map(|face| face.families.first().map(|family| family.0.clone()))
72 .collect_vec();
73 result.sort();
74 result.dedup();
75 result
76 }
77
78 fn font_id(&self, font: &Font) -> Result<FontId> {
79 // todo(linux): Do we need to use CosmicText's Font APIs? Can we consolidate this to use font_kit?
80 let mut state = self.0.write();
81
82 let candidates = if let Some(font_ids) = state.font_ids_by_family_cache.get(&font.family) {
83 font_ids.as_slice()
84 } else {
85 let font_ids = state.load_family(&font.family, &font.features)?;
86 state
87 .font_ids_by_family_cache
88 .insert(font.family.clone(), font_ids);
89 state.font_ids_by_family_cache[&font.family].as_ref()
90 };
91
92 // todo(linux) ideally we would make fontdb's `find_best_match` pub instead of using font-kit here
93 let candidate_properties = candidates
94 .iter()
95 .map(|font_id| {
96 let database_id = state.loaded_fonts_store[font_id.0].id();
97 let face_info = state.font_system.db().face(database_id).expect("");
98 face_info_into_properties(face_info)
99 })
100 .collect::<SmallVec<[_; 4]>>();
101
102 let ix =
103 font_kit::matching::find_best_match(&candidate_properties, &font_into_properties(font))
104 .context("requested font family contains no font matching the other parameters")?;
105
106 Ok(candidates[ix])
107 }
108
109 fn font_metrics(&self, font_id: FontId) -> FontMetrics {
110 let metrics = self.0.read().loaded_fonts_store[font_id.0]
111 .as_swash()
112 .metrics(&[]);
113
114 FontMetrics {
115 units_per_em: metrics.units_per_em as u32,
116 ascent: metrics.ascent,
117 descent: -metrics.descent, // todo(linux) confirm this is correct
118 line_gap: metrics.leading,
119 underline_position: metrics.underline_offset,
120 underline_thickness: metrics.stroke_size,
121 cap_height: metrics.cap_height,
122 x_height: metrics.x_height,
123 // todo(linux): Compute this correctly
124 bounding_box: Bounds {
125 origin: point(0.0, 0.0),
126 size: size(metrics.max_width, metrics.ascent + metrics.descent),
127 },
128 }
129 }
130
131 fn typographic_bounds(&self, font_id: FontId, glyph_id: GlyphId) -> Result<Bounds<f32>> {
132 let lock = self.0.read();
133 let glyph_metrics = lock.loaded_fonts_store[font_id.0]
134 .as_swash()
135 .glyph_metrics(&[]);
136 let glyph_id = glyph_id.0 as u16;
137 // todo(linux): Compute this correctly
138 // see https://github.com/servo/font-kit/blob/master/src/loaders/freetype.rs#L614-L620
139 Ok(Bounds {
140 origin: point(0.0, 0.0),
141 size: size(
142 glyph_metrics.advance_width(glyph_id),
143 glyph_metrics.advance_height(glyph_id),
144 ),
145 })
146 }
147
148 fn advance(&self, font_id: FontId, glyph_id: GlyphId) -> Result<Size<f32>> {
149 self.0.read().advance(font_id, glyph_id)
150 }
151
152 fn glyph_for_char(&self, font_id: FontId, ch: char) -> Option<GlyphId> {
153 self.0.read().glyph_for_char(font_id, ch)
154 }
155
156 fn glyph_raster_bounds(&self, params: &RenderGlyphParams) -> Result<Bounds<DevicePixels>> {
157 self.0.write().raster_bounds(params)
158 }
159
160 fn rasterize_glyph(
161 &self,
162 params: &RenderGlyphParams,
163 raster_bounds: Bounds<DevicePixels>,
164 ) -> Result<(Size<DevicePixels>, Vec<u8>)> {
165 self.0.write().rasterize_glyph(params, raster_bounds)
166 }
167
168 fn layout_line(&self, text: &str, font_size: Pixels, runs: &[FontRun]) -> LineLayout {
169 self.0.write().layout_line(text, font_size, runs)
170 }
171}
172
173impl CosmicTextSystemState {
174 #[profiling::function]
175 fn add_fonts(&mut self, fonts: Vec<Cow<'static, [u8]>>) -> Result<()> {
176 let db = self.font_system.db_mut();
177 for bytes in fonts {
178 match bytes {
179 Cow::Borrowed(embedded_font) => {
180 db.load_font_data(embedded_font.to_vec());
181 }
182 Cow::Owned(bytes) => {
183 db.load_font_data(bytes);
184 }
185 }
186 }
187 Ok(())
188 }
189
190 // todo(linux) handle `FontFeatures`
191 #[profiling::function]
192 fn load_family(
193 &mut self,
194 name: &str,
195 _features: &FontFeatures,
196 ) -> Result<SmallVec<[FontId; 4]>> {
197 // TODO: Determine the proper system UI font.
198 let name = if name == ".SystemUIFont" {
199 "Zed Plex Sans"
200 } else {
201 name
202 };
203
204 let mut font_ids = SmallVec::new();
205 let families = self
206 .font_system
207 .db()
208 .faces()
209 .filter(|face| face.families.iter().any(|family| *name == family.0))
210 .map(|face| (face.id, face.post_script_name.clone()))
211 .collect::<SmallVec<[_; 4]>>();
212
213 for (font_id, postscript_name) in families {
214 let font = self
215 .font_system
216 .get_font(font_id)
217 .ok_or_else(|| anyhow!("Could not load font"))?;
218
219 // HACK: To let the storybook run and render Windows caption icons. We should actually do better font fallback.
220 let allowed_bad_font_names = [
221 "SegoeFluentIcons", // NOTE: Segoe fluent icons postscript name is inconsistent
222 "Segoe Fluent Icons",
223 ];
224
225 if font.as_swash().charmap().map('m') == 0
226 && !allowed_bad_font_names.contains(&postscript_name.as_str())
227 {
228 self.font_system.db_mut().remove_face(font.id());
229 continue;
230 };
231
232 let font_id = FontId(self.loaded_fonts_store.len());
233 font_ids.push(font_id);
234 self.loaded_fonts_store.push(font);
235 self.postscript_names.insert(font_id, postscript_name);
236 }
237
238 Ok(font_ids)
239 }
240
241 fn advance(&self, font_id: FontId, glyph_id: GlyphId) -> Result<Size<f32>> {
242 let width = self.loaded_fonts_store[font_id.0]
243 .as_swash()
244 .glyph_metrics(&[])
245 .advance_width(glyph_id.0 as u16);
246 let height = self.loaded_fonts_store[font_id.0]
247 .as_swash()
248 .glyph_metrics(&[])
249 .advance_height(glyph_id.0 as u16);
250 Ok(Size { width, height })
251 }
252
253 fn glyph_for_char(&self, font_id: FontId, ch: char) -> Option<GlyphId> {
254 let glyph_id = self.loaded_fonts_store[font_id.0]
255 .as_swash()
256 .charmap()
257 .map(ch);
258 if glyph_id == 0 {
259 None
260 } else {
261 Some(GlyphId(glyph_id.into()))
262 }
263 }
264
265 fn is_emoji(&self, font_id: FontId) -> bool {
266 // TODO: Include other common emoji fonts
267 self.postscript_names
268 .get(&font_id)
269 .map_or(false, |postscript_name| postscript_name == "NotoColorEmoji")
270 }
271
272 fn raster_bounds(&mut self, params: &RenderGlyphParams) -> Result<Bounds<DevicePixels>> {
273 let font = &self.loaded_fonts_store[params.font_id.0];
274 let image = self
275 .swash_cache
276 .get_image(
277 &mut self.font_system,
278 CacheKey::new(
279 font.id(),
280 params.glyph_id.0 as u16,
281 (params.font_size * params.scale_factor).into(),
282 (0.0, 0.0),
283 cosmic_text::CacheKeyFlags::empty(),
284 )
285 .0,
286 )
287 .clone()
288 .with_context(|| format!("no image for {params:?} in font {font:?}"))?;
289 Ok(Bounds {
290 origin: point(image.placement.left.into(), (-image.placement.top).into()),
291 size: size(image.placement.width.into(), image.placement.height.into()),
292 })
293 }
294
295 #[profiling::function]
296 fn rasterize_glyph(
297 &mut self,
298 params: &RenderGlyphParams,
299 glyph_bounds: Bounds<DevicePixels>,
300 ) -> Result<(Size<DevicePixels>, Vec<u8>)> {
301 if glyph_bounds.size.width.0 == 0 || glyph_bounds.size.height.0 == 0 {
302 Err(anyhow!("glyph bounds are empty"))
303 } else {
304 let bitmap_size = glyph_bounds.size;
305 let font = &self.loaded_fonts_store[params.font_id.0];
306 let subpixel_shift = params
307 .subpixel_variant
308 .map(|v| v as f32 / (SUBPIXEL_VARIANTS as f32 * params.scale_factor));
309 let mut image = self
310 .swash_cache
311 .get_image(
312 &mut self.font_system,
313 CacheKey::new(
314 font.id(),
315 params.glyph_id.0 as u16,
316 (params.font_size * params.scale_factor).into(),
317 (subpixel_shift.x, subpixel_shift.y.trunc()),
318 cosmic_text::CacheKeyFlags::empty(),
319 )
320 .0,
321 )
322 .clone()
323 .with_context(|| format!("no image for {params:?} in font {font:?}"))?;
324
325 if params.is_emoji {
326 // Convert from RGBA to BGRA.
327 for pixel in image.data.chunks_exact_mut(4) {
328 pixel.swap(0, 2);
329 }
330 }
331
332 Ok((bitmap_size, image.data))
333 }
334 }
335
336 fn font_id_for_cosmic_id(&mut self, id: cosmic_text::fontdb::ID) -> FontId {
337 if let Some(ix) = self
338 .loaded_fonts_store
339 .iter()
340 .position(|font| font.id() == id)
341 {
342 FontId(ix)
343 } else {
344 // This matches the behavior of the mac text system
345 let font = self.font_system.get_font(id).unwrap();
346 let face = self
347 .font_system
348 .db()
349 .faces()
350 .find(|info| info.id == id)
351 .unwrap();
352
353 let font_id = FontId(self.loaded_fonts_store.len());
354 self.loaded_fonts_store.push(font);
355 self.postscript_names
356 .insert(font_id, face.post_script_name.clone());
357
358 font_id
359 }
360 }
361
362 #[profiling::function]
363 fn layout_line(&mut self, text: &str, font_size: Pixels, font_runs: &[FontRun]) -> LineLayout {
364 let mut attrs_list = AttrsList::new(Attrs::new());
365 let mut offs = 0;
366 for run in font_runs {
367 let font = &self.loaded_fonts_store[run.font_id.0];
368 let font = self.font_system.db().face(font.id()).unwrap();
369 attrs_list.add_span(
370 offs..(offs + run.len),
371 Attrs::new()
372 .family(Family::Name(&font.families.first().unwrap().0))
373 .stretch(font.stretch)
374 .style(font.style)
375 .weight(font.weight),
376 );
377 offs += run.len;
378 }
379 let mut line = ShapeLine::new(
380 &mut self.font_system,
381 text,
382 &attrs_list,
383 cosmic_text::Shaping::Advanced,
384 4,
385 );
386 let mut layout = Vec::with_capacity(1);
387 line.layout_to_buffer(
388 &mut self.scratch,
389 font_size.0,
390 None, // We do our own wrapping
391 cosmic_text::Wrap::None,
392 None,
393 &mut layout,
394 None,
395 );
396
397 let mut runs = Vec::new();
398 let layout = layout.first().unwrap();
399 for glyph in &layout.glyphs {
400 let font_id = glyph.font_id;
401 let font_id = self.font_id_for_cosmic_id(font_id);
402 let is_emoji = self.is_emoji(font_id);
403 let mut glyphs = SmallVec::new();
404
405 // HACK: Prevent crash caused by variation selectors.
406 if glyph.glyph_id == 3 && is_emoji {
407 continue;
408 }
409
410 // todo(linux) this is definitely wrong, each glyph in glyphs from cosmic-text is a cluster with one glyph, ShapedRun takes a run of glyphs with the same font and direction
411 glyphs.push(ShapedGlyph {
412 id: GlyphId(glyph.glyph_id as u32),
413 position: point(glyph.x.into(), glyph.y.into()),
414 index: glyph.start,
415 is_emoji,
416 });
417
418 runs.push(crate::ShapedRun { font_id, glyphs });
419 }
420
421 LineLayout {
422 font_size,
423 width: layout.w.into(),
424 ascent: layout.max_ascent.into(),
425 descent: layout.max_descent.into(),
426 runs,
427 len: text.len(),
428 }
429 }
430}
431
432impl From<RectF> for Bounds<f32> {
433 fn from(rect: RectF) -> Self {
434 Bounds {
435 origin: point(rect.origin_x(), rect.origin_y()),
436 size: size(rect.width(), rect.height()),
437 }
438 }
439}
440
441impl From<RectI> for Bounds<DevicePixels> {
442 fn from(rect: RectI) -> Self {
443 Bounds {
444 origin: point(DevicePixels(rect.origin_x()), DevicePixels(rect.origin_y())),
445 size: size(DevicePixels(rect.width()), DevicePixels(rect.height())),
446 }
447 }
448}
449
450impl From<Vector2I> for Size<DevicePixels> {
451 fn from(value: Vector2I) -> Self {
452 size(value.x().into(), value.y().into())
453 }
454}
455
456impl From<RectI> for Bounds<i32> {
457 fn from(rect: RectI) -> Self {
458 Bounds {
459 origin: point(rect.origin_x(), rect.origin_y()),
460 size: size(rect.width(), rect.height()),
461 }
462 }
463}
464
465impl From<Point<u32>> for Vector2I {
466 fn from(size: Point<u32>) -> Self {
467 Vector2I::new(size.x as i32, size.y as i32)
468 }
469}
470
471impl From<Vector2F> for Size<f32> {
472 fn from(vec: Vector2F) -> Self {
473 size(vec.x(), vec.y())
474 }
475}
476
477impl From<FontWeight> for cosmic_text::Weight {
478 fn from(value: FontWeight) -> Self {
479 cosmic_text::Weight(value.0 as u16)
480 }
481}
482
483impl From<FontStyle> for cosmic_text::Style {
484 fn from(style: FontStyle) -> Self {
485 match style {
486 FontStyle::Normal => cosmic_text::Style::Normal,
487 FontStyle::Italic => cosmic_text::Style::Italic,
488 FontStyle::Oblique => cosmic_text::Style::Oblique,
489 }
490 }
491}
492
493fn font_into_properties(font: &crate::Font) -> font_kit::properties::Properties {
494 font_kit::properties::Properties {
495 style: match font.style {
496 crate::FontStyle::Normal => font_kit::properties::Style::Normal,
497 crate::FontStyle::Italic => font_kit::properties::Style::Italic,
498 crate::FontStyle::Oblique => font_kit::properties::Style::Oblique,
499 },
500 weight: font_kit::properties::Weight(font.weight.0),
501 stretch: Default::default(),
502 }
503}
504
505fn face_info_into_properties(
506 face_info: &cosmic_text::fontdb::FaceInfo,
507) -> font_kit::properties::Properties {
508 font_kit::properties::Properties {
509 style: match face_info.style {
510 cosmic_text::Style::Normal => font_kit::properties::Style::Normal,
511 cosmic_text::Style::Italic => font_kit::properties::Style::Italic,
512 cosmic_text::Style::Oblique => font_kit::properties::Style::Oblique,
513 },
514 // both libs use the same values for weight
515 weight: font_kit::properties::Weight(face_info.weight.0.into()),
516 stretch: match face_info.stretch {
517 cosmic_text::Stretch::Condensed => font_kit::properties::Stretch::CONDENSED,
518 cosmic_text::Stretch::Expanded => font_kit::properties::Stretch::EXPANDED,
519 cosmic_text::Stretch::ExtraCondensed => font_kit::properties::Stretch::EXTRA_CONDENSED,
520 cosmic_text::Stretch::ExtraExpanded => font_kit::properties::Stretch::EXTRA_EXPANDED,
521 cosmic_text::Stretch::Normal => font_kit::properties::Stretch::NORMAL,
522 cosmic_text::Stretch::SemiCondensed => font_kit::properties::Stretch::SEMI_CONDENSED,
523 cosmic_text::Stretch::SemiExpanded => font_kit::properties::Stretch::SEMI_EXPANDED,
524 cosmic_text::Stretch::UltraCondensed => font_kit::properties::Stretch::ULTRA_CONDENSED,
525 cosmic_text::Stretch::UltraExpanded => font_kit::properties::Stretch::ULTRA_EXPANDED,
526 },
527 }
528}