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