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 LinuxTextSystem(RwLock<LinuxTextSystemState>);
22
23struct LinuxTextSystemState {
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 LinuxTextSystem {
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(LinuxTextSystemState {
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 LinuxTextSystem {
53 fn default() -> Self {
54 Self::new()
55 }
56}
57
58impl PlatformTextSystem for LinuxTextSystem {
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 LinuxTextSystemState {
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, we should actually do better font fallback
239 if font.as_swash().charmap().map('m') == 0 || postscript_name == "Segoe Fluent Icons" {
240 self.font_system.db_mut().remove_face(font.id());
241 continue;
242 };
243
244 let font_id = FontId(self.loaded_fonts_store.len());
245 font_ids.push(font_id);
246 self.loaded_fonts_store.push(font);
247 self.postscript_names.insert(font_id, postscript_name);
248 }
249
250 Ok(font_ids)
251 }
252
253 fn advance(&self, font_id: FontId, glyph_id: GlyphId) -> Result<Size<f32>> {
254 let width = self.loaded_fonts_store[font_id.0]
255 .as_swash()
256 .glyph_metrics(&[])
257 .advance_width(glyph_id.0 as u16);
258 let height = self.loaded_fonts_store[font_id.0]
259 .as_swash()
260 .glyph_metrics(&[])
261 .advance_height(glyph_id.0 as u16);
262 Ok(Size { width, height })
263 }
264
265 fn glyph_for_char(&self, font_id: FontId, ch: char) -> Option<GlyphId> {
266 let glyph_id = self.loaded_fonts_store[font_id.0]
267 .as_swash()
268 .charmap()
269 .map(ch);
270 if glyph_id == 0 {
271 None
272 } else {
273 Some(GlyphId(glyph_id.into()))
274 }
275 }
276
277 fn is_emoji(&self, font_id: FontId) -> bool {
278 // TODO: Include other common emoji fonts
279 self.postscript_names
280 .get(&font_id)
281 .map_or(false, |postscript_name| postscript_name == "NotoColorEmoji")
282 }
283
284 fn raster_bounds(&mut self, params: &RenderGlyphParams) -> Result<Bounds<DevicePixels>> {
285 let font = &self.loaded_fonts_store[params.font_id.0];
286 let font_system = &mut self.font_system;
287 let image = self
288 .swash_cache
289 .get_image(
290 font_system,
291 CacheKey::new(
292 font.id(),
293 params.glyph_id.0 as u16,
294 (params.font_size * params.scale_factor).into(),
295 (0.0, 0.0),
296 cosmic_text::CacheKeyFlags::empty(),
297 )
298 .0,
299 )
300 .clone()
301 .unwrap();
302 Ok(Bounds {
303 origin: point(image.placement.left.into(), (-image.placement.top).into()),
304 size: size(image.placement.width.into(), image.placement.height.into()),
305 })
306 }
307
308 #[profiling::function]
309 fn rasterize_glyph(
310 &mut self,
311 params: &RenderGlyphParams,
312 glyph_bounds: Bounds<DevicePixels>,
313 ) -> Result<(Size<DevicePixels>, Vec<u8>)> {
314 if glyph_bounds.size.width.0 == 0 || glyph_bounds.size.height.0 == 0 {
315 Err(anyhow!("glyph bounds are empty"))
316 } else {
317 // todo(linux) handle subpixel variants
318 let bitmap_size = glyph_bounds.size;
319 let font = &self.loaded_fonts_store[params.font_id.0];
320 let font_system = &mut self.font_system;
321 let image = self
322 .swash_cache
323 .get_image(
324 font_system,
325 CacheKey::new(
326 font.id(),
327 params.glyph_id.0 as u16,
328 (params.font_size * params.scale_factor).into(),
329 (0.0, 0.0),
330 cosmic_text::CacheKeyFlags::empty(),
331 )
332 .0,
333 )
334 .clone()
335 .unwrap();
336
337 Ok((bitmap_size, image.data))
338 }
339 }
340
341 fn font_id_for_cosmic_id(&mut self, id: cosmic_text::fontdb::ID) -> FontId {
342 if let Some(ix) = self
343 .loaded_fonts_store
344 .iter()
345 .position(|font| font.id() == id)
346 {
347 FontId(ix)
348 } else {
349 // This matches the behavior of the mac text system
350 let font = self.font_system.get_font(id).unwrap();
351 let face = self
352 .font_system
353 .db()
354 .faces()
355 .find(|info| info.id == id)
356 .unwrap();
357
358 let font_id = FontId(self.loaded_fonts_store.len());
359 self.loaded_fonts_store.push(font);
360 self.postscript_names
361 .insert(font_id, face.post_script_name.clone());
362
363 font_id
364 }
365 }
366
367 // todo(linux) This is all a quick first pass, maybe we should be using cosmic_text::Buffer
368 #[profiling::function]
369 fn layout_line(&mut self, text: &str, font_size: Pixels, font_runs: &[FontRun]) -> LineLayout {
370 let mut attrs_list = AttrsList::new(Attrs::new());
371 let mut offs = 0;
372 for run in font_runs {
373 // todo(linux) We need to check we are doing utf properly
374 let font = &self.loaded_fonts_store[run.font_id.0];
375 let font = self.font_system.db().face(font.id()).unwrap();
376 attrs_list.add_span(
377 offs..(offs + run.len),
378 Attrs::new()
379 .family(Family::Name(&font.families.first().unwrap().0))
380 .stretch(font.stretch)
381 .style(font.style)
382 .weight(font.weight),
383 );
384 offs += run.len;
385 }
386 let mut line = BufferLine::new(text, attrs_list, cosmic_text::Shaping::Advanced);
387
388 let layout = line.layout(
389 &mut self.font_system,
390 font_size.0,
391 f32::MAX, // We do our own wrapping
392 cosmic_text::Wrap::None,
393 None,
394 );
395 let mut runs = Vec::new();
396
397 let layout = layout.first().unwrap();
398 for glyph in &layout.glyphs {
399 let font_id = glyph.font_id;
400 let font_id = self.font_id_for_cosmic_id(font_id);
401 let mut glyphs = SmallVec::new();
402 // 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
403 glyphs.push(ShapedGlyph {
404 id: GlyphId(glyph.glyph_id as u32),
405 position: point((glyph.x).into(), glyph.y.into()),
406 index: glyph.start,
407 is_emoji: self.is_emoji(font_id),
408 });
409
410 runs.push(crate::ShapedRun { font_id, glyphs });
411 }
412
413 LineLayout {
414 font_size,
415 width: layout.w.into(),
416 ascent: layout.max_ascent.into(),
417 descent: layout.max_descent.into(),
418 runs,
419 len: text.len(),
420 }
421 }
422}
423
424impl From<RectF> for Bounds<f32> {
425 fn from(rect: RectF) -> Self {
426 Bounds {
427 origin: point(rect.origin_x(), rect.origin_y()),
428 size: size(rect.width(), rect.height()),
429 }
430 }
431}
432
433impl From<RectI> for Bounds<DevicePixels> {
434 fn from(rect: RectI) -> Self {
435 Bounds {
436 origin: point(DevicePixels(rect.origin_x()), DevicePixels(rect.origin_y())),
437 size: size(DevicePixels(rect.width()), DevicePixels(rect.height())),
438 }
439 }
440}
441
442impl From<Vector2I> for Size<DevicePixels> {
443 fn from(value: Vector2I) -> Self {
444 size(value.x().into(), value.y().into())
445 }
446}
447
448impl From<RectI> for Bounds<i32> {
449 fn from(rect: RectI) -> Self {
450 Bounds {
451 origin: point(rect.origin_x(), rect.origin_y()),
452 size: size(rect.width(), rect.height()),
453 }
454 }
455}
456
457impl From<Point<u32>> for Vector2I {
458 fn from(size: Point<u32>) -> Self {
459 Vector2I::new(size.x as i32, size.y as i32)
460 }
461}
462
463impl From<Vector2F> for Size<f32> {
464 fn from(vec: Vector2F) -> Self {
465 size(vec.x(), vec.y())
466 }
467}
468
469impl From<FontWeight> for cosmic_text::Weight {
470 fn from(value: FontWeight) -> Self {
471 cosmic_text::Weight(value.0 as u16)
472 }
473}
474
475impl From<FontStyle> for cosmic_text::Style {
476 fn from(style: FontStyle) -> Self {
477 match style {
478 FontStyle::Normal => cosmic_text::Style::Normal,
479 FontStyle::Italic => cosmic_text::Style::Italic,
480 FontStyle::Oblique => cosmic_text::Style::Oblique,
481 }
482 }
483}
484
485fn font_into_properties(font: &crate::Font) -> font_kit::properties::Properties {
486 font_kit::properties::Properties {
487 style: match font.style {
488 crate::FontStyle::Normal => font_kit::properties::Style::Normal,
489 crate::FontStyle::Italic => font_kit::properties::Style::Italic,
490 crate::FontStyle::Oblique => font_kit::properties::Style::Oblique,
491 },
492 weight: font_kit::properties::Weight(font.weight.0),
493 stretch: Default::default(),
494 }
495}
496
497fn face_info_into_properties(
498 face_info: &cosmic_text::fontdb::FaceInfo,
499) -> font_kit::properties::Properties {
500 font_kit::properties::Properties {
501 style: match face_info.style {
502 cosmic_text::Style::Normal => font_kit::properties::Style::Normal,
503 cosmic_text::Style::Italic => font_kit::properties::Style::Italic,
504 cosmic_text::Style::Oblique => font_kit::properties::Style::Oblique,
505 },
506 // both libs use the same values for weight
507 weight: font_kit::properties::Weight(face_info.weight.0.into()),
508 stretch: match face_info.stretch {
509 cosmic_text::Stretch::Condensed => font_kit::properties::Stretch::CONDENSED,
510 cosmic_text::Stretch::Expanded => font_kit::properties::Stretch::EXPANDED,
511 cosmic_text::Stretch::ExtraCondensed => font_kit::properties::Stretch::EXTRA_CONDENSED,
512 cosmic_text::Stretch::ExtraExpanded => font_kit::properties::Stretch::EXTRA_EXPANDED,
513 cosmic_text::Stretch::Normal => font_kit::properties::Stretch::NORMAL,
514 cosmic_text::Stretch::SemiCondensed => font_kit::properties::Stretch::SEMI_CONDENSED,
515 cosmic_text::Stretch::SemiExpanded => font_kit::properties::Stretch::SEMI_EXPANDED,
516 cosmic_text::Stretch::UltraCondensed => font_kit::properties::Stretch::ULTRA_CONDENSED,
517 cosmic_text::Stretch::UltraExpanded => font_kit::properties::Stretch::ULTRA_EXPANDED,
518 },
519 }
520}