use super::fonts::{FaceId, FontBook};
use rustybuzz::{Direction, Feature, Script, ShapePlan, UnicodeBuffer, script, ttf_parser::Tag};
use std::collections::HashMap;
use std::rc::Rc;
use std::sync::Arc;
type MaybeFace<'a> = Option<rustybuzz::Face<'a>>;
self_cell::self_cell!(
struct ParsedFace {
owner: Arc<Vec<u8>>,
#[covariant]
dependent: MaybeFace,
}
);
#[derive(Debug, Clone, Copy)]
pub struct ShapedGlyph {
pub id: u16,
pub advance: f32,
pub dx: f32,
pub dy: f32,
pub cluster: usize,
}
#[derive(Debug, Clone)]
pub struct Shaped {
pub glyphs: Vec<ShapedGlyph>,
pub width: f32,
}
type PlanKey = (FaceId, Direction, Option<Script>, bool);
#[derive(Default)]
pub struct Shaper {
cache: HashMap<(FaceId, String, bool, bool), Rc<Shaped>>,
faces: HashMap<FaceId, ParsedFace>,
plans: HashMap<PlanKey, ShapePlan>,
}
impl Shaper {
pub fn shape(&mut self, book: &FontBook, face: FaceId, text: &str, kern: bool, rtl: bool) -> Rc<Shaped> {
let key = (face, text.to_string(), kern, rtl);
if let Some(shaped) = self.cache.get(&key) {
return shaped.clone();
}
let font = book.get(face);
let parsed = self.faces.entry(face).or_insert_with(|| {
ParsedFace::new(font.data.clone(), |data| rustybuzz::Face::from_slice(data, font.index))
});
let shaped = Rc::new(match parsed.borrow_dependent() {
Some(hb) => {
let buffer = buffer(text, rtl);
let script = Some(buffer.script()).filter(|found| *found != script::UNKNOWN);
let plan = self
.plans
.entry((face, buffer.direction(), script, kern))
.or_insert_with(|| ShapePlan::new(hb, buffer.direction(), script, None, &features(kern)));
glyphs(rustybuzz::shape_with_plan(hb, plan, buffer), font.metrics.upem)
}
None => Shaped {
glyphs: Vec::new(),
width: 0.0,
},
});
self.cache.insert(key, shaped.clone());
shaped
}
}
fn buffer(text: &str, rtl: bool) -> UnicodeBuffer {
let mut buffer = UnicodeBuffer::new();
buffer.push_str(text);
buffer.guess_segment_properties();
if rtl {
buffer.set_direction(Direction::RightToLeft);
}
buffer
}
fn features(kern: bool) -> Vec<Feature> {
let off = |tag: &[u8; 4]| Feature::new(Tag::from_bytes(tag), 0, ..);
let mut features = vec![off(b"liga"), off(b"clig")];
if !kern {
features.push(off(b"kern"));
}
features
}
fn glyphs(output: rustybuzz::GlyphBuffer, upem: f32) -> Shaped {
let mut glyphs = Vec::with_capacity(output.len());
let mut width = 0.0;
for (info, pos) in output.glyph_infos().iter().zip(output.glyph_positions()) {
let advance = pos.x_advance as f32 / upem;
width += advance;
glyphs.push(ShapedGlyph {
id: info.glyph_id as u16,
advance,
dx: pos.x_offset as f32 / upem,
dy: pos.y_offset as f32 / upem,
cluster: info.cluster as usize,
});
}
Shaped { glyphs, width }
}