Upload spectral-font/src/font.rs
Browse files- spectral-font/src/font.rs +65 -0
spectral-font/src/font.rs
ADDED
|
@@ -0,0 +1,65 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
use std::sync::Arc;
|
| 2 |
+
|
| 3 |
+
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
|
| 4 |
+
pub enum FontStyle {
|
| 5 |
+
Regular = 0,
|
| 6 |
+
Bold = 1,
|
| 7 |
+
Italic = 2,
|
| 8 |
+
BoldItalic = 3,
|
| 9 |
+
}
|
| 10 |
+
|
| 11 |
+
impl Default for FontStyle {
|
| 12 |
+
fn default() -> Self { FontStyle::Regular }
|
| 13 |
+
}
|
| 14 |
+
|
| 15 |
+
pub struct Font {
|
| 16 |
+
pub id: u32,
|
| 17 |
+
pub data: Arc<Vec<u8>>,
|
| 18 |
+
pub index: u32,
|
| 19 |
+
pub style: FontStyle,
|
| 20 |
+
pub family_name: String,
|
| 21 |
+
pub rasterizer: fontdue::Font,
|
| 22 |
+
}
|
| 23 |
+
|
| 24 |
+
impl Font {
|
| 25 |
+
pub fn from_bytes(id: u32, data: Arc<Vec<u8>>, index: u32, style: FontStyle) -> Option<Self> {
|
| 26 |
+
let settings = fontdue::FontSettings {
|
| 27 |
+
collection_index: index,
|
| 28 |
+
scale: 40.0,
|
| 29 |
+
load_substitutions: true,
|
| 30 |
+
};
|
| 31 |
+
let rasterizer = fontdue::Font::from_bytes(&**data, settings).ok()?;
|
| 32 |
+
let family_name = format!("Font-{}", id);
|
| 33 |
+
Some(Self { id, data, index, style, family_name, rasterizer })
|
| 34 |
+
}
|
| 35 |
+
|
| 36 |
+
pub fn rasterize_glyph(&self, glyph_id: u16, px: f32) -> (fontdue::Metrics, Vec<u8>) {
|
| 37 |
+
self.rasterizer.rasterize_indexed(glyph_id, px)
|
| 38 |
+
}
|
| 39 |
+
|
| 40 |
+
pub fn lookup_glyph(&self, ch: char) -> u16 {
|
| 41 |
+
self.rasterizer.lookup_glyph_index(ch)
|
| 42 |
+
}
|
| 43 |
+
}
|
| 44 |
+
|
| 45 |
+
pub struct FontFamily {
|
| 46 |
+
pub name: String,
|
| 47 |
+
pub fonts: [Option<Font>; 4],
|
| 48 |
+
}
|
| 49 |
+
|
| 50 |
+
impl FontFamily {
|
| 51 |
+
pub fn new(name: &str) -> Self {
|
| 52 |
+
Self { name: name.to_string(), fonts: [None, None, None, None] }
|
| 53 |
+
}
|
| 54 |
+
|
| 55 |
+
pub fn add_font(&mut self, font: Font) {
|
| 56 |
+
self.fonts[font.style as usize] = Some(font);
|
| 57 |
+
}
|
| 58 |
+
|
| 59 |
+
pub fn get_font(&self, style: FontStyle) -> Option<&Font> {
|
| 60 |
+
self.fonts[style as usize].as_ref()
|
| 61 |
+
.or_else(|| self.fonts[FontStyle::Bold as usize].as_ref())
|
| 62 |
+
.or_else(|| self.fonts[FontStyle::Italic as usize].as_ref())
|
| 63 |
+
.or_else(|| self.fonts[FontStyle::Regular as usize].as_ref())
|
| 64 |
+
}
|
| 65 |
+
}
|