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