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