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