glyphslib 0.2.7

A Rust library for reading, writing, and manipulating Glyphs font source files
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
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
use std::collections::{BTreeMap, BTreeSet};

use crate::{
    common::Orientation,
    glyphs2,
    glyphs3::{self, Axis, LocalizedPropertyKey, Metric, MetricType, MetricValue, Property, Stem},
};

impl From<glyphs2::Node> for glyphs3::Node {
    fn from(val: glyphs2::Node) -> Self {
        glyphs3::Node {
            x: val.x,
            y: val.y,
            node_type: val.node_type,
            user_data: None,
        }
    }
}
impl From<glyphs2::Guide> for glyphs3::Guide {
    fn from(val: glyphs2::Guide) -> Self {
        glyphs3::Guide {
            orientation: val.alignment,
            angle: val.angle,
            locked: val.locked,
            pos: val.pos,
            size: val.scale,
            filter: val.filter,
            grid: val.grid,
            length: val.length,
            lock_angle: val.lock_angle,
            name: val.name,
            show_measurement: val.show_measurement,
            user_data: Some(val.user_data),
            ..Default::default()
        }
    }
}
impl From<glyphs2::Anchor> for glyphs3::Anchor {
    fn from(val: glyphs2::Anchor) -> Self {
        glyphs3::Anchor {
            pos: val.position,
            name: val.name,
            locked: false,
            orientation: Orientation::Left,
            user_data: None,
        }
    }
}
impl From<glyphs2::BackgroundImage> for glyphs3::BackgroundImage {
    fn from(val: glyphs2::BackgroundImage) -> Self {
        let decomposed = decompose(&val.transform);
        glyphs3::BackgroundImage {
            angle: decomposed.rotation.to_degrees(), // I think it's degrees?
            crop: Some((0.0, 0.0, 0.0, 0.0)),
            image_path: val.image_path,
            locked: val.locked,
            scale: decomposed.scale,
            pos: decomposed.translation,
        }
    }
}

struct DecomposedAffine {
    translation: (f32, f32),
    scale: (f32, f32),
    rotation: f32,
    // I don't care about skew
}

fn decompose(t: &glyphs2::Transform) -> DecomposedAffine {
    let delta = t.m11 * t.m22 - t.m12 * t.m21;
    let translation = (t.t_x, t.t_y);
    let (rotation, scale) = if t.m11 != 0.0 || t.m12 != 0.0 {
        let r = (t.m11 * t.m11 + t.m12 * t.m12).sqrt();
        let angle = if t.m12 > 0.0 {
            (t.m11 / r).acos()
        } else {
            -(t.m11 / r).acos()
        };
        (angle, (r, delta / r))
    } else if t.m21 != 0.0 || t.m22 != 0.0 {
        let s = (t.m21 * t.m21 + t.m22 * t.m22).sqrt();
        let angle = if t.m22 > 0.0 {
            (t.m22 / s).asin()
        } else {
            -(t.m22 / s).asin()
        };
        ((std::f32::consts::PI / 2.0) - angle, (delta / s, s))
    } else {
        (0.0, (0.0, 0.0))
    };
    DecomposedAffine {
        translation,
        scale,
        rotation,
    }
}

impl From<glyphs2::Layer> for glyphs3::Layer {
    fn from(val: glyphs2::Layer) -> Self {
        let attrs = BTreeMap::new();
        let shapes = val
            .components
            .into_iter()
            .map(Into::into)
            .map(glyphs3::Shape::Component)
            .chain(
                val.paths
                    .into_iter()
                    .map(Into::into)
                    .map(glyphs3::Shape::Path),
            )
            .collect();
        glyphs3::Layer {
            anchors: val.anchors.into_iter().map(Into::into).collect(),
            annotations: val.annotations,
            associated_master_id: val.associated_master_id,
            attr: attrs,
            background: val
                .background
                .map(|x| Box::new(std::convert::Into::<glyphs3::Layer>::into(*x))),
            background_image: val.background_image.map(Into::into),
            color: None,
            guides: val.guides.into_iter().map(Into::into).collect(),
            hints: vec![], // XXX Todo, one day
            layer_id: val.layer_id,
            metric_bottom: None,
            metric_left: val.metric_left,
            metric_right: val.metric_right,
            metric_top: None,
            metric_vert_width: None,
            metric_vert_origin: None,
            metric_width: val.metric_width,
            name: val.name,
            part_selection: BTreeMap::new(), // Maybe Glyphs2 smart component data is stored in user data?
            shapes,
            user_data: val.user_data,
            vert_origin: None,
            vert_width: val.vert_width,
            visible: val.visible,
            width: val.width,
        }
    }
}

impl From<glyphs2::Component> for glyphs3::Component {
    fn from(val: glyphs2::Component) -> Self {
        let decomposed = decompose(&val.transform);
        glyphs3::Component {
            alignment: val.alignment,
            anchor: val.anchor,
            angle: decomposed.rotation.to_degrees(),
            position: decomposed.translation,
            component_glyph: val.component_glyph,
            scale: decomposed.scale,
            locked: val.locked,
            smart_component_location: val.smart_component_location,
            user_data: val.user_data,
            ..Default::default()
        }
    }
}

impl From<glyphs2::Path> for glyphs3::Path {
    fn from(val: glyphs2::Path) -> Self {
        glyphs3::Path {
            closed: val.closed,
            nodes: val.nodes.into_iter().map(Into::into).collect(),
            attr: BTreeMap::new(),
        }
    }
}

impl From<glyphs2::Glyph> for glyphs3::Glyph {
    fn from(val: glyphs2::Glyph) -> Self {
        glyphs3::Glyph {
            name: val.name,
            production: val.production,
            script: val.script,
            category: val.category,
            color: val.color,
            export: val.export,
            kern_left: val.kern_left,
            kern_right: val.kern_right,
            kern_top: val.kern_top,
            kern_bottom: val.kern_bottom,
            last_change: val.last_change,
            layers: val.layers.into_iter().map(Into::into).collect(),
            metric_bottom: val.metric_bottom,
            metric_left: val.metric_left,
            metric_right: val.metric_right,
            metric_top: val.metric_top,
            metric_vert_width: val.metric_vert_width,
            metric_width: val.metric_width,
            note: val.note,
            smart_component_settings: val.smart_component_settings.into_iter().collect(),
            user_data: val.user_data,
            unicode: val.unicode,
            ..Default::default()
        }
    }
}

impl From<glyphs2::Glyphs2> for glyphs3::Glyphs3 {
    fn from(val: glyphs2::Glyphs2) -> Self {
        let axes = val.determine_axes();
        let properties = val.glyphs3_properties();
        let metrics = val.glyphs3_metrics();
        let stems = val.glyphs3_stems();
        let mut font = glyphs3::Glyphs3 {
            app_version: val.app_version,
            format_version: 3,
            display_strings: val.display_strings,
            axes: vec![], // Fix you later
            classes: val.classes,
            custom_parameters: val.custom_parameters,
            date: val.date,
            family_name: val.family_name,
            feature_prefixes: val.feature_prefixes,
            features: val.features,
            masters: val
                .masters
                .iter()
                .map(|x| x.to_glyphs3(&axes, &metrics, &stems))
                .collect(),
            glyphs: val.glyphs.into_iter().map(Into::into).collect(),
            instances: val.instances.iter().map(|x| x.to_glyphs3(&axes)).collect(),
            kerning: val.kerning,
            kerning_rtl: BTreeMap::new(),
            kerning_vertical: val.kerning_vertical,
            metrics,
            note: "".to_string(),
            numbers: vec![],
            properties,
            settings: glyphs3::Settings {
                disables_automatic_alignment: val.disables_automatic_alignment,
                disables_nice_names: val.disables_nice_names,
                grid_length: val.grid_length,
                grid_sub_division: val.grid_sub_division,
                keyboard_increment: val.keyboard_increment,
                keyboard_increment_big: val.keyboard_increment_big,
                keyboard_increment_huge: val.keyboard_increment_huge,
                keep_alternates_together: val.keep_alternates_together,
                ..Default::default()
            },
            stems,
            units_per_em: val.units_per_em,
            user_data: val.user_data,
            version: val.version,
        };
        font.axes = axes;
        font
    }
}

impl glyphs2::Master {
    fn axis_values(&self, num_axes: usize) -> Vec<i32> {
        match num_axes {
            0 => vec![self.weight_value],
            1 => vec![self.weight_value, self.width_value],
            2 => vec![self.weight_value, self.width_value, self.custom_value],
            3 => vec![
                self.weight_value,
                self.width_value,
                self.custom_value,
                self.custom_value_1,
            ],
            4 => vec![
                self.weight_value,
                self.width_value,
                self.custom_value,
                self.custom_value_1,
                self.custom_value_2,
            ],
            _ => vec![
                self.weight_value,
                self.width_value,
                self.custom_value,
                self.custom_value_1,
                self.custom_value_2,
                self.custom_value_3,
            ],
        }
    }

    fn to_glyphs3(&self, axes: &[Axis], metrics: &[Metric], _stems: &[Stem]) -> glyphs3::Master {
        let alignment_to_overshoot: Vec<(f32, f32)> = self
            .alignment_zones
            .iter()
            .map(|z| (z.position, z.overshoot))
            .collect();
        let find_overshoot = |v| {
            alignment_to_overshoot
                .iter()
                .find(|(pos, _)| *pos == v)
                .map(|(_, over)| *over)
                .unwrap_or(0.0)
        };
        let metric_values = metrics
            .iter()
            .map(|m| match m.metric_type {
                Some(MetricType::Ascender) => MetricValue {
                    pos: self.ascender.unwrap_or_default(),
                    over: find_overshoot(self.ascender.unwrap_or_default()),
                },
                Some(MetricType::Baseline) => MetricValue {
                    pos: 0.0,
                    over: find_overshoot(0.0),
                },
                Some(MetricType::CapHeight) => MetricValue {
                    pos: self.cap_height.unwrap_or_default(),
                    over: find_overshoot(self.cap_height.unwrap_or_default()),
                },
                Some(MetricType::Descender) => MetricValue {
                    pos: self.descender.unwrap_or_default(),
                    over: find_overshoot(self.descender.unwrap_or_default()),
                },
                Some(MetricType::XHeight) => MetricValue {
                    pos: self.x_height.unwrap_or_default(),
                    over: find_overshoot(self.x_height.unwrap_or_default()),
                },
                _ => panic!("Can't happen"),
            })
            .collect();

        let mut name_particles = vec![];
        let axis_tags: BTreeSet<&str> = axes.iter().map(|a| a.tag.as_str()).collect();
        if axis_tags.contains("wght") && self.weight != "Regular" {
            name_particles.push(self.weight.as_str());
        }
        if axis_tags.contains("wdth") && self.width != "Regular" {
            name_particles.push(self.width.as_str());
        }
        if let Some(custom) = self.custom.as_ref() {
            name_particles.push(custom.as_str());
        }
        let name = if name_particles.is_empty() {
            "Regular".to_string()
        } else {
            name_particles.join(" ")
        };
        glyphs3::Master {
            id: self.id.clone(),
            user_data: self.user_data.clone(),
            axes_values: self
                .axis_values(axes.len())
                .iter()
                .copied()
                .map(|x| x as f32)
                .collect(),
            custom_parameters: self.custom_parameters.clone(),
            guides: self.guides.iter().cloned().map(Into::into).collect(),
            icon_name: self.icon_name.clone(),
            metric_values,
            name,
            number_values: vec![],
            properties: vec![], // XXX - maybe some custom parameters?
            stem_values: self
                .horizontal_stems
                .iter()
                .chain(self.vertical_stems.iter())
                .copied()
                .map(|x| x as f32)
                .collect(),
            visible: self.visible,
            ..Default::default()
        }
    }
}

impl glyphs2::Glyphs2 {
    fn determine_axes(&self) -> Vec<glyphs3::Axis> {
        // If we have an Axes custom parameter, start with that.
        if let Some(axes_param) = self.custom_parameters.iter().find(|x| x.name == "Axes") {
            if let Some(axes_cp) = axes_param.value.as_array() {
                let axes = axes_cp
                    .iter()
                    .flat_map(|x| x.as_dict())
                    .map(|d| glyphs3::Axis {
                        name: d
                            .get("Name")
                            .and_then(|x| x.as_str())
                            .unwrap_or_default()
                            .to_string(),
                        tag: d
                            .get("Tag")
                            .and_then(|x| x.as_str())
                            .unwrap_or_default()
                            .to_string(),
                        hidden: d.contains_key("Hidden"),
                    })
                    .collect::<Vec<_>>();
                return axes;
            }
        }
        // Else we only have one or two "default" axes (weight/width/both); work it out the hard way
        let mut axes = vec![];
        let weight_values: Vec<i32> = self.masters.iter().map(|x| x.weight_value).collect();
        let (weight_min, weight_max) = (
            weight_values.iter().copied().min().unwrap_or(100),
            weight_values.iter().copied().max().unwrap_or(100),
        );
        if weight_min != weight_max {
            axes.push(glyphs3::Axis {
                name: "Weight".to_string(),
                tag: "wght".to_string(),
                hidden: false,
            });
        }
        let width_values: Vec<i32> = self.masters.iter().map(|x| x.width_value).collect();
        let (width_min, width_max) = (
            width_values.iter().copied().min().unwrap_or(100),
            width_values.iter().copied().max().unwrap_or(100),
        );
        if width_min != width_max {
            axes.push(glyphs3::Axis {
                name: "Width".to_string(),
                tag: "wdth".to_string(),
                hidden: false,
            });
        }
        axes
    }

    fn glyphs3_properties(&self) -> Vec<Property> {
        let mut properties = vec![];
        if let Some(copyright) = self.copyright.as_ref() {
            properties.push(Property::localized_with_default(
                LocalizedPropertyKey::Copyrights,
                copyright.clone(),
            ));
        }
        if let Some(designer) = self.designer.as_ref() {
            properties.push(Property::localized_with_default(
                LocalizedPropertyKey::Designers,
                designer.clone(),
            ));
        }
        if let Some(design_url) = self.designer_url.as_ref() {
            properties.push(Property::singular(
                glyphs3::SingularPropertyKey::DesignerUrl,
                design_url.clone(),
            ))
        }
        if let Some(manufacturer) = self.manufacturer.as_ref() {
            properties.push(Property::localized_with_default(
                LocalizedPropertyKey::Manufacturers,
                manufacturer.clone(),
            ));
        }
        if let Some(manufacturer_url) = self.manufacturer_url.as_ref() {
            properties.push(Property::singular(
                glyphs3::SingularPropertyKey::ManufacturerUrl,
                manufacturer_url.clone(),
            ))
        }
        properties
    }

    fn glyphs3_metrics(&self) -> Vec<Metric> {
        let mut metrics = vec![];
        if self.masters.iter().any(|m| m.ascender.is_some()) {
            metrics.push(Metric {
                name: "ascender".to_string(),
                filter: None,
                metric_type: Some(MetricType::Ascender),
            });
        }
        metrics.push(Metric {
            name: "baseline".to_string(),
            filter: None,
            metric_type: Some(MetricType::Baseline),
        });
        if self.masters.iter().any(|m| m.cap_height.is_some()) {
            metrics.push(Metric {
                name: "capHeight".to_string(),
                filter: None,
                metric_type: Some(MetricType::CapHeight),
            });
        }
        if self.masters.iter().any(|m| m.descender.is_some()) {
            metrics.push(Metric {
                name: "descender".to_string(),
                filter: None,
                metric_type: Some(MetricType::Descender),
            });
        }
        if self.masters.iter().any(|m| m.x_height.is_some()) {
            metrics.push(Metric {
                name: "xHeight".to_string(),
                filter: None,
                metric_type: Some(MetricType::XHeight),
            });
        }
        metrics
    }

    fn glyphs3_stems(&self) -> Vec<glyphs3::Stem> {
        let mut stems = vec![];
        let h_count = self
            .masters
            .iter()
            .map(|m| m.horizontal_stems.len())
            .max()
            .unwrap_or(0);
        for i in 0..h_count {
            stems.push(glyphs3::Stem {
                horizontal: true,
                name: format!("H-Stem {}", i + 1),
            });
        }
        let v_count = self
            .masters
            .iter()
            .map(|m| m.vertical_stems.len())
            .max()
            .unwrap_or(0);
        for i in 0..v_count {
            stems.push(glyphs3::Stem {
                horizontal: false,
                name: format!("V-Stem {}", i + 1),
            });
        }
        stems
    }
}

impl glyphs2::Instance {
    fn axis_values(&self, axes: &[Axis]) -> Vec<f32> {
        if let Some(cp) = self
            .custom_parameters
            .iter()
            .find(|x| x.name == "Axis Location")
            .and_then(|x| x.value.as_array())
        {
            let location = cp
                .iter()
                .flat_map(|x| x.as_dict())
                .filter_map(|d| {
                    let name = d.get("Axis")?.as_str()?;
                    // Sometimes it's a string. :-/
                    let loc = d.get("Location")?;
                    if let Some(loc_str) = loc.as_str() {
                        if let Ok(loc_num) = loc_str.parse::<f32>() {
                            return Some((name, loc_num));
                        }
                    }
                    let value = loc.as_f64()? as f32;
                    Some((name, value))
                })
                .collect::<BTreeMap<_, _>>();
            // 0.0 here looks bad. If we have an incomplete location, we should probably
            // fill it with the default for that axis, but we don't know what the default is yet.
            let location = axes
                .iter()
                .map(|a| location.get(a.name.as_str()).copied().unwrap_or(0.0))
                .collect::<Vec<_>>();
            return location;
        }
        let num_axes = axes.len();
        match num_axes {
            0 => vec![self.weight_value],
            1 => vec![self.weight_value, self.width_value],
            2 => vec![self.weight_value, self.width_value, self.custom_value],
            3 => vec![
                self.weight_value,
                self.width_value,
                self.custom_value,
                self.custom_value_1,
            ],
            4 => vec![
                self.weight_value,
                self.width_value,
                self.custom_value,
                self.custom_value_1,
                self.custom_value_2,
            ],
            _ => vec![
                self.weight_value,
                self.width_value,
                self.custom_value,
                self.custom_value_1,
                self.custom_value_2,
                self.custom_value_3,
            ],
        }
    }

    fn to_glyphs3(&self, axes: &[Axis]) -> glyphs3::Instance {
        let weight_value = match self.weight_class.as_deref() {
            Some("Thin") => Some(100),
            Some("ExtraLight") => Some(200),
            Some("Light") => Some(300),
            Some("Regular") => Some(400),
            Some("Medium") => Some(500),
            Some("SemiBold") => Some(600),
            Some("Bold") => Some(700),
            Some("ExtraBold") => Some(800),
            Some("Black") => Some(900),
            _ => None,
        };
        let width_value = match self.width_class.as_deref() {
            Some("Ultra Condensed") => Some(1),
            Some("Extra Condensed") => Some(2),
            Some("Condensed") => Some(3),
            Some("Semi Condensed") => Some(4),
            Some("Regular") => Some(5),
            Some("Medium") => Some(5),
            Some("Medium (normal)") => Some(5),
            Some("Semi Expanded") => Some(6),
            Some("Expanded") => Some(7),
            Some("Extra Expanded") => Some(8),
            Some("Ultra Expanded") => Some(9),
            _ => None,
        };
        glyphs3::Instance {
            axes_values: self.axis_values(axes),
            custom_parameters: self.custom_parameters.clone(),
            exports: self.exports,
            is_bold: self.is_bold,
            is_italic: self.is_italic,
            link_style: self.link_style.clone(),
            name: self.name.clone(),
            properties: vec![],
            user_data: self.user_data.clone(),
            weight_class: weight_value,
            width_class: width_value,
            ..Default::default()
        }
    }
}