use std::borrow::Cow;
use std::sync::Arc;
use canvist_layout::FontSpec;
use parley::FontContext;
use parley::FontFamily;
use parley::FontStyle;
use parley::FontWeight;
use parley::LayoutContext;
use parley::PositionedLayoutItem;
use parley::StyleProperty;
use parley::fontique::Blob;
use parley::fontique::Collection;
use parley::fontique::CollectionOptions;
use parley::fontique::GenericFamily;
use parley::fontique::SourceCache;
use peniko::FontData;
use rustc_hash::FxHashMap;
pub const BUNDLED_FONT: &[u8] = include_bytes!("../fonts/AtkinsonHyperlegible-Regular.ttf");
const GENERICS: [GenericFamily; 7] = [
GenericFamily::SansSerif,
GenericFamily::Serif,
GenericFamily::Monospace,
GenericFamily::SystemUi,
GenericFamily::UiSansSerif,
GenericFamily::UiSerif,
GenericFamily::UiMonospace,
];
const CACHE_LIMIT: usize = 4_096;
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Glyph {
pub id: u32,
pub x: f32,
pub y: f32,
}
#[derive(Clone, Debug)]
pub struct ShapedRun {
pub font: FontData,
pub size: f32,
pub glyphs: Vec<Glyph>,
pub coords: Vec<i16>,
pub embolden: bool,
pub skew: Option<f32>,
}
impl ShapedRun {
#[must_use]
pub fn embolden_amount(&self) -> f64 {
if self.embolden {
f64::from(self.size) / 48.0
} else {
0.0
}
}
#[must_use]
pub fn shear(&self) -> Option<f64> {
self.skew
.map(|degrees| f64::from(degrees).to_radians().tan())
}
}
type ShapeKey = (String, u32, u16, bool, String);
pub struct Shaper {
fonts: FontContext,
layouts: LayoutContext<()>,
cache: FxHashMap<ShapeKey, Arc<[ShapedRun]>>,
}
impl std::fmt::Debug for Shaper {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Shaper")
.field("cached", &self.cache.len())
.finish_non_exhaustive()
}
}
impl Default for Shaper {
fn default() -> Self {
Self::new()
}
}
impl Shaper {
#[must_use]
pub fn new() -> Self {
let collection = Collection::new(CollectionOptions {
shared: false,
system_fonts: false,
});
let mut shaper = Self {
fonts: FontContext {
collection,
source_cache: SourceCache::default(),
},
layouts: LayoutContext::new(),
cache: FxHashMap::default(),
};
let families = shaper.register(BUNDLED_FONT.to_vec());
for generic in GENERICS {
shaper
.fonts
.collection
.set_generic_families(generic, families.iter().copied());
}
shaper
}
#[must_use]
pub fn with_system_fonts() -> Self {
let collection = Collection::new(CollectionOptions {
shared: false,
system_fonts: true,
});
let mut shaper = Self {
fonts: FontContext {
collection,
source_cache: SourceCache::default(),
},
layouts: LayoutContext::new(),
cache: FxHashMap::default(),
};
shaper.register(BUNDLED_FONT.to_vec());
shaper
}
pub fn register_font(&mut self, data: Vec<u8>) {
self.register(data);
self.cache.clear();
}
fn register(&mut self, data: Vec<u8>) -> Vec<parley::fontique::FamilyId> {
self.fonts
.collection
.register_fonts(Blob::from(data), None)
.into_iter()
.map(|(family, _)| family)
.collect()
}
pub fn shape(&mut self, font: &FontSpec, text: &str, letter_spacing: f32) -> Arc<[ShapedRun]> {
let key = (
font.family.to_string(),
font.size.to_bits() ^ letter_spacing.to_bits().rotate_left(16),
font.weight,
font.italic,
text.to_owned(),
);
if let Some(found) = self.cache.get(&key) {
return found.clone();
}
if self.cache.len() >= CACHE_LIMIT {
self.cache.clear();
}
let runs: Arc<[ShapedRun]> = self.shape_uncached(font, text, letter_spacing).into();
self.cache.insert(key, runs.clone());
runs
}
fn shape_uncached(
&mut self,
font: &FontSpec,
text: &str,
letter_spacing: f32,
) -> Vec<ShapedRun> {
let mut builder = self
.layouts
.ranged_builder(&mut self.fonts, text, 1.0, false);
builder.push_default(StyleProperty::FontFamily(FontFamily::Source(
Cow::Borrowed(&font.family),
)));
builder.push_default(StyleProperty::FontSize(font.size));
builder.push_default(StyleProperty::FontWeight(FontWeight::new(f32::from(
font.weight,
))));
builder.push_default(StyleProperty::LetterSpacing(letter_spacing));
builder.push_default(StyleProperty::FontStyle(if font.italic {
FontStyle::Italic
} else {
FontStyle::Normal
}));
let mut layout = builder.build(text);
layout.break_all_lines(None);
layout
.lines()
.flat_map(|line| line.items().filter_map(glyph_run).collect::<Vec<_>>())
.collect()
}
}
fn glyph_run(item: PositionedLayoutItem<'_, ()>) -> Option<ShapedRun> {
match item {
PositionedLayoutItem::GlyphRun(run) => Some(shaped(&run)),
PositionedLayoutItem::InlineBox(_) => None,
}
}
fn shaped(run: &parley::GlyphRun<'_, ()>) -> ShapedRun {
let baseline = run.baseline();
let glyphs = run
.positioned_glyphs()
.map(|glyph| {
Glyph {
id: glyph.id,
x: glyph.x,
y: glyph.y - baseline,
}
})
.collect();
let synthesis = run.run().synthesis();
ShapedRun {
font: run.run().font().clone(),
size: run.run().font_size(),
glyphs,
coords: run
.run()
.normalized_coords()
.iter()
.map(|coord| coord.to_bits())
.collect(),
embolden: synthesis.embolden(),
skew: synthesis.skew(),
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn shapes_with_the_bundled_font_and_caches() {
let mut shaper = Shaper::new();
let font = FontSpec {
family: "Atkinson Hyperlegible, sans-serif".into(),
size: 16.0,
weight: 400,
italic: false,
};
let runs = shaper.shape(&font, "Hello", 0.0);
let glyphs: usize = runs.iter().map(|run| run.glyphs.len()).sum();
assert_eq!(glyphs, 5);
assert!(runs[0].glyphs.windows(2).all(|pair| pair[0].x < pair[1].x));
assert!(Arc::ptr_eq(&runs, &shaper.shape(&font, "Hello", 0.0)));
}
}