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::Font as CosmicTextFont;
  9use cosmic_text::{
 10    fontdb::Query, Attrs, AttrsList, BufferLine, CacheKey, Family, FontSystem, SwashCache,
 11};
 12use parking_lot::{RwLock, RwLockUpgradableReadGuard};
 13use pathfinder_geometry::{
 14    rect::{RectF, RectI},
 15    vector::{Vector2F, Vector2I},
 16};
 17use smallvec::SmallVec;
 18use std::{borrow::Cow, sync::Arc};
 19
 20pub(crate) struct WindowsTextSystem(RwLock<WindowsTextSystemState>);
 21
 22struct WindowsTextSystemState {
 23    swash_cache: SwashCache,
 24    font_system: FontSystem,
 25    fonts: Vec<Arc<CosmicTextFont>>,
 26    font_selections: HashMap<Font, FontId>,
 27    font_ids_by_family_name: HashMap<SharedString, SmallVec<[FontId; 4]>>,
 28    postscript_names_by_font_id: HashMap<FontId, String>,
 29}
 30
 31impl WindowsTextSystem {
 32    pub(crate) fn new() -> Self {
 33        let mut font_system = FontSystem::new();
 34        Self(RwLock::new(WindowsTextSystemState {
 35            font_system,
 36            swash_cache: SwashCache::new(),
 37            fonts: Vec::new(),
 38            font_selections: HashMap::default(),
 39            // font_ids_by_postscript_name: HashMap::default(),
 40            font_ids_by_family_name: HashMap::default(),
 41            postscript_names_by_font_id: HashMap::default(),
 42        }))
 43    }
 44}
 45
 46impl Default for WindowsTextSystem {
 47    fn default() -> Self {
 48        Self::new()
 49    }
 50}
 51
 52#[allow(unused)]
 53impl PlatformTextSystem for WindowsTextSystem {
 54    fn add_fonts(&self, fonts: Vec<Cow<'static, [u8]>>) -> Result<()> {
 55        self.0.write().add_fonts(fonts)
 56    }
 57
 58    // todo(windows) ensure that this integrates with platform font loading
 59    // do we need to do more than call load_system_fonts()?
 60    fn all_font_names(&self) -> Vec<String> {
 61        self.0
 62            .read()
 63            .font_system
 64            .db()
 65            .faces()
 66            .map(|face| face.post_script_name.clone())
 67            .collect()
 68    }
 69
 70    // todo(windows)
 71    fn all_font_families(&self) -> Vec<String> {
 72        Vec::new()
 73    }
 74
 75    fn font_id(&self, font: &Font) -> Result<FontId> {
 76        // todo(windows): Do we need to use CosmicText's Font APIs? Can we consolidate this to use font_kit?
 77        let lock = self.0.upgradable_read();
 78        if let Some(font_id) = lock.font_selections.get(font) {
 79            Ok(*font_id)
 80        } else {
 81            let mut lock = RwLockUpgradableReadGuard::upgrade(lock);
 82            let candidates = if let Some(font_ids) = lock.font_ids_by_family_name.get(&font.family)
 83            {
 84                font_ids.as_slice()
 85            } else {
 86                let font_ids = lock.load_family(&font.family, font.features)?;
 87                lock.font_ids_by_family_name
 88                    .insert(font.family.clone(), font_ids);
 89                lock.font_ids_by_family_name[&font.family].as_ref()
 90            };
 91
 92            let id = lock
 93                .font_system
 94                .db()
 95                .query(&Query {
 96                    families: &[Family::Name(&font.family)],
 97                    weight: font.weight.into(),
 98                    style: font.style.into(),
 99                    stretch: Default::default(),
100                })
101                .context("no font")?;
102
103            let font_id = if let Some(font_id) = lock.fonts.iter().position(|font| font.id() == id)
104            {
105                FontId(font_id)
106            } else {
107                // Font isn't in fonts so add it there, this is because we query all the fonts in the db
108                // and maybe we haven't loaded it yet
109                let font_id = FontId(lock.fonts.len());
110                let font = lock.font_system.get_font(id).unwrap();
111                lock.fonts.push(font);
112                font_id
113            };
114
115            lock.font_selections.insert(font.clone(), font_id);
116            Ok(font_id)
117        }
118    }
119
120    fn font_metrics(&self, font_id: FontId) -> FontMetrics {
121        let metrics = self.0.read().fonts[font_id.0].as_swash().metrics(&[]);
122
123        FontMetrics {
124            units_per_em: metrics.units_per_em as u32,
125            ascent: metrics.ascent,
126            descent: -metrics.descent, // todo(windows) confirm this is correct
127            line_gap: metrics.leading,
128            underline_position: metrics.underline_offset,
129            underline_thickness: metrics.stroke_size,
130            cap_height: metrics.cap_height,
131            x_height: metrics.x_height,
132            // todo(windows): Compute this correctly
133            bounding_box: Bounds {
134                origin: point(0.0, 0.0),
135                size: size(metrics.max_width, metrics.ascent + metrics.descent),
136            },
137        }
138    }
139
140    fn typographic_bounds(&self, font_id: FontId, glyph_id: GlyphId) -> Result<Bounds<f32>> {
141        let lock = self.0.read();
142        let metrics = lock.fonts[font_id.0].as_swash().metrics(&[]);
143        let glyph_metrics = lock.fonts[font_id.0].as_swash().glyph_metrics(&[]);
144        let glyph_id = glyph_id.0 as u16;
145        // todo(windows): 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(windows) 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 WindowsTextSystemState {
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    #[profiling::function]
210    fn load_family(
211        &mut self,
212        name: &SharedString,
213        _features: FontFeatures,
214    ) -> Result<SmallVec<[FontId; 4]>> {
215        let mut font_ids = SmallVec::new();
216        let families = self
217            .font_system
218            .db()
219            .faces()
220            .filter(|face| face.families.iter().any(|family| *name == family.0))
221            .map(|face| (face.id, face.post_script_name.clone()))
222            .collect::<SmallVec<[_; 4]>>();
223
224        for (font_id, postscript_name) in families {
225            let font = self
226                .font_system
227                .get_font(font_id)
228                .ok_or_else(|| anyhow!("Could not load font"))?;
229            // TODO: figure out why this is causing fluent icons from loading
230            // if font.as_swash().charmap().map('m') == 0 {
231            //     self.font_system.db_mut().remove_face(font.id());
232            //     continue;
233            // };
234
235            let font_id = FontId(self.fonts.len());
236            font_ids.push(font_id);
237            self.fonts.push(font);
238            self.postscript_names_by_font_id
239                .insert(font_id, postscript_name);
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(windows): 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(windows) 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                    cosmic_text::CacheKeyFlags::empty(),
288                )
289                .0,
290            )
291            .clone()
292            .unwrap();
293        Ok(Bounds {
294            origin: point(image.placement.left.into(), (-image.placement.top).into()),
295            size: size(image.placement.width.into(), image.placement.height.into()),
296        })
297    }
298
299    #[profiling::function]
300    fn rasterize_glyph(
301        &mut self,
302        params: &RenderGlyphParams,
303        glyph_bounds: Bounds<DevicePixels>,
304    ) -> Result<(Size<DevicePixels>, Vec<u8>)> {
305        if glyph_bounds.size.width.0 == 0 || glyph_bounds.size.height.0 == 0 {
306            Err(anyhow!("glyph bounds are empty"))
307        } else {
308            // todo(windows) handle subpixel variants
309            let bitmap_size = glyph_bounds.size;
310            let font = &self.fonts[params.font_id.0];
311            let font_system = &mut self.font_system;
312            let image = self
313                .swash_cache
314                .get_image(
315                    font_system,
316                    CacheKey::new(
317                        font.id(),
318                        params.glyph_id.0 as u16,
319                        (params.font_size * params.scale_factor).into(),
320                        (0.0, 0.0),
321                        cosmic_text::CacheKeyFlags::empty(),
322                    )
323                    .0,
324                )
325                .clone()
326                .unwrap();
327
328            Ok((bitmap_size, image.data))
329        }
330    }
331
332    // todo(windows) This is all a quick first pass, maybe we should be using cosmic_text::Buffer
333    #[profiling::function]
334    fn layout_line(&mut self, text: &str, font_size: Pixels, font_runs: &[FontRun]) -> LineLayout {
335        let mut attrs_list = AttrsList::new(Attrs::new());
336        let mut offs = 0;
337        for run in font_runs {
338            // todo(windows) We need to check we are doing utf properly
339            let font = &self.fonts[run.font_id.0];
340            let font = self.font_system.db().face(font.id()).unwrap();
341            attrs_list.add_span(
342                offs..offs + run.len,
343                Attrs::new()
344                    .family(Family::Name(&font.families.first().unwrap().0))
345                    .stretch(font.stretch)
346                    .style(font.style)
347                    .weight(font.weight),
348            );
349            offs += run.len;
350        }
351        let mut line = BufferLine::new(text, attrs_list, cosmic_text::Shaping::Advanced);
352        let layout = line.layout(
353            &mut self.font_system,
354            font_size.0,
355            f32::MAX, // todo(windows) we don't have a width cause this should technically not be wrapped I believe
356            cosmic_text::Wrap::None,
357            None,
358        );
359        let mut runs = Vec::new();
360        // todo(windows) 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
361        let layout = layout.first().unwrap();
362        for glyph in &layout.glyphs {
363            let font_id = glyph.font_id;
364            let font_id = FontId(
365                self.fonts
366                    .iter()
367                    .position(|font| font.id() == font_id)
368                    .unwrap(),
369            );
370            let mut glyphs = SmallVec::new();
371            // todo(windows) 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
372            glyphs.push(ShapedGlyph {
373                id: GlyphId(glyph.glyph_id as u32),
374                position: point((glyph.x).into(), glyph.y.into()),
375                index: glyph.start,
376                is_emoji: self.is_emoji(font_id),
377            });
378            runs.push(crate::ShapedRun { font_id, glyphs });
379        }
380        LineLayout {
381            font_size,
382            width: layout.w.into(),
383            ascent: layout.max_ascent.into(),
384            descent: layout.max_descent.into(),
385            runs,
386            len: text.len(),
387        }
388    }
389}
390
391impl From<RectF> for Bounds<f32> {
392    fn from(rect: RectF) -> Self {
393        Bounds {
394            origin: point(rect.origin_x(), rect.origin_y()),
395            size: size(rect.width(), rect.height()),
396        }
397    }
398}
399
400impl From<RectI> for Bounds<DevicePixels> {
401    fn from(rect: RectI) -> Self {
402        Bounds {
403            origin: point(DevicePixels(rect.origin_x()), DevicePixels(rect.origin_y())),
404            size: size(DevicePixels(rect.width()), DevicePixels(rect.height())),
405        }
406    }
407}
408
409impl From<Vector2I> for Size<DevicePixels> {
410    fn from(value: Vector2I) -> Self {
411        size(value.x().into(), value.y().into())
412    }
413}
414
415impl From<RectI> for Bounds<i32> {
416    fn from(rect: RectI) -> Self {
417        Bounds {
418            origin: point(rect.origin_x(), rect.origin_y()),
419            size: size(rect.width(), rect.height()),
420        }
421    }
422}
423
424impl From<Point<u32>> for Vector2I {
425    fn from(size: Point<u32>) -> Self {
426        Vector2I::new(size.x as i32, size.y as i32)
427    }
428}
429
430impl From<Vector2F> for Size<f32> {
431    fn from(vec: Vector2F) -> Self {
432        size(vec.x(), vec.y())
433    }
434}
435
436impl From<FontWeight> for cosmic_text::Weight {
437    fn from(value: FontWeight) -> Self {
438        cosmic_text::Weight(value.0 as u16)
439    }
440}
441
442impl From<FontStyle> for cosmic_text::Style {
443    fn from(style: FontStyle) -> Self {
444        match style {
445            FontStyle::Normal => cosmic_text::Style::Normal,
446            FontStyle::Italic => cosmic_text::Style::Italic,
447            FontStyle::Oblique => cosmic_text::Style::Oblique,
448        }
449    }
450}