text_system.rs

  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, 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        let mut font_system = FontSystem::new();
 40
 41        // todo(linux) make font loading non-blocking
 42        font_system.db_mut().load_system_fonts();
 43
 44        Self(RwLock::new(CosmicTextSystemState {
 45            font_system,
 46            swash_cache: SwashCache::new(),
 47            scratch: ShapeBuffer::default(),
 48            loaded_fonts_store: Vec::new(),
 49            font_ids_by_family_cache: HashMap::default(),
 50            postscript_names: HashMap::default(),
 51        }))
 52    }
 53}
 54
 55impl Default for CosmicTextSystem {
 56    fn default() -> Self {
 57        Self::new()
 58    }
 59}
 60
 61impl PlatformTextSystem for CosmicTextSystem {
 62    fn add_fonts(&self, fonts: Vec<Cow<'static, [u8]>>) -> Result<()> {
 63        self.0.write().add_fonts(fonts)
 64    }
 65
 66    fn all_font_names(&self) -> Vec<String> {
 67        let mut result = self
 68            .0
 69            .read()
 70            .font_system
 71            .db()
 72            .faces()
 73            .filter_map(|face| face.families.first().map(|family| family.0.clone()))
 74            .collect_vec();
 75        result.sort();
 76        result.dedup();
 77        result
 78    }
 79
 80    fn all_font_families(&self) -> Vec<String> {
 81        self.0
 82            .read()
 83            .font_system
 84            .db()
 85            .faces()
 86            // todo(linux) this will list the same font family multiple times
 87            .filter_map(|face| face.families.first().map(|family| family.0.clone()))
 88            .collect_vec()
 89    }
 90
 91    fn font_id(&self, font: &Font) -> Result<FontId> {
 92        // todo(linux): Do we need to use CosmicText's Font APIs? Can we consolidate this to use font_kit?
 93        let mut state = self.0.write();
 94
 95        let candidates = if let Some(font_ids) = state.font_ids_by_family_cache.get(&font.family) {
 96            font_ids.as_slice()
 97        } else {
 98            let font_ids = state.load_family(&font.family, &font.features)?;
 99            state
100                .font_ids_by_family_cache
101                .insert(font.family.clone(), font_ids);
102            state.font_ids_by_family_cache[&font.family].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            let font_id = FontId(self.loaded_fonts_store.len());
246            font_ids.push(font_id);
247            self.loaded_fonts_store.push(font);
248            self.postscript_names.insert(font_id, postscript_name);
249        }
250
251        Ok(font_ids)
252    }
253
254    fn advance(&self, font_id: FontId, glyph_id: GlyphId) -> Result<Size<f32>> {
255        let width = self.loaded_fonts_store[font_id.0]
256            .as_swash()
257            .glyph_metrics(&[])
258            .advance_width(glyph_id.0 as u16);
259        let height = self.loaded_fonts_store[font_id.0]
260            .as_swash()
261            .glyph_metrics(&[])
262            .advance_height(glyph_id.0 as u16);
263        Ok(Size { width, height })
264    }
265
266    fn glyph_for_char(&self, font_id: FontId, ch: char) -> Option<GlyphId> {
267        let glyph_id = self.loaded_fonts_store[font_id.0]
268            .as_swash()
269            .charmap()
270            .map(ch);
271        if glyph_id == 0 {
272            None
273        } else {
274            Some(GlyphId(glyph_id.into()))
275        }
276    }
277
278    fn is_emoji(&self, font_id: FontId) -> bool {
279        // TODO: Include other common emoji fonts
280        self.postscript_names
281            .get(&font_id)
282            .map_or(false, |postscript_name| postscript_name == "NotoColorEmoji")
283    }
284
285    fn raster_bounds(&mut self, params: &RenderGlyphParams) -> Result<Bounds<DevicePixels>> {
286        let font = &self.loaded_fonts_store[params.font_id.0];
287        let font_system = &mut self.font_system;
288        let image = self
289            .swash_cache
290            .get_image(
291                font_system,
292                CacheKey::new(
293                    font.id(),
294                    params.glyph_id.0 as u16,
295                    (params.font_size * params.scale_factor).into(),
296                    (0.0, 0.0),
297                    cosmic_text::CacheKeyFlags::empty(),
298                )
299                .0,
300            )
301            .clone()
302            .with_context(|| format!("no image for {params:?} in font {font:?}"))?;
303        Ok(Bounds {
304            origin: point(image.placement.left.into(), (-image.placement.top).into()),
305            size: size(image.placement.width.into(), image.placement.height.into()),
306        })
307    }
308
309    #[profiling::function]
310    fn rasterize_glyph(
311        &mut self,
312        params: &RenderGlyphParams,
313        glyph_bounds: Bounds<DevicePixels>,
314    ) -> Result<(Size<DevicePixels>, Vec<u8>)> {
315        if glyph_bounds.size.width.0 == 0 || glyph_bounds.size.height.0 == 0 {
316            Err(anyhow!("glyph bounds are empty"))
317        } else {
318            // todo(linux) handle subpixel variants
319            let bitmap_size = glyph_bounds.size;
320            let font = &self.loaded_fonts_store[params.font_id.0];
321            let font_system = &mut self.font_system;
322            let mut image = self
323                .swash_cache
324                .get_image(
325                    font_system,
326                    CacheKey::new(
327                        font.id(),
328                        params.glyph_id.0 as u16,
329                        (params.font_size * params.scale_factor).into(),
330                        (0.0, 0.0),
331                        cosmic_text::CacheKeyFlags::empty(),
332                    )
333                    .0,
334                )
335                .clone()
336                .with_context(|| format!("no image for {params:?} in font {font:?}"))?;
337
338            if params.is_emoji {
339                // Convert from RGBA to BGRA.
340                for pixel in image.data.chunks_exact_mut(4) {
341                    pixel.swap(0, 2);
342                }
343            }
344
345            Ok((bitmap_size, image.data))
346        }
347    }
348
349    fn font_id_for_cosmic_id(&mut self, id: cosmic_text::fontdb::ID) -> FontId {
350        if let Some(ix) = self
351            .loaded_fonts_store
352            .iter()
353            .position(|font| font.id() == id)
354        {
355            FontId(ix)
356        } else {
357            // This matches the behavior of the mac text system
358            let font = self.font_system.get_font(id).unwrap();
359            let face = self
360                .font_system
361                .db()
362                .faces()
363                .find(|info| info.id == id)
364                .unwrap();
365
366            let font_id = FontId(self.loaded_fonts_store.len());
367            self.loaded_fonts_store.push(font);
368            self.postscript_names
369                .insert(font_id, face.post_script_name.clone());
370
371            font_id
372        }
373    }
374
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            let font = &self.loaded_fonts_store[run.font_id.0];
381            let font = self.font_system.db().face(font.id()).unwrap();
382            attrs_list.add_span(
383                offs..(offs + run.len),
384                Attrs::new()
385                    .family(Family::Name(&font.families.first().unwrap().0))
386                    .stretch(font.stretch)
387                    .style(font.style)
388                    .weight(font.weight),
389            );
390            offs += run.len;
391        }
392        let mut line = ShapeLine::new_in_buffer(
393            &mut self.scratch,
394            &mut self.font_system,
395            text,
396            &attrs_list,
397            cosmic_text::Shaping::Advanced,
398            4,
399        );
400
401        let mut layout = Vec::with_capacity(1);
402        line.layout_to_buffer(
403            &mut self.scratch,
404            font_size.0,
405            None, // We do our own wrapping
406            cosmic_text::Wrap::None,
407            None,
408            &mut layout,
409            None,
410        );
411
412        let mut runs = Vec::new();
413        let layout = layout.first().unwrap();
414        for glyph in &layout.glyphs {
415            let font_id = glyph.font_id;
416            let font_id = self.font_id_for_cosmic_id(font_id);
417            let is_emoji = self.is_emoji(font_id);
418            let mut glyphs = SmallVec::new();
419
420            // HACK: Prevent crash caused by variation selectors.
421            if glyph.glyph_id == 3 && is_emoji {
422                continue;
423            }
424
425            // 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
426            glyphs.push(ShapedGlyph {
427                id: GlyphId(glyph.glyph_id as u32),
428                position: point(glyph.x.into(), glyph.y.into()),
429                index: glyph.start,
430                is_emoji,
431            });
432
433            runs.push(crate::ShapedRun { font_id, glyphs });
434        }
435
436        LineLayout {
437            font_size,
438            width: layout.w.into(),
439            ascent: layout.max_ascent.into(),
440            descent: layout.max_descent.into(),
441            runs,
442            len: text.len(),
443        }
444    }
445}
446
447impl From<RectF> for Bounds<f32> {
448    fn from(rect: RectF) -> Self {
449        Bounds {
450            origin: point(rect.origin_x(), rect.origin_y()),
451            size: size(rect.width(), rect.height()),
452        }
453    }
454}
455
456impl From<RectI> for Bounds<DevicePixels> {
457    fn from(rect: RectI) -> Self {
458        Bounds {
459            origin: point(DevicePixels(rect.origin_x()), DevicePixels(rect.origin_y())),
460            size: size(DevicePixels(rect.width()), DevicePixels(rect.height())),
461        }
462    }
463}
464
465impl From<Vector2I> for Size<DevicePixels> {
466    fn from(value: Vector2I) -> Self {
467        size(value.x().into(), value.y().into())
468    }
469}
470
471impl From<RectI> for Bounds<i32> {
472    fn from(rect: RectI) -> Self {
473        Bounds {
474            origin: point(rect.origin_x(), rect.origin_y()),
475            size: size(rect.width(), rect.height()),
476        }
477    }
478}
479
480impl From<Point<u32>> for Vector2I {
481    fn from(size: Point<u32>) -> Self {
482        Vector2I::new(size.x as i32, size.y as i32)
483    }
484}
485
486impl From<Vector2F> for Size<f32> {
487    fn from(vec: Vector2F) -> Self {
488        size(vec.x(), vec.y())
489    }
490}
491
492impl From<FontWeight> for cosmic_text::Weight {
493    fn from(value: FontWeight) -> Self {
494        cosmic_text::Weight(value.0 as u16)
495    }
496}
497
498impl From<FontStyle> for cosmic_text::Style {
499    fn from(style: FontStyle) -> Self {
500        match style {
501            FontStyle::Normal => cosmic_text::Style::Normal,
502            FontStyle::Italic => cosmic_text::Style::Italic,
503            FontStyle::Oblique => cosmic_text::Style::Oblique,
504        }
505    }
506}
507
508fn font_into_properties(font: &crate::Font) -> font_kit::properties::Properties {
509    font_kit::properties::Properties {
510        style: match font.style {
511            crate::FontStyle::Normal => font_kit::properties::Style::Normal,
512            crate::FontStyle::Italic => font_kit::properties::Style::Italic,
513            crate::FontStyle::Oblique => font_kit::properties::Style::Oblique,
514        },
515        weight: font_kit::properties::Weight(font.weight.0),
516        stretch: Default::default(),
517    }
518}
519
520fn face_info_into_properties(
521    face_info: &cosmic_text::fontdb::FaceInfo,
522) -> font_kit::properties::Properties {
523    font_kit::properties::Properties {
524        style: match face_info.style {
525            cosmic_text::Style::Normal => font_kit::properties::Style::Normal,
526            cosmic_text::Style::Italic => font_kit::properties::Style::Italic,
527            cosmic_text::Style::Oblique => font_kit::properties::Style::Oblique,
528        },
529        // both libs use the same values for weight
530        weight: font_kit::properties::Weight(face_info.weight.0.into()),
531        stretch: match face_info.stretch {
532            cosmic_text::Stretch::Condensed => font_kit::properties::Stretch::CONDENSED,
533            cosmic_text::Stretch::Expanded => font_kit::properties::Stretch::EXPANDED,
534            cosmic_text::Stretch::ExtraCondensed => font_kit::properties::Stretch::EXTRA_CONDENSED,
535            cosmic_text::Stretch::ExtraExpanded => font_kit::properties::Stretch::EXTRA_EXPANDED,
536            cosmic_text::Stretch::Normal => font_kit::properties::Stretch::NORMAL,
537            cosmic_text::Stretch::SemiCondensed => font_kit::properties::Stretch::SEMI_CONDENSED,
538            cosmic_text::Stretch::SemiExpanded => font_kit::properties::Stretch::SEMI_EXPANDED,
539            cosmic_text::Stretch::UltraCondensed => font_kit::properties::Stretch::ULTRA_CONDENSED,
540            cosmic_text::Stretch::UltraExpanded => font_kit::properties::Stretch::ULTRA_EXPANDED,
541        },
542    }
543}