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 family = self
217            .font_system
218            .get_font_matches(Attrs::new().family(cosmic_text::Family::Name(name)));
219        for font in family.as_ref() {
220            let font = self.font_system.get_font(*font).unwrap();
221            // TODO: figure out why this is causing fluent icons from loading
222            // if font.as_swash().charmap().map('m') == 0 {
223            //     self.font_system.db_mut().remove_face(font.id());
224            //     continue;
225            // };
226
227            let font_id = FontId(self.fonts.len());
228            font_ids.push(font_id);
229            self.fonts.push(font);
230        }
231        Ok(font_ids)
232    }
233
234    fn advance(&self, font_id: FontId, glyph_id: GlyphId) -> Result<Size<f32>> {
235        let width = self.fonts[font_id.0]
236            .as_swash()
237            .glyph_metrics(&[])
238            .advance_width(glyph_id.0 as u16);
239        let height = self.fonts[font_id.0]
240            .as_swash()
241            .glyph_metrics(&[])
242            .advance_height(glyph_id.0 as u16);
243        Ok(Size { width, height })
244    }
245
246    fn glyph_for_char(&self, font_id: FontId, ch: char) -> Option<GlyphId> {
247        let glyph_id = self.fonts[font_id.0].as_swash().charmap().map(ch);
248        if glyph_id == 0 {
249            None
250        } else {
251            Some(GlyphId(glyph_id.into()))
252        }
253    }
254
255    fn is_emoji(&self, font_id: FontId) -> bool {
256        // todo(windows): implement this correctly
257        self.postscript_names_by_font_id
258            .get(&font_id)
259            .map_or(false, |postscript_name| {
260                postscript_name == "AppleColorEmoji"
261            })
262    }
263
264    // todo(windows) both raster functions have problems because I am not sure this is the correct mapping from cosmic text to gpui system
265    fn raster_bounds(&mut self, params: &RenderGlyphParams) -> Result<Bounds<DevicePixels>> {
266        let font = &self.fonts[params.font_id.0];
267        let font_system = &mut self.font_system;
268        let image = self
269            .swash_cache
270            .get_image(
271                font_system,
272                CacheKey::new(
273                    font.id(),
274                    params.glyph_id.0 as u16,
275                    (params.font_size * params.scale_factor).into(),
276                    (0.0, 0.0),
277                )
278                .0,
279            )
280            .clone()
281            .unwrap();
282        Ok(Bounds {
283            origin: point(image.placement.left.into(), (-image.placement.top).into()),
284            size: size(image.placement.width.into(), image.placement.height.into()),
285        })
286    }
287
288    #[profiling::function]
289    fn rasterize_glyph(
290        &mut self,
291        params: &RenderGlyphParams,
292        glyph_bounds: Bounds<DevicePixels>,
293    ) -> Result<(Size<DevicePixels>, Vec<u8>)> {
294        if glyph_bounds.size.width.0 == 0 || glyph_bounds.size.height.0 == 0 {
295            Err(anyhow!("glyph bounds are empty"))
296        } else {
297            // todo(windows) handle subpixel variants
298            let bitmap_size = glyph_bounds.size;
299            let font = &self.fonts[params.font_id.0];
300            let font_system = &mut self.font_system;
301            let image = self
302                .swash_cache
303                .get_image(
304                    font_system,
305                    CacheKey::new(
306                        font.id(),
307                        params.glyph_id.0 as u16,
308                        (params.font_size * params.scale_factor).into(),
309                        (0.0, 0.0),
310                    )
311                    .0,
312                )
313                .clone()
314                .unwrap();
315
316            Ok((bitmap_size, image.data))
317        }
318    }
319
320    // todo(windows) This is all a quick first pass, maybe we should be using cosmic_text::Buffer
321    #[profiling::function]
322    fn layout_line(&mut self, text: &str, font_size: Pixels, font_runs: &[FontRun]) -> LineLayout {
323        let mut attrs_list = AttrsList::new(Attrs::new());
324        let mut offs = 0;
325        for run in font_runs {
326            // todo(windows) We need to check we are doing utf properly
327            let font = &self.fonts[run.font_id.0];
328            let font = self.font_system.db().face(font.id()).unwrap();
329            attrs_list.add_span(
330                offs..offs + run.len,
331                Attrs::new()
332                    .family(Family::Name(&font.families.first().unwrap().0))
333                    .stretch(font.stretch)
334                    .style(font.style)
335                    .weight(font.weight),
336            );
337            offs += run.len;
338        }
339        let mut line = BufferLine::new(text, attrs_list, cosmic_text::Shaping::Advanced);
340        let layout = line.layout(
341            &mut self.font_system,
342            font_size.0,
343            f32::MAX, // todo(windows) we don't have a width cause this should technically not be wrapped I believe
344            cosmic_text::Wrap::None,
345        );
346        let mut runs = Vec::new();
347        // 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
348        let layout = layout.first().unwrap();
349        for glyph in &layout.glyphs {
350            let font_id = glyph.font_id;
351            let font_id = FontId(
352                self.fonts
353                    .iter()
354                    .position(|font| font.id() == font_id)
355                    .unwrap(),
356            );
357            let mut glyphs = SmallVec::new();
358            // 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
359            glyphs.push(ShapedGlyph {
360                id: GlyphId(glyph.glyph_id as u32),
361                position: point((glyph.x).into(), glyph.y.into()),
362                index: glyph.start,
363                is_emoji: self.is_emoji(font_id),
364            });
365            runs.push(crate::ShapedRun { font_id, glyphs });
366        }
367        LineLayout {
368            font_size,
369            width: layout.w.into(),
370            ascent: layout.max_ascent.into(),
371            descent: layout.max_descent.into(),
372            runs,
373            len: text.len(),
374        }
375    }
376}
377
378impl From<RectF> for Bounds<f32> {
379    fn from(rect: RectF) -> Self {
380        Bounds {
381            origin: point(rect.origin_x(), rect.origin_y()),
382            size: size(rect.width(), rect.height()),
383        }
384    }
385}
386
387impl From<RectI> for Bounds<DevicePixels> {
388    fn from(rect: RectI) -> Self {
389        Bounds {
390            origin: point(DevicePixels(rect.origin_x()), DevicePixels(rect.origin_y())),
391            size: size(DevicePixels(rect.width()), DevicePixels(rect.height())),
392        }
393    }
394}
395
396impl From<Vector2I> for Size<DevicePixels> {
397    fn from(value: Vector2I) -> Self {
398        size(value.x().into(), value.y().into())
399    }
400}
401
402impl From<RectI> for Bounds<i32> {
403    fn from(rect: RectI) -> Self {
404        Bounds {
405            origin: point(rect.origin_x(), rect.origin_y()),
406            size: size(rect.width(), rect.height()),
407        }
408    }
409}
410
411impl From<Point<u32>> for Vector2I {
412    fn from(size: Point<u32>) -> Self {
413        Vector2I::new(size.x as i32, size.y as i32)
414    }
415}
416
417impl From<Vector2F> for Size<f32> {
418    fn from(vec: Vector2F) -> Self {
419        size(vec.x(), vec.y())
420    }
421}
422
423impl From<FontWeight> for cosmic_text::Weight {
424    fn from(value: FontWeight) -> Self {
425        cosmic_text::Weight(value.0 as u16)
426    }
427}
428
429impl From<FontStyle> for cosmic_text::Style {
430    fn from(style: FontStyle) -> Self {
431        match style {
432            FontStyle::Normal => cosmic_text::Style::Normal,
433            FontStyle::Italic => cosmic_text::Style::Italic,
434            FontStyle::Oblique => cosmic_text::Style::Oblique,
435        }
436    }
437}