use std::{
collections::BTreeMap,
hash::{Hash, Hasher},
sync::Arc,
};
use ahash::AHashMap;
use crate::{
mutex::Mutex,
text::{
font::{Font, FontImpl},
Galley,
},
Texture, TextureAtlas,
};
#[derive(Copy, Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
#[cfg_attr(feature = "persistence", derive(serde::Deserialize, serde::Serialize))]
#[cfg_attr(feature = "persistence", serde(rename_all = "snake_case"))]
pub enum TextStyle {
Small,
Body,
Button,
Heading,
Monospace,
}
impl TextStyle {
pub fn all() -> impl Iterator<Item = TextStyle> {
[
TextStyle::Small,
TextStyle::Body,
TextStyle::Button,
TextStyle::Heading,
TextStyle::Monospace,
]
.iter()
.copied()
}
}
#[derive(Copy, Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
#[cfg_attr(feature = "persistence", derive(serde::Deserialize, serde::Serialize))]
#[cfg_attr(feature = "persistence", serde(rename_all = "snake_case"))]
pub enum FontFamily {
Monospace,
Proportional,
}
pub type FontData = std::borrow::Cow<'static, [u8]>;
fn rusttype_font_from_font_data(name: &str, data: &FontData) -> rusttype::Font<'static> {
match data {
std::borrow::Cow::Borrowed(bytes) => rusttype::Font::try_from_bytes(bytes),
std::borrow::Cow::Owned(bytes) => rusttype::Font::try_from_vec(bytes.clone()),
}
.unwrap_or_else(|| panic!("Error parsing {:?} TTF/OTF font file", name))
}
#[derive(Clone, Debug, PartialEq)]
#[cfg_attr(feature = "persistence", derive(serde::Deserialize, serde::Serialize))]
#[cfg_attr(feature = "persistence", serde(default))]
pub struct FontDefinitions {
#[cfg_attr(feature = "persistence", serde(skip))]
pub font_data: BTreeMap<String, FontData>,
pub fonts_for_family: BTreeMap<FontFamily, Vec<String>>,
pub family_and_size: BTreeMap<TextStyle, (FontFamily, f32)>,
}
impl Default for FontDefinitions {
fn default() -> Self {
#[allow(unused)]
let mut font_data: BTreeMap<String, FontData> = BTreeMap::new();
let mut fonts_for_family = BTreeMap::new();
#[cfg(feature = "default_fonts")]
{
font_data.insert(
"ProggyClean".to_owned(),
std::borrow::Cow::Borrowed(include_bytes!("../../fonts/ProggyClean.ttf")),
);
font_data.insert(
"Ubuntu-Light".to_owned(),
std::borrow::Cow::Borrowed(include_bytes!("../../fonts/Ubuntu-Light.ttf")),
);
font_data.insert(
"NotoEmoji-Regular".to_owned(),
std::borrow::Cow::Borrowed(include_bytes!("../../fonts/NotoEmoji-Regular.ttf")),
);
font_data.insert(
"emoji-icon-font".to_owned(),
std::borrow::Cow::Borrowed(include_bytes!("../../fonts/emoji-icon-font.ttf")),
);
fonts_for_family.insert(
FontFamily::Monospace,
vec![
"ProggyClean".to_owned(),
"Ubuntu-Light".to_owned(),
"NotoEmoji-Regular".to_owned(),
"emoji-icon-font".to_owned(),
],
);
fonts_for_family.insert(
FontFamily::Proportional,
vec![
"Ubuntu-Light".to_owned(),
"NotoEmoji-Regular".to_owned(),
"emoji-icon-font".to_owned(),
],
);
}
#[cfg(not(feature = "default_fonts"))]
{
fonts_for_family.insert(FontFamily::Monospace, vec![]);
fonts_for_family.insert(FontFamily::Proportional, vec![]);
}
let mut family_and_size = BTreeMap::new();
family_and_size.insert(TextStyle::Small, (FontFamily::Proportional, 10.0));
family_and_size.insert(TextStyle::Body, (FontFamily::Proportional, 14.0));
family_and_size.insert(TextStyle::Button, (FontFamily::Proportional, 16.0));
family_and_size.insert(TextStyle::Heading, (FontFamily::Proportional, 20.0));
family_and_size.insert(TextStyle::Monospace, (FontFamily::Monospace, 13.0));
Self {
font_data,
fonts_for_family,
family_and_size,
}
}
}
pub struct Fonts {
pixels_per_point: f32,
definitions: FontDefinitions,
fonts: BTreeMap<TextStyle, Font>,
atlas: Arc<Mutex<TextureAtlas>>,
buffered_texture: Mutex<Arc<Texture>>,
galley_cache: Mutex<GalleyCache>,
}
impl Fonts {
pub fn from_definitions(pixels_per_point: f32, definitions: FontDefinitions) -> Self {
assert!(
0.0 < pixels_per_point && pixels_per_point < 100.0,
"pixels_per_point out of range: {}",
pixels_per_point
);
let mut atlas = TextureAtlas::new(2048, 64);
{
let pos = atlas.allocate((1, 1));
assert_eq!(pos, (0, 0));
atlas.texture_mut()[pos] = 255;
}
let atlas = Arc::new(Mutex::new(atlas));
let mut font_impl_cache = FontImplCache::new(atlas.clone(), pixels_per_point, &definitions);
let fonts = definitions
.family_and_size
.iter()
.map(|(&text_style, &(family, scale_in_points))| {
let fonts = &definitions.fonts_for_family.get(&family);
let fonts = fonts.unwrap_or_else(|| {
panic!("FontFamily::{:?} is not bound to any fonts", family)
});
let fonts: Vec<Arc<FontImpl>> = fonts
.iter()
.map(|font_name| font_impl_cache.font_impl(font_name, scale_in_points))
.collect();
(text_style, Font::new(text_style, fonts))
})
.collect();
{
let mut atlas = atlas.lock();
let texture = atlas.texture_mut();
use std::collections::hash_map::DefaultHasher;
let mut hasher = DefaultHasher::default();
texture.pixels.hash(&mut hasher);
texture.version = hasher.finish();
}
Self {
pixels_per_point,
definitions,
fonts,
atlas,
buffered_texture: Default::default(),
galley_cache: Default::default(),
}
}
#[inline(always)]
pub fn pixels_per_point(&self) -> f32 {
self.pixels_per_point
}
pub fn definitions(&self) -> &FontDefinitions {
&self.definitions
}
#[inline(always)]
pub fn round_to_pixel(&self, point: f32) -> f32 {
(point * self.pixels_per_point).round() / self.pixels_per_point
}
pub fn texture(&self) -> Arc<Texture> {
let atlas = self.atlas.lock();
let mut buffered_texture = self.buffered_texture.lock();
if buffered_texture.version != atlas.texture().version {
*buffered_texture = Arc::new(atlas.texture().clone());
}
buffered_texture.clone()
}
pub fn glyph_width(&self, text_style: TextStyle, c: char) -> f32 {
self.fonts[&text_style].glyph_width(c)
}
pub fn row_height(&self, text_style: TextStyle) -> f32 {
self.fonts[&text_style].row_height()
}
pub fn layout_no_wrap(&self, text_style: TextStyle, text: String) -> Arc<Galley> {
self.layout_multiline(text_style, text, f32::INFINITY)
}
pub fn layout_single_line(&self, text_style: TextStyle, text: String) -> Arc<Galley> {
self.galley_cache.lock().layout(
&self.fonts,
LayoutJob {
text_style,
text,
layout_params: LayoutParams::SingleLine,
},
)
}
pub fn layout_multiline(
&self,
text_style: TextStyle,
text: String,
max_width_in_points: f32,
) -> Arc<Galley> {
self.layout_multiline_with_indentation_and_max_width(
text_style,
text,
0.0,
max_width_in_points,
)
}
pub fn layout_multiline_with_indentation_and_max_width(
&self,
text_style: TextStyle,
text: String,
first_row_indentation: f32,
max_width_in_points: f32,
) -> Arc<Galley> {
self.galley_cache.lock().layout(
&self.fonts,
LayoutJob {
text_style,
text,
layout_params: LayoutParams::Multiline {
first_row_indentation: first_row_indentation.into(),
max_width_in_points: max_width_in_points.into(),
},
},
)
}
pub fn num_galleys_in_cache(&self) -> usize {
self.galley_cache.lock().num_galleys_in_cache()
}
pub fn end_frame(&self) {
self.galley_cache.lock().end_frame()
}
}
impl std::ops::Index<TextStyle> for Fonts {
type Output = Font;
#[inline(always)]
fn index(&self, text_style: TextStyle) -> &Font {
&self.fonts[&text_style]
}
}
#[derive(Clone, Copy, Eq, PartialEq, Hash)]
enum LayoutParams {
SingleLine,
Multiline {
first_row_indentation: ordered_float::OrderedFloat<f32>,
max_width_in_points: ordered_float::OrderedFloat<f32>,
},
}
#[derive(Clone, Eq, PartialEq, Hash)]
struct LayoutJob {
text_style: TextStyle,
layout_params: LayoutParams,
text: String,
}
struct CachedGalley {
last_used: u32,
galley: Arc<Galley>,
}
#[derive(Default)]
struct GalleyCache {
generation: u32,
cache: AHashMap<LayoutJob, CachedGalley>,
}
impl GalleyCache {
fn layout(&mut self, fonts: &BTreeMap<TextStyle, Font>, job: LayoutJob) -> Arc<Galley> {
if let Some(cached) = self.cache.get_mut(&job) {
cached.last_used = self.generation;
cached.galley.clone()
} else {
let LayoutJob {
text_style,
layout_params,
text,
} = job.clone();
let font = &fonts[&text_style];
let galley = match layout_params {
LayoutParams::SingleLine => font.layout_single_line(text),
LayoutParams::Multiline {
first_row_indentation,
max_width_in_points,
} => font.layout_multiline_with_indentation_and_max_width(
text,
first_row_indentation.into_inner(),
max_width_in_points.into_inner(),
),
};
let galley = Arc::new(galley);
self.cache.insert(
job,
CachedGalley {
last_used: self.generation,
galley: galley.clone(),
},
);
galley
}
}
pub fn num_galleys_in_cache(&self) -> usize {
self.cache.len()
}
pub fn end_frame(&mut self) {
let current_generation = self.generation;
self.cache.retain(|_key, cached| {
cached.last_used == current_generation
});
self.generation = self.generation.wrapping_add(1);
}
}
struct FontImplCache {
atlas: Arc<Mutex<TextureAtlas>>,
pixels_per_point: f32,
rusttype_fonts: BTreeMap<String, Arc<rusttype::Font<'static>>>,
cache: Vec<(String, f32, Arc<FontImpl>)>,
}
impl FontImplCache {
pub fn new(
atlas: Arc<Mutex<TextureAtlas>>,
pixels_per_point: f32,
definitions: &super::FontDefinitions,
) -> Self {
let rusttype_fonts = definitions
.font_data
.iter()
.map(|(name, font_data)| {
(
name.clone(),
Arc::new(rusttype_font_from_font_data(name, font_data)),
)
})
.collect();
Self {
atlas,
pixels_per_point,
rusttype_fonts,
cache: Default::default(),
}
}
pub fn rusttype_font(&self, font_name: &str) -> Arc<rusttype::Font<'static>> {
self.rusttype_fonts
.get(font_name)
.unwrap_or_else(|| panic!("No font data found for {:?}", font_name))
.clone()
}
pub fn font_impl(&mut self, font_name: &str, scale_in_points: f32) -> Arc<FontImpl> {
for entry in &self.cache {
if (entry.0.as_str(), entry.1) == (font_name, scale_in_points) {
return entry.2.clone();
}
}
let y_offset = if font_name == "emoji-icon-font" {
scale_in_points * 0.235
} else {
0.0
};
let y_offset = y_offset - 3.0;
let scale_in_points = if font_name == "emoji-icon-font" {
scale_in_points * 0.8
} else {
scale_in_points
};
let font_impl = Arc::new(FontImpl::new(
self.atlas.clone(),
self.pixels_per_point,
self.rusttype_font(font_name),
scale_in_points,
y_offset,
));
self.cache
.push((font_name.to_owned(), scale_in_points, font_impl.clone()));
font_impl
}
}