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