text_system.rs

  1use crate::{
  2    Bounds, DevicePixels, Font, FontFeatures, FontId, FontMetrics, FontRun, FontStyle, FontWeight,
  3    GlyphId, LineLayout, Pixels, PlatformTextSystem, Point, RenderGlyphParams, SUBPIXEL_VARIANTS,
  4    ShapedGlyph, SharedString, Size, point, size,
  5};
  6use anyhow::{Context as _, Ok, Result, anyhow};
  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_store: Vec<Arc<CosmicTextFont>>,
 42    /// Contains enabled font features for each loaded font.
 43    features_store: Vec<CosmicFontFeatures>,
 44    /// Caches the `FontId`s associated with a specific family to avoid iterating the font database
 45    /// for every font face in a family.
 46    font_ids_by_family_cache: HashMap<FontKey, SmallVec<[FontId; 4]>>,
 47    /// The name of each font associated with the given font id
 48    postscript_names: HashMap<FontId, String>,
 49}
 50
 51impl CosmicTextSystem {
 52    pub(crate) fn new() -> Self {
 53        // todo(linux) make font loading non-blocking
 54        let mut font_system = FontSystem::new();
 55
 56        Self(RwLock::new(CosmicTextSystemState {
 57            font_system,
 58            swash_cache: SwashCache::new(),
 59            scratch: ShapeBuffer::default(),
 60            loaded_fonts_store: Vec::new(),
 61            features_store: Vec::new(),
 62            font_ids_by_family_cache: HashMap::default(),
 63            postscript_names: 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_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            // Convert features into cosmic_text struct.
246            let mut font_features = CosmicFontFeatures::new();
247            for feature in _features.0.iter() {
248                let name_bytes: [u8; 4] = feature
249                    .0
250                    .as_bytes()
251                    .try_into()
252                    .map_err(|_| anyhow!("Incorrect feature flag format"))?;
253
254                let tag = cosmic_text::FeatureTag::new(&name_bytes);
255
256                font_features.set(tag, feature.1);
257            }
258
259            let font_id = FontId(self.loaded_fonts_store.len());
260            font_ids.push(font_id);
261            self.loaded_fonts_store.push(font);
262            self.features_store.push(font_features);
263            self.postscript_names.insert(font_id, postscript_name);
264        }
265
266        Ok(font_ids)
267    }
268
269    fn advance(&self, font_id: FontId, glyph_id: GlyphId) -> Result<Size<f32>> {
270        let width = self.loaded_fonts_store[font_id.0]
271            .as_swash()
272            .glyph_metrics(&[])
273            .advance_width(glyph_id.0 as u16);
274        let height = self.loaded_fonts_store[font_id.0]
275            .as_swash()
276            .glyph_metrics(&[])
277            .advance_height(glyph_id.0 as u16);
278        Ok(Size { width, height })
279    }
280
281    fn glyph_for_char(&self, font_id: FontId, ch: char) -> Option<GlyphId> {
282        let glyph_id = self.loaded_fonts_store[font_id.0]
283            .as_swash()
284            .charmap()
285            .map(ch);
286        if glyph_id == 0 {
287            None
288        } else {
289            Some(GlyphId(glyph_id.into()))
290        }
291    }
292
293    fn is_emoji(&self, font_id: FontId) -> bool {
294        // TODO: Include other common emoji fonts
295        self.postscript_names
296            .get(&font_id)
297            .map_or(false, |postscript_name| postscript_name == "NotoColorEmoji")
298    }
299
300    fn raster_bounds(&mut self, params: &RenderGlyphParams) -> Result<Bounds<DevicePixels>> {
301        let font = &self.loaded_fonts_store[params.font_id.0];
302        let image = self
303            .swash_cache
304            .get_image(
305                &mut self.font_system,
306                CacheKey::new(
307                    font.id(),
308                    params.glyph_id.0 as u16,
309                    (params.font_size * params.scale_factor).into(),
310                    (0.0, 0.0),
311                    cosmic_text::CacheKeyFlags::empty(),
312                )
313                .0,
314            )
315            .clone()
316            .with_context(|| format!("no image for {params:?} in font {font:?}"))?;
317        Ok(Bounds {
318            origin: point(image.placement.left.into(), (-image.placement.top).into()),
319            size: size(image.placement.width.into(), image.placement.height.into()),
320        })
321    }
322
323    #[profiling::function]
324    fn rasterize_glyph(
325        &mut self,
326        params: &RenderGlyphParams,
327        glyph_bounds: Bounds<DevicePixels>,
328    ) -> Result<(Size<DevicePixels>, Vec<u8>)> {
329        if glyph_bounds.size.width.0 == 0 || glyph_bounds.size.height.0 == 0 {
330            Err(anyhow!("glyph bounds are empty"))
331        } else {
332            let bitmap_size = glyph_bounds.size;
333            let font = &self.loaded_fonts_store[params.font_id.0];
334            let subpixel_shift = params
335                .subpixel_variant
336                .map(|v| v as f32 / (SUBPIXEL_VARIANTS as f32 * params.scale_factor));
337            let mut image = self
338                .swash_cache
339                .get_image(
340                    &mut self.font_system,
341                    CacheKey::new(
342                        font.id(),
343                        params.glyph_id.0 as u16,
344                        (params.font_size * params.scale_factor).into(),
345                        (subpixel_shift.x, subpixel_shift.y.trunc()),
346                        cosmic_text::CacheKeyFlags::empty(),
347                    )
348                    .0,
349                )
350                .clone()
351                .with_context(|| format!("no image for {params:?} in font {font:?}"))?;
352
353            if params.is_emoji {
354                // Convert from RGBA to BGRA.
355                for pixel in image.data.chunks_exact_mut(4) {
356                    pixel.swap(0, 2);
357                }
358            }
359
360            Ok((bitmap_size, image.data))
361        }
362    }
363
364    fn font_id_for_cosmic_id(&mut self, id: cosmic_text::fontdb::ID) -> FontId {
365        if let Some(ix) = self
366            .loaded_fonts_store
367            .iter()
368            .position(|font| font.id() == id)
369        {
370            FontId(ix)
371        } else {
372            // This matches the behavior of the mac text system
373            let font = self.font_system.get_font(id).unwrap();
374            let face = self
375                .font_system
376                .db()
377                .faces()
378                .find(|info| info.id == id)
379                .unwrap();
380
381            let font_id = FontId(self.loaded_fonts_store.len());
382            self.loaded_fonts_store.push(font);
383            self.postscript_names
384                .insert(font_id, face.post_script_name.clone());
385
386            font_id
387        }
388    }
389
390    #[profiling::function]
391    fn layout_line(&mut self, text: &str, font_size: Pixels, font_runs: &[FontRun]) -> LineLayout {
392        let mut attrs_list = AttrsList::new(&Attrs::new());
393        let mut offs = 0;
394        for run in font_runs {
395            let font = &self.loaded_fonts_store[run.font_id.0];
396            let font = self.font_system.db().face(font.id()).unwrap();
397
398            let features = self.features_store[run.font_id.0].clone();
399
400            attrs_list.add_span(
401                offs..(offs + run.len),
402                &Attrs::new()
403                    .family(Family::Name(&font.families.first().unwrap().0))
404                    .stretch(font.stretch)
405                    .style(font.style)
406                    .weight(font.weight)
407                    .font_features(features),
408            );
409            offs += run.len;
410        }
411        let mut line = ShapeLine::new(
412            &mut self.font_system,
413            text,
414            &attrs_list,
415            cosmic_text::Shaping::Advanced,
416            4,
417        );
418        let mut layout = Vec::with_capacity(1);
419        line.layout_to_buffer(
420            &mut self.scratch,
421            font_size.0,
422            None, // We do our own wrapping
423            cosmic_text::Wrap::None,
424            None,
425            &mut layout,
426            None,
427        );
428
429        let mut runs = Vec::new();
430        let layout = layout.first().unwrap();
431        for glyph in &layout.glyphs {
432            let font_id = glyph.font_id;
433            let font_id = self.font_id_for_cosmic_id(font_id);
434            let is_emoji = self.is_emoji(font_id);
435            let mut glyphs = SmallVec::new();
436
437            // HACK: Prevent crash caused by variation selectors.
438            if glyph.glyph_id == 3 && is_emoji {
439                continue;
440            }
441
442            // 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
443            glyphs.push(ShapedGlyph {
444                id: GlyphId(glyph.glyph_id as u32),
445                position: point(glyph.x.into(), glyph.y.into()),
446                index: glyph.start,
447                is_emoji,
448            });
449
450            runs.push(crate::ShapedRun { font_id, glyphs });
451        }
452
453        LineLayout {
454            font_size,
455            width: layout.w.into(),
456            ascent: layout.max_ascent.into(),
457            descent: layout.max_descent.into(),
458            runs,
459            len: text.len(),
460        }
461    }
462}
463
464impl From<RectF> for Bounds<f32> {
465    fn from(rect: RectF) -> Self {
466        Bounds {
467            origin: point(rect.origin_x(), rect.origin_y()),
468            size: size(rect.width(), rect.height()),
469        }
470    }
471}
472
473impl From<RectI> for Bounds<DevicePixels> {
474    fn from(rect: RectI) -> Self {
475        Bounds {
476            origin: point(DevicePixels(rect.origin_x()), DevicePixels(rect.origin_y())),
477            size: size(DevicePixels(rect.width()), DevicePixels(rect.height())),
478        }
479    }
480}
481
482impl From<Vector2I> for Size<DevicePixels> {
483    fn from(value: Vector2I) -> Self {
484        size(value.x().into(), value.y().into())
485    }
486}
487
488impl From<RectI> for Bounds<i32> {
489    fn from(rect: RectI) -> Self {
490        Bounds {
491            origin: point(rect.origin_x(), rect.origin_y()),
492            size: size(rect.width(), rect.height()),
493        }
494    }
495}
496
497impl From<Point<u32>> for Vector2I {
498    fn from(size: Point<u32>) -> Self {
499        Vector2I::new(size.x as i32, size.y as i32)
500    }
501}
502
503impl From<Vector2F> for Size<f32> {
504    fn from(vec: Vector2F) -> Self {
505        size(vec.x(), vec.y())
506    }
507}
508
509impl From<FontWeight> for cosmic_text::Weight {
510    fn from(value: FontWeight) -> Self {
511        cosmic_text::Weight(value.0 as u16)
512    }
513}
514
515impl From<FontStyle> for cosmic_text::Style {
516    fn from(style: FontStyle) -> Self {
517        match style {
518            FontStyle::Normal => cosmic_text::Style::Normal,
519            FontStyle::Italic => cosmic_text::Style::Italic,
520            FontStyle::Oblique => cosmic_text::Style::Oblique,
521        }
522    }
523}
524
525fn font_into_properties(font: &crate::Font) -> font_kit::properties::Properties {
526    font_kit::properties::Properties {
527        style: match font.style {
528            crate::FontStyle::Normal => font_kit::properties::Style::Normal,
529            crate::FontStyle::Italic => font_kit::properties::Style::Italic,
530            crate::FontStyle::Oblique => font_kit::properties::Style::Oblique,
531        },
532        weight: font_kit::properties::Weight(font.weight.0),
533        stretch: Default::default(),
534    }
535}
536
537fn face_info_into_properties(
538    face_info: &cosmic_text::fontdb::FaceInfo,
539) -> font_kit::properties::Properties {
540    font_kit::properties::Properties {
541        style: match face_info.style {
542            cosmic_text::Style::Normal => font_kit::properties::Style::Normal,
543            cosmic_text::Style::Italic => font_kit::properties::Style::Italic,
544            cosmic_text::Style::Oblique => font_kit::properties::Style::Oblique,
545        },
546        // both libs use the same values for weight
547        weight: font_kit::properties::Weight(face_info.weight.0.into()),
548        stretch: match face_info.stretch {
549            cosmic_text::Stretch::Condensed => font_kit::properties::Stretch::CONDENSED,
550            cosmic_text::Stretch::Expanded => font_kit::properties::Stretch::EXPANDED,
551            cosmic_text::Stretch::ExtraCondensed => font_kit::properties::Stretch::EXTRA_CONDENSED,
552            cosmic_text::Stretch::ExtraExpanded => font_kit::properties::Stretch::EXTRA_EXPANDED,
553            cosmic_text::Stretch::Normal => font_kit::properties::Stretch::NORMAL,
554            cosmic_text::Stretch::SemiCondensed => font_kit::properties::Stretch::SEMI_CONDENSED,
555            cosmic_text::Stretch::SemiExpanded => font_kit::properties::Stretch::SEMI_EXPANDED,
556            cosmic_text::Stretch::UltraCondensed => font_kit::properties::Stretch::ULTRA_CONDENSED,
557            cosmic_text::Stretch::UltraExpanded => font_kit::properties::Stretch::ULTRA_EXPANDED,
558        },
559    }
560}