swash/shape/
engine.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
use super::{aat, at};

use super::buffer::*;
use super::internal::{self, at::Gdef, raw_tag, Bytes, RawFont, RawTag};
use crate::font::FontRef;
use crate::text::{Language, Script};

use core::ops::Range;

/// Shaping engine that handles the various methods available in
/// an OpenType font.
pub struct Engine<'a> {
    pub data: Bytes<'a>,
    pub gdef: Gdef<'a>,
    pub gsub: at::StageOffsets,
    pub gpos: at::StageOffsets,
    pub morx: u32,
    pub ltag: u32,
    pub kerx: u32,
    pub ankr: u32,
    pub kern: u32,
    pub storage: at::Storage,
    pub coords: &'a [i16],
    pub script: Script,
    pub lang: Option<Language>,
    pub tags: [RawTag; 4],
    pub sub_mode: SubMode,
    pub pos_mode: PosMode,
    pub use_ot: bool,
    pub use_aat: bool,
    pub mode: EngineMode,
}

impl<'a> Engine<'a> {
    /// Creates a new shaping engine from precreated metadata.
    pub fn new(
        metadata: &EngineMetadata,
        font_data: &'a [u8],
        coords: &'a [i16],
        script: Script,
        lang: Option<Language>,
    ) -> Self {
        let data = Bytes::new(font_data);
        let gdef = Gdef::from_offset(font_data, metadata.gdef).unwrap_or_else(Gdef::empty);
        let script_tag = script.to_opentype();
        let lang_tag = lang.and_then(|l| l.to_opentype());
        let (gsub, stags) = if metadata.sub_mode == SubMode::Gsub {
            at::StageOffsets::new(&data, metadata.gsub, script_tag, lang_tag).unwrap_or_default()
        } else {
            (at::StageOffsets::default(), [0, 0])
        };
        let (gpos, ptags) = if metadata.pos_mode == PosMode::Gpos {
            at::StageOffsets::new(&data, metadata.gpos, script_tag, lang_tag).unwrap_or_default()
        } else {
            (at::StageOffsets::default(), [0, 0])
        };
        let tags = [stags[0], stags[1], ptags[0], ptags[1]];
        let use_ot = gsub.lang != 0 || gpos.lang != 0;
        let use_aat = metadata.morx != 0 || metadata.kerx != 0;
        let mode = if gsub.lang != 0 && script.is_complex() {
            if script == Script::Myanmar {
                EngineMode::Myanmar
            } else {
                EngineMode::Complex
            }
        } else {
            EngineMode::Simple
        };
        let mut sub_mode = metadata.sub_mode;
        let mut pos_mode = metadata.pos_mode;
        if sub_mode == SubMode::Gsub && gsub.lang == 0 {
            sub_mode = SubMode::None;
        }
        if pos_mode == PosMode::Gpos && gpos.lang == 0 {
            pos_mode = PosMode::None;
        }
        Self {
            data,
            gdef,
            gsub,
            gpos,
            morx: metadata.morx,
            ltag: metadata.ltag,
            kerx: metadata.kerx,
            ankr: metadata.ankr,
            kern: metadata.kern,
            storage: at::Storage::default(),
            coords,
            script,
            lang,
            tags,
            sub_mode,
            pos_mode,
            use_ot,
            use_aat,
            mode,
        }
    }
}

/// OpenType shaping.
impl<'a> Engine<'a> {
    /// Returns the script and language tags that have been selected for
    /// the GSUB and GPOS tables.
    pub fn tags(&self) -> &[RawTag; 4] {
        &self.tags
    }

    /// Builds a feature store for the current engine configuration.
    pub fn collect_features(
        &self,
        builder: &mut at::FeatureStoreBuilder,
        store: &mut at::FeatureStore,
    ) {
        builder.build(
            store,
            self.data.data(),
            self.coords,
            &self.gdef,
            &self.gsub,
            &self.gpos,
        );
        store.groups = store.groups(self.script);
    }

    /// Returns true if feature variations are supported.
    pub fn has_feature_vars(&self) -> bool {
        self.gsub.var != 0 || self.gpos.var != 0
    }

    /// Sets glyph and mark classes for the specified range of the buffer.
    pub fn set_classes(&self, buffer: &mut Buffer, range: Option<Range<usize>>) {
        if !self.gdef.ok() {
            return;
        }
        let slice = if let Some(range) = range {
            &mut buffer.glyphs[range]
        } else {
            &mut buffer.glyphs[..]
        };
        let gdef = &self.gdef;
        if gdef.has_mark_classes() {
            for g in slice.iter_mut() {
                g.class = gdef.class(g.id) as u8;
                g.mark_type = gdef.mark_class(g.id) as u8;
            }
        } else {
            for g in slice.iter_mut() {
                g.class = gdef.class(g.id) as u8;
            }
        }
    }

    /// Applies the GSUB features to the specified range of the buffer.
    pub fn gsub(
        &mut self,
        store: &at::FeatureStore,
        feature_mask: impl Into<at::FeatureMask>,
        buffer: &mut Buffer,
        buffer_range: Option<Range<usize>>,
    ) -> bool {
        at::apply(
            0,
            &self.data,
            self.gsub.base,
            self.coords,
            &self.gdef,
            &mut self.storage,
            store,
            feature_mask.into(),
            buffer,
            buffer_range,
        ) == Some(true)
    }

    /// Applies the GPOS features to the specified range of the buffer.
    pub fn gpos(
        &mut self,
        store: &at::FeatureStore,
        feature_mask: impl Into<at::FeatureMask>,
        buffer: &mut Buffer,
        buffer_range: Option<Range<usize>>,
    ) -> bool {
        at::apply(
            1,
            &self.data,
            self.gpos.base,
            self.coords,
            &self.gdef,
            &mut self.storage,
            store,
            feature_mask.into(),
            buffer,
            buffer_range,
        ) == Some(true)
    }
}

/// Apple shaping.
impl<'a> Engine<'a> {
    /// Converts a feature list into a sorted collection of AAT selectors.
    pub fn collect_selectors(&self, features: &[(RawTag, u16)], selectors: &mut Vec<(u16, u16)>) {
        use internal::aat::morx::feature_from_tag;
        selectors.clear();
        for (tag, value) in features {
            if let Some((selector, [on, off])) = feature_from_tag(*tag) {
                let setting = if *value == 0 { off } else { on };
                selectors.push((selector, setting));
            }
        }
        selectors.sort_unstable();
    }

    /// Applies the extended metamorphosis table.
    pub fn morx(&self, buffer: &mut Buffer, selectors: &[(u16, u16)]) {
        if self.morx != 0 {
            aat::apply_morx(self.data.data(), self.morx, buffer, selectors);
            buffer.ensure_order(false);
        }
    }

    /// Applies the extended kerning table.
    pub fn kerx(&self, buffer: &mut Buffer, disable_kern: bool) {
        if self.kerx != 0 {
            aat::apply_kerx(self.data.data(), self.kerx, self.ankr, buffer, disable_kern);
            buffer.ensure_order(false);
        }
    }

    /// Applies the kerning table.
    pub fn kern(&self, buffer: &mut Buffer) {
        if self.kern != 0 {
            aat::apply_kern(self.data.data(), self.kern, buffer);
        }
    }
}

/// The overall mode of the engine based on a combination of the
/// supported tables and the selected script.
#[derive(Copy, Clone, PartialEq, Eq, Debug)]
pub enum EngineMode {
    Simple,
    Myanmar,
    Complex,
}

/// The substitution mode supported by the engine.
#[derive(Copy, Clone, PartialEq, Eq, Debug)]
pub enum SubMode {
    None,
    Gsub,
    Morx,
}

/// The positioning mode supported by the engine.
#[derive(Copy, Clone, PartialEq, Eq, Debug)]
pub enum PosMode {
    None,
    Gpos,
    Kerx,
    Kern,
}

/// Metadata for creating a shaping engine.
#[derive(Copy, Clone)]
pub struct EngineMetadata {
    pub gdef: u32,
    pub gsub: u32,
    pub gpos: u32,
    pub morx: u32,
    pub ltag: u32,
    pub kerx: u32,
    pub ankr: u32,
    pub kern: u32,
    pub sub_mode: SubMode,
    pub pos_mode: PosMode,
}

impl EngineMetadata {
    pub fn from_font(font: &FontRef) -> Self {
        let mut this = Self {
            gdef: font.table_offset(raw_tag(b"GDEF")),
            gsub: font.table_offset(raw_tag(b"GSUB")),
            gpos: font.table_offset(raw_tag(b"GPOS")),
            morx: font.table_offset(raw_tag(b"morx")),
            ltag: font.table_offset(raw_tag(b"ltag")),
            kerx: font.table_offset(raw_tag(b"kerx")),
            ankr: font.table_offset(raw_tag(b"ankr")),
            kern: font.table_offset(raw_tag(b"kern")),
            sub_mode: SubMode::None,
            pos_mode: PosMode::None,
        };
        if this.gsub != 0 {
            this.sub_mode = SubMode::Gsub;
        } else if this.morx != 0 {
            this.sub_mode = SubMode::Morx;
        }
        if this.gpos != 0 {
            this.pos_mode = PosMode::Gpos;
        } else if this.kerx != 0 {
            this.pos_mode = PosMode::Kerx;
        } else if this.kern != 0 {
            this.pos_mode = PosMode::Kern;
        }
        this
    }
}