1use std::sync::Arc;
20
21use harfrust::{
22 Buffer, Direction, Feature, FontFuncs, GlyphExtents, GlyphId, Language, Script, ShapeOptions, ShapePlan,
23 ShaperFont, Tag,
24};
25use mln_style::hash::HashMap;
26use parking_lot::Mutex;
27use unicode_properties::{GeneralCategory, UnicodeGeneralCategory};
28
29use crate::text::face::{Face, SDF_FONT_SIZE};
30use crate::text::glyph::{FontData, Glyph, GlyphID, GlyphIDType};
31
32#[derive(Clone, Copy, PartialEq, Debug, Default, mln_wire::Wire)]
35pub struct GlyphAdjust {
36 pub x_offset: f32,
37 pub y_offset: f32,
38 pub advance: f32,
39}
40
41impl GlyphAdjust {
42 #[must_use]
43 pub fn new(x_offset: f32, y_offset: f32, advance: f32) -> Self {
44 GlyphAdjust { x_offset, y_offset, advance }
45 }
46}
47
48#[derive(Clone, Debug, Default, PartialEq, mln_wire::Wire)]
50pub struct ShapedText {
51 pub glyphs: Vec<GlyphID>,
52 pub adjusts: Vec<GlyphAdjust>,
53}
54
55fn get_default_language() -> Language {
57 Language::new("c").expect("non-empty")
58}
59
60#[must_use]
64pub(crate) fn get_unicode_script(c: char) -> [u8; 4] {
65 if c.general_category() == GeneralCategory::NonspacingMark {
66 return Script::INHERITED.tag().to_be_bytes();
67 }
68 harfrust::unicode::script(u32::from(c)).tag().to_be_bytes()
69}
70
71type ShapePlans = HashMap<([u8; 4], bool), Arc<ShapePlan>>;
73
74pub struct Shaper {
76 type_: GlyphIDType,
77 face: Face,
78 plans: Mutex<ShapePlans>,
81}
82
83fn hb_tiny_features() -> [Feature; 3] {
85 [
86 Feature::new(Tag::new(b"frac"), 0, ..),
87 Feature::new(Tag::new(b"numr"), 0, ..),
88 Feature::new(Tag::new(b"dnom"), 0, ..),
89 ]
90}
91
92struct NoGlyphExtents;
94
95impl FontFuncs for NoGlyphExtents {
96 fn glyph_extents(&self, _font: &ShaperFont, _glyph: GlyphId) -> Option<GlyphExtents> {
97 None
98 }
99}
100
101impl Shaper {
102 pub fn new(type_: GlyphIDType, data: impl Into<FontData>) -> Self {
105 Shaper::at_weight(type_, data, crate::text::weight::REGULAR_WEIGHT)
106 }
107
108 pub fn at_weight(type_: GlyphIDType, data: impl Into<FontData>, weight: f32) -> Self {
111 Shaper { type_, face: Face::new(data, weight), plans: Mutex::new(HashMap::default()) }
112 }
113
114 #[must_use]
116 pub fn valid(&self) -> bool {
117 self.face.is_valid()
118 }
119
120 #[must_use]
124 pub fn glyph_of(&self, c: char) -> Option<GlyphID> {
125 Some(GlyphID::with_type(self.face.glyph_of(c)?, self.type_))
126 }
127
128 #[must_use]
130 pub fn rasterize_glyph(&self, glyph: GlyphID) -> Glyph {
131 self.face.rasterize_glyph(glyph)
132 }
133
134 fn plan(
135 &self,
136 font: &harfrust::Font,
137 script: [u8; 4],
138 rtl: bool,
139 language: &Language,
140 features: &[Feature],
141 ) -> Arc<ShapePlan> {
142 let mut plans = self.plans.lock();
143 Arc::clone(plans.entry((script, rtl)).or_insert_with(|| {
144 Arc::new(ShapePlan::new(font, direction(rtl), Some(to_script(script)), Some(language), features))
145 }))
146 }
147
148 pub fn shape(&self, text: &[char], rtl: bool, shaped: &mut ShapedText) {
152 struct TextPart {
153 text: Vec<char>,
154 script: [u8; 4],
155 }
156
157 const INVALID: [u8; 4] = [0; 4];
159
160 if text.is_empty() {
161 return;
162 }
163 let Some(font) = self.face.font() else {
165 return;
166 };
167
168 let is_neutral = |script: &[u8; 4]| matches!(script, b"Zyyy" | b"Zinh" | b"Zzzz");
169
170 let mut text_parts: Vec<TextPart> = Vec::new();
171 if rtl {
172 for &ch in text {
178 let script = get_unicode_script(ch);
179 let part_script = if is_neutral(&script) { INVALID } else { script };
180 match text_parts.last_mut() {
181 Some(last) if part_script == INVALID || last.script == script || last.script == INVALID => {
182 if last.script == INVALID {
183 last.script = part_script;
184 }
185 last.text.push(ch);
186 }
187 _ => text_parts.push(TextPart { text: vec![ch], script: part_script }),
188 }
189 }
190 for text_part in &mut text_parts {
191 if text_part.script == INVALID {
192 text_part.script = *b"Arab";
193 }
194 }
195 text_parts.reverse();
198 } else {
199 for &ch in text {
200 let script = get_unicode_script(ch);
201 match text_parts.last_mut() {
202 Some(last) if last.script == script || script == *b"Zinh" => last.text.push(ch),
203 _ => text_parts.push(TextPart { text: vec![ch], script }),
204 }
205 }
206 }
207
208 for text_part in &text_parts {
209 let Some(buffer) = self.shape_part(font, &text_part.text, text_part.script, rtl) else {
210 continue;
211 };
212
213 let glyph_info = buffer.glyph_infos();
214 let glyph_pos = buffer.glyph_positions();
215 shaped.glyphs.reserve(glyph_info.len());
216 shaped.adjusts.reserve(glyph_info.len());
217 for (info, pos) in glyph_info.iter().zip(glyph_pos) {
218 shaped.glyphs.push(GlyphID::with_type(info.glyph_id as u16, self.type_));
219 shaped.adjusts.push(GlyphAdjust {
220 x_offset: pos.x_offset as f32 / 64.0,
221 y_offset: pos.y_offset.wrapping_neg() as f32 / 64.0,
222 advance: pos.x_advance as f32 / 64.0,
223 });
224 }
225 }
226 }
227
228 fn shape_part(&self, font: &harfrust::Font, text: &[char], script: [u8; 4], rtl: bool) -> Option<Buffer> {
230 let shaper_font = ShaperFont::new(font).with_scale(SDF_FONT_SIZE * 64).with_font_funcs(Some(&NoGlyphExtents));
231 let language = get_default_language();
232 let features = hb_tiny_features();
233
234 let mut buffer = Buffer::new();
235 buffer.set_direction(direction(rtl));
236 buffer.set_script(Some(to_script(script)));
237 buffer.set_language(Some(language.clone()));
238 for (cluster, &c) in (0..).zip(text) {
241 buffer.push(u32::from(c), cluster);
242 }
243
244 let plan = self.plan(font, script, rtl, &language, &features);
245 let options = ShapeOptions::new().plan(Some(&plan)).features(&features);
246 harfrust::shape(&shaper_font, &mut buffer, options).ok()?;
249 Some(buffer)
250 }
251}
252
253fn direction(rtl: bool) -> Direction {
255 if rtl { Direction::RightToLeft } else { Direction::LeftToRight }
256}
257
258fn to_script(tag: [u8; 4]) -> Script {
260 Script::from_iso15924_tag(Tag::new(&tag)).unwrap_or(Script::UNKNOWN)
261}
262
263#[cfg(test)]
264mod tests {
265 use super::*;
266
267 #[test]
268 fn script_segmentation_classifies_characters() {
269 assert_eq!(&get_unicode_script('a'), b"Latn");
270 assert_eq!(&get_unicode_script(' '), b"Zyyy");
271 assert_eq!(&get_unicode_script('\u{0301}'), b"Zinh");
272 assert_eq!(&get_unicode_script('\u{0941}'), b"Zinh"); assert_eq!(&get_unicode_script('\u{0627}'), b"Arab");
274 assert_eq!(&get_unicode_script('\u{4E2D}'), b"Hani");
275 assert_eq!(&get_unicode_script('\u{AC00}'), b"Hang");
276 assert_eq!(&get_unicode_script('\u{20000}'), b"Hani"); assert_eq!(&get_unicode_script('\u{1F600}'), b"Zyyy");
278 }
279}