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. Indexed by `FontId`.
 27    ///
 28    /// When a font is requested via `LinuxTextSystem::font_id` all faces of the requested family
 29    /// are loaded at once via `Self::load_family`. Not every item in this list is therefore actually
 30    /// being used to render text on the screen.
 31    // A reference to these fonts is also stored in `font_system`, but calling `FontSystem::get_font`
 32    // would require a mutable reference and therefore a write lock
 33    loaded_fonts_store: Vec<Arc<CosmicTextFont>>,
 34    /// Caches the `FontId`s associated with a specific family to avoid iterating the font database
 35    /// for every font face in a family.
 36    font_ids_by_family_cache: HashMap<SharedString, SmallVec<[FontId; 4]>>,
 37}
 38
 39impl LinuxTextSystem {
 40    pub(crate) fn new() -> Self {
 41        let mut font_system = FontSystem::new();
 42
 43        // todo(linux) make font loading non-blocking
 44        font_system.db_mut().load_system_fonts();
 45
 46        Self(RwLock::new(LinuxTextSystemState {
 47            font_system,
 48            swash_cache: SwashCache::new(),
 49            loaded_fonts_store: Vec::new(),
 50            font_ids_by_family_cache: HashMap::default(),
 51        }))
 52    }
 53}
 54
 55impl Default for LinuxTextSystem {
 56    fn default() -> Self {
 57        Self::new()
 58    }
 59}
 60
 61impl PlatformTextSystem for LinuxTextSystem {
 62    fn add_fonts(&self, fonts: Vec<Cow<'static, [u8]>>) -> Result<()> {
 63        self.0.write().add_fonts(fonts)
 64    }
 65
 66    // todo(linux) ensure that this integrates with platform font loading
 67    // do we need to do more than call load_system_fonts()?
 68    fn all_font_names(&self) -> Vec<String> {
 69        self.0
 70            .read()
 71            .font_system
 72            .db()
 73            .faces()
 74            .map(|face| face.post_script_name.clone())
 75            .collect()
 76    }
 77
 78    fn all_font_families(&self) -> Vec<String> {
 79        self.0
 80            .read()
 81            .font_system
 82            .db()
 83            .faces()
 84            // todo(linux) this will list the same font family multiple times
 85            .filter_map(|face| face.families.first().map(|family| family.0.clone()))
 86            .collect_vec()
 87    }
 88
 89    fn font_id(&self, font: &Font) -> Result<FontId> {
 90        // todo(linux): Do we need to use CosmicText's Font APIs? Can we consolidate this to use font_kit?
 91        let mut state = self.0.write();
 92
 93        let candidates = if let Some(font_ids) = state.font_ids_by_family_cache.get(&font.family) {
 94            font_ids.as_slice()
 95        } else {
 96            let font_ids = state.load_family(&font.family, font.features)?;
 97            state
 98                .font_ids_by_family_cache
 99                .insert(font.family.clone(), font_ids);
100            state.font_ids_by_family_cache[&font.family].as_ref()
101        };
102
103        // todo(linux) ideally we would make fontdb's `find_best_match` pub instead of using font-kit here
104        let candidate_properties = candidates
105            .iter()
106            .map(|font_id| {
107                let database_id = state.loaded_fonts_store[font_id.0].id();
108                let face_info = state.font_system.db().face(database_id).expect("");
109                face_info_into_properties(face_info)
110            })
111            .collect::<SmallVec<[_; 4]>>();
112
113        let ix =
114            font_kit::matching::find_best_match(&candidate_properties, &font_into_properties(font))
115                .context("requested font family contains no font matching the other parameters")?;
116
117        Ok(candidates[ix])
118    }
119
120    fn font_metrics(&self, font_id: FontId) -> FontMetrics {
121        let metrics = self.0.read().loaded_fonts_store[font_id.0]
122            .as_swash()
123            .metrics(&[]);
124
125        FontMetrics {
126            units_per_em: metrics.units_per_em as u32,
127            ascent: metrics.ascent,
128            descent: -metrics.descent, // todo(linux) confirm this is correct
129            line_gap: metrics.leading,
130            underline_position: metrics.underline_offset,
131            underline_thickness: metrics.stroke_size,
132            cap_height: metrics.cap_height,
133            x_height: metrics.x_height,
134            // todo(linux): Compute this correctly
135            bounding_box: Bounds {
136                origin: point(0.0, 0.0),
137                size: size(metrics.max_width, metrics.ascent + metrics.descent),
138            },
139        }
140    }
141
142    fn typographic_bounds(&self, font_id: FontId, glyph_id: GlyphId) -> Result<Bounds<f32>> {
143        let lock = self.0.read();
144        let glyph_metrics = lock.loaded_fonts_store[font_id.0]
145            .as_swash()
146            .glyph_metrics(&[]);
147        let glyph_id = glyph_id.0 as u16;
148        // todo(linux): Compute this correctly
149        // see https://github.com/servo/font-kit/blob/master/src/loaders/freetype.rs#L614-L620
150        Ok(Bounds {
151            origin: point(0.0, 0.0),
152            size: size(
153                glyph_metrics.advance_width(glyph_id),
154                glyph_metrics.advance_height(glyph_id),
155            ),
156        })
157    }
158
159    fn advance(&self, font_id: FontId, glyph_id: GlyphId) -> Result<Size<f32>> {
160        self.0.read().advance(font_id, glyph_id)
161    }
162
163    fn glyph_for_char(&self, font_id: FontId, ch: char) -> Option<GlyphId> {
164        self.0.read().glyph_for_char(font_id, ch)
165    }
166
167    fn glyph_raster_bounds(&self, params: &RenderGlyphParams) -> Result<Bounds<DevicePixels>> {
168        self.0.write().raster_bounds(params)
169    }
170
171    fn rasterize_glyph(
172        &self,
173        params: &RenderGlyphParams,
174        raster_bounds: Bounds<DevicePixels>,
175    ) -> Result<(Size<DevicePixels>, Vec<u8>)> {
176        self.0.write().rasterize_glyph(params, raster_bounds)
177    }
178
179    fn layout_line(&self, text: &str, font_size: Pixels, runs: &[FontRun]) -> LineLayout {
180        self.0.write().layout_line(text, font_size, runs)
181    }
182
183    // todo(linux) Confirm that this has been superseded by the LineWrapper
184    fn wrap_line(
185        &self,
186        _text: &str,
187        _font_id: FontId,
188        _font_size: Pixels,
189        _width: Pixels,
190    ) -> Vec<usize> {
191        unimplemented!()
192    }
193}
194
195impl LinuxTextSystemState {
196    #[profiling::function]
197    fn add_fonts(&mut self, fonts: Vec<Cow<'static, [u8]>>) -> Result<()> {
198        let db = self.font_system.db_mut();
199        for bytes in fonts {
200            match bytes {
201                Cow::Borrowed(embedded_font) => {
202                    db.load_font_data(embedded_font.to_vec());
203                }
204                Cow::Owned(bytes) => {
205                    db.load_font_data(bytes);
206                }
207            }
208        }
209        Ok(())
210    }
211
212    // todo(linux) handle `FontFeatures`
213    #[profiling::function]
214    fn load_family(
215        &mut self,
216        name: &SharedString,
217        _features: FontFeatures,
218    ) -> Result<SmallVec<[FontId; 4]>> {
219        let mut font_ids = SmallVec::new();
220        let family = self
221            .font_system
222            .get_font_matches(Attrs::new().family(cosmic_text::Family::Name(name)));
223        for font in family.as_ref() {
224            let font = self.font_system.get_font(*font).unwrap();
225            if font.as_swash().charmap().map('m') == 0 {
226                self.font_system.db_mut().remove_face(font.id());
227                continue;
228            };
229
230            let font_id = FontId(self.loaded_fonts_store.len());
231            font_ids.push(font_id);
232            self.loaded_fonts_store.push(font);
233        }
234        Ok(font_ids)
235    }
236
237    fn advance(&self, font_id: FontId, glyph_id: GlyphId) -> Result<Size<f32>> {
238        let width = self.loaded_fonts_store[font_id.0]
239            .as_swash()
240            .glyph_metrics(&[])
241            .advance_width(glyph_id.0 as u16);
242        let height = self.loaded_fonts_store[font_id.0]
243            .as_swash()
244            .glyph_metrics(&[])
245            .advance_height(glyph_id.0 as u16);
246        Ok(Size { width, height })
247    }
248
249    fn glyph_for_char(&self, font_id: FontId, ch: char) -> Option<GlyphId> {
250        let glyph_id = self.loaded_fonts_store[font_id.0]
251            .as_swash()
252            .charmap()
253            .map(ch);
254        if glyph_id == 0 {
255            None
256        } else {
257            Some(GlyphId(glyph_id.into()))
258        }
259    }
260
261    // todo(linux)
262    fn is_emoji(&self, _font_id: FontId) -> bool {
263        false
264    }
265
266    // todo(linux) both raster functions have problems because I am not sure this is the correct mapping from cosmic text to gpui system
267    fn raster_bounds(&mut self, params: &RenderGlyphParams) -> Result<Bounds<DevicePixels>> {
268        let font = &self.loaded_fonts_store[params.font_id.0];
269        let font_system = &mut self.font_system;
270        let image = self
271            .swash_cache
272            .get_image(
273                font_system,
274                CacheKey::new(
275                    font.id(),
276                    params.glyph_id.0 as u16,
277                    (params.font_size * params.scale_factor).into(),
278                    (0.0, 0.0),
279                )
280                .0,
281            )
282            .clone()
283            .unwrap();
284        Ok(Bounds {
285            origin: point(image.placement.left.into(), (-image.placement.top).into()),
286            size: size(image.placement.width.into(), image.placement.height.into()),
287        })
288    }
289
290    #[profiling::function]
291    fn rasterize_glyph(
292        &mut self,
293        params: &RenderGlyphParams,
294        glyph_bounds: Bounds<DevicePixels>,
295    ) -> Result<(Size<DevicePixels>, Vec<u8>)> {
296        if glyph_bounds.size.width.0 == 0 || glyph_bounds.size.height.0 == 0 {
297            Err(anyhow!("glyph bounds are empty"))
298        } else {
299            // todo(linux) handle subpixel variants
300            let bitmap_size = glyph_bounds.size;
301            let font = &self.loaded_fonts_store[params.font_id.0];
302            let font_system = &mut self.font_system;
303            let image = self
304                .swash_cache
305                .get_image(
306                    font_system,
307                    CacheKey::new(
308                        font.id(),
309                        params.glyph_id.0 as u16,
310                        (params.font_size * params.scale_factor).into(),
311                        (0.0, 0.0),
312                    )
313                    .0,
314                )
315                .clone()
316                .unwrap();
317
318            Ok((bitmap_size, image.data))
319        }
320    }
321
322    // todo(linux) This is all a quick first pass, maybe we should be using cosmic_text::Buffer
323    #[profiling::function]
324    fn layout_line(&mut self, text: &str, font_size: Pixels, font_runs: &[FontRun]) -> LineLayout {
325        let mut attrs_list = AttrsList::new(Attrs::new());
326        let mut offs = 0;
327        for run in font_runs {
328            // todo(linux) We need to check we are doing utf properly
329            let font = &self.loaded_fonts_store[run.font_id.0];
330            let font = self.font_system.db().face(font.id()).unwrap();
331            attrs_list.add_span(
332                offs..offs + run.len,
333                Attrs::new()
334                    .family(Family::Name(&font.families.first().unwrap().0))
335                    .stretch(font.stretch)
336                    .style(font.style)
337                    .weight(font.weight),
338            );
339            offs += run.len;
340        }
341        let mut line = BufferLine::new(text, attrs_list, cosmic_text::Shaping::Advanced);
342        let layout = line.layout(
343            &mut self.font_system,
344            font_size.0,
345            f32::MAX, // todo(linux) we don't have a width cause this should technically not be wrapped I believe
346            cosmic_text::Wrap::None,
347        );
348        let mut runs = Vec::new();
349        // todo(linux) what I think can happen is layout returns possibly multiple lines which means we should be probably working with it higher up in the text rendering
350        let layout = layout.first().unwrap();
351        for glyph in &layout.glyphs {
352            let font_id = glyph.font_id;
353            let font_id = FontId(
354                self.loaded_fonts_store
355                    .iter()
356                    .position(|font| font.id() == font_id)
357                    .unwrap(),
358            );
359            let mut glyphs = SmallVec::new();
360            // 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
361            glyphs.push(ShapedGlyph {
362                id: GlyphId(glyph.glyph_id as u32),
363                position: point((glyph.x).into(), glyph.y.into()),
364                index: glyph.start,
365                is_emoji: self.is_emoji(font_id),
366            });
367            runs.push(crate::ShapedRun { font_id, glyphs });
368        }
369        LineLayout {
370            font_size,
371            width: layout.w.into(),
372            ascent: layout.max_ascent.into(),
373            descent: layout.max_descent.into(),
374            runs,
375            len: text.len(),
376        }
377    }
378}
379
380impl From<RectF> for Bounds<f32> {
381    fn from(rect: RectF) -> Self {
382        Bounds {
383            origin: point(rect.origin_x(), rect.origin_y()),
384            size: size(rect.width(), rect.height()),
385        }
386    }
387}
388
389impl From<RectI> for Bounds<DevicePixels> {
390    fn from(rect: RectI) -> Self {
391        Bounds {
392            origin: point(DevicePixels(rect.origin_x()), DevicePixels(rect.origin_y())),
393            size: size(DevicePixels(rect.width()), DevicePixels(rect.height())),
394        }
395    }
396}
397
398impl From<Vector2I> for Size<DevicePixels> {
399    fn from(value: Vector2I) -> Self {
400        size(value.x().into(), value.y().into())
401    }
402}
403
404impl From<RectI> for Bounds<i32> {
405    fn from(rect: RectI) -> Self {
406        Bounds {
407            origin: point(rect.origin_x(), rect.origin_y()),
408            size: size(rect.width(), rect.height()),
409        }
410    }
411}
412
413impl From<Point<u32>> for Vector2I {
414    fn from(size: Point<u32>) -> Self {
415        Vector2I::new(size.x as i32, size.y as i32)
416    }
417}
418
419impl From<Vector2F> for Size<f32> {
420    fn from(vec: Vector2F) -> Self {
421        size(vec.x(), vec.y())
422    }
423}
424
425impl From<FontWeight> for cosmic_text::Weight {
426    fn from(value: FontWeight) -> Self {
427        cosmic_text::Weight(value.0 as u16)
428    }
429}
430
431impl From<FontStyle> for cosmic_text::Style {
432    fn from(style: FontStyle) -> Self {
433        match style {
434            FontStyle::Normal => cosmic_text::Style::Normal,
435            FontStyle::Italic => cosmic_text::Style::Italic,
436            FontStyle::Oblique => cosmic_text::Style::Oblique,
437        }
438    }
439}
440
441fn font_into_properties(font: &crate::Font) -> font_kit::properties::Properties {
442    font_kit::properties::Properties {
443        style: match font.style {
444            crate::FontStyle::Normal => font_kit::properties::Style::Normal,
445            crate::FontStyle::Italic => font_kit::properties::Style::Italic,
446            crate::FontStyle::Oblique => font_kit::properties::Style::Oblique,
447        },
448        weight: font_kit::properties::Weight(font.weight.0),
449        stretch: Default::default(),
450    }
451}
452
453fn face_info_into_properties(
454    face_info: &cosmic_text::fontdb::FaceInfo,
455) -> font_kit::properties::Properties {
456    font_kit::properties::Properties {
457        style: match face_info.style {
458            cosmic_text::Style::Normal => font_kit::properties::Style::Normal,
459            cosmic_text::Style::Italic => font_kit::properties::Style::Italic,
460            cosmic_text::Style::Oblique => font_kit::properties::Style::Oblique,
461        },
462        // both libs use the same values for weight
463        weight: font_kit::properties::Weight(face_info.weight.0.into()),
464        stretch: match face_info.stretch {
465            cosmic_text::Stretch::Condensed => font_kit::properties::Stretch::CONDENSED,
466            cosmic_text::Stretch::Expanded => font_kit::properties::Stretch::EXPANDED,
467            cosmic_text::Stretch::ExtraCondensed => font_kit::properties::Stretch::EXTRA_CONDENSED,
468            cosmic_text::Stretch::ExtraExpanded => font_kit::properties::Stretch::EXTRA_EXPANDED,
469            cosmic_text::Stretch::Normal => font_kit::properties::Stretch::NORMAL,
470            cosmic_text::Stretch::SemiCondensed => font_kit::properties::Stretch::SEMI_CONDENSED,
471            cosmic_text::Stretch::SemiExpanded => font_kit::properties::Stretch::SEMI_EXPANDED,
472            cosmic_text::Stretch::UltraCondensed => font_kit::properties::Stretch::ULTRA_CONDENSED,
473            cosmic_text::Stretch::UltraExpanded => font_kit::properties::Stretch::ULTRA_EXPANDED,
474        },
475    }
476}