Skip to main content

kova_native_text/
system.rs

1//! Font database, fallback and glyph rasterization.
2
3use cosmic_text::{FontSystem, SwashCache, SwashContent};
4
5/// Identifies a rasterized glyph: font, glyph id, pixel size, subpixel offset
6/// and weight. Used as the glyph atlas key.
7#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
8pub struct GlyphKey(pub(crate) cosmic_text::CacheKey);
9
10/// A rasterized glyph bitmap.
11#[derive(Clone, Debug)]
12pub struct RasterizedGlyph {
13    /// Offset of the bitmap's left edge from the glyph origin (device px).
14    pub left: i32,
15    /// Offset of the bitmap's top edge above the baseline (device px).
16    pub top: i32,
17    pub width: u32,
18    pub height: u32,
19    /// `true`: premultiplied RGBA (emoji). `false`: 8-bit coverage mask.
20    pub is_color: bool,
21    pub data: Vec<u8>,
22}
23
24/// Owns fonts and performs shaping-related lookups and rasterization.
25///
26/// One `TextSystem` is shared by all windows of an application.
27pub struct TextSystem {
28    pub(crate) fonts: FontSystem,
29    swash: SwashCache,
30    ui_family: String,
31    mono_family: String,
32}
33
34impl Default for TextSystem {
35    fn default() -> Self {
36        Self::new()
37    }
38}
39
40impl TextSystem {
41    /// Loads system fonts and picks the platform UI font as default family.
42    pub fn new() -> Self {
43        let mut fonts = FontSystem::new();
44        let candidates: &[&str] = if cfg!(target_os = "windows") {
45            &["Segoe UI Variable Text", "Segoe UI", "Arial"]
46        } else if cfg!(target_os = "macos") {
47            &[
48                "SF Pro Text",
49                ".AppleSystemUIFont",
50                "Helvetica Neue",
51                "Helvetica",
52            ]
53        } else {
54            &[
55                "Inter",
56                "Cantarell",
57                "Ubuntu",
58                "Noto Sans",
59                "DejaVu Sans",
60                "Liberation Sans",
61            ]
62        };
63        let ui_family = candidates
64            .iter()
65            .find(|name| Self::db_has_family(&fonts, name))
66            .map(|s| s.to_string())
67            .unwrap_or_else(|| "sans-serif".to_string());
68        // Variable "Segoe UI Variable" works, but its static sibling has better
69        // weight coverage across Windows versions.
70        let ui_family =
71            if ui_family == "Segoe UI Variable Text" && Self::db_has_family(&fonts, "Segoe UI") {
72                "Segoe UI".to_string()
73            } else {
74                ui_family
75            };
76        if ui_family != "sans-serif" {
77            fonts.db_mut().set_sans_serif_family(ui_family.clone());
78        }
79        let mono_candidates: &[&str] = if cfg!(target_os = "windows") {
80            &["Cascadia Mono", "Consolas", "Courier New"]
81        } else if cfg!(target_os = "macos") {
82            &["SF Mono", "Menlo", "Monaco", "Courier"]
83        } else {
84            &[
85                "JetBrains Mono",
86                "DejaVu Sans Mono",
87                "Ubuntu Mono",
88                "Noto Sans Mono",
89                "Liberation Mono",
90            ]
91        };
92        let mono_family = mono_candidates
93            .iter()
94            .find(|name| Self::db_has_family(&fonts, name))
95            .map(|s| s.to_string())
96            .unwrap_or_else(|| ui_family.clone());
97        fonts.db_mut().set_monospace_family(mono_family.clone());
98        log::debug!(
99            "kova-native-text: {} font faces, UI family '{ui_family}'",
100            fonts.db().len()
101        );
102        TextSystem {
103            fonts,
104            swash: SwashCache::new(),
105            ui_family,
106            mono_family,
107        }
108    }
109
110    fn db_has_family(fonts: &FontSystem, name: &str) -> bool {
111        fonts.db().faces().any(|f| {
112            f.families
113                .iter()
114                .any(|(family, _)| family.eq_ignore_ascii_case(name))
115        })
116    }
117
118    /// The family used when a style does not specify one.
119    pub fn ui_family(&self) -> &str {
120        &self.ui_family
121    }
122
123    /// The platform monospace family, used for the generic
124    /// [`MONOSPACE`](crate::MONOSPACE) family name.
125    pub fn mono_family(&self) -> &str {
126        &self.mono_family
127    }
128
129    /// Resolves generic family names (`"monospace"`) to installed families.
130    pub fn resolve_family<'a>(&'a self, family: Option<&'a str>) -> &'a str {
131        match family {
132            None => &self.ui_family,
133            Some(f) if f.eq_ignore_ascii_case(crate::MONOSPACE) => &self.mono_family,
134            Some(f) => f,
135        }
136    }
137
138    /// Overrides the default UI family.
139    pub fn set_ui_family(&mut self, family: impl Into<String>) {
140        self.ui_family = family.into();
141        self.fonts
142            .db_mut()
143            .set_sans_serif_family(self.ui_family.clone());
144    }
145
146    pub fn has_family(&self, name: &str) -> bool {
147        Self::db_has_family(&self.fonts, name)
148    }
149
150    /// Registers a font from memory (TTF/OTF/TTC).
151    pub fn load_font(&mut self, data: Vec<u8>) {
152        self.fonts.db_mut().load_font_data(data);
153    }
154
155    pub fn face_count(&self) -> usize {
156        self.fonts.db().len()
157    }
158
159    /// Rasterizes a glyph. Returns `None` for empty glyphs (e.g. spaces).
160    pub fn rasterize(&mut self, key: GlyphKey) -> Option<RasterizedGlyph> {
161        let image = self.swash.get_image_uncached(&mut self.fonts, key.0)?;
162        if image.placement.width == 0 || image.placement.height == 0 {
163            return None;
164        }
165        let (is_color, data) = match image.content {
166            SwashContent::Mask => (false, image.data),
167            SwashContent::SubpixelMask => {
168                // Collapse RGB coverage to grayscale coverage.
169                let data = image
170                    .data
171                    .as_chunks::<4>()
172                    .0
173                    .iter()
174                    .map(|px| ((px[0] as u16 + px[1] as u16 + px[2] as u16) / 3) as u8)
175                    .collect();
176                (false, data)
177            }
178            SwashContent::Color => {
179                let mut data = image.data;
180                for px in data.as_chunks_mut::<4>().0 {
181                    let a = px[3] as u16;
182                    px[0] = ((px[0] as u16 * a + 127) / 255) as u8;
183                    px[1] = ((px[1] as u16 * a + 127) / 255) as u8;
184                    px[2] = ((px[2] as u16 * a + 127) / 255) as u8;
185                }
186                (true, data)
187            }
188        };
189        Some(RasterizedGlyph {
190            left: image.placement.left,
191            top: image.placement.top,
192            width: image.placement.width,
193            height: image.placement.height,
194            is_color,
195            data,
196        })
197    }
198}