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