use std::sync::Arc;
use harfrust::{
Buffer, Direction, Feature, FontFuncs, GlyphExtents, GlyphId, Language, Script, ShapeOptions, ShapePlan,
ShaperFont, Tag,
};
use mln_style::hash::HashMap;
use parking_lot::Mutex;
use unicode_properties::{GeneralCategory, UnicodeGeneralCategory};
use crate::text::face::{Face, SDF_FONT_SIZE};
use crate::text::glyph::{FontData, Glyph, GlyphID, GlyphIDType};
#[derive(Clone, Copy, PartialEq, Debug, Default, mln_wire::Wire)]
pub struct GlyphAdjust {
pub x_offset: f32,
pub y_offset: f32,
pub advance: f32,
}
impl GlyphAdjust {
#[must_use]
pub fn new(x_offset: f32, y_offset: f32, advance: f32) -> Self {
GlyphAdjust { x_offset, y_offset, advance }
}
}
#[derive(Clone, Debug, Default, PartialEq, mln_wire::Wire)]
pub struct ShapedText {
pub glyphs: Vec<GlyphID>,
pub adjusts: Vec<GlyphAdjust>,
}
fn get_default_language() -> Language {
Language::new("c").expect("non-empty")
}
#[must_use]
pub(crate) fn get_unicode_script(c: char) -> [u8; 4] {
if c.general_category() == GeneralCategory::NonspacingMark {
return Script::INHERITED.tag().to_be_bytes();
}
harfrust::unicode::script(u32::from(c)).tag().to_be_bytes()
}
type ShapePlans = HashMap<([u8; 4], bool), Arc<ShapePlan>>;
pub struct Shaper {
type_: GlyphIDType,
face: Face,
plans: Mutex<ShapePlans>,
}
fn hb_tiny_features() -> [Feature; 3] {
[
Feature::new(Tag::new(b"frac"), 0, ..),
Feature::new(Tag::new(b"numr"), 0, ..),
Feature::new(Tag::new(b"dnom"), 0, ..),
]
}
struct NoGlyphExtents;
impl FontFuncs for NoGlyphExtents {
fn glyph_extents(&self, _font: &ShaperFont, _glyph: GlyphId) -> Option<GlyphExtents> {
None
}
}
impl Shaper {
pub fn new(type_: GlyphIDType, data: impl Into<FontData>) -> Self {
Shaper::at_weight(type_, data, crate::text::weight::REGULAR_WEIGHT)
}
pub fn at_weight(type_: GlyphIDType, data: impl Into<FontData>, weight: f32) -> Self {
Shaper { type_, face: Face::new(data, weight), plans: Mutex::new(HashMap::default()) }
}
#[must_use]
pub fn valid(&self) -> bool {
self.face.is_valid()
}
#[must_use]
pub fn glyph_of(&self, c: char) -> Option<GlyphID> {
Some(GlyphID::with_type(self.face.glyph_of(c)?, self.type_))
}
#[must_use]
pub fn rasterize_glyph(&self, glyph: GlyphID) -> Glyph {
self.face.rasterize_glyph(glyph)
}
fn plan(
&self,
font: &harfrust::Font,
script: [u8; 4],
rtl: bool,
language: &Language,
features: &[Feature],
) -> Arc<ShapePlan> {
let mut plans = self.plans.lock();
Arc::clone(plans.entry((script, rtl)).or_insert_with(|| {
Arc::new(ShapePlan::new(font, direction(rtl), Some(to_script(script)), Some(language), features))
}))
}
pub fn shape(&self, text: &[char], rtl: bool, shaped: &mut ShapedText) {
struct TextPart {
text: Vec<char>,
script: [u8; 4],
}
const INVALID: [u8; 4] = [0; 4];
if text.is_empty() {
return;
}
let Some(font) = self.face.font() else {
return;
};
let is_neutral = |script: &[u8; 4]| matches!(script, b"Zyyy" | b"Zinh" | b"Zzzz");
let mut text_parts: Vec<TextPart> = Vec::new();
if rtl {
for &ch in text {
let script = get_unicode_script(ch);
let part_script = if is_neutral(&script) { INVALID } else { script };
match text_parts.last_mut() {
Some(last) if part_script == INVALID || last.script == script || last.script == INVALID => {
if last.script == INVALID {
last.script = part_script;
}
last.text.push(ch);
}
_ => text_parts.push(TextPart { text: vec![ch], script: part_script }),
}
}
for text_part in &mut text_parts {
if text_part.script == INVALID {
text_part.script = *b"Arab";
}
}
text_parts.reverse();
} else {
for &ch in text {
let script = get_unicode_script(ch);
match text_parts.last_mut() {
Some(last) if last.script == script || script == *b"Zinh" => last.text.push(ch),
_ => text_parts.push(TextPart { text: vec![ch], script }),
}
}
}
for text_part in &text_parts {
let Some(buffer) = self.shape_part(font, &text_part.text, text_part.script, rtl) else {
continue;
};
let glyph_info = buffer.glyph_infos();
let glyph_pos = buffer.glyph_positions();
shaped.glyphs.reserve(glyph_info.len());
shaped.adjusts.reserve(glyph_info.len());
for (info, pos) in glyph_info.iter().zip(glyph_pos) {
shaped.glyphs.push(GlyphID::with_type(info.glyph_id as u16, self.type_));
shaped.adjusts.push(GlyphAdjust {
x_offset: pos.x_offset as f32 / 64.0,
y_offset: pos.y_offset.wrapping_neg() as f32 / 64.0,
advance: pos.x_advance as f32 / 64.0,
});
}
}
}
fn shape_part(&self, font: &harfrust::Font, text: &[char], script: [u8; 4], rtl: bool) -> Option<Buffer> {
let shaper_font = ShaperFont::new(font).with_scale(SDF_FONT_SIZE * 64).with_font_funcs(Some(&NoGlyphExtents));
let language = get_default_language();
let features = hb_tiny_features();
let mut buffer = Buffer::new();
buffer.set_direction(direction(rtl));
buffer.set_script(Some(to_script(script)));
buffer.set_language(Some(language.clone()));
for (cluster, &c) in (0..).zip(text) {
buffer.push(u32::from(c), cluster);
}
let plan = self.plan(font, script, rtl, &language, &features);
let options = ShapeOptions::new().plan(Some(&plan)).features(&features);
harfrust::shape(&shaper_font, &mut buffer, options).ok()?;
Some(buffer)
}
}
fn direction(rtl: bool) -> Direction {
if rtl { Direction::RightToLeft } else { Direction::LeftToRight }
}
fn to_script(tag: [u8; 4]) -> Script {
Script::from_iso15924_tag(Tag::new(&tag)).unwrap_or(Script::UNKNOWN)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn script_segmentation_classifies_characters() {
assert_eq!(&get_unicode_script('a'), b"Latn");
assert_eq!(&get_unicode_script(' '), b"Zyyy");
assert_eq!(&get_unicode_script('\u{0301}'), b"Zinh");
assert_eq!(&get_unicode_script('\u{0941}'), b"Zinh"); assert_eq!(&get_unicode_script('\u{0627}'), b"Arab");
assert_eq!(&get_unicode_script('\u{4E2D}'), b"Hani");
assert_eq!(&get_unicode_script('\u{AC00}'), b"Hang");
assert_eq!(&get_unicode_script('\u{20000}'), b"Hani"); assert_eq!(&get_unicode_script('\u{1F600}'), b"Zyyy");
}
}