-
Notifications
You must be signed in to change notification settings - Fork 13
/
ir.rs
2525 lines (2251 loc) · 90 KB
/
ir.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
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
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! Font IR types.
use std::{
collections::{hash_map::RandomState, BTreeMap, BTreeSet, HashMap, HashSet},
fmt::{Debug, Display},
io::Read,
path::PathBuf,
};
use chrono::{DateTime, Utc};
use indexmap::IndexSet;
use kurbo::{Affine, BezPath, PathEl, Point};
use log::{log_enabled, trace, warn};
use ordered_float::OrderedFloat;
use serde::{de::Error as _, Deserialize, Serialize};
use smol_str::SmolStr;
use write_fonts::{
tables::{gdef::GlyphClassDef, os2::SelectionFlags},
types::{GlyphId16, NameId, Tag},
OtRound,
};
use fontdrasil::{
coords::{NormalizedCoord, NormalizedLocation, UserLocation},
types::{Axis, GlyphName},
};
use crate::{
error::{
BadAnchor, BadAnchorReason, BadGlyph, BadGlyphKind, PathConversionError,
VariationModelError,
},
orchestration::{IdAware, Persistable, WorkId},
variations::VariationModel,
};
pub const DEFAULT_VENDOR_ID: &str = "NONE";
const DEFAULT_VENDOR_ID_TAG: Tag = Tag::new(b"NONE");
/// Global font info that cannot vary across the design space.
///
/// For example, upem, axis definitions, etc, as distinct from
/// metadata that varies across design space such as ascender/descender.
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
pub struct StaticMetadata {
/// See <https://learn.microsoft.com/en-us/typography/opentype/spec/head>.
pub units_per_em: u16,
/// Every axis used by the font being compiled, including point axes.
///
/// This is relatively rarely what you want.
pub all_source_axes: Vec<Axis>,
/// Every variable (non-point) axis used by the font being compiled.
///
/// If empty this is a static font.
pub axes: Vec<Axis>,
/// Named locations in variation space
pub named_instances: Vec<NamedInstance>,
/// A model of how variation space is split into regions that have deltas.
///
/// This copy includes all locations used in the entire font. That is, every
/// location any glyph has an instance. Use of a location not in the global model
/// is an error. This model enforces the no delta at the default location constraint
/// used in things like gvar.
pub variation_model: VariationModel,
/// Glyphsapp only; named numbers defined per-master
pub number_values: HashMap<NormalizedLocation, BTreeMap<SmolStr, OrderedFloat<f64>>>,
default_location: NormalizedLocation,
/// See <https://learn.microsoft.com/en-us/typography/opentype/spec/name>.
pub names: HashMap<NameKey, String>,
/// See <https://learn.microsoft.com/en-us/typography/opentype/spec/post> and
/// <https://github.com/adobe-type-tools/agl-specification>
pub postscript_names: PostscriptNames,
/// Italic angle in counter-clockwise degrees from the vertical. Zero for
/// upright fonts, negative for right-leaning fonts.
/// See <https://learn.microsoft.com/en-us/typography/opentype/spec/post>.
pub italic_angle: OrderedFloat<f64>,
/// Miscellaneous font-wide data that didn't seem worthy of top billing
pub misc: MiscMetadata,
pub gdef_categories: GdefCategories,
}
#[derive(Serialize, Deserialize, Default, Debug, Clone, PartialEq, Eq)]
pub struct GdefCategories {
/// A map of glyphs to categories.
///
/// If this is empty, classes should be inferred.
pub categories: BTreeMap<GlyphName, GlyphClassDef>,
/// If set, we should prefer categories defined in FEA source to ones here.
///
/// This is set for UFO/DS sources, but not for glyphs sources.
pub prefer_gdef_categories_in_fea: bool,
}
/// Metadata primarily feeding the OS/2 table.
///
/// <https://learn.microsoft.com/en-us/typography/opentype/spec/os2>
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
pub struct MiscMetadata {
/// See <https://learn.microsoft.com/en-us/typography/opentype/spec/os2#fstype>
pub fs_type: Option<u16>,
/// See <https://learn.microsoft.com/en-us/typography/opentype/spec/os2#fsselection>
pub selection_flags: SelectionFlags,
/// See <https://learn.microsoft.com/en-us/typography/opentype/spec/os2#achvendid>
pub vendor_id: Tag,
/// UFO appears to allow negative major versions.
///
/// See <https://unifiedfontobject.org/versions/ufo3/fontinfo.plist/#generic-identification-information>
pub version_major: i32,
pub version_minor: u32,
pub head_flags: u16,
pub lowest_rec_ppm: u16,
pub created: Option<DateTime<Utc>>,
}
/// The name of every glyph, in the order it will be emitted
///
/// <https://rsheeter.github.io/font101/#glyph-ids-and-the-cmap-table>
#[derive(Serialize, Deserialize, Default, Debug, Clone, PartialEq, Eq)]
pub struct GlyphOrder(IndexSet<GlyphName>);
impl Extend<GlyphName> for GlyphOrder {
fn extend<T: IntoIterator<Item = GlyphName>>(&mut self, iter: T) {
self.0.extend(iter)
}
}
impl FromIterator<GlyphName> for GlyphOrder {
fn from_iter<T: IntoIterator<Item = GlyphName>>(iter: T) -> Self {
GlyphOrder(iter.into_iter().collect::<IndexSet<_>>())
}
}
impl GlyphOrder {
pub fn new() -> Self {
GlyphOrder(IndexSet::new())
}
pub fn glyph_id(&self, name: &GlyphName) -> Option<GlyphId16> {
self.0
.get_index_of(name)
.map(|i| i as u32)
.map(|gid| GlyphId16::new(gid as u16))
}
pub fn glyph_name(&self, index: usize) -> Option<&GlyphName> {
self.0.get_index(index)
}
pub fn contains(&self, name: &GlyphName) -> bool {
self.0.contains(name)
}
pub fn iter(&self) -> impl Iterator<Item = &GlyphName> {
self.0.iter()
}
pub fn remove(&mut self, name: &GlyphName) -> bool {
self.0.shift_remove(name)
}
pub fn difference<'a>(
&'a self,
other: &'a GlyphOrder,
) -> indexmap::set::Difference<'a, GlyphName, RandomState> {
self.0.difference(&other.0)
}
pub fn insert(&mut self, name: GlyphName) -> bool {
self.0.insert(name)
}
pub fn is_empty(&self) -> bool {
self.0.is_empty()
}
pub fn len(&self) -> usize {
self.0.len()
}
pub(crate) fn set_glyph_id(&mut self, name: &GlyphName, new_index: usize) {
match self.0.get_index_of(name) {
Some(index) if index == new_index => (), // nop
Some(index) => self.0.move_index(index, new_index),
None => {
self.insert(name.clone());
self.set_glyph_id(name, new_index)
}
}
}
}
impl IntoIterator for GlyphOrder {
type Item = GlyphName;
type IntoIter = <IndexSet<GlyphName> as IntoIterator>::IntoIter;
fn into_iter(self) -> Self::IntoIter {
self.0.into_iter()
}
}
/// Glyph names mapped to postscript names
pub type PostscriptNames = HashMap<GlyphName, GlyphName>;
/// In logical (reading) order
pub type KernPair = (KernSide, KernSide);
/// IR representation of kerning groups.
///
/// In UFO terms, roughly [groups.plist](https://unifiedfontobject.org/versions/ufo3/groups.plist/)
/// plus the set of locations that can have kerning.
#[derive(Serialize, Deserialize, Debug, Default, Clone, PartialEq, Eq)]
pub struct KerningGroups {
pub groups: BTreeMap<KernGroup, BTreeSet<GlyphName>>,
/// The locations that have kerning defined.
///
/// Must be a subset of the master locations.
pub locations: BTreeSet<NormalizedLocation>,
/// Optional group renaming map, meant for [KerningInstance] to consume
///
/// The rhs should be the name used in the groups map.
pub old_to_new_group_names: BTreeMap<KernGroup, KernGroup>,
}
/// IR representation of kerning for a location.
///
/// In UFO terms, roughly [kerning.plist](https://unifiedfontobject.org/versions/ufo3/kerning.plist/).
#[derive(Serialize, Deserialize, Debug, Default, Clone, PartialEq, Eq)]
pub struct KerningInstance {
pub location: NormalizedLocation,
/// An adjustment to the space *between* two glyphs in logical order.
///
/// Maps (side1, side2) => a mapping location:adjustment.
///
/// Used for both LTR and RTL. The BE application differs but the concept
/// is the same.
pub kerns: BTreeMap<KernPair, OrderedFloat<f32>>,
}
/// A named set of glyphs with common kerning behaviour
///
/// Identical sets can have different behaviour depending on whether or not they
/// are in the first or second logical position.
#[derive(Clone, Debug, PartialEq, PartialOrd, Eq, Ord, Hash)]
pub enum KernGroup {
Side1(SmolStr),
Side2(SmolStr),
}
/// One side of a kern pair, represented as a glyph or group name
///
/// <https://unifiedfontobject.org/versions/ufo3/kerning.plist/#kerning-pair-types>
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum KernSide {
Glyph(GlyphName),
Group(KernGroup),
}
impl Display for KernSide {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
KernSide::Glyph(g) => Display::fmt(g, f),
KernSide::Group(name) => write!(f, "@{name}"),
}
}
}
impl Display for KernGroup {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
KernGroup::Side1(name) => write!(f, "side1.{name}"),
KernGroup::Side2(name) => write!(f, "side2.{name}"),
}
}
}
// we need custom impls here because yaml does not support nested enums
impl Serialize for KernGroup {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
match self {
KernGroup::Side1(name) => serializer.serialize_str(&format!("side1.{name}")),
KernGroup::Side2(name) => serializer.serialize_str(&format!("side2.{name}")),
}
}
}
impl<'de> Deserialize<'de> for KernGroup {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: serde::Deserializer<'de>,
{
let s = String::deserialize(deserializer)?;
s.strip_prefix("side1.")
.map(|s| KernGroup::Side1(s.into()))
.or_else(|| s.strip_prefix("side2.").map(|s| KernGroup::Side2(s.into())))
.ok_or_else(|| D::Error::custom(format!("missing side1/side2 prefix: {s}")))
}
}
impl KernSide {
#[inline]
pub fn is_glyph(&self) -> bool {
matches!(self, KernSide::Glyph(_))
}
#[inline]
pub fn is_group(&self) -> bool {
matches!(self, KernSide::Group(_))
}
}
impl StaticMetadata {
// TODO: we could consider a builder or something for this?
#[allow(clippy::too_many_arguments)]
pub fn new(
units_per_em: u16,
names: HashMap<NameKey, String>,
axes: Vec<Axis>,
named_instances: Vec<NamedInstance>,
global_locations: HashSet<NormalizedLocation>,
postscript_names: PostscriptNames,
italic_angle: f64,
gdef_categories: GdefCategories,
glyphsapp_number_values: Option<
HashMap<NormalizedLocation, BTreeMap<SmolStr, OrderedFloat<f64>>>,
>,
) -> Result<StaticMetadata, VariationModelError> {
// Point axes are less exciting than ranged ones
let variable_axes: Vec<_> = axes.iter().filter(|a| !a.is_point()).cloned().collect();
// Claim names for axes and named instances
let mut name_id_gen = 255;
let mut key_to_name = names;
let mut visited = HashSet::new();
variable_axes
.iter()
.map(|axis| &axis.name)
.chain(named_instances.iter().map(|ni| &ni.name))
.for_each(|name| {
if !visited.insert(name) {
return;
}
name_id_gen += 1;
key_to_name.insert(NameKey::new(name_id_gen.into(), name), name.clone());
});
let variation_model = VariationModel::new(global_locations, variable_axes.clone())?;
let default_location = axes
.iter()
.map(|a| (a.tag, NormalizedCoord::new(0.0)))
.collect();
Ok(StaticMetadata {
units_per_em,
names: key_to_name,
all_source_axes: axes,
axes: variable_axes,
named_instances,
variation_model,
default_location,
postscript_names,
italic_angle: italic_angle.into(),
gdef_categories,
number_values: glyphsapp_number_values.unwrap_or_default(),
misc: MiscMetadata {
fs_type: None, // default is, sigh, inconsistent across source formats
selection_flags: Default::default(),
vendor_id: DEFAULT_VENDOR_ID_TAG,
// https://github.com/googlefonts/ufo2ft/blob/0d2688cd847d003b41104534d16973f72ef26c40/Lib/ufo2ft/fontInfoData.py#L353-L354
version_major: 0,
version_minor: 0,
// <https://github.com/googlefonts/ufo2ft/blob/0d2688cd847d003b41104534d16973f72ef26c40/Lib/ufo2ft/fontInfoData.py#L364>
lowest_rec_ppm: 6,
// <https://github.com/googlefonts/ufo2ft/blob/0d2688cd847d003b41104534d16973f72ef26c40/Lib/ufo2ft/fontInfoData.py#L365>
head_flags: 3,
created: None,
},
})
}
/// The default on all variable axes.
pub fn default_location(&self) -> &NormalizedLocation {
&self.default_location
}
pub fn axis(&self, tag: &Tag) -> Option<&Axis> {
self.axes.iter().find(|a| &a.tag == tag)
}
}
/// Global metrics. Ascender/descender, cap height, etc.
///
/// Represents the values of these metrics at a specific position in design space.
/// At a minimum should be defined at the default location.
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
pub struct GlobalMetrics(
pub(crate) HashMap<GlobalMetric, HashMap<NormalizedLocation, OrderedFloat<f32>>>,
);
#[derive(Serialize, Deserialize, Debug, Copy, Clone, PartialEq, Eq, Hash)]
pub enum GlobalMetric {
Ascender,
Descender,
HheaAscender,
HheaDescender,
HheaLineGap,
Os2TypoAscender,
Os2TypoDescender,
Os2TypoLineGap,
Os2WinAscent,
Os2WinDescent,
CapHeight,
CaretSlopeRise,
CaretSlopeRun,
CaretOffset,
UnderlineThickness,
UnderlinePosition,
XHeight,
StrikeoutPosition,
StrikeoutSize,
SubscriptXOffset,
SubscriptXSize,
SubscriptYOffset,
SubscriptYSize,
SuperscriptXOffset,
SuperscriptXSize,
SuperscriptYOffset,
SuperscriptYSize,
}
impl GlobalMetric {
/// Return the 4-byte tag used to represent a global metric in the `MVAR` table.
///
/// `None` if this metric is not associated with an `MVAR` value tag, or if
/// we don't support it yet (e.g. vertical typesetting metrics).
///
/// <https://learn.microsoft.com/en-us/typography/opentype/spec/mvar#value-tags>
pub fn mvar_tag(&self) -> Option<Tag> {
// We support the same subset of the metrics defined in the spec
// as fonttools does (except vertical ones which we don't support yet):
// https://github.com/fonttools/fonttools/blob/0c5cb3b/Lib/fontTools/varLib/mvar.py
match self {
GlobalMetric::Os2TypoAscender => Some(Tag::new(b"hasc")),
GlobalMetric::Os2TypoDescender => Some(Tag::new(b"hdsc")),
GlobalMetric::Os2TypoLineGap => Some(Tag::new(b"hlgp")),
GlobalMetric::Os2WinAscent => Some(Tag::new(b"hcla")),
GlobalMetric::Os2WinDescent => Some(Tag::new(b"hcld")),
// TODO: support vertical global metrics
// https://github.com/googlefonts/fontc/issues/668
// GlobalMetric::VheaAscender => Some(Tag::new(b"vasc")),
// GlobalMetric::VheaDescender => Some(Tag::new(b"vdsc")),
// GlobalMetric::VheaLineGap => Some(Tag::new(b"vlgp")),
GlobalMetric::CaretSlopeRise => Some(Tag::new(b"hcrs")),
GlobalMetric::CaretSlopeRun => Some(Tag::new(b"hcrn")),
GlobalMetric::CaretOffset => Some(Tag::new(b"hcof")),
// GlobalMetric::VheaCaretSlopeRise => Some(Tag::new(b"vcrs")),
// GlobalMetric::VheaCaretSlopeRun => Some(Tag::new(b"vcrn")),
// GlobalMetric::VheaCaretOffset => Some(Tag::new(b"vcof")),
GlobalMetric::XHeight => Some(Tag::new(b"xhgt")),
GlobalMetric::CapHeight => Some(Tag::new(b"cpht")),
GlobalMetric::SubscriptXSize => Some(Tag::new(b"sbxs")),
GlobalMetric::SubscriptYSize => Some(Tag::new(b"sbys")),
GlobalMetric::SubscriptXOffset => Some(Tag::new(b"sbxo")),
GlobalMetric::SubscriptYOffset => Some(Tag::new(b"sbyo")),
GlobalMetric::SuperscriptXSize => Some(Tag::new(b"spxs")),
GlobalMetric::SuperscriptYSize => Some(Tag::new(b"spys")),
GlobalMetric::SuperscriptXOffset => Some(Tag::new(b"spxo")),
GlobalMetric::SuperscriptYOffset => Some(Tag::new(b"spyo")),
GlobalMetric::StrikeoutSize => Some(Tag::new(b"strs")),
GlobalMetric::StrikeoutPosition => Some(Tag::new(b"stro")),
GlobalMetric::UnderlineThickness => Some(Tag::new(b"unds")),
GlobalMetric::UnderlinePosition => Some(Tag::new(b"undo")),
// TODO gsp0, gsp1, etc. for gasp table
_ => None,
}
}
}
/// Adjust Y offset based on italic angle, to get X offset.
///
/// <https://github.com/googlefonts/ufo2ft/blob/0d2688cd847d003b41104534d16973f72ef26c40/Lib/ufo2ft/outlineCompiler.py#L571-L573>
fn adjust_offset(offset: f64, angle: f64) -> f64 {
if angle.abs() >= f64::EPSILON {
offset * (-angle).to_radians().tan()
} else {
0.0
}
}
/// Map of values associated with a given global metric at various locations.
pub type GlobalMetricValues = HashMap<NormalizedLocation, OrderedFloat<f32>>;
impl GlobalMetrics {
/// Creates a new [GlobalMetrics] with default values at the default location.
pub fn new(
default_location: NormalizedLocation,
units_per_em: u16,
x_height: Option<f64>,
ascender: Option<f64>,
descender: Option<f64>,
italic_angle: f64,
) -> GlobalMetrics {
let mut metrics = GlobalMetrics(HashMap::new());
metrics.populate_defaults(
&default_location,
units_per_em,
x_height,
ascender,
descender,
Some(italic_angle),
);
metrics
}
/// Populate default values for all metrics at the given location.
///
/// This is used to populate the default values for the default location whenever a
/// new [GlobalMetrics] is created. But it can also be used to populate the
/// default values for other non-default locations, to make these 'dense'
/// (i.e. non 'sparse'). That is the current behavior of fontmake when building
/// variable fonts from Glyphs or Designspace sources.
pub fn populate_defaults(
&mut self,
location: &NormalizedLocation,
units_per_em: u16,
x_height: Option<f64>,
ascender: Option<f64>,
descender: Option<f64>,
italic_angle: Option<f64>,
) {
let units_per_em = units_per_em as f64;
let mut set = |metric, value| self.set(metric, location.clone(), value as f32);
// https://github.com/googlefonts/ufo2ft/blob/fca66fe3ea1ea88ffb36f8264b21ce042d3afd05/Lib/ufo2ft/fontInfoData.py#L38-L45
let ascender = ascender.unwrap_or(0.8 * units_per_em);
let descender = descender.unwrap_or(-0.2 * units_per_em);
set(GlobalMetric::Ascender, ascender);
set(GlobalMetric::Descender, descender);
// https://github.com/googlefonts/ufo2ft/blob/0d2688cd847d003b41104534d16973f72ef26c40/Lib/ufo2ft/fontInfoData.py#L229-L238
let typo_line_gap = units_per_em * 1.2 + descender - ascender;
let typo_line_gap = if typo_line_gap > 0.0 {
typo_line_gap
} else {
0.0
};
set(GlobalMetric::Os2TypoLineGap, typo_line_gap);
// https://github.com/googlefonts/ufo2ft/blob/0d2688cd847d003b41104534d16973f72ef26c40/Lib/ufo2ft/fontInfoData.py#L215-L226
set(GlobalMetric::Os2TypoAscender, ascender);
set(GlobalMetric::Os2TypoDescender, descender);
// https://github.com/googlefonts/ufo2ft/blob/0d2688cd847d003b41104534d16973f72ef26c40/Lib/ufo2ft/fontInfoData.py#L126-L130
set(GlobalMetric::HheaAscender, ascender + typo_line_gap);
set(GlobalMetric::HheaDescender, descender);
// https://github.com/googlefonts/ufo2ft/blob/0d2688cd847d003b41104534d16973f72ef26c40/Lib/ufo2ft/fontInfoData.py#L366
set(GlobalMetric::HheaLineGap, 0.0);
// https://github.com/googlefonts/ufo2ft/blob/0d2688cd847d003b41104534d16973f72ef26c40/Lib/ufo2ft/fontInfoData.py#L241-L254
set(GlobalMetric::Os2WinAscent, ascender + typo_line_gap);
set(GlobalMetric::Os2WinDescent, descender.abs());
// https://github.com/googlefonts/ufo2ft/blob/fca66fe3ea1ea88ffb36f8264b21ce042d3afd05/Lib/ufo2ft/fontInfoData.py#L48-L55
set(GlobalMetric::CapHeight, 0.7 * units_per_em);
let x_height = x_height.unwrap_or(0.5 * units_per_em);
set(GlobalMetric::XHeight, x_height);
// https://github.com/googlefonts/ufo2ft/blob/150c2d6a00da9d5854173c8457a553ce03b89cf7/Lib/ufo2ft/fontInfoData.py#L133-L148
// https://github.com/googlefonts/ufo2ft/blob/150c2d6a00da9d5854173c8457a553ce03b89cf7/Lib/ufo2ft/fontInfoData.py#L151-L161
let italic_angle = italic_angle.unwrap_or(0.0);
set(GlobalMetric::CaretSlopeRise, units_per_em);
set(
GlobalMetric::CaretSlopeRun,
adjust_offset(units_per_em, italic_angle),
);
// https://github.com/googlefonts/ufo2ft/blob/0d2688cd847d003b41104534d16973f72ef26c40/Lib/ufo2ft/fontInfoData.py#L367
set(GlobalMetric::CaretOffset, 0.0);
// https://github.com/googlefonts/ufo2ft/blob/0d2688cd847d003b41104534d16973f72ef26c40/Lib/ufo2ft/outlineCompiler.py#L575-L616
let subscript_x_size = units_per_em * 0.65;
let subscript_y_size = units_per_em * 0.60;
let subscript_y_offset = units_per_em * 0.075;
let superscript_y_offset = units_per_em * 0.35;
set(GlobalMetric::SubscriptXSize, subscript_x_size);
set(GlobalMetric::SubscriptYSize, subscript_y_size);
set(
GlobalMetric::SubscriptXOffset,
adjust_offset(-subscript_y_offset, italic_angle),
);
set(GlobalMetric::SubscriptYOffset, subscript_y_offset);
set(GlobalMetric::SuperscriptXSize, subscript_x_size);
set(GlobalMetric::SuperscriptYSize, subscript_y_size);
set(
GlobalMetric::SuperscriptXOffset,
adjust_offset(superscript_y_offset, italic_angle),
);
set(GlobalMetric::SuperscriptYOffset, superscript_y_offset);
// // https://github.com/googlefonts/ufo2ft/blob/0d2688cd847d003b41104534d16973f72ef26c40/Lib/ufo2ft/fontInfoData.py#L313-L316
set(GlobalMetric::StrikeoutSize, 0.05 * units_per_em);
set(GlobalMetric::StrikeoutPosition, x_height * 0.6);
// ufo2ft and Glyphs.app have different defaults for the post.underlinePosition:
// the former uses 0.075*UPEM whereas the latter 0.1*UPEM (both use the same
// underlineThickness 0.05*UPEM). We prefer to match Glyphs.app as more widely used.
// https://github.com/googlefonts/ufo2ft/blob/main/Lib/ufo2ft/fontInfoData.py#L313-L322
// https://github.com/googlefonts/glyphsLib/blob/main/Lib/glyphsLib/builder/custom_params.py#L1116-L1125
set(GlobalMetric::UnderlineThickness, 0.05 * units_per_em);
set(GlobalMetric::UnderlinePosition, -0.1 * units_per_em);
}
fn values(&self, metric: GlobalMetric) -> &GlobalMetricValues {
// We presume that ctor initializes for every GlobalMetric
self.0.get(&metric).unwrap()
}
fn values_mut(&mut self, metric: GlobalMetric) -> &mut GlobalMetricValues {
self.0.entry(metric).or_default()
}
pub fn get(&self, metric: GlobalMetric, pos: &NormalizedLocation) -> OrderedFloat<f32> {
let Some(value) = self.values(metric).get(pos) else {
panic!("interpolated metric values are not yet supported");
};
*value
}
pub fn set(
&mut self,
metric: GlobalMetric,
pos: NormalizedLocation,
value: impl Into<OrderedFloat<f32>>,
) {
self.values_mut(metric).insert(pos, value.into());
}
pub fn set_if_some(
self: &mut GlobalMetrics,
metric: GlobalMetric,
pos: NormalizedLocation,
maybe_value: Option<impl Into<OrderedFloat<f64>>>,
) {
if let Some(value) = maybe_value {
self.set(metric, pos, value.into().into_inner() as f32);
}
}
pub fn at(&self, pos: &NormalizedLocation) -> GlobalMetricsInstance {
GlobalMetricsInstance {
pos: pos.clone(),
ascender: self.get(GlobalMetric::Ascender, pos),
descender: self.get(GlobalMetric::Descender, pos),
caret_slope_rise: self.get(GlobalMetric::CaretSlopeRise, pos),
caret_slope_run: self.get(GlobalMetric::CaretSlopeRun, pos),
caret_offset: self.get(GlobalMetric::CaretOffset, pos),
cap_height: self.get(GlobalMetric::CapHeight, pos),
x_height: self.get(GlobalMetric::XHeight, pos),
subscript_x_size: self.get(GlobalMetric::SubscriptXSize, pos),
subscript_y_size: self.get(GlobalMetric::SubscriptYSize, pos),
subscript_x_offset: self.get(GlobalMetric::SubscriptXOffset, pos),
subscript_y_offset: self.get(GlobalMetric::SubscriptYOffset, pos),
superscript_x_size: self.get(GlobalMetric::SuperscriptXSize, pos),
superscript_y_size: self.get(GlobalMetric::SuperscriptYSize, pos),
superscript_x_offset: self.get(GlobalMetric::SuperscriptXOffset, pos),
superscript_y_offset: self.get(GlobalMetric::SuperscriptYOffset, pos),
strikeout_size: self.get(GlobalMetric::StrikeoutSize, pos),
strikeout_position: self.get(GlobalMetric::StrikeoutPosition, pos),
os2_typo_ascender: self.get(GlobalMetric::Os2TypoAscender, pos),
os2_typo_descender: self.get(GlobalMetric::Os2TypoDescender, pos),
os2_typo_line_gap: self.get(GlobalMetric::Os2TypoLineGap, pos),
os2_win_ascent: self.get(GlobalMetric::Os2WinAscent, pos),
os2_win_descent: self.get(GlobalMetric::Os2WinDescent, pos),
hhea_ascender: self.get(GlobalMetric::HheaAscender, pos),
hhea_descender: self.get(GlobalMetric::HheaDescender, pos),
hhea_line_gap: self.get(GlobalMetric::HheaLineGap, pos),
underline_thickness: self.get(GlobalMetric::UnderlineThickness, pos),
underline_position: self.get(GlobalMetric::UnderlinePosition, pos),
}
}
pub fn iter(&self) -> impl Iterator<Item = (&GlobalMetric, &GlobalMetricValues)> + '_ {
self.0.iter()
}
}
/// Metrics at a specific [NormalizedLocation]
#[derive(Default, Debug, Clone, PartialEq, Eq)]
pub struct GlobalMetricsInstance {
pub pos: NormalizedLocation,
pub ascender: OrderedFloat<f32>,
pub descender: OrderedFloat<f32>,
pub caret_slope_rise: OrderedFloat<f32>,
pub caret_slope_run: OrderedFloat<f32>,
pub caret_offset: OrderedFloat<f32>,
pub cap_height: OrderedFloat<f32>,
pub x_height: OrderedFloat<f32>,
pub os2_typo_ascender: OrderedFloat<f32>,
pub os2_typo_descender: OrderedFloat<f32>,
pub os2_typo_line_gap: OrderedFloat<f32>,
pub os2_win_ascent: OrderedFloat<f32>,
pub os2_win_descent: OrderedFloat<f32>,
pub hhea_ascender: OrderedFloat<f32>,
pub hhea_descender: OrderedFloat<f32>,
pub hhea_line_gap: OrderedFloat<f32>,
pub strikeout_position: OrderedFloat<f32>,
pub strikeout_size: OrderedFloat<f32>,
pub subscript_x_offset: OrderedFloat<f32>,
pub subscript_x_size: OrderedFloat<f32>,
pub subscript_y_offset: OrderedFloat<f32>,
pub subscript_y_size: OrderedFloat<f32>,
pub superscript_x_offset: OrderedFloat<f32>,
pub superscript_x_size: OrderedFloat<f32>,
pub superscript_y_offset: OrderedFloat<f32>,
pub superscript_y_size: OrderedFloat<f32>,
pub underline_thickness: OrderedFloat<f32>,
pub underline_position: OrderedFloat<f32>,
}
/// Helps accumulate 'name' values.
///
/// See <https://github.com/googlefonts/ufo2ft/blob/fca66fe3ea1ea88ffb36f8264b21ce042d3afd05/Lib/ufo2ft/outlineCompiler.py#L367>.
#[derive(Default)]
pub struct NameBuilder {
names: HashMap<NameKey, String>,
/// Helps lookup entries in name when all we have is a NameId
name_to_key: HashMap<NameId, NameKey>,
version_major: i32,
version_minor: u32,
}
/// Returns true if the style name is one of the four standard style names.
fn is_ribbi(style_name: &str) -> bool {
matches!(
style_name.to_lowercase().as_str(),
"regular" | "italic" | "bold" | "bold italic"
)
}
impl NameBuilder {
pub fn add(&mut self, name_id: NameId, value: String) {
let key = NameKey::new(name_id, &value);
self.names.insert(key, value);
self.name_to_key.insert(name_id, key);
}
pub fn remove(&mut self, name_id: NameId) {
if let Some(key) = self.name_to_key.remove(&name_id) {
self.names.remove(&key);
}
}
pub fn add_if_present(&mut self, name_id: NameId, value: &Option<String>) {
if let Some(value) = value.as_ref().cloned() {
self.add(name_id, value);
}
}
pub fn apply_fallback(&mut self, name_id: NameId, fallbacks: &[NameId]) {
if self.contains_key(name_id) {
return;
}
if let Some(fallback) = self.get_fallback_or_default(name_id, fallbacks) {
self.add(name_id, fallback.to_string());
}
}
pub fn contains_key(&self, name_id: NameId) -> bool {
self.name_to_key.contains_key(&name_id)
}
pub fn get(&self, name_id: NameId) -> Option<&str> {
self.name_to_key
.get(&name_id)
.and_then(|key| self.names.get(key).map(|s| s.as_str()))
}
pub fn into_inner(self) -> HashMap<NameKey, String> {
self.names
}
pub fn get_fallback_or_default(&self, name_id: NameId, fallbacks: &[NameId]) -> Option<&str> {
fallbacks
.iter()
.find_map(|n| {
let key = self.name_to_key.get(n)?;
self.names.get(key).map(|s| s.as_str())
})
.or_else(|| default_value(name_id))
}
/// Fetch a fallback that definitely has a value in a String
///
/// Only safe to use with names that have default valuesa to fall back to
/// if the fallback itself is missing.
fn fallback_string(&self, name_id: NameId, fallback: NameId) -> String {
self.get_fallback_or_default(name_id, &[fallback])
.unwrap()
.to_string()
}
pub fn apply_default_fallbacks(&mut self, vendor_id: &str) {
// If the legacy subfamily isn't set, we fall back to the typographic subfamily;
// but because the spec recommends the former to only contain "Regular",
// "Bold", "Italic", or "Bold Italic", if this fallback isn't RIBBI already,
// we append it to the legacy family name and set the legacy subfamily to the
// default "Regular", the same way fontmake does via ufo2ft.
// https://github.com/googlefonts/ufo2ft/blob/bb79cae53f1c160c7174ebef0d463c7a28a7552a/Lib/ufo2ft/fontInfoData.py#L76
let family_suffix = if self.contains_key(NameId::SUBFAMILY_NAME) {
// assume this is good, no need to add suffix to family name.
None
} else {
let fallback_subfamily =
self.fallback_string(NameId::SUBFAMILY_NAME, NameId::TYPOGRAPHIC_SUBFAMILY_NAME);
let (fallback_subfamily, family_suffix) = if is_ribbi(&fallback_subfamily) {
(fallback_subfamily, None)
} else {
("Regular".to_string(), Some(fallback_subfamily))
};
self.add(NameId::SUBFAMILY_NAME, fallback_subfamily);
family_suffix
};
// https://github.com/googlefonts/ufo2ft/blob/bb79cae53f1c160c7174ebef0d463c7a28a7552a/Lib/ufo2ft/fontInfoData.py#L57
if !self.contains_key(NameId::FAMILY_NAME) {
let mut fallback_family =
self.fallback_string(NameId::FAMILY_NAME, NameId::TYPOGRAPHIC_FAMILY_NAME);
if let Some(family_suffix) = family_suffix.as_ref() {
fallback_family.push(' ');
fallback_family.push_str(family_suffix);
}
self.add(NameId::FAMILY_NAME, fallback_family);
};
// https://github.com/googlefonts/ufo2ft/blob/fca66fe3ea1ea88ffb36f8264b21ce042d3afd05/Lib/ufo2ft/fontInfoData.py#L188
self.apply_fallback(NameId::TYPOGRAPHIC_FAMILY_NAME, &[NameId::FAMILY_NAME]);
// https://github.com/googlefonts/ufo2ft/blob/fca66fe3ea1ea88ffb36f8264b21ce042d3afd05/Lib/ufo2ft/fontInfoData.py#L195
self.apply_fallback(
NameId::TYPOGRAPHIC_SUBFAMILY_NAME,
&[NameId::SUBFAMILY_NAME],
);
// https://github.com/googlefonts/ufo2ft/blob/fca66fe3ea1ea88ffb36f8264b21ce042d3afd05/Lib/ufo2ft/fontInfoData.py#L169
if !self.contains_key(NameId::VERSION_STRING) {
let major = self.version_major;
let minor = self.version_minor;
self.add(
NameId::VERSION_STRING,
format!("Version {major}.{minor:0>3}"),
);
}
// https://github.com/googlefonts/ufo2ft/blob/fca66fe3ea1ea88ffb36f8264b21ce042d3afd05/Lib/ufo2ft/fontInfoData.py#L296
if !self.contains_key(NameId::FULL_NAME) {
self.add(
NameId::FULL_NAME,
format!(
"{} {}",
self.get(NameId::TYPOGRAPHIC_FAMILY_NAME)
.unwrap_or_default(),
self.get(NameId::TYPOGRAPHIC_SUBFAMILY_NAME)
.unwrap_or_default(),
),
);
}
// https://github.com/googlefonts/ufo2ft/blob/fca66fe3ea1ea88ffb36f8264b21ce042d3afd05/Lib/ufo2ft/fontInfoData.py#L178-L185
if !self.contains_key(NameId::POSTSCRIPT_NAME) {
let mut value = format!(
"{}-{}",
self.get(NameId::TYPOGRAPHIC_FAMILY_NAME)
.unwrap_or_default(),
self.get(NameId::TYPOGRAPHIC_SUBFAMILY_NAME)
.unwrap_or_default(),
);
normalize_for_postscript(&mut value, false);
self.add(NameId::POSTSCRIPT_NAME, value);
}
// https://github.com/googlefonts/ufo2ft/blob/fca66fe3ea1ea88ffb36f8264b21ce042d3afd05/Lib/ufo2ft/fontInfoData.py#L178-L185
if !self.contains_key(NameId::UNIQUE_ID) {
let version = self
.get(NameId::VERSION_STRING)
.unwrap()
.replace("Version ", "");
// fontmake pulls the openTypeOS2VendorID but we don't have that so just use their default
let postscript_name = self.get(NameId::POSTSCRIPT_NAME).unwrap();
self.add(
NameId::UNIQUE_ID,
format!("{version};{vendor_id};{postscript_name}"),
);
}
// https://github.com/googlefonts/ufo2ft/blob/main/Lib/ufo2ft/outlineCompiler.py#L417-L421
// Drop typographic names if they match the legacy ones
if let Some(family) = self.get(NameId::FAMILY_NAME) {
if Some(family) == self.get(NameId::TYPOGRAPHIC_FAMILY_NAME) {
self.remove(NameId::TYPOGRAPHIC_FAMILY_NAME);
}
}
if let Some(subfamily) = self.get(NameId::SUBFAMILY_NAME) {
if Some(subfamily) == self.get(NameId::TYPOGRAPHIC_SUBFAMILY_NAME) {
self.remove(NameId::TYPOGRAPHIC_SUBFAMILY_NAME);
}
}
}
pub fn set_version(&mut self, major: i32, minor: u32) {
self.version_major = major;
self.version_minor = minor;
}
}
/// <https://github.com/googlefonts/ufo2ft/blob/fca66fe3ea1ea88ffb36f8264b21ce042d3afd05/Lib/ufo2ft/fontInfoData.py#L263>
fn normalize_for_postscript(value: &mut String, allow_spaces: bool) {
value.retain(|c| {
if !allow_spaces && c.is_ascii_whitespace() {
return false;
}
if "[](){}<>/%".contains(c) {
return false;
}
if !(33..127).contains(&(c as u32)) {
warn!("fontmake performs decomposition, we just ignore the character");
return false;
}
true
});
}
/// Match fontmake defaults.
pub fn default_value(name: NameId) -> Option<&'static str> {
match name {
// https://github.com/googlefonts/ufo2ft/blob/fca66fe3ea1ea88ffb36f8264b21ce042d3afd05/Lib/ufo2ft/fontInfoData.py#L352
NameId::FAMILY_NAME => Some("New Font"),
// https://github.com/googlefonts/ufo2ft/blob/fca66fe3ea1ea88ffb36f8264b21ce042d3afd05/Lib/ufo2ft/fontInfoData.py#L77
NameId::SUBFAMILY_NAME => Some("Regular"),
_ => None,
}
}
/// The encoding for a Windows-platform (which works everywhere) name.
///
/// See <https://learn.microsoft.com/en-us/typography/opentype/spec/name#platform-specific-encoding-and-language-ids-windows-platform-platform-id-3>
fn encoding_for(value: &str) -> u16 {
if value.chars().all(|c| (c as u32) < 0xFFFF) {
1 // Unicode BMP
} else {
10 // Unicode full repetoire
}
}
/// See <https://learn.microsoft.com/en-us/typography/opentype/spec/name>
#[derive(Serialize, Deserialize, Debug, Copy, Clone, PartialEq, Eq, Hash)]
pub struct NameKey {
pub name_id: NameId,
pub platform_id: u16,
pub encoding_id: u16,
pub lang_id: u16,
}
impl NameKey {
/// Create's a [NameKey] suitable for use with the provided value.
///
/// The value matters because if it uses values from outside the Unicode BMP
/// the key changes.
pub fn new(name_id: NameId, value: &str) -> NameKey {
// The spec offers a Unicode platform but fontmake uses Windows because that's more widely supported.
// Match that. <https://github.com/googlefonts/ufo2ft/blob/fca66fe3ea1ea88ffb36f8264b21ce042d3afd05/Lib/ufo2ft/outlineCompiler.py#L430-L432>.
NameKey {
platform_id: 3, // Windows
encoding_id: encoding_for(value),
// https://learn.microsoft.com/en-us/typography/opentype/spec/name#windows-language-ids
lang_id: 0x409, // English, United States.
name_id,
}
}