hboard/src/text.rs

189 lines
5.7 KiB
Rust

use std::{
collections::HashMap,
fmt::Debug,
hash::Hash,
io,
path::Path,
time::{Duration, Instant},
};
use serde::{Deserialize, Serialize};
use swash::{
scale::{image::Image, Render, ScaleContext, Scaler, Source, StrikeWith},
FontRef,
};
#[derive(Copy, Clone, PartialOrd, Ord, PartialEq, Eq, Hash, Debug, Deserialize, Serialize)]
pub struct CacheKey(pub(crate) u64);
impl CacheKey {
/// Generates a new cache key.
pub fn new() -> Self {
use core::sync::atomic::{AtomicU64, Ordering};
static KEY: AtomicU64 = AtomicU64::new(1);
Self(KEY.fetch_add(1, Ordering::Relaxed))
}
}
impl Default for CacheKey {
fn default() -> Self {
Self::new()
}
}
#[derive(PartialEq)]
struct GlyphCacheKey {
font_key: CacheKey,
font_size: f32,
glyph_id: u16,
offset_x: f32,
offset_y: f32,
}
impl Eq for GlyphCacheKey {}
impl Hash for GlyphCacheKey {
fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
self.font_key.hash(state);
self.font_size.to_bits().hash(state);
self.glyph_id.hash(state);
self.offset_x.to_bits().hash(state);
self.offset_y.to_bits().hash(state);
}
}
#[derive(Copy, Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
pub struct FontHandle {
id: usize,
offset: u32,
key: CacheKey,
}
#[derive(Default)]
pub struct FontDb {
font_files: Vec<&'static [u8]>,
fonts: HashMap<String, FontHandle>,
glyph_cache: HashMap<GlyphCacheKey, (Instant, Option<Image>)>,
}
impl Debug for FontDb {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("FontDb")
.field("fonts", &self.fonts)
.finish_non_exhaustive()
}
}
impl FontDb {
pub fn load_font(&mut self, file: impl AsRef<Path>) -> io::Result<()> {
let mut any_added = false;
let data = std::fs::read(file)?;
let id = self.font_files.len();
for font in std::iter::successors(Some(0usize), |i| Some(i + 1))
.map_while(|i| FontRef::from_index(&data, i))
{
let mut full = None;
for str in font.localized_strings() {
match str.id() {
swash::StringId::Full => {
if !str.is_decodable() {
continue;
}
let x: String = str.chars().collect();
if !x.is_empty() {
full = Some(x);
break;
}
}
swash::StringId::Family => {
if !str.is_decodable() {
continue;
}
let x: String = str.chars().collect();
if !x.is_empty() {
full = Some(x);
}
}
_ => {}
}
}
let Some(name) = full else {
continue;
};
self.fonts.entry(name).or_insert_with(|| {
any_added = true;
FontHandle {
id,
offset: font.offset,
key: CacheKey::new(),
}
});
}
if any_added {
self.font_files.push(Box::leak(data.into_boxed_slice()));
}
Ok(())
}
pub fn get_font(&self, font_handle: FontHandle) -> Option<FontRef<'static>> {
FontRef::from_offset(self.font_files[font_handle.id], font_handle.offset)
}
pub fn font_handle(&self, font_name: &str) -> Option<FontHandle> {
self.fonts
.get(font_name)
.or_else(|| self.fonts.get(&(font_name.to_owned() + " Regular")))
.copied()
}
pub fn _gc(&mut self) {
const GC_CUTOFF: Duration = Duration::from_secs(600);
let cutoff = Instant::now() - GC_CUTOFF;
self.glyph_cache.retain(|_k, v| v.0 >= cutoff);
}
pub fn render_glyph(
&mut self,
font_handle: FontHandle,
font_size: f32,
glyph: u16,
offset: (f32, f32),
scaler: Option<&mut Scaler>,
) -> Option<&Image> {
let FontHandle {
id,
offset: font_offset,
key,
} = font_handle;
let ret = self
.glyph_cache
.entry(GlyphCacheKey {
font_key: key,
font_size,
glyph_id: glyph,
offset_x: offset.0,
offset_y: offset.1,
})
.or_insert_with(|| {
let font_file = &self.font_files[id];
let font = FontRef::from_offset(font_file, font_offset).unwrap();
let mut render = Render::new(&[
Source::ColorOutline(0),
Source::ColorBitmap(StrikeWith::BestFit),
Source::Bitmap(StrikeWith::BestFit),
Source::Outline,
]);
let mut img = Image::new();
render.offset((offset.0 % 1.0, -(offset.0 % 1.0)).into());
(
Instant::now(),
if let Some(scaler) = scaler {
render.render_into(scaler, glyph, &mut img)
} else {
let mut context = ScaleContext::new();
let mut scaler = context.builder(font).size(font_size).hint(true).build();
render.render_into(&mut scaler, glyph, &mut img)
}
.then_some(img),
)
});
ret.0 = Instant::now();
ret.1.as_ref()
}
}