Skip to main content

wgame_typography/
lib.rs

1//! CPU font loading, shaping metrics, and cached glyph rasterization.
2//!
3//! [`Font`] owns validated font data, [`TextMetrics`] shapes text with swash, and
4//! [`FontAtlas`] caches glyph images. Rasterization supports monochrome outlines.
5//! Color emoji/bitmap-only fonts, font fallback, automatic line wrapping,
6//! bidirectional paragraph layout, and editable-text navigation are not implemented.
7
8#![forbid(unsafe_code)]
9
10mod atlas;
11mod metrics;
12
13pub use self::atlas::{FontAtlas, GlyphImageInfo, RasterSettings};
14pub use metrics::TextMetrics;
15pub use swash;
16
17use std::rc::Rc;
18
19use anyhow::{Result, anyhow};
20use swash::{CacheKey, FontRef};
21
22/// A font loaded from font data.
23#[derive(Clone)]
24pub struct Font {
25    contents: Rc<[u8]>,
26    offset: u32,
27    key: CacheKey,
28}
29
30impl Font {
31    /// Creates a new font from font data.
32    pub fn new(contents: impl Into<Vec<u8>>, index: usize) -> Result<Self> {
33        let contents = Rc::from(contents.into());
34        let font = FontRef::from_index(&contents, index)
35            .ok_or_else(|| anyhow!("Font data validation error"))?;
36        let (offset, key) = (font.offset, font.key);
37        Ok(Self {
38            contents,
39            offset,
40            key,
41        })
42    }
43
44    /// Measures the given text at the specified size.
45    pub fn metrics<T: Into<String>>(&self, size: f32, text: T) -> TextMetrics {
46        TextMetrics::new(self, size, text)
47    }
48
49    /// Returns a font reference.
50    pub fn as_ref(&'_ self) -> FontRef<'_> {
51        FontRef {
52            data: &self.contents,
53            offset: self.offset,
54            key: self.key,
55        }
56    }
57}