text_system.rs

  1mod font_features;
  2mod line_wrapper;
  3mod text_layout_cache;
  4
  5use anyhow::anyhow;
  6pub use font_features::*;
  7use line_wrapper::*;
  8pub use text_layout_cache::*;
  9
 10use crate::{
 11    px, Bounds, Hsla, Pixels, PlatformTextSystem, Point, Result, SharedString, Size, UnderlineStyle,
 12};
 13use collections::HashMap;
 14use core::fmt;
 15use parking_lot::{Mutex, RwLock};
 16use std::{
 17    fmt::{Debug, Display, Formatter},
 18    hash::{Hash, Hasher},
 19    ops::{Deref, DerefMut},
 20    sync::Arc,
 21};
 22
 23#[derive(Hash, PartialEq, Eq, Clone, Copy, Debug)]
 24pub struct FontId(pub usize);
 25
 26#[derive(Hash, PartialEq, Eq, Clone, Copy, Debug)]
 27pub struct FontFamilyId(pub usize);
 28
 29pub struct TextSystem {
 30    text_layout_cache: Arc<TextLayoutCache>,
 31    platform_text_system: Arc<dyn PlatformTextSystem>,
 32    font_ids_by_font: RwLock<HashMap<Font, FontId>>,
 33    fonts_by_font_id: RwLock<HashMap<FontId, Font>>,
 34    font_metrics: RwLock<HashMap<Font, FontMetrics>>,
 35    wrapper_pool: Mutex<HashMap<FontWithSize, Vec<LineWrapper>>>,
 36}
 37
 38impl TextSystem {
 39    pub fn new(platform_text_system: Arc<dyn PlatformTextSystem>) -> Self {
 40        TextSystem {
 41            text_layout_cache: Arc::new(TextLayoutCache::new(platform_text_system.clone())),
 42            platform_text_system,
 43            font_metrics: RwLock::new(HashMap::default()),
 44            font_ids_by_font: RwLock::new(HashMap::default()),
 45            fonts_by_font_id: RwLock::new(HashMap::default()),
 46            wrapper_pool: Mutex::new(HashMap::default()),
 47        }
 48    }
 49
 50    pub fn font_id(&self, font: &Font) -> Result<FontId> {
 51        if let Some(font_id) = self.font_ids_by_font.read().get(font) {
 52            Ok(*font_id)
 53        } else {
 54            let font_id = self.platform_text_system.font_id(font)?;
 55            self.font_ids_by_font.write().insert(font.clone(), font_id);
 56            self.fonts_by_font_id.write().insert(font_id, font.clone());
 57
 58            Ok(font_id)
 59        }
 60    }
 61
 62    pub fn with_font<T>(&self, font_id: FontId, f: impl FnOnce(&Self, &Font) -> T) -> Result<T> {
 63        self.fonts_by_font_id
 64            .read()
 65            .get(&font_id)
 66            .ok_or_else(|| anyhow!("font not found"))
 67            .map(|font| f(self, font))
 68    }
 69
 70    pub fn bounding_box(&self, font: &Font, font_size: Pixels) -> Result<Bounds<Pixels>> {
 71        self.read_metrics(&font, |metrics| metrics.bounding_box(font_size))
 72    }
 73
 74    pub fn typographic_bounds(
 75        &self,
 76        font: &Font,
 77        font_size: Pixels,
 78        character: char,
 79    ) -> Result<Bounds<Pixels>> {
 80        let font_id = self.font_id(font)?;
 81        let glyph_id = self
 82            .platform_text_system
 83            .glyph_for_char(font_id, character)
 84            .ok_or_else(|| anyhow!("glyph not found for character '{}'", character))?;
 85        let bounds = self
 86            .platform_text_system
 87            .typographic_bounds(font_id, glyph_id)?;
 88        self.read_metrics(font, |metrics| {
 89            (bounds / metrics.units_per_em as f32 * font_size.0).map(px)
 90        })
 91    }
 92
 93    pub fn advance(&self, font: &Font, font_size: Pixels, ch: char) -> Result<Size<Pixels>> {
 94        let font_id = self.font_id(font)?;
 95        let glyph_id = self
 96            .platform_text_system
 97            .glyph_for_char(font_id, ch)
 98            .ok_or_else(|| anyhow!("glyph not found for character '{}'", ch))?;
 99        let result =
100            self.platform_text_system.advance(font_id, glyph_id)? / self.units_per_em(font)? as f32;
101
102        let result = result * font_size;
103        Ok(todo!())
104    }
105
106    pub fn units_per_em(&self, font: &Font) -> Result<u32> {
107        self.read_metrics(font, |metrics| metrics.units_per_em as u32)
108    }
109
110    pub fn line_height(&self, font_size: Pixels) -> Pixels {
111        todo!()
112        // self.font_cache.line_height(font_size)
113    }
114
115    pub fn cap_height(&self, font: &Font, font_size: Pixels) -> Result<Pixels> {
116        self.read_metrics(font, |metrics| metrics.cap_height(font_size))
117    }
118
119    pub fn x_height(&self, font: &Font, font_size: Pixels) -> Result<Pixels> {
120        self.read_metrics(font, |metrics| metrics.x_height(font_size))
121    }
122
123    pub fn ascent(&self, font: &Font, font_size: Pixels) -> Result<Pixels> {
124        self.read_metrics(font, |metrics| metrics.ascent(font_size))
125    }
126
127    pub fn descent(&self, font: &Font, font_size: Pixels) -> Result<Pixels> {
128        self.read_metrics(font, |metrics| metrics.descent(font_size))
129    }
130
131    pub fn baseline_offset(&self, font: &Font, font_size: Pixels) -> Result<Pixels> {
132        let line_height = self.line_height(font_size);
133        let ascent = self.ascent(font, font_size)?;
134        let descent = self.descent(font, font_size)?;
135        let padding_top = (line_height - ascent - descent) / 2.;
136        Ok(padding_top + ascent)
137    }
138
139    fn read_metrics<T>(&self, font: &Font, read: impl FnOnce(&FontMetrics) -> T) -> Result<T> {
140        if let Some(metrics) = self.font_metrics.read().get(font) {
141            Ok(read(metrics))
142        } else {
143            let font_id = self.platform_text_system.font_id(&font)?;
144            let mut lock = self.font_metrics.write();
145            let metrics = lock
146                .entry(font.clone())
147                .or_insert_with(|| self.platform_text_system.font_metrics(font_id));
148            Ok(read(metrics))
149        }
150    }
151
152    pub fn layout_str<'a>(
153        &'a self,
154        text: &'a str,
155        font_size: Pixels,
156        runs: &'a [(usize, RunStyle)],
157    ) -> Line {
158        self.text_layout_cache.layout_str(text, font_size, runs)
159    }
160
161    pub fn finish_frame(&self) {
162        self.text_layout_cache.finish_frame()
163    }
164
165    pub fn line_wrapper(self: &Arc<Self>, font: Font, font_size: Pixels) -> LineWrapperHandle {
166        let lock = &mut self.wrapper_pool.lock();
167        let wrappers = lock
168            .entry(FontWithSize {
169                font: font.clone(),
170                font_size,
171            })
172            .or_default();
173        let wrapper = wrappers.pop().unwrap_or_else(|| {
174            LineWrapper::new(font, font_size, self.platform_text_system.clone())
175        });
176
177        LineWrapperHandle {
178            wrapper: Some(wrapper),
179            text_system: self.clone(),
180        }
181    }
182}
183
184#[derive(Hash, Eq, PartialEq)]
185struct FontWithSize {
186    font: Font,
187    font_size: Pixels,
188}
189
190pub struct LineWrapperHandle {
191    wrapper: Option<LineWrapper>,
192    text_system: Arc<TextSystem>,
193}
194
195impl Drop for LineWrapperHandle {
196    fn drop(&mut self) {
197        let mut state = self.text_system.wrapper_pool.lock();
198        let wrapper = self.wrapper.take().unwrap();
199        state
200            .get_mut(&FontWithSize {
201                font: wrapper.font.clone(),
202                font_size: wrapper.font_size,
203            })
204            .unwrap()
205            .push(wrapper);
206    }
207}
208
209impl Deref for LineWrapperHandle {
210    type Target = LineWrapper;
211
212    fn deref(&self) -> &Self::Target {
213        self.wrapper.as_ref().unwrap()
214    }
215}
216
217impl DerefMut for LineWrapperHandle {
218    fn deref_mut(&mut self) -> &mut Self::Target {
219        self.wrapper.as_mut().unwrap()
220    }
221}
222
223/// The degree of blackness or stroke thickness of a font. This value ranges from 100.0 to 900.0,
224/// with 400.0 as normal.
225#[derive(Clone, Copy, Debug, PartialEq, PartialOrd)]
226pub struct FontWeight(pub f32);
227
228impl Default for FontWeight {
229    #[inline]
230    fn default() -> FontWeight {
231        FontWeight::NORMAL
232    }
233}
234
235impl Hash for FontWeight {
236    fn hash<H: Hasher>(&self, state: &mut H) {
237        state.write_u32(u32::from_be_bytes(self.0.to_be_bytes()));
238    }
239}
240
241impl Eq for FontWeight {}
242
243impl FontWeight {
244    /// Thin weight (100), the thinnest value.
245    pub const THIN: FontWeight = FontWeight(100.0);
246    /// Extra light weight (200).
247    pub const EXTRA_LIGHT: FontWeight = FontWeight(200.0);
248    /// Light weight (300).
249    pub const LIGHT: FontWeight = FontWeight(300.0);
250    /// Normal (400).
251    pub const NORMAL: FontWeight = FontWeight(400.0);
252    /// Medium weight (500, higher than normal).
253    pub const MEDIUM: FontWeight = FontWeight(500.0);
254    /// Semibold weight (600).
255    pub const SEMIBOLD: FontWeight = FontWeight(600.0);
256    /// Bold weight (700).
257    pub const BOLD: FontWeight = FontWeight(700.0);
258    /// Extra-bold weight (800).
259    pub const EXTRA_BOLD: FontWeight = FontWeight(800.0);
260    /// Black weight (900), the thickest value.
261    pub const BLACK: FontWeight = FontWeight(900.0);
262}
263
264/// Allows italic or oblique faces to be selected.
265#[derive(Clone, Copy, Eq, PartialEq, Debug, Hash)]
266pub enum FontStyle {
267    /// A face that is neither italic not obliqued.
268    Normal,
269    /// A form that is generally cursive in nature.
270    Italic,
271    /// A typically-sloped version of the regular face.
272    Oblique,
273}
274
275impl Default for FontStyle {
276    fn default() -> FontStyle {
277        FontStyle::Normal
278    }
279}
280
281impl Display for FontStyle {
282    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
283        Debug::fmt(self, f)
284    }
285}
286
287#[derive(Clone, Debug, PartialEq, Eq)]
288pub struct RunStyle {
289    pub font: Font,
290    pub color: Hsla,
291    pub underline: Option<UnderlineStyle>,
292}
293
294#[derive(Copy, Clone, Debug, Eq, PartialEq, Hash)]
295pub struct GlyphId(u32);
296
297impl From<GlyphId> for u32 {
298    fn from(value: GlyphId) -> Self {
299        value.0
300    }
301}
302
303impl From<u16> for GlyphId {
304    fn from(num: u16) -> Self {
305        GlyphId(num as u32)
306    }
307}
308
309impl From<u32> for GlyphId {
310    fn from(num: u32) -> Self {
311        GlyphId(num)
312    }
313}
314
315#[derive(Clone, Debug)]
316pub struct Glyph {
317    pub id: GlyphId,
318    pub position: Point<Pixels>,
319    pub index: usize,
320    pub is_emoji: bool,
321}
322
323#[derive(Default, Debug)]
324pub struct LineLayout {
325    pub font_size: Pixels,
326    pub width: Pixels,
327    pub ascent: Pixels,
328    pub descent: Pixels,
329    pub runs: Vec<Run>,
330    pub len: usize,
331}
332
333#[derive(Debug)]
334pub struct Run {
335    pub font_id: FontId,
336    pub glyphs: Vec<Glyph>,
337}
338
339#[derive(Clone, Debug, Eq, PartialEq, Hash)]
340pub struct Font {
341    pub family: SharedString,
342    pub features: FontFeatures,
343    pub weight: FontWeight,
344    pub style: FontStyle,
345}
346
347pub fn font(family: impl Into<SharedString>) -> Font {
348    Font {
349        family: family.into(),
350        features: FontFeatures::default(),
351        weight: FontWeight::default(),
352        style: FontStyle::default(),
353    }
354}
355
356impl Font {
357    pub fn bold(mut self) -> Self {
358        self.weight = FontWeight::BOLD;
359        self
360    }
361}
362
363/// A struct for storing font metrics.
364/// It is used to define the measurements of a typeface.
365#[derive(Clone, Copy, Debug)]
366pub struct FontMetrics {
367    /// The number of font units that make up the "em square",
368    /// a scalable grid for determining the size of a typeface.
369    pub(crate) units_per_em: u32,
370
371    /// The vertical distance from the baseline of the font to the top of the glyph covers.
372    pub(crate) ascent: f32,
373
374    /// The vertical distance from the baseline of the font to the bottom of the glyph covers.
375    pub(crate) descent: f32,
376
377    /// The recommended additional space to add between lines of type.
378    pub(crate) line_gap: f32,
379
380    /// The suggested position of the underline.
381    pub(crate) underline_position: f32,
382
383    /// The suggested thickness of the underline.
384    pub(crate) underline_thickness: f32,
385
386    /// The height of a capital letter measured from the baseline of the font.
387    pub(crate) cap_height: f32,
388
389    /// The height of a lowercase x.
390    pub(crate) x_height: f32,
391
392    /// The outer limits of the area that the font covers.
393    pub(crate) bounding_box: Bounds<f32>,
394}
395
396impl FontMetrics {
397    /// Returns the vertical distance from the baseline of the font to the top of the glyph covers in pixels.
398    pub fn ascent(&self, font_size: Pixels) -> Pixels {
399        Pixels((self.ascent / self.units_per_em as f32) * font_size.0)
400    }
401
402    /// Returns the vertical distance from the baseline of the font to the bottom of the glyph covers in pixels.
403    pub fn descent(&self, font_size: Pixels) -> Pixels {
404        Pixels((self.descent / self.units_per_em as f32) * font_size.0)
405    }
406
407    /// Returns the recommended additional space to add between lines of type in pixels.
408    pub fn line_gap(&self, font_size: Pixels) -> Pixels {
409        Pixels((self.line_gap / self.units_per_em as f32) * font_size.0)
410    }
411
412    /// Returns the suggested position of the underline in pixels.
413    pub fn underline_position(&self, font_size: Pixels) -> Pixels {
414        Pixels((self.underline_position / self.units_per_em as f32) * font_size.0)
415    }
416
417    /// Returns the suggested thickness of the underline in pixels.
418    pub fn underline_thickness(&self, font_size: Pixels) -> Pixels {
419        Pixels((self.underline_thickness / self.units_per_em as f32) * font_size.0)
420    }
421
422    /// Returns the height of a capital letter measured from the baseline of the font in pixels.
423    pub fn cap_height(&self, font_size: Pixels) -> Pixels {
424        Pixels((self.cap_height / self.units_per_em as f32) * font_size.0)
425    }
426
427    /// Returns the height of a lowercase x in pixels.
428    pub fn x_height(&self, font_size: Pixels) -> Pixels {
429        Pixels((self.x_height / self.units_per_em as f32) * font_size.0)
430    }
431
432    /// Returns the outer limits of the area that the font covers in pixels.
433    pub fn bounding_box(&self, font_size: Pixels) -> Bounds<Pixels> {
434        (self.bounding_box / self.units_per_em as f32 * font_size.0).map(px)
435    }
436}