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, 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
181impl CosmicTextSystemState {
182    #[profiling::function]
183    fn add_fonts(&mut self, fonts: Vec<Cow<'static, [u8]>>) -> Result<()> {
184        let db = self.font_system.db_mut();
185        for bytes in fonts {
186            match bytes {
187                Cow::Borrowed(embedded_font) => {
188                    db.load_font_data(embedded_font.to_vec());
189                }
190                Cow::Owned(bytes) => {
191                    db.load_font_data(bytes);
192                }
193            }
194        }
195        Ok(())
196    }
197
198    // todo(linux) handle `FontFeatures`
199    #[profiling::function]
200    fn load_family(
201        &mut self,
202        name: &str,
203        _features: &FontFeatures,
204    ) -> Result<SmallVec<[FontId; 4]>> {
205        // TODO: Determine the proper system UI font.
206        let name = if name == ".SystemUIFont" {
207            "Zed Sans"
208        } else {
209            name
210        };
211
212        let mut font_ids = SmallVec::new();
213        let families = self
214            .font_system
215            .db()
216            .faces()
217            .filter(|face| face.families.iter().any(|family| *name == family.0))
218            .map(|face| (face.id, face.post_script_name.clone()))
219            .collect::<SmallVec<[_; 4]>>();
220
221        for (font_id, postscript_name) in families {
222            let font = self
223                .font_system
224                .get_font(font_id)
225                .ok_or_else(|| anyhow!("Could not load font"))?;
226
227            // HACK: To let the storybook run and render Windows caption icons. We should actually do better font fallback.
228            let allowed_bad_font_names = [
229                "SegoeFluentIcons", // NOTE: Segoe fluent icons postscript name is inconsistent
230                "Segoe Fluent Icons",
231            ];
232
233            if font.as_swash().charmap().map('m') == 0
234                && !allowed_bad_font_names.contains(&postscript_name.as_str())
235            {
236                self.font_system.db_mut().remove_face(font.id());
237                continue;
238            };
239
240            let font_id = FontId(self.loaded_fonts_store.len());
241            font_ids.push(font_id);
242            self.loaded_fonts_store.push(font);
243            self.postscript_names.insert(font_id, postscript_name);
244        }
245
246        Ok(font_ids)
247    }
248
249    fn advance(&self, font_id: FontId, glyph_id: GlyphId) -> Result<Size<f32>> {
250        let width = self.loaded_fonts_store[font_id.0]
251            .as_swash()
252            .glyph_metrics(&[])
253            .advance_width(glyph_id.0 as u16);
254        let height = self.loaded_fonts_store[font_id.0]
255            .as_swash()
256            .glyph_metrics(&[])
257            .advance_height(glyph_id.0 as u16);
258        Ok(Size { width, height })
259    }
260
261    fn glyph_for_char(&self, font_id: FontId, ch: char) -> Option<GlyphId> {
262        let glyph_id = self.loaded_fonts_store[font_id.0]
263            .as_swash()
264            .charmap()
265            .map(ch);
266        if glyph_id == 0 {
267            None
268        } else {
269            Some(GlyphId(glyph_id.into()))
270        }
271    }
272
273    fn is_emoji(&self, font_id: FontId) -> bool {
274        // TODO: Include other common emoji fonts
275        self.postscript_names
276            .get(&font_id)
277            .map_or(false, |postscript_name| postscript_name == "NotoColorEmoji")
278    }
279
280    fn raster_bounds(&mut self, params: &RenderGlyphParams) -> Result<Bounds<DevicePixels>> {
281        let font = &self.loaded_fonts_store[params.font_id.0];
282        let font_system = &mut self.font_system;
283        let image = self
284            .swash_cache
285            .get_image(
286                font_system,
287                CacheKey::new(
288                    font.id(),
289                    params.glyph_id.0 as u16,
290                    (params.font_size * params.scale_factor).into(),
291                    (0.0, 0.0),
292                    cosmic_text::CacheKeyFlags::empty(),
293                )
294                .0,
295            )
296            .clone()
297            .with_context(|| format!("no image for {params:?} in font {font:?}"))?;
298        Ok(Bounds {
299            origin: point(image.placement.left.into(), (-image.placement.top).into()),
300            size: size(image.placement.width.into(), image.placement.height.into()),
301        })
302    }
303
304    #[profiling::function]
305    fn rasterize_glyph(
306        &mut self,
307        params: &RenderGlyphParams,
308        glyph_bounds: Bounds<DevicePixels>,
309    ) -> Result<(Size<DevicePixels>, Vec<u8>)> {
310        if glyph_bounds.size.width.0 == 0 || glyph_bounds.size.height.0 == 0 {
311            Err(anyhow!("glyph bounds are empty"))
312        } else {
313            // todo(linux) handle subpixel variants
314            let bitmap_size = glyph_bounds.size;
315            let font = &self.loaded_fonts_store[params.font_id.0];
316            let font_system = &mut self.font_system;
317            let mut image = self
318                .swash_cache
319                .get_image(
320                    font_system,
321                    CacheKey::new(
322                        font.id(),
323                        params.glyph_id.0 as u16,
324                        (params.font_size * params.scale_factor).into(),
325                        (0.0, 0.0),
326                        cosmic_text::CacheKeyFlags::empty(),
327                    )
328                    .0,
329                )
330                .clone()
331                .with_context(|| format!("no image for {params:?} in font {font:?}"))?;
332
333            if params.is_emoji {
334                // Convert from RGBA to BGRA.
335                for pixel in image.data.chunks_exact_mut(4) {
336                    pixel.swap(0, 2);
337                }
338            }
339
340            Ok((bitmap_size, image.data))
341        }
342    }
343
344    fn font_id_for_cosmic_id(&mut self, id: cosmic_text::fontdb::ID) -> FontId {
345        if let Some(ix) = self
346            .loaded_fonts_store
347            .iter()
348            .position(|font| font.id() == id)
349        {
350            FontId(ix)
351        } else {
352            // This matches the behavior of the mac text system
353            let font = self.font_system.get_font(id).unwrap();
354            let face = self
355                .font_system
356                .db()
357                .faces()
358                .find(|info| info.id == id)
359                .unwrap();
360
361            let font_id = FontId(self.loaded_fonts_store.len());
362            self.loaded_fonts_store.push(font);
363            self.postscript_names
364                .insert(font_id, face.post_script_name.clone());
365
366            font_id
367        }
368    }
369
370    // todo(linux) This is all a quick first pass, maybe we should be using cosmic_text::Buffer
371    #[profiling::function]
372    fn layout_line(&mut self, text: &str, font_size: Pixels, font_runs: &[FontRun]) -> LineLayout {
373        let mut attrs_list = AttrsList::new(Attrs::new());
374        let mut offs = 0;
375        for run in font_runs {
376            // todo(linux) We need to check we are doing utf properly
377            let font = &self.loaded_fonts_store[run.font_id.0];
378            let font = self.font_system.db().face(font.id()).unwrap();
379            attrs_list.add_span(
380                offs..(offs + run.len),
381                Attrs::new()
382                    .family(Family::Name(&font.families.first().unwrap().0))
383                    .stretch(font.stretch)
384                    .style(font.style)
385                    .weight(font.weight),
386            );
387            offs += run.len;
388        }
389        let mut line = BufferLine::new(text, attrs_list, cosmic_text::Shaping::Advanced);
390
391        let layout = line.layout(
392            &mut self.font_system,
393            font_size.0,
394            f32::MAX, // We do our own wrapping
395            cosmic_text::Wrap::None,
396            None,
397        );
398        let mut runs = Vec::new();
399
400        let layout = layout.first().unwrap();
401        for glyph in &layout.glyphs {
402            let font_id = glyph.font_id;
403            let font_id = self.font_id_for_cosmic_id(font_id);
404            let is_emoji = self.is_emoji(font_id);
405            let mut glyphs = SmallVec::new();
406
407            // HACK: Prevent crash caused by variation selectors.
408            if glyph.glyph_id == 3 && is_emoji {
409                continue;
410            }
411
412            // 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
413            glyphs.push(ShapedGlyph {
414                id: GlyphId(glyph.glyph_id as u32),
415                position: point((glyph.x).into(), glyph.y.into()),
416                index: glyph.start,
417                is_emoji,
418            });
419
420            runs.push(crate::ShapedRun { font_id, glyphs });
421        }
422
423        LineLayout {
424            font_size,
425            width: layout.w.into(),
426            ascent: layout.max_ascent.into(),
427            descent: layout.max_descent.into(),
428            runs,
429            len: text.len(),
430        }
431    }
432}
433
434impl From<RectF> for Bounds<f32> {
435    fn from(rect: RectF) -> Self {
436        Bounds {
437            origin: point(rect.origin_x(), rect.origin_y()),
438            size: size(rect.width(), rect.height()),
439        }
440    }
441}
442
443impl From<RectI> for Bounds<DevicePixels> {
444    fn from(rect: RectI) -> Self {
445        Bounds {
446            origin: point(DevicePixels(rect.origin_x()), DevicePixels(rect.origin_y())),
447            size: size(DevicePixels(rect.width()), DevicePixels(rect.height())),
448        }
449    }
450}
451
452impl From<Vector2I> for Size<DevicePixels> {
453    fn from(value: Vector2I) -> Self {
454        size(value.x().into(), value.y().into())
455    }
456}
457
458impl From<RectI> for Bounds<i32> {
459    fn from(rect: RectI) -> Self {
460        Bounds {
461            origin: point(rect.origin_x(), rect.origin_y()),
462            size: size(rect.width(), rect.height()),
463        }
464    }
465}
466
467impl From<Point<u32>> for Vector2I {
468    fn from(size: Point<u32>) -> Self {
469        Vector2I::new(size.x as i32, size.y as i32)
470    }
471}
472
473impl From<Vector2F> for Size<f32> {
474    fn from(vec: Vector2F) -> Self {
475        size(vec.x(), vec.y())
476    }
477}
478
479impl From<FontWeight> for cosmic_text::Weight {
480    fn from(value: FontWeight) -> Self {
481        cosmic_text::Weight(value.0 as u16)
482    }
483}
484
485impl From<FontStyle> for cosmic_text::Style {
486    fn from(style: FontStyle) -> Self {
487        match style {
488            FontStyle::Normal => cosmic_text::Style::Normal,
489            FontStyle::Italic => cosmic_text::Style::Italic,
490            FontStyle::Oblique => cosmic_text::Style::Oblique,
491        }
492    }
493}
494
495fn font_into_properties(font: &crate::Font) -> font_kit::properties::Properties {
496    font_kit::properties::Properties {
497        style: match font.style {
498            crate::FontStyle::Normal => font_kit::properties::Style::Normal,
499            crate::FontStyle::Italic => font_kit::properties::Style::Italic,
500            crate::FontStyle::Oblique => font_kit::properties::Style::Oblique,
501        },
502        weight: font_kit::properties::Weight(font.weight.0),
503        stretch: Default::default(),
504    }
505}
506
507fn face_info_into_properties(
508    face_info: &cosmic_text::fontdb::FaceInfo,
509) -> font_kit::properties::Properties {
510    font_kit::properties::Properties {
511        style: match face_info.style {
512            cosmic_text::Style::Normal => font_kit::properties::Style::Normal,
513            cosmic_text::Style::Italic => font_kit::properties::Style::Italic,
514            cosmic_text::Style::Oblique => font_kit::properties::Style::Oblique,
515        },
516        // both libs use the same values for weight
517        weight: font_kit::properties::Weight(face_info.weight.0.into()),
518        stretch: match face_info.stretch {
519            cosmic_text::Stretch::Condensed => font_kit::properties::Stretch::CONDENSED,
520            cosmic_text::Stretch::Expanded => font_kit::properties::Stretch::EXPANDED,
521            cosmic_text::Stretch::ExtraCondensed => font_kit::properties::Stretch::EXTRA_CONDENSED,
522            cosmic_text::Stretch::ExtraExpanded => font_kit::properties::Stretch::EXTRA_EXPANDED,
523            cosmic_text::Stretch::Normal => font_kit::properties::Stretch::NORMAL,
524            cosmic_text::Stretch::SemiCondensed => font_kit::properties::Stretch::SEMI_CONDENSED,
525            cosmic_text::Stretch::SemiExpanded => font_kit::properties::Stretch::SEMI_EXPANDED,
526            cosmic_text::Stretch::UltraCondensed => font_kit::properties::Stretch::ULTRA_CONDENSED,
527            cosmic_text::Stretch::UltraExpanded => font_kit::properties::Stretch::ULTRA_EXPANDED,
528        },
529    }
530}