swash/internal/
var.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
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
//! Font and metric variation tables.

use skrifa::raw::{FontData, FontRead};

use super::{fixed::Fixed, raw_tag, Array, Bytes, RawFont, RawTag, U24};

pub const FVAR: RawTag = raw_tag(b"fvar");
pub const AVAR: RawTag = raw_tag(b"avar");
pub const HVAR: RawTag = raw_tag(b"HVAR");
pub const VVAR: RawTag = raw_tag(b"VVAR");
pub const MVAR: RawTag = raw_tag(b"MVAR");

/// Font variations table.
#[derive(Copy, Clone)]
pub struct Fvar<'a> {
    data: Bytes<'a>,
    axis_offset: u16,
    axis_count: u16,
    axis_size: u16,
    inst_count: u16,
    inst_size: u16,
}

impl<'a> Fvar<'a> {
    pub fn new(data: &'a [u8]) -> Self {
        let b = Bytes::new(data);
        let axis_offset = b.read_or_default::<u16>(4);
        let axis_count = b.read_or_default::<u16>(8);
        let axis_size = b.read_or_default::<u16>(10);
        let inst_count = b.read_or_default::<u16>(12);
        let inst_size = b.read_or_default::<u16>(14);
        Self {
            data: b,
            axis_offset,
            axis_count,
            axis_size,
            inst_count,
            inst_size,
        }
    }

    pub fn from_font(font: impl RawFont<'a>) -> Option<Self> {
        Some(Self::new(font.table_data(FVAR)?))
    }

    pub fn axis_count(&self) -> u16 {
        self.axis_count
    }

    pub fn get_axis(&self, index: u16) -> Option<VarAxis> {
        if index >= self.axis_count {
            return None;
        }
        let b = &self.data;
        let base = self.axis_offset as usize;
        let offset = base + index as usize * self.axis_size as usize;
        let tag = b.read::<u32>(offset)?;
        let min = Fixed(b.read::<i32>(offset + 4)?);
        let default = Fixed(b.read::<i32>(offset + 8)?);
        let max = Fixed(b.read::<i32>(offset + 12)?);
        let flags = b.read::<u16>(offset + 16)?;
        let name_id = b.read::<u16>(offset + 18)?;
        Some(VarAxis {
            index,
            tag,
            name_id,
            flags,
            min,
            default,
            max,
        })
    }

    pub fn get_axis_by_tag(&self, tag: RawTag) -> Option<VarAxis> {
        let b = &self.data;
        let base = self.axis_offset as usize;
        let axis_size = self.axis_size as usize;
        for i in 0..self.axis_count as usize {
            let tag_offset = base + i * axis_size;
            if b.read_u32(tag_offset) == Some(tag) {
                return self.get_axis(i as u16);
            }
        }
        None
    }

    pub fn instance_count(&self) -> u16 {
        self.inst_count
    }

    pub fn get_instance(&self, index: u16) -> Option<VarInstance<'a>> {
        if index >= self.inst_count {
            return None;
        }
        let b = &self.data;
        let base = self.axis_offset as usize + (self.axis_count as usize * self.axis_size as usize);
        let offset = base + index as usize * self.inst_size as usize;
        let name_id = b.read::<u16>(offset)?;
        let values = b.read_array::<Fixed>(offset + 4, self.axis_count as usize)?;
        let ps_name_offset = 4 + self.axis_count as usize * 4;
        let postscript_name_id = if ps_name_offset == self.inst_size as usize - 2 {
            b.read::<u16>(ps_name_offset)
        } else {
            None
        };
        Some(VarInstance {
            index,
            name_id,
            postscript_name_id,
            values,
        })
    }
}

/// Axis of variation in a variable font.
#[derive(Copy, Clone, Default)]
pub struct VarAxis {
    pub index: u16,
    pub tag: RawTag,
    pub name_id: u16,
    pub flags: u16,
    pub min: Fixed,
    pub default: Fixed,
    pub max: Fixed,
}

impl VarAxis {
    /// Returns true if the axis should be hidden in a user interface.
    pub fn is_hidden(&self) -> bool {
        self.flags & 1 != 0
    }

    /// Returns a normalized axis coordinate for the specified value in 2.14
    /// fixed point format.
    pub fn normalized_coord(&self, mut value: Fixed, avar: Option<(&[u8], u32)>) -> i16 {
        use core::cmp::Ordering::*;
        if value < self.min {
            value = self.min;
        } else if value > self.max {
            value = self.max;
        }
        value = match value.cmp(&self.default) {
            Less => -((self.default - value) / (self.default - self.min)),
            Greater => (value - self.default) / (self.max - self.default),
            Equal => Fixed(0),
        };
        value = value.min(Fixed::ONE).max(-Fixed::ONE);
        value = avar
            .and_then(|(data, avar)| adjust_axis(data, avar, self.index, value))
            .unwrap_or(value);
        value.to_f2dot14()
    }
}

/// Named instance in a variable font.
#[derive(Copy, Clone)]
pub struct VarInstance<'a> {
    pub index: u16,
    pub name_id: u16,
    pub postscript_name_id: Option<u16>,
    pub values: Array<'a, Fixed>,
}

/// Metrics variation table.
pub struct Mvar<'a> {
    data: Bytes<'a>,
    coords: &'a [i16],
    rec_size: usize,
    rec_count: usize,
    store: u32,
}

impl<'a> Mvar<'a> {
    pub fn new(data: &'a [u8], mvar: u32, coords: &'a [i16]) -> Option<Self> {
        let b = Bytes::with_offset(data, mvar as usize)?;
        let rec_size = b.read::<u16>(6)? as usize;
        let rec_count = b.read::<u16>(8)? as usize;
        let store = b.read::<u16>(10)? as u32;
        if rec_count == 0 || store == 0 {
            return None;
        }
        Some(Self {
            data: b,
            coords,
            rec_size,
            rec_count,
            store,
        })
    }

    pub fn delta(&self, metric: RawTag) -> f32 {
        self.read_delta(metric).map(|d| d.to_f32()).unwrap_or(0.)
    }

    #[inline(always)]
    fn read_delta(&self, metric: RawTag) -> Option<Fixed> {
        let base = 12;
        let b = &self.data;
        let rec_size = self.rec_size;
        let mut l = 0;
        let mut h = self.rec_count;
        while l < h {
            use core::cmp::Ordering::*;
            let i = (l + h) / 2;
            let offset = base + i * rec_size;
            let t = b.read::<u32>(offset)?;
            match metric.cmp(&t) {
                Less => h = i,
                Greater => l = i + 1,
                Equal => {
                    let inner = b.read::<u16>(offset + 4)?;
                    let outer = b.read::<u16>(offset + 6)?;
                    return item_delta(b.data(), self.store, outer, inner, self.coords);
                }
            }
        }
        None
    }
}

/// Returns the advance delta for the specified glyph.
pub fn advance_delta(data: &[u8], xvar: u32, glyph_id: u16, coords: &[i16]) -> f32 {
    metric_delta(data, xvar, 8, glyph_id, coords)
        .map(|d| d.to_f32())
        .unwrap_or(0.)
}

/// Returns the side bearing delta for the specified glyph.
pub fn sb_delta(data: &[u8], xvar: u32, glyph_id: u16, coords: &[i16]) -> f32 {
    metric_delta(data, xvar, 12, glyph_id, coords)
        .map(|d| d.to_f32())
        .unwrap_or(0.)
}

/// Applies adjustments to a coordinate according to the optional axis
/// variation table.
pub fn adjust_axis(data: &[u8], avar: u32, axis: u16, coord: Fixed) -> Option<Fixed> {
    if avar == 0 {
        return None;
    }
    let avar =
        skrifa::raw::tables::avar::Avar::read(FontData::new(data.get(avar as usize..)?)).ok()?;
    let mapping = avar
        .axis_segment_maps()
        .get(axis as usize)
        .transpose()
        .ok()??;
    Some(Fixed(
        mapping
            .apply(skrifa::raw::types::Fixed::from_bits(coord.0))
            .to_bits(),
    ))
}

/// Returns a delta from an item variation store.
pub fn item_delta(
    data: &[u8],
    offset: u32,
    outer: u16,
    inner: u16,
    coords: &[i16],
) -> Option<Fixed> {
    if offset == 0 {
        return None;
    }
    let b = Bytes::new(data);
    let store = offset as usize;
    if outer >= b.read::<u16>(store + 6)? {
        return None;
    }
    let region_base = store + b.read::<u32>(store + 2)? as usize;
    let axis_count = b.read::<u16>(region_base)? as usize;
    let region_record_size = axis_count * 6;
    let region_count = b.read::<u16>(region_base + 2)? as usize;
    let data_base = store + b.read::<u32>(store + 8 + outer as usize * 4)? as usize;
    let region_index_base = data_base + 6;
    let region_index_count = b.read::<u16>(data_base + 4)? as usize;
    let (short_count, mut delta_base) = {
        let inner = inner as usize;
        let short_count = b.read::<u16>(data_base + 2)? as usize;
        let count = region_index_count;
        let base = data_base + 6 + count * 2;
        let elem_len = (count - short_count) + short_count * 2;
        let offset = base + inner * elem_len;
        (short_count, offset)
    };
    const ZERO: Fixed = Fixed::ZERO;
    const ONE: Fixed = Fixed::ONE;
    let mut idx = 0;
    let mut delta = ZERO;
    for i in 0..region_index_count {
        let region_index = b.read::<u16>(region_index_base + i * 2)? as usize;
        if region_index >= region_count {
            return None;
        }
        let region_offset = region_base + 4 + region_index * region_record_size;
        let mut scalar = ONE;
        for axis in 0..axis_count {
            let region_axis_base = region_offset + axis * 6;
            let start = Fixed::from_f2dot14(b.read::<i16>(region_axis_base)?);
            let peak = Fixed::from_f2dot14(b.read::<i16>(region_axis_base + 2)?);
            let end = Fixed::from_f2dot14(b.read::<i16>(region_axis_base + 4)?);
            let coord = coords
                .get(axis)
                .map(|c| Fixed::from_f2dot14(*c))
                .unwrap_or(ZERO);
            if start > peak || peak > end || peak == ZERO || start < ZERO && end > ZERO {
                continue;
            } else if coord < start || coord > end {
                scalar = ZERO;
                break;
            } else if coord == peak {
                continue;
            } else if coord < peak {
                scalar = scalar * (coord - start) / (peak - start);
            } else {
                scalar = scalar * (end - coord) / (end - peak);
            };
        }
        let val = if idx >= short_count {
            delta_base += 1;
            b.read::<i8>(delta_base - 1)? as i16
        } else {
            delta_base += 2;
            b.read::<i16>(delta_base - 2)?
        };
        idx += 1;
        delta += scalar * Fixed::from_i32(val as i32);
    }
    Some(delta)
}

#[inline(always)]
fn metric_delta(
    data: &[u8],
    base: u32,
    which: usize,
    glyph_id: u16,
    coords: &[i16],
) -> Option<Fixed> {
    if base == 0 {
        return None;
    }
    let b = Bytes::new(data);
    let mut store = b.read::<u32>(base as usize + 4)?;
    if store == 0 {
        return None;
    }
    store += base;
    let mut offset = b.read::<u32>(base as usize + which)? as usize;
    if offset == 0 {
        if which == 8 {
            return item_delta(data, store, 0, glyph_id, coords);
        } else {
            return None;
        }
    }
    offset += base as usize;
    let format = b.read::<u16>(offset)? as u32;
    let count = b.read::<u16>(offset + 2)?;
    let bit_count = (format & 0xF) + 1;
    let entry_size = ((format & 0x30) >> 4) + 1;
    let base = offset + 4;
    let index = if glyph_id >= count {
        count - 1
    } else {
        glyph_id
    } as usize;
    let entry = match entry_size {
        1 => b.read::<u8>(base + index)? as u32,
        2 => b.read::<u16>(base + index * 2)? as u32,
        3 => b.read::<U24>(base + index * 3)?.0,
        4 => b.read::<u32>(base + index * 4)?,
        _ => return None,
    };
    let outer = entry >> bit_count;
    let inner = entry & ((1 << bit_count) - 1);
    item_delta(data, store, outer as u16, inner as u16, coords)
}

/// Tags for metrics from the `MVAR` table.
pub mod mvar_tags {
    use super::{raw_tag, RawTag};

    /// Horizontal ascender.
    pub const HASC: RawTag = raw_tag(b"hasc");
    /// Horizontal descender.
    pub const HDSC: RawTag = raw_tag(b"hdsc");
    /// Horizontal line gap.
    pub const HLGP: RawTag = raw_tag(b"hlgp");

    /// Horizontal caret rise.
    pub const HCRS: RawTag = raw_tag(b"hcrs");
    /// Horizontal caret run.
    pub const HCRN: RawTag = raw_tag(b"hcrn");
    /// Horizontal caret offset.
    pub const HCOF: RawTag = raw_tag(b"hcof");

    /// Horizontal clipping ascent.
    pub const HCLA: RawTag = raw_tag(b"hcla");
    /// Horizontal clipping descent.
    pub const HCLD: RawTag = raw_tag(b"hcld");

    /// Vertical ascender.
    pub const VASC: RawTag = raw_tag(b"vasc");
    /// Vertical descender.
    pub const VDSC: RawTag = raw_tag(b"vdsc");
    /// Vertical line gap.
    pub const VLGP: RawTag = raw_tag(b"vlgp");

    /// Vertical caret rise.
    pub const VCRS: RawTag = raw_tag(b"vcrs");
    /// Vertical caret run.
    pub const VCRN: RawTag = raw_tag(b"vcrn");
    /// Vertical caret offset.
    pub const VCOF: RawTag = raw_tag(b"vcof");

    /// X-height.
    pub const XHGT: RawTag = raw_tag(b"xhgt");
    /// Cap height.
    pub const CPHT: RawTag = raw_tag(b"cpht");

    /// Underline offset.
    pub const UNDO: RawTag = raw_tag(b"undo");
    /// Underline size.
    pub const UNDS: RawTag = raw_tag(b"unds");

    /// Strikeout offset.
    pub const STRO: RawTag = raw_tag(b"stro");
    /// Strikeout size.
    pub const STRS: RawTag = raw_tag(b"strs");

    /// Subscript x-offset.
    pub const SBXO: RawTag = raw_tag(b"sbxo");
    /// Subscript y-offset.
    pub const SBYO: RawTag = raw_tag(b"sbyo");
    /// Subscript x-size.
    pub const SBXS: RawTag = raw_tag(b"sbxs");
    /// Subscript y-size.
    pub const SBYS: RawTag = raw_tag(b"sbys");

    /// Superscript x-offset.
    pub const SPXO: RawTag = raw_tag(b"spxo");
    /// Superscript y-offset.
    pub const SPYO: RawTag = raw_tag(b"spyo");
    /// Superscript x-size.
    pub const SPXS: RawTag = raw_tag(b"spxs");
    /// Superscript y-size.
    pub const SPYS: RawTag = raw_tag(b"spys");
}