Skip to main content

harfrust/ot/shaper/
khmer.rs

1use super::indic::category;
2use super::syllabic::*;
3use super::*;
4use crate::ot::map::*;
5use crate::plan::ShapePlan;
6use crate::unicode::{CharExt, Codepoint};
7use crate::ShaperFont;
8use crate::{GlyphInfo, Mask, Tag};
9use alloc::boxed::Box;
10
11pub const KHMER_SHAPER: OtShaper = OtShaper {
12    collect_features: Some(collect_features),
13    override_features: Some(override_features),
14    create_data: Some(|plan| Box::new(KhmerShapePlan::new(plan))),
15    preprocess_text: None,
16    postprocess_glyphs: None,
17    normalization_preference: NormalizationMode::ComposedDiacriticsNoShortCircuit,
18    decompose: Some(decompose),
19    compose: Some(compose),
20    setup_masks: Some(setup_masks),
21    gpos_tag: None,
22    reorder_marks: None,
23    zero_width_marks: ZeroWidthMarks::None,
24    fallback_position: false,
25};
26
27impl GlyphInfo {
28    declare_buffer_var_alias!(
29        OT_SHAPER_VAR_U8_CATEGORY_VAR,
30        u8,
31        KHMER_CATEGORY_VAR,
32        khmer_category,
33        set_khmer_category
34    );
35}
36
37const KHMER_FEATURES: &[(Tag, MapFeatureFlags)] = &[
38    // Basic features.
39    // These features are applied all at once, before reordering, constrained
40    // to the syllable.
41    (Tag::new(b"pref"), F_MANUAL_JOINERS | F_PER_SYLLABLE),
42    (Tag::new(b"blwf"), F_MANUAL_JOINERS | F_PER_SYLLABLE),
43    (Tag::new(b"abvf"), F_MANUAL_JOINERS | F_PER_SYLLABLE),
44    (Tag::new(b"pstf"), F_MANUAL_JOINERS | F_PER_SYLLABLE),
45    (Tag::new(b"cfar"), F_MANUAL_JOINERS | F_PER_SYLLABLE),
46    // Other features.
47    // These features are applied all at once after clearing syllables.
48    (Tag::new(b"pres"), F_GLOBAL_MANUAL_JOINERS),
49    (Tag::new(b"abvs"), F_GLOBAL_MANUAL_JOINERS),
50    (Tag::new(b"blws"), F_GLOBAL_MANUAL_JOINERS),
51    (Tag::new(b"psts"), F_GLOBAL_MANUAL_JOINERS),
52];
53
54// Must be in the same order as the KHMER_FEATURES array.
55mod khmer_feature {
56    pub const PREF: usize = 0;
57    pub const BLWF: usize = 1;
58    pub const ABVF: usize = 2;
59    pub const PSTF: usize = 3;
60    pub const CFAR: usize = 4;
61}
62
63impl GlyphInfo {
64    fn set_khmer_properties(&mut self) {
65        let u = self.glyph_id;
66        let (cat, _) = indic_table::get_categories(u);
67
68        self.set_khmer_category(cat);
69    }
70}
71
72struct KhmerShapePlan {
73    mask_array: [Mask; KHMER_FEATURES.len()],
74}
75
76impl KhmerShapePlan {
77    fn new(plan: &ShapePlan) -> Self {
78        let mut mask_array = [0; KHMER_FEATURES.len()];
79        for (i, feature) in KHMER_FEATURES.iter().enumerate() {
80            mask_array[i] = if feature.1 & F_GLOBAL != 0 {
81                0
82            } else {
83                plan.ot_map.get_1_mask(feature.0)
84            }
85        }
86
87        KhmerShapePlan { mask_array }
88    }
89}
90
91fn collect_features(planner: &mut ShapePlanner) {
92    // Do this before any lookups have been applied.
93    planner.ot_map.add_gsub_pause(Some(setup_syllables));
94    planner.ot_map.add_gsub_pause(Some(reorder_khmer));
95
96    // Testing suggests that Uniscribe does NOT pause between basic
97    // features.  Test with KhmerUI.ttf and the following three
98    // sequences:
99    //
100    //   U+1789,U+17BC
101    //   U+1789,U+17D2,U+1789
102    //   U+1789,U+17D2,U+1789,U+17BC
103    //
104    // https://github.com/harfbuzz/harfbuzz/issues/974
105    planner
106        .ot_map
107        .enable_feature(Tag::new(b"locl"), F_PER_SYLLABLE, 1);
108    planner
109        .ot_map
110        .enable_feature(Tag::new(b"ccmp"), F_PER_SYLLABLE, 1);
111
112    for feature in KHMER_FEATURES.iter().take(5) {
113        planner.ot_map.add_feature(feature.0, feature.1, 1);
114    }
115
116    /* https://github.com/harfbuzz/harfbuzz/issues/3531 */
117    planner.ot_map.add_gsub_pause(Some(syllabic_clear_var)); // Don't need syllables anymore.
118
119    for feature in KHMER_FEATURES.iter().skip(5) {
120        planner.ot_map.add_feature(feature.0, feature.1, 1);
121    }
122}
123
124fn setup_syllables(_: &ShapePlan, _: &ShaperFont<'_, '_>, buffer: &mut Buffer) -> Option<bool> {
125    buffer.allocate_var(GlyphInfo::SYLLABLE_VAR);
126
127    khmer_machine::find_syllables_khmer(buffer);
128
129    let mut start = 0;
130    let mut end = buffer.next_syllable(0);
131    while start < buffer.len {
132        buffer.unsafe_to_break(Some(start), Some(end));
133        start = end;
134        end = buffer.next_syllable(start);
135    }
136
137    Some(false)
138}
139
140fn reorder_khmer(plan: &ShapePlan, font: &ShaperFont<'_, '_>, buffer: &mut Buffer) -> Option<bool> {
141    use super::khmer_machine::SyllableType;
142
143    let mut ret = false;
144    if !buffer_message!(buffer, font, "start reordering khmer") {
145        buffer.deallocate_var(GlyphInfo::KHMER_CATEGORY_VAR);
146        return Some(ret);
147    }
148
149    if insert_dotted_circles(
150        font,
151        buffer,
152        SyllableType::BrokenCluster as u8,
153        category::OT_DOTTEDCIRCLE,
154        Some(category::OT_Repha),
155        None,
156    )? {
157        ret = true;
158    }
159
160    let khmer_plan = plan.data::<KhmerShapePlan>();
161
162    let mut start = 0;
163    let mut end = buffer.next_syllable(0);
164    while start < buffer.len {
165        if reorder_syllable_khmer(khmer_plan, start, end, buffer).is_none() {
166            buffer.index_failed();
167        }
168        start = end;
169        end = buffer.next_syllable(start);
170    }
171
172    buffer.deallocate_var(GlyphInfo::KHMER_CATEGORY_VAR);
173
174    buffer_message!(buffer, font, "end reordering khmer");
175    Some(ret)
176}
177
178fn reorder_syllable_khmer(
179    khmer_plan: &KhmerShapePlan,
180    start: usize,
181    end: usize,
182    buffer: &mut Buffer,
183) -> Option<()> {
184    use super::khmer_machine::SyllableType;
185
186    let syllable_type = match buffer.info.get(start)?.syllable() & 0x0F {
187        0 => SyllableType::ConsonantSyllable,
188        1 => SyllableType::BrokenCluster,
189        2 => SyllableType::NonKhmerCluster,
190        _ => unreachable!(),
191    };
192
193    match syllable_type {
194        SyllableType::ConsonantSyllable | SyllableType::BrokenCluster => {
195            reorder_consonant_syllable(khmer_plan, start, end, buffer)?;
196        }
197        SyllableType::NonKhmerCluster => {}
198    }
199    Some(())
200}
201
202// Rules from:
203// https://docs.microsoft.com/en-us/typography/script-development/devanagari
204fn reorder_consonant_syllable(
205    plan: &KhmerShapePlan,
206    start: usize,
207    end: usize,
208    buffer: &mut Buffer,
209) -> Option<()> {
210    // Setup masks.
211    {
212        // Post-base
213        let mask = plan.mask_array[khmer_feature::BLWF]
214            | plan.mask_array[khmer_feature::ABVF]
215            | plan.mask_array[khmer_feature::PSTF];
216        for info in buffer.info.get_mut(start + 1..end)? {
217            info.mask |= mask;
218        }
219    }
220
221    let mut num_coengs = 0;
222    for i in start + 1..end {
223        // When a COENG + (Cons | IndV) combination are found (and subscript count
224        // is less than two) the character combination is handled according to the
225        // subscript type of the character following the COENG.
226        //
227        // ...
228        //
229        // Subscript Type 2 - The COENG + RO characters are reordered to immediately
230        // before the base glyph. Then the COENG + RO characters are assigned to have
231        // the 'pref' OpenType feature applied to them.
232        let cat = buffer.info.get(i)?.indic_category();
233        if cat == category::OT_H && num_coengs <= 2 && i + 1 < end {
234            num_coengs += 1;
235
236            if buffer.info.get(i + 1)?.indic_category() == category::OT_Ra {
237                for info in buffer.info.get_mut(i..i + 2)? {
238                    info.mask |= plan.mask_array[khmer_feature::PREF];
239                }
240
241                // Move the Coeng,Ro sequence to the start.
242                buffer.merge_clusters(start, i + 2);
243                buffer.info.get_mut(start..i + 2)?.rotate_right(2);
244
245                // Mark the subsequent stuff with 'cfar'.  Used in Khmer.
246                // Read the feature spec.
247                // This allows distinguishing the following cases with MS Khmer fonts:
248                // U+1784,U+17D2,U+179A,U+17D2,U+1782
249                // U+1784,U+17D2,U+1782,U+17D2,U+179A
250                if plan.mask_array[khmer_feature::CFAR] != 0 {
251                    for info in buffer.info.get_mut(i + 2..end)? {
252                        info.mask |= plan.mask_array[khmer_feature::CFAR];
253                    }
254                }
255
256                num_coengs = 2; // Done.
257            }
258        } else if cat == category::OT_VPre {
259            // Reorder left matra piece.
260
261            // Move to the start.
262            buffer.merge_clusters(start, i + 1);
263            buffer.info.get_mut(start..=i)?.rotate_right(1);
264        }
265    }
266    Some(())
267}
268
269fn override_features(planner: &mut ShapePlanner) {
270    // Khmer spec has 'clig' as part of required shaping features:
271    // "Apply feature 'clig' to form ligatures that are desired for
272    // typographical correctness.", hence in overrides...
273    planner.ot_map.enable_feature(Tag::new(b"clig"), F_NONE, 1);
274
275    planner.ot_map.disable_feature(Tag::new(b"liga"));
276}
277
278fn decompose(_: &NormalizeContext, ab: Codepoint) -> Option<(Codepoint, Codepoint)> {
279    // Decompose split matras that don't have Unicode decompositions.
280    match ab {
281        0x17BE | 0x17BF | 0x17C0 | 0x17C4 | 0x17C5 => Some((0x17C1, ab)),
282        _ => unicode::decompose_impl(ab),
283    }
284}
285
286fn compose(_: &NormalizeContext, a: Codepoint, b: Codepoint) -> Option<Codepoint> {
287    // Avoid recomposing split matras.
288    if a.general_category().is_mark() {
289        return None;
290    }
291    unicode::compose(a, b)
292}
293
294fn setup_masks(_: &ShapePlan, _: &ShaperFont<'_, '_>, buffer: &mut Buffer) {
295    buffer.allocate_var(GlyphInfo::KHMER_CATEGORY_VAR);
296
297    // We cannot setup masks here.  We save information about characters
298    // and setup masks later on in a pause-callback.
299    for info in buffer.info_slice_mut() {
300        info.set_khmer_properties();
301    }
302}