fontmerge 0.2.1

Merge two font source files, copying glyphs and OpenType layout features from one font to another
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
use std::{collections::HashSet, fmt::Display};

use babelfont::{BabelfontError, DesignCoord, Font, Tag};
use fontdrasil::coords::{DesignSpace, Location};
use itertools::Itertools;

use crate::error::FontmergeError;

pub(crate) fn fontdrasil_axes(
    axes: &[babelfont::Axis],
) -> Result<fontdrasil::types::Axes, FontmergeError> {
    let axes = axes
        .iter()
        .map(|ax| ax.clone().try_into())
        .collect::<Result<Vec<fontdrasil::types::Axis>, _>>()
        .map_err(|e: BabelfontError| FontmergeError::Font(format!("Axis conversion error: {}", e)));
    Ok(fontdrasil::types::Axes::new(axes?))
}

pub(crate) fn convert_between_designspaces(
    loc: &Location<DesignSpace>,
    from_ds: &fontdrasil::types::Axes,
    to_ds: &fontdrasil::types::Axes,
    clamp_to_boundaries: bool,
) -> Result<(Location<DesignSpace>, bool), crate::error::FontmergeError> {
    let mut clamped = false;
    // First convert to userspace
    let mut user_loc = loc.to_user(from_ds)?;
    // Remove all axes which do not appear in the target DS
    user_loc.retain(|tag, _| to_ds.get(tag).is_some());
    // Fill all axes which appear in the target DS but not the source DS with their default value
    for axis in to_ds.iter() {
        if !user_loc.contains(axis.tag) {
            user_loc.insert(axis.tag, axis.default);
        }
        // If we are outside the bounds of this axis, clamp if requested
        if clamp_to_boundaries && let Some(value) = user_loc.get(axis.tag) {
            if value < axis.min {
                user_loc.insert(axis.tag, axis.min);
                clamped = true;
            } else if value > axis.max {
                user_loc.insert(axis.tag, axis.max);
                clamped = true;
            }
        }
    }
    // And convert to designspace of target DS
    Ok((user_loc.to_design(to_ds)?, clamped))
}

pub(crate) fn within_bounds(
    axes: &fontdrasil::types::Axes,
    loc: &fontdrasil::coords::Location<DesignSpace>,
) -> bool {
    for axis in axes.iter() {
        if let Some(value) = loc.get(axis.tag)
            && (value < axis.min.to_design(&axis.converter)
                || value > axis.max.to_design(&axis.converter))
        {
            log::trace!(
                "Location {:?} out of bounds on axis '{}': {} not in [{}, {}]",
                loc,
                axis.tag,
                value.to_f64(),
                axis.min.to_f64(),
                axis.max.to_f64()
            );
            return false;
        }
    }
    true
}

pub enum Strategy {
    Exact {
        layer: String,
        master_name: String,
        clamped: bool,
    },
    InterpolateOrIntermediate {
        location: Location<DesignSpace>,
        clamped: bool,
    },
    #[allow(dead_code)]
    Failed(String),
}

impl Display for Strategy {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Strategy::Exact {
                layer,
                master_name,
                clamped,
            } => write!(
                f,
                "use font 2's layer '{}' from master {} {}",
                layer,
                master_name,
                if *clamped { " (clamped)" } else { "" }
            ),
            Strategy::InterpolateOrIntermediate { location, clamped } => write!(
                f,
                "interpolate at location {:?} (or try an intermediate layer){}",
                location,
                if *clamped { " (clamped)" } else { "" }
            ),
            Strategy::Failed(reason) => write!(f, "give up: {}", reason),
        }
    }
}

pub(crate) fn map_designspaces(
    font1: &babelfont::Font,
    f1_nonsparse_master_ids: &[String],
    font2: &babelfont::Font,
) -> Result<Vec<Strategy>, FontmergeError> {
    let ds1 = fontdrasil_axes(&font1.axes)?;
    let ds2 = fontdrasil_axes(&font2.axes)?;
    let mut results = vec![];

    let f1_axes_not_in_f2 = font1
        .axes
        .iter()
        .filter(|a1| !font2.axes.iter().any(|a2| a2.tag == a1.tag))
        .collect::<Vec<&babelfont::Axis>>();
    if !f1_axes_not_in_f2.is_empty() {
        log::warn!(
            "Font 1 has axes not present in Font 2: {}. These will be ignored when matching masters, and no variation will be present on these glyphs.",
            f1_axes_not_in_f2
                .iter()
                .map(|a| a.tag.to_string())
                .collect::<Vec<String>>()
                .join(", ")
        );
    }
    let f2_axes_not_in_f1 = font2
        .axes
        .iter()
        .filter(|a2| !font1.axes.iter().any(|a1| a1.tag == a2.tag))
        .collect::<Vec<&babelfont::Axis>>();
    if !f2_axes_not_in_f1.is_empty() {
        log::warn!(
            "Font 2 has axes not present in Font 1: {}. These will be ignored when matching masters; the default location will be used.",
            f2_axes_not_in_f1
                .iter()
                .map(|a| a.tag.to_string())
                .collect::<Vec<String>>()
                .join(", ")
        );
    }

    // For each non-sparse master in font1, we need to find something in font2 at that location
    for master_id in f1_nonsparse_master_ids.iter() {
        #[allow(clippy::unwrap_used)]
        // We know these masters are in font1 because that's where we got the IDs from
        let master = font1.masters.iter().find(|m| &m.id == master_id).unwrap();

        // What would it be in font2's designspace?
        let (loc2, clamped) = convert_between_designspaces(&master.location, &ds1, &ds2, true)?;
        log::trace!(
            "Looking for a match for font1 master '{}' at location {:?} in font2's designspace",
            master.name.get_default().unwrap_or(&master.id),
            loc2
        );

        if let Some(exact) = font2.masters.iter().find(|m| m.location == loc2) {
            #[allow(clippy::unwrap_used)] // We found it
            let master_name = font2
                .masters
                .iter()
                .find(|m| m.id == exact.id)
                .unwrap()
                .name
                .get_default()
                .unwrap_or(&exact.id)
                .to_string();
            results.push(Strategy::Exact {
                layer: exact.id.clone(),
                master_name,
                clamped,
            });
            continue;
        }
        // No exact match. If this location is strictly within the designspace bounds of font2, we can interpolate
        log::trace!(
            "No exact match found for font1 master '{}' at location {:?}, checking for interpolation",
            master.id,
            loc2
        );
        results.push(Strategy::InterpolateOrIntermediate {
            location: loc2,
            clamped,
        });
    }
    Ok(results)
}

pub(crate) fn add_needed_masters(
    font1: &mut babelfont::Font,
    font2: &mut babelfont::Font,
    process_avar_mapping: bool,
) -> Result<(), FontmergeError> {
    let ds1 = fontdrasil_axes(&font1.axes)?;
    let ds2 = fontdrasil_axes(&font2.axes)?;

    assert!(
        sanity_check(font1),
        "Font failed sanity check *before* adding needed masters, file was insane"
    );

    // If there are axis mappings in font2 that don't exist in font1 we need to
    // make intermediate masters for them in font2! This may get messy.
    let mut intermediate_mappings: Vec<(Tag, &DesignCoord)> = vec![];
    for f2_axis in font2.axes.iter() {
        let Some(f1_axis) = font1.axes.iter().find(|a| a.tag == f2_axis.tag) else {
            continue;
        };
        let Some(f2_map) = f2_axis.map.as_ref() else {
            continue;
        };
        for (user, design) in f2_map.iter() {
            if f1_axis.userspace_to_designspace(*user)? != *design && process_avar_mapping {
                // If the problem is at the min or max, ignore it, we're mapping those already
                #[allow(clippy::unwrap_used)]
                // We know these are Some() because we converted to fontdrasil previously
                if (user.to_f64() - f2_axis.min.unwrap().to_f64()).abs() < f64::EPSILON
                    || (user.to_f64() - f2_axis.max.unwrap().to_f64()).abs() < f64::EPSILON
                {
                    continue;
                }
                intermediate_mappings.push((f2_axis.tag, design));
            }
        }
    }
    let mut already_added = font2
        .masters
        .iter()
        .filter(|m| !m.is_sparse(font2))
        .map(|m| m.location.clone())
        .collect::<HashSet<_>>();
    // Masters which we create here purely to reproduce font 2's avar mapping. They exist
    // so that we can interpolate layers at these locations, but they must *not* be added to
    // font 1 as masters; instead their layers are re-homed as intermediate (associated)
    // layers during glyph merging.
    let mut avar_intermediate_master_ids: HashSet<String> = HashSet::new();
    for (tag, design) in intermediate_mappings {
        log::warn!(
            "Adding intermediate masters to font 2 for axis '{}' at design value {} to satisfy avar table change",
            tag,
            design.to_f64()
        );
        // I *think* we need to add a master for *each master* in font2 already
        let new_masters = font2
            .masters
            .iter()
            .filter(|m| !m.is_sparse(font2))
            .filter_map(|m| {
                let mut new_m = m.clone();
                // A clone shares its source's ID, but masters must have unique IDs: the
                // interpolated layers we create below are associated with the new master by
                // ID, and reusing an existing ID would make them resolve to the wrong master
                // (and make the source master look like an avar intermediate).
                new_m.id = uuid::Uuid::new_v4().to_string();
                new_m.location.insert(tag, *design);
                // Only add if we don't already have one at this location
                if already_added.contains(&new_m.location) {
                    log::debug!(" Already have master at {:?}", new_m.location);
                    return None;
                }
                log::debug!(" Adding intermediate master at {:?}", new_m.location);
                already_added.insert(new_m.location.clone());
                Some(new_m)
            })
            .collect::<Vec<_>>();
        // Interpolate!
        let mut new_layer_list = Vec::new();
        for new_master in new_masters.iter() {
            for glyph in font2.glyphs.iter() {
                let mut new_layer = font2.interpolate_glyph(&glyph.name, &new_master.location)?;
                new_layer.master = babelfont::LayerType::DefaultForMaster(new_master.id.clone());
                new_layer_list.push((glyph.name.clone(), new_layer));
            }
        }
        // Insert new layers
        for (glyph_name, new_layer) in new_layer_list.into_iter() {
            if let Some(glyph) = font2.glyphs.iter_mut().find(|g| g.name == glyph_name) {
                glyph.layers.push(new_layer);
            }
        }

        for new_master in new_masters.iter() {
            avar_intermediate_master_ids.insert(new_master.id.clone());
        }
        font2.masters.extend(new_masters);
    }
    log::debug!(
        "font2 master situation now: {}",
        font2
            .masters
            .iter()
            .map(|m| format!(
                "'{}' at {:?} {}",
                m.name.get_default().unwrap_or(&m.id),
                m.location,
                if m.is_sparse(font2) { "(sparse)" } else { "" }
            ))
            .collect::<Vec<String>>()
            .join(", ")
    );

    for f2_master in font2.masters.iter() {
        if f2_master.is_sparse(font2) {
            continue;
        } // Well thank goodness for that

        // Avar intermediate masters are deliberately *not* added to font 1 as masters. Their
        // interpolated layers are carried across during glyph merging and added to the merged
        // glyphs as intermediate layers associated with the nearest real master, which avoids
        // forcing every existing host glyph to have a layer at this location.
        if avar_intermediate_master_ids.contains(&f2_master.id) {
            log::debug!(
                "Not adding avar intermediate master '{}' at location {:?} to font 1 as a master; its layers will be added as intermediate layers instead",
                f2_master.name.get_default().unwrap_or(&f2_master.id),
                f2_master.location
            );
            continue;
        }

        // if this is non-default for an axis we don't have in f1, ignore it
        #[allow(clippy::unwrap_used)] // We know these axes are in ds2
        if f2_master
            .location
            .to_user(&ds2)?
            .iter()
            .any(|(tag, value)| ds1.get(tag).is_none() && ds2.get(tag).unwrap().default != *value)
        {
            log::debug!(
                "Skipping font 2 master '{}' at location {:?} because it has non-default values on axes not in font 1",
                f2_master.name.get_default().unwrap_or(&f2_master.id),
                f2_master.location.to_user(&ds2)
            );
            continue;
        }

        // Convert f2 master's location to userspace and then to f1's design space
        let (loc1_design, clamped) =
            convert_between_designspaces(&f2_master.location, &ds2, &ds1, true)?;
        if clamped {
            log::warn!(
                "Font 2 master '{}' at location {:?} is out of bounds for Font 1's designspace; skipping addition",
                f2_master.name.get_default().unwrap_or(&f2_master.id),
                f2_master.location
            );
            continue;
        }
        // AAARGH - if this includes any axes we don't have in font2, we need to add masters at min, max *and* default for those axes
        // Cartesian product time!
        let new_axes = ds1
            .iter()
            .filter(|a1| !ds2.iter().any(|a2| a2.tag == a1.tag))
            .map(|a| vec![(a.tag, a.min), (a.tag, a.default), (a.tag, a.max)]);
        let mut locations_to_add = vec![];
        for new_locs in new_axes.multi_cartesian_product() {
            let mut loc = loc1_design.to_user(&ds1)?;
            for (tag, value) in new_locs.iter() {
                loc.insert(*tag, *value);
            }
            locations_to_add.push(loc.to_design(&ds1)?);
        }
        for loc1_design in locations_to_add.into_iter() {
            // Do we have one already?
            if font1.masters.iter().any(|m| m.location == loc1_design) {
                continue;
            }
            let user_location = loc1_design.to_user(&ds1)?;
            let master_name = user_location
                .iter()
                .map(|(tag, value)| format!("{}={}", tag, value.to_f64()))
                .join(", ");
            let master = babelfont::Master::new(
                master_name.clone(),
                uuid::Uuid::new_v4().to_string(),
                loc1_design.clone(),
            );
            log::info!(
                "Added new master '{}' at location {:?} (font2 location {:?}) to font 1",
                master_name,
                user_location,
                f2_master.location
            );
            font1.masters.push(master);
        }
    }

    assert!(
        sanity_check(font1),
        "Font failed sanity check after adding needed masters"
    );

    Ok(())
}

/// Find the ID of the master whose location is nearest to `location`.
///
/// Distance is measured as a Euclidean distance in user (rather than design) coordinates,
/// so that an axis mapping (avar) does not distort the result.
pub(crate) fn nearest_master_id(
    masters: &[babelfont::Master],
    axes: &fontdrasil::types::Axes,
    location: &Location<DesignSpace>,
) -> Option<String> {
    let target = location.to_user(axes).ok()?;
    let mut best: Option<(f64, String)> = None;
    for master in masters.iter() {
        let Ok(master_user) = master.location.to_user(axes) else {
            continue;
        };
        let mut distance = 0.0f64;
        for axis in axes.iter() {
            let Some(target_value) = target.get(axis.tag) else {
                continue;
            };
            let master_value = master_user.get(axis.tag).unwrap_or(target_value);
            let delta = target_value.to_f64() - master_value.to_f64();
            distance += delta * delta;
        }
        if best
            .as_ref()
            .is_none_or(|(best_distance, _)| distance < *best_distance)
        {
            best = Some((distance, master.id.clone()));
        }
    }
    best.map(|(_, id)| id)
}

pub(crate) fn sanity_check(font: &Font) -> bool {
    // Check master locations are distinct
    let mut ok = true;
    let mut seen_locations = HashSet::new();
    for master in font.masters.iter() {
        if seen_locations.contains(&master.location) {
            log::error!(
                "Sanity check: master '{}' has the same location {:?} as another master",
                master.name.get_default().unwrap_or(&master.id),
                master.location
            );
            ok = false;
        } else {
            seen_locations.insert(master.location.clone());
        }
    }
    for glyph in font.glyphs.iter() {
        // Check that non-master layer locations do not duplicate master locations
        for layer in glyph.layers.iter() {
            if layer.is_background {
                continue;
            } // I don't care about background layers here
            if let Some(loc) = &layer.location
                && seen_locations.contains(loc)
            {
                log::error!(
                    "Sanity check: glyph '{}' has a non-master layer at location {:?} which duplicates a master location",
                    glyph.name,
                    loc
                );
                ok = false;
            }
        }
        // Check that glyphs only have one layer per master
        let layer_ids = glyph
            .layers
            .iter()
            .filter(|layer| !layer.is_background)
            .filter_map(|l| match &l.master {
                babelfont::LayerType::DefaultForMaster(id) => Some(id),
                babelfont::LayerType::AssociatedWithMaster(_) => None,
                babelfont::LayerType::FreeFloating => None,
            })
            .collect::<Vec<&String>>();
        let mut seen_layer_ids = HashSet::new();
        for id in layer_ids.iter() {
            if seen_layer_ids.contains(id) {
                log::error!(
                    "Sanity check: glyph '{}' has multiple layers for master ID '{}'",
                    glyph.name,
                    id
                );
                ok = false;
            } else {
                seen_layer_ids.insert(id);
            }
        }
    }

    ok
}