autobase 0.2.1

Utilities for manipulating BASE tables for OpenType fonts
Documentation
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
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
//! Abstract the BASE table into a manageable structure.
//!
//! Handles both reading and writing binary BASE table data, and exporting to AFDKO feature syntax.

use std::collections::{BTreeMap, BTreeSet};

use itertools::Itertools;
use skrifa::{FontRef, Tag};
use write_fonts::{tables::base as write_base, FontBuilder};

use crate::error::AutobaseError;

/// A MinMax represents the highest and lowest points of a set of glyphs, along with
/// the word that produced each extreme. This is useful for debugging and for
/// understanding why a particular BASE table was generated.
#[derive(Clone, Debug, PartialEq)]
pub struct MinMax {
    pub highest: Option<i16>,
    pub highest_word: String,
    pub lowest: Option<i16>,
    pub lowest_word: String,
}

impl MinMax {
    pub fn new_min_max(low: i16, high: i16) -> Self {
        Self {
            lowest: Some(low),
            highest: Some(high),
            lowest_word: "<from font>".to_string(),
            highest_word: "<from font>".to_string(),
        }
    }

    /// Convert to a Skrifa MinMax representation for writing to a font.
    pub fn to_skrifa(&self) -> write_base::MinMax {
        write_base::MinMax::new(
            self.lowest.map(write_base::BaseCoord::format_1),
            self.highest.map(write_base::BaseCoord::format_1),
            vec![],
        )
    }

    /// Create a MinMax from a Skrifa MinMax representation read from a font.
    fn from_skrifa(mm: &skrifa::raw::tables::base::MinMax) -> Result<Self, AutobaseError> {
        Ok(Self {
            highest: mm.max_coord().transpose()?.map(|c| c.coordinate()),
            highest_word: "<from font>".to_string(),
            lowest: mm.min_coord().transpose()?.map(|c| c.coordinate()),
            lowest_word: "<from font>".to_string(),
        })
    }

    pub fn merge(&mut self, other: &MinMax, tolerance: Option<u16>) {
        let tolerance = tolerance.unwrap_or(0);
        if let Some(other_high) = other.highest {
            if self.highest.is_none() || self.highest.unwrap() < other_high - tolerance as i16 {
                self.highest = Some(other_high);
                self.highest_word = other.highest_word.clone();
            }
        }
        if let Some(other_low) = other.lowest {
            if self.lowest.is_none() || self.lowest.unwrap() > other_low + tolerance as i16 {
                self.lowest = Some(other_low);
                self.lowest_word = other.lowest_word.clone();
            }
        }
    }

    pub fn is_empty(&self) -> bool {
        self.highest.is_none() && self.lowest.is_none()
    }

    fn unset_highest(&mut self) {
        self.highest = None;
        self.highest_word = "<none>".to_string();
    }
    fn unset_lowest(&mut self) {
        self.lowest = None;
        self.lowest_word = "<none>".to_string();
    }

    pub fn with_inliers_removed(&self, limits: &MinMax) -> MinMax {
        let mut new = self.clone();
        if let (Some(high), Some(limit_high)) = (new.highest, limits.highest) {
            if high < limit_high {
                new.unset_highest();
            }
        }
        if let (Some(low), Some(limit_low)) = (new.lowest, limits.lowest) {
            if low > limit_low {
                new.unset_lowest();
            }
        }
        new
    }

    pub fn with_nulls_replaced(&self, defaults: &MinMax) -> MinMax {
        let mut new = self.clone();
        if new.highest.is_none() {
            new.highest = defaults.highest;
            new.highest_word = "<default>".to_string();
        }
        if new.lowest.is_none() {
            new.lowest = defaults.lowest;
            new.lowest_word = "<default>".to_string();
        }
        new
    }

    pub fn extend(&self, extend_by: u16) -> MinMax {
        let mut new = self.clone();
        if let Some(high) = self.highest {
            new.highest = Some(high + extend_by as i16);
        }
        if let Some(low) = self.lowest {
            new.lowest = Some(low - extend_by as i16);
        }
        new
    }
}

impl std::fmt::Display for MinMax {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "MinMax<")?;
        if let Some(min) = &self.lowest {
            write!(f, " min: {:?} (from {})", min, self.lowest_word)?;
        }
        if let Some(max) = &self.highest {
            if self.lowest.is_some() {
                write!(f, ",")?;
            }
            write!(f, " max: {:?} (from {})", max, self.highest_word)?;
        }
        write!(f, ">")
    }
}

/// A BaseScript represents the BASE table data for a particular script, including
/// its default baseline, any other baselines, and MinMax data for the script as a
/// whole and for any languages within the script.
#[derive(Clone, Debug)]
pub struct BaseScript {
    /// The script tag, e.g. 'hani'
    ///
    /// Note that this is an OpenType script tag, not a ISO 15924 code.
    pub script: Tag,
    /// The default baseline tag, e.g. 'romn'
    pub default_baseline: Option<Tag>,
    /// A map of baseline tags to their y-coordinates
    pub baselines: BTreeMap<Tag, i16>,
    /// The default MinMax for the script
    pub default_minmax: Option<MinMax>,
    /// A map of language tags to their MinMax values
    ///
    /// The language tag is a 4-character OpenType language tag.
    pub languages: BTreeMap<Tag, MinMax>,
}

impl BaseScript {
    pub fn new(script: Tag) -> Self {
        Self {
            script,
            default_baseline: None,
            baselines: BTreeMap::new(),
            default_minmax: None,
            languages: BTreeMap::new(),
        }
    }

    /// Convert to a Skrifa BaseScriptRecord representation for writing to a font.
    pub fn to_skrifa(
        &self,
        baseline_tags: &[Tag],
    ) -> Result<write_base::BaseScriptRecord, AutobaseError> {
        let default_minmax = self.default_minmax.as_ref().map(|x| x.to_skrifa());
        let language_minmax: Vec<write_base::BaseLangSysRecord> = self
            .languages
            .iter()
            .map(|(lang, mm)| write_base::BaseLangSysRecord::new(*lang, mm.to_skrifa()))
            .collect();
        let baseline_index = self
            .default_baseline
            .map(|baseline_tag| {
                baseline_tags
                    .iter()
                    .position(|tag| *tag == baseline_tag)
                    .ok_or(AutobaseError::BaselineTagNotFound {
                        script: self.script,
                        tag: baseline_tag,
                    })
            })
            .transpose()?;
        let baselines: Vec<write_base::BaseCoord> = baseline_tags
            .iter()
            .map(|tag| {
                if let Some(y) = self.baselines.get(tag) {
                    write_base::BaseCoord::format_1(*y)
                } else {
                    write_base::BaseCoord::format_1(0)
                }
            })
            .collect();

        let base_values: Option<write_base::BaseValues> = baseline_index
            .map(|baseline_index| write_base::BaseValues::new(baseline_index as u16, baselines));

        Ok(write_base::BaseScriptRecord::new(
            self.script,
            write_base::BaseScript::new(base_values, default_minmax, language_minmax),
        ))
    }

    pub fn simplify(&mut self, tolerance: Option<u16>) {
        let tolerance = tolerance.unwrap_or(0);
        if let Some(script_default) = &self.default_minmax {
            // First, remove entries that are close to the script default
            for (lang, v) in self.languages.iter_mut() {
                let pruned = v.with_inliers_removed(&script_default.extend(tolerance));
                if pruned != *v {
                    log::info!(
                        "Not emitting script record {} for {}/{} (within {} of script default)",
                        v,
                        self.script,
                        lang,
                        tolerance,
                    );
                    *v = pruned;
                }
            }
            // Next remove entries that are now empty
            self.languages
                .retain(|_, v| v.lowest.is_some() || v.highest.is_some());
        }
    }

    pub fn merge(&self, other: &BaseScript, tolerance: Option<u16>) -> Self {
        let mut merged = self.clone();
        if let Some(other_def) = &other.default_minmax {
            if let Some(merged_def) = &mut merged.default_minmax {
                merged_def.merge(other_def, tolerance);
            } else {
                merged.default_minmax = Some(other_def.clone());
            }
        }
        for (lang, other_mm) in &other.languages {
            if let Some(merged_mm) = merged.languages.get_mut(lang) {
                merged_mm.merge(other_mm, tolerance);
            } else {
                merged.languages.insert(*lang, other_mm.clone());
            }
        }
        merged
    }
}

/// A BaseTable represents the entire BASE table, with horizontal and vertical axes.
#[derive(Clone, Debug, Default)]
pub struct BaseTable {
    /// The horizontal axis BaseScript records
    pub horizontal: Vec<BaseScript>,
    /// The vertical axis BaseScript records
    pub vertical: Vec<BaseScript>,
}

impl BaseTable {
    /// Convert to a Skrifa Base representation for writing to a font.
    pub fn to_skrifa(&self) -> Result<write_base::Base, AutobaseError> {
        let mut baseline_tags: BTreeMap<Tag, ()> = BTreeMap::new();
        for script in self.horizontal.iter().chain(self.vertical.iter()) {
            if let Some(def) = script.default_baseline {
                baseline_tags.insert(def, ());
            }
        }
        let baseline_tags: Vec<Tag> = baseline_tags.into_keys().collect();

        let mut horizontal_scripts: Vec<write_base::BaseScriptRecord> = self
            .horizontal
            .iter()
            .map(|s| s.to_skrifa(&baseline_tags))
            .collect::<Result<Vec<_>, _>>()?;
        let mut vertical_scripts: Vec<write_base::BaseScriptRecord> = self
            .vertical
            .iter()
            .map(|s| s.to_skrifa(&baseline_tags))
            .collect::<Result<Vec<_>, _>>()?;
        horizontal_scripts.sort_by_key(|r| r.base_script_tag);
        vertical_scripts.sort_by_key(|r| r.base_script_tag);

        let horizontal_axis = if !horizontal_scripts.is_empty() {
            Some(write_base::Axis::new(
                Some(write_base::BaseTagList::new(baseline_tags.clone())),
                write_base::BaseScriptList::new(horizontal_scripts),
            ))
        } else {
            None
        };
        let vertical_axis = if !vertical_scripts.is_empty() {
            Some(write_base::Axis::new(
                Some(write_base::BaseTagList::new(baseline_tags)),
                write_base::BaseScriptList::new(vertical_scripts),
            ))
        } else {
            None
        };

        Ok(write_base::Base::new(horizontal_axis, vertical_axis))
    }

    /// Export the BASE table to AFDKO feature syntax.
    pub fn to_fea(&self) -> String {
        let mut fea = "table BASE {\n".to_string();
        for (axis, scripts) in [
            ("HorizAxis", &self.horizontal),
            (" VertAxis", &self.vertical),
        ] {
            if scripts.is_empty() {
                continue;
            }
            // gather all baseline tags
            let mut baseline_tags: BTreeSet<Tag> = BTreeSet::new();
            for script in scripts.iter() {
                if let Some(def) = script.default_baseline {
                    baseline_tags.insert(def);
                }
                for lang in script.baselines.keys() {
                    baseline_tags.insert(*lang);
                }
            }
            let baseline_tags: Vec<Tag> = baseline_tags.into_iter().collect();

            // HorizAxis.BaseTagList <baseline tag>+;
            if !baseline_tags.is_empty() {
                fea.push_str(&format!(
                    " {}.BaseTagList      {};\n",
                    axis,
                    baseline_tags.iter().map(|x| x.to_string()).join(" ")
                ));

                // HorizAxis.BaseScriptList <script record> (, <script record>)*;
                // <script tag> <default baseline tag> <base coord>+
                fea.push_str(&format!(" {}.BaseScriptList ", axis));
                for script_record in scripts.iter() {
                    fea.push_str(&format!(
                        "\n    {} {}               ",
                        script_record.script,
                        script_record
                            .default_baseline
                            .unwrap_or_else(|| Tag::new(b"romn"))
                    ));
                    for tag in baseline_tags.iter() {
                        if let Some(y) = script_record.baselines.get(tag) {
                            fea.push_str(&format!("{:>4} ", y));
                        } else {
                            fea.push_str("0 ");
                        }
                    }
                    fea.pop(); // remove last space
                    fea.push(','); // separate records with commas
                }
                fea.pop(); // remove last comma
                fea.push_str(";\n");
            }
            // HorizAxis.MinMax <minmax record>;
            for script_record in scripts.iter() {
                if let Some(mm) = script_record.default_minmax.as_ref() {
                    fea.push_str(&format!(
                        " {}.MinMax {} dflt {}, {};\n",
                        axis,
                        script_record.script,
                        mm.lowest
                            .map(|x| x.to_string())
                            .unwrap_or_else(|| "NULL".to_string()),
                        mm.highest
                            .map(|x| x.to_string())
                            .unwrap_or_else(|| "NULL".to_string())
                    ));
                    for (lang, coord) in script_record.languages.iter() {
                        fea.push_str(&format!(
                            " {}.MinMax {} {} {}, {};\n",
                            axis,
                            script_record.script,
                            lang,
                            coord
                                .lowest
                                .map(|x| x.to_string())
                                .unwrap_or_else(|| "NULL".to_string()),
                            coord
                                .highest
                                .map(|x| x.to_string())
                                .unwrap_or_else(|| "NULL".to_string())
                        ));
                    }
                }
            }
            fea.push('\n');
        }
        fea.pop();
        fea.push_str("} BASE;\n");
        fea
    }

    fn _axis_to_base_scripts(
        axis: &skrifa::raw::tables::base::Axis,
    ) -> Result<Vec<BaseScript>, AutobaseError> {
        let script_list = axis.base_script_list()?;
        let base_tag_list: Vec<Tag> = axis
            .base_tag_list()
            .transpose()?
            .map(|b| b.baseline_tags().iter().map(|x| x.get()).collect())
            .unwrap_or(vec![]);
        let mut base_scripts = vec![];
        for script_record in script_list.base_script_records() {
            let script_tag = script_record.base_script_tag();
            let base_script = script_record.base_script(script_list.offset_data())?;
            let default_minmax = base_script
                .default_min_max()
                .transpose()?
                .map(|mm| MinMax::from_skrifa(&mm))
                .transpose()?;
            let mut languages = BTreeMap::new();
            for langsys in base_script.base_lang_sys_records() {
                let lang_tag = langsys.base_lang_sys_tag();
                let min_max = langsys.min_max(base_script.offset_data())?;
                languages.insert(lang_tag, MinMax::from_skrifa(&min_max)?);
            }
            let mut baselines = BTreeMap::new();
            let mut default_baseline_index = 0;
            if let Some(base_values) = base_script.base_values().transpose()? {
                baselines = base_values
                    .base_coords()
                    .iter()
                    .flatten()
                    .enumerate()
                    .map(|(i, coord)| (base_tag_list[i], coord.coordinate()))
                    .collect();
                default_baseline_index = base_values.default_baseline_index() as usize;
            }
            base_scripts.push(BaseScript {
                script: script_tag,
                default_baseline: base_tag_list.get(default_baseline_index).cloned(),
                baselines,
                default_minmax,
                languages,
            });
        }
        Ok(base_scripts)
    }

    /// Create a BaseTable from a Skrifa Base representation read from a font.
    pub fn from_skrifa(base: &skrifa::raw::tables::base::Base) -> Result<Self, AutobaseError> {
        Ok(Self {
            horizontal: base
                .horiz_axis()
                .transpose()?
                .map_or(Ok(vec![]), |a| Self::_axis_to_base_scripts(&a))?,
            vertical: base
                .vert_axis()
                .transpose()?
                .map_or(Ok(vec![]), |a| Self::_axis_to_base_scripts(&a))?,
        })
    }

    /// Create a new BASE table
    pub fn new(horizontal: Vec<BaseScript>, vertical: Vec<BaseScript>) -> Self {
        Self {
            horizontal,
            vertical,
        }
    }

    /// Add the BASE table to a binary font, returning the new binary data.
    pub fn add_to_binary(&self, font: &FontRef) -> Result<Vec<u8>, AutobaseError> {
        let mut new_font = FontBuilder::new();
        new_font.add_table(&self.to_skrifa()?)?;
        new_font.copy_missing_tables(font.clone());
        let binary = new_font.build();
        Ok(binary)
    }

    pub fn merge(&mut self, other: &BaseTable, tolerance: Option<u16>) {
        for (my_axis, their_axis) in [
            (&mut self.horizontal, &other.horizontal),
            (&mut self.vertical, &other.vertical),
        ] {
            // For each script in other, see if we have it already
            for script in their_axis.iter() {
                // Find a matching script in self
                if let Some(my_script) = my_axis.iter().find(|s| s.script == script.script) {
                    my_script.merge(script, tolerance);
                } else {
                    my_axis.push(script.clone());
                }
            }
        }
    }

    pub fn simplify(&mut self, tolerance: Option<u16>) {
        for script in self.horizontal.iter_mut().chain(self.vertical.iter_mut()) {
            script.simplify(tolerance);
        }
    }
}