babelfont 0.1.1-pre

A universal font format converter and processor
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
use crate::{
    anchor::Anchor,
    common::{Color, FormatSpecific},
    guide::Guide,
    shape::Shape,
    BabelfontError, Component, Font, Node, Path,
};
use fontdrasil::coords::DesignLocation;
use kurbo::Shape as KurboShape;
use serde::{Deserialize, Serialize};

#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
#[cfg_attr(feature = "typescript", derive(typescript_type_def::TypeDef))]
/// The type of a layer in relation to masters
pub enum LayerType {
    /// A default layer for a master
    DefaultForMaster(String),
    /// A layer associated with a master but not the default
    AssociatedWithMaster(String),
    /// A free-floating layer not associated with any master
    #[default]
    FreeFloating,
}
impl LayerType {
    fn is_default(&self) -> bool {
        matches!(self, LayerType::FreeFloating)
    }
}

#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[cfg_attr(feature = "typescript", derive(typescript_type_def::TypeDef))]
/// A layer of a glyph in a font
pub struct Layer {
    /// The advance width of the layer
    pub width: f32,
    /// The name of the layer
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub name: Option<String>,
    /// The ID of the layer
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub id: Option<String>,
    /// The relationship between this layer and a master, if any
    #[serde(default, skip_serializing_if = "LayerType::is_default")]
    pub master: LayerType,
    /// Guidelines in the layer
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub guides: Vec<Guide>,
    /// Shapes (paths and components) in the layer
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub shapes: Vec<Shape>,
    /// Anchors in the layer
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub anchors: Vec<Anchor>,
    /// The color of the layer
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub color: Option<Color>,
    /// The index of the layer in a color font
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub layer_index: Option<i32>,
    /// Whether this layer is a background layer
    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
    pub is_background: bool,
    /// The ID of the background layer for this layer, if any
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub background_layer_id: Option<String>,
    #[serde(
        default,
        skip_serializing_if = "Option::is_none",
        serialize_with = "crate::serde_helpers::option_design_location_to_map",
        deserialize_with = "crate::serde_helpers::option_design_location_from_map"
    )]
    #[cfg_attr(
        feature = "typescript",
        type_def(type_of = "Option<std::collections::HashMap<String, f32>>")
    )]
    /// The location of the layer in design space, if it is not at the default location for a master
    pub location: Option<DesignLocation>,
    #[serde(default, skip_serializing_if = "FormatSpecific::is_empty")]
    /// Format-specific data for the layer
    pub format_specific: FormatSpecific,
}

impl Layer {
    /// Create a new layer with the given advance width
    pub fn new(width: f32) -> Layer {
        Layer {
            width,
            ..Default::default()
        }
    }

    /// Iterate over the components in the layer
    pub fn components(&self) -> impl DoubleEndedIterator<Item = &Component> {
        self.shapes.iter().filter_map(|x| {
            if let Shape::Component(c) = x {
                Some(c)
            } else {
                None
            }
        })
    }

    /// Iterate over the paths in the layer
    pub fn paths(&self) -> impl DoubleEndedIterator<Item = &Path> {
        self.shapes.iter().filter_map(|x| {
            if let Shape::Path(p) = x {
                Some(p)
            } else {
                None
            }
        })
    }

    /// Clear all components from the layer
    pub fn clear_components(&mut self) {
        self.shapes.retain(|sh| matches!(sh, Shape::Path(_)));
    }

    /// Add a component to the layer
    pub fn push_component(&mut self, c: Component) {
        self.shapes.push(Shape::Component(c))
    }
    /// Add a path to the layer
    pub fn push_path(&mut self, p: Path) {
        self.shapes.push(Shape::Path(p))
    }

    /// Check if the layer has any components
    pub fn has_components(&self) -> bool {
        self.shapes
            .iter()
            .any(|sh| matches!(sh, Shape::Component(_)))
    }

    /// Check if the layer has any paths
    pub fn has_paths(&self) -> bool {
        self.shapes.iter().any(|sh| matches!(sh, Shape::Path(_)))
    }

    /// Decompose all components in the layer, replacing them with their decomposed paths
    pub fn decompose(&mut self, font: &Font) {
        let decomposed_shapes = self
            .decomposed_components(font)
            .into_iter()
            .map(Shape::Path);
        self.shapes.retain(|sh| matches!(sh, Shape::Path(_)));
        self.shapes.extend(decomposed_shapes);
    }

    /// Return a new layer with all components decomposed into paths
    pub fn decomposed(&self, font: &Font) -> Layer {
        let decomposed_shapes = self
            .decomposed_components(font)
            .into_iter()
            .map(Shape::Path);
        Layer {
            width: self.width,
            name: self.name.clone(),
            id: self.id.clone(),
            master: self.master.clone(),
            guides: self.guides.clone(),
            anchors: self.anchors.clone(),
            color: self.color,
            layer_index: self.layer_index,
            is_background: self.is_background,
            background_layer_id: self.background_layer_id.clone(),
            location: self.location.clone(),
            shapes: self
                .shapes
                .iter()
                .filter(|sh| matches!(sh, Shape::Path(_)))
                .cloned()
                .chain(decomposed_shapes)
                .collect(),
            format_specific: self.format_specific.clone(),
        }
    }

    /// Return a vector of decomposed paths from all components in the layer
    pub fn decomposed_components(&self, font: &Font) -> Vec<Path> {
        let mut contours = Vec::new();

        let mut stack: Vec<(&Component, kurbo::Affine)> = Vec::new();
        for component in self.components() {
            stack.push((component, component.transform));
            while let Some((component, transform)) = stack.pop() {
                let referenced_glyph = match font.glyphs.get(&component.reference) {
                    Some(g) => g,
                    None => continue,
                };
                let new_outline = match self
                    .id
                    .as_ref()
                    .and_then(|id| referenced_glyph.get_layer(id))
                {
                    Some(g) => g,
                    None => continue,
                };

                for contour in new_outline.paths() {
                    let mut decomposed_contour = Path::default();
                    for node in &contour.nodes {
                        let new_point = transform * kurbo::Point::new(node.x, node.y);
                        decomposed_contour.nodes.push(Node {
                            x: new_point.x,
                            y: new_point.y,
                            nodetype: node.nodetype,
                            smooth: node.smooth,
                        })
                    }
                    decomposed_contour.closed = contour.closed;
                    contours.push(decomposed_contour);
                }

                // Depth-first decomposition means we need to extend the stack reversed, so
                // the first component is taken out next.
                for new_component in new_outline.components().rev() {
                    let new_transform: kurbo::Affine = new_component.transform;
                    stack.push((new_component, transform * new_transform));
                }
            }
        }

        contours
    }

    /// Calculate the bounding box of the layer
    ///
    /// If the layer has components, an error is returned and the layer must be decomposed first
    pub fn bounds(&self) -> Result<crate::Rect, BabelfontError> {
        if self.has_components() {
            return Err(BabelfontError::NeedsDecomposition);
        }
        let paths: Result<Vec<kurbo::BezPath>, BabelfontError> =
            self.paths().map(|p| p.to_kurbo()).collect();
        let bbox: kurbo::Rect = paths?
            .iter()
            .map(|p| p.bounding_box())
            .reduce(|accum, item| accum.union(item))
            .unwrap_or_default();
        Ok(bbox)
    }

    /// Calculate the left side bearing of the layer
    ///
    /// If the layer has components, an error is returned and the layer must be decomposed first
    pub fn lsb(&self) -> Result<f32, BabelfontError> {
        let bounds: kurbo::Rect = self.bounds()?;
        Ok(bounds.min_x() as f32)
    }

    /// Calculate the right side bearing of the layer
    ///
    /// If the layer has components, an error is returned and the layer must be decomposed first
    pub fn rsb(&self) -> Result<f32, BabelfontError> {
        let bounds = self.bounds()?;
        Ok(self.width - bounds.max_x() as f32)
    }
}

#[cfg(feature = "glyphs")]
pub(crate) mod glyphs {
    use crate::convertors::glyphs3::copy_user_data;
    use std::collections::BTreeMap;

    use fontdrasil::types::Tag;
    use glyphslib::Plist;
    use smol_str::SmolStr;

    use crate::convertors::glyphs3::{
        UserData, KEY_ANNOTATIONS, KEY_LAYER_HINTS, KEY_LAYER_IMAGE, KEY_USER_DATA,
    };

    use super::*;

    impl From<&glyphslib::glyphs3::Layer> for Layer {
        fn from(val: &glyphslib::glyphs3::Layer) -> Self {
            let format_specific = {
                let mut fs = FormatSpecific::default();
                if !val.visible {
                    fs.insert("visible".into(), serde_json::Value::Bool(false));
                }
                if !val.hints.is_empty() {
                    fs.insert(
                        KEY_LAYER_HINTS.into(),
                        serde_json::to_value(&val.hints).unwrap_or(serde_json::Value::Null),
                    );
                }
                if !val.annotations.is_empty() {
                    fs.insert(
                        KEY_ANNOTATIONS.into(),
                        serde_json::to_value(&val.annotations).unwrap_or(serde_json::Value::Null),
                    );
                }
                if let Some(bg_image) = &val.background_image {
                    fs.insert(
                        KEY_LAYER_IMAGE.into(),
                        serde_json::to_value(bg_image).unwrap_or(serde_json::Value::Null),
                    );
                }
                copy_user_data(&mut fs, &val.user_data);
                fs
            };
            Layer {
                id: Some(val.layer_id.clone()),
                master: match &val.associated_master_id {
                    Some(m) => LayerType::AssociatedWithMaster(m.clone()),
                    None => LayerType::DefaultForMaster(val.layer_id.clone()),
                },
                name: val.name.clone(),
                color: None,
                shapes: val.shapes.iter().map(Into::into).collect(),
                width: val.width,
                guides: val.guides.iter().map(Into::into).collect(),
                anchors: val.anchors.iter().map(Into::into).collect(),
                layer_index: None,
                is_background: false,
                background_layer_id: None,
                location: None,
                format_specific,
            }
        }
    }

    pub(crate) fn layer_to_glyphs(val: &Layer, axes_order: &[Tag]) -> glyphslib::glyphs3::Layer {
        let mut attr: BTreeMap<SmolStr, _> = BTreeMap::new();
        if let Some(coords) = &val.location {
            attr.insert(
                "coordinates".into(),
                axes_order
                    .iter()
                    .map(|axis_tag| coords.get(*axis_tag).map(|x| x.to_f64()).unwrap_or(0.0))
                    .collect::<Vec<_>>()
                    .into(),
            );
        }
        glyphslib::glyphs3::Layer {
            layer_id: match val.master {
                LayerType::DefaultForMaster(ref m) => m.clone(),
                _ => val.id.clone().unwrap_or_default(),
            },
            name: val.name.clone(),
            width: val.width,
            shapes: val.shapes.iter().map(Into::into).collect(),
            guides: val.guides.iter().map(Into::into).collect(),
            anchors: val.anchors.iter().map(Into::into).collect(),
            annotations: val
                .format_specific
                .get(KEY_ANNOTATIONS)
                .and_then(|x| {
                    serde_json::from_value::<Vec<BTreeMap<SmolStr, Plist>>>(x.clone()).ok()
                })
                .unwrap_or_default(),
            associated_master_id: match val.master {
                LayerType::AssociatedWithMaster(ref m) => Some(m.clone()),
                _ => None,
            },
            attr,
            background: None,
            background_image: val
                .format_specific
                .get(KEY_LAYER_IMAGE)
                .map(|x| {
                    serde_json::from_value::<glyphslib::glyphs3::BackgroundImage>(x.clone()).ok()
                })
                .unwrap_or_default(),
            color: None,
            hints: val
                .format_specific
                .get(KEY_LAYER_HINTS)
                .and_then(|x| {
                    serde_json::from_value::<Vec<BTreeMap<SmolStr, Plist>>>(x.clone()).ok()
                })
                .unwrap_or_default(),
            metric_bottom: None,
            metric_left: None,
            metric_right: None,
            metric_top: None,
            metric_vert_width: None,
            metric_width: None,
            part_selection: BTreeMap::new(),
            user_data: val
                .format_specific
                .get(KEY_USER_DATA)
                .and_then(|x| serde_json::from_value::<UserData>(x.clone()).ok())
                .unwrap_or_default(),
            vert_origin: None,
            vert_width: None,
            visible: val
                .format_specific
                .get("visible")
                .and_then(|x| x.as_bool())
                .unwrap_or(true),
        }
    }
}

#[cfg(feature = "fontra")]
mod fontra {
    use super::*;
    use crate::convertors::fontra;

    impl From<&Layer> for fontra::Layer {
        fn from(val: &Layer) -> Self {
            let mut path = fontra::PackedPath::default();
            for p in val.paths() {
                path.push_path(p);
            }

            fontra::Layer {
                glyph: fontra::StaticGlyph {
                    path,
                    components: val.components().map(|c| c.into()).collect(),
                    x_advance: val.width,
                    y_advance: 0.0,
                    anchors: val.anchors.iter().map(|a| a.into()).collect(),
                    guides: vec![],
                },
            }
        }
    }
}