-
Notifications
You must be signed in to change notification settings - Fork 447
/
__init__.py
1576 lines (1290 loc) · 57.3 KB
/
__init__.py
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
""" Partially instantiate a variable font.
The module exports an `instantiateVariableFont` function and CLI that allow to
create full instances (i.e. static fonts) from variable fonts, as well as "partial"
variable fonts that only contain a subset of the original variation space.
For example, if you wish to pin the width axis to a given location while also
restricting the weight axis to 400..700 range, you can do::
$ fonttools varLib.instancer ./NotoSans-VF.ttf wdth=85 wght=400:700
See `fonttools varLib.instancer --help` for more info on the CLI options.
The module's entry point is the `instantiateVariableFont` function, which takes
a TTFont object and a dict specifying either axis coodinates or (min, max) ranges,
and returns a new TTFont representing either a partial VF, or full instance if all
the VF axes were given an explicit coordinate.
E.g. here's how to pin the wght axis at a given location in a wght+wdth variable
font, keeping only the deltas associated with the wdth axis::
| >>> from fontTools import ttLib
| >>> from fontTools.varLib import instancer
| >>> varfont = ttLib.TTFont("path/to/MyVariableFont.ttf")
| >>> [a.axisTag for a in varfont["fvar"].axes] # the varfont's current axes
| ['wght', 'wdth']
| >>> partial = instancer.instantiateVariableFont(varfont, {"wght": 300})
| >>> [a.axisTag for a in partial["fvar"].axes] # axes left after pinning 'wght'
| ['wdth']
If the input location specifies all the axes, the resulting instance is no longer
'variable' (same as using fontools varLib.mutator):
| >>> instance = instancer.instantiateVariableFont(
| ... varfont, {"wght": 700, "wdth": 67.5}
| ... )
| >>> "fvar" not in instance
| True
If one just want to drop an axis at the default location, without knowing in
advance what the default value for that axis is, one can pass a `None` value:
| >>> instance = instancer.instantiateVariableFont(varfont, {"wght": None})
| >>> len(varfont["fvar"].axes)
| 1
From the console script, this is equivalent to passing `wght=drop` as input.
This module is similar to fontTools.varLib.mutator, which it's intended to supersede.
Note that, unlike varLib.mutator, when an axis is not mentioned in the input
location, the varLib.instancer will keep the axis and the corresponding deltas,
whereas mutator implicitly drops the axis at its default coordinate.
The module supports all the following "levels" of instancing, which can of
course be combined:
L1
dropping one or more axes while leaving the default tables unmodified;
| >>> font = instancer.instantiateVariableFont(varfont, {"wght": None})
L2
dropping one or more axes while pinning them at non-default locations;
| >>> font = instancer.instantiateVariableFont(varfont, {"wght": 700})
L3
restricting the range of variation of one or more axes, by setting either
a new minimum or maximum, potentially -- though not necessarily -- dropping
entire regions of variations that fall completely outside this new range.
| >>> font = instancer.instantiateVariableFont(varfont, {"wght": (100, 300)})
L4
moving the default location of an axis, by specifying (min,defalt,max) values:
| >>> font = instancer.instantiateVariableFont(varfont, {"wght": (100, 300, 700)})
Currently only TrueType-flavored variable fonts (i.e. containing 'glyf' table)
are supported, but support for CFF2 variable fonts will be added soon.
The discussion and implementation of these features are tracked at
https://github.com/fonttools/fonttools/issues/1537
"""
from fontTools.misc.fixedTools import (
floatToFixedToFloat,
strToFixedToFloat,
otRound,
)
from fontTools.varLib.models import normalizeValue, piecewiseLinearMap
from fontTools.ttLib import TTFont
from fontTools.ttLib.tables.TupleVariation import TupleVariation
from fontTools.ttLib.tables import _g_l_y_f
from fontTools import varLib
# we import the `subset` module because we use the `prune_lookups` method on the GSUB
# table class, and that method is only defined dynamically upon importing `subset`
from fontTools import subset # noqa: F401
from fontTools.varLib import builder
from fontTools.varLib.mvar import MVAR_ENTRIES
from fontTools.varLib.merger import MutatorMerger
from fontTools.varLib.instancer import names
from .featureVars import instantiateFeatureVariations
from fontTools.misc.cliTools import makeOutputFileName
from fontTools.varLib.instancer import solver
import collections
import dataclasses
from contextlib import contextmanager
from copy import deepcopy
from enum import IntEnum
import logging
import os
import re
from typing import Dict, Iterable, Mapping, Optional, Sequence, Tuple, Union
import warnings
log = logging.getLogger("fontTools.varLib.instancer")
def AxisRange(minimum, maximum):
warnings.warn(
"AxisRange is deprecated; use AxisTriple instead",
DeprecationWarning,
stacklevel=2,
)
return AxisTriple(minimum, None, maximum)
def NormalizedAxisRange(minimum, maximum):
warnings.warn(
"NormalizedAxisRange is deprecated; use AxisTriple instead",
DeprecationWarning,
stacklevel=2,
)
return NormalizedAxisTriple(minimum, None, maximum)
@dataclasses.dataclass(frozen=True, order=True, repr=False)
class AxisTriple(Sequence):
"""A triple of (min, default, max) axis values.
Any of the values can be None, in which case the limitRangeAndPopulateDefaults()
method can be used to fill in the missing values based on the fvar axis values.
"""
minimum: Optional[float]
default: Optional[float]
maximum: Optional[float]
def __post_init__(self):
if self.default is None and self.minimum == self.maximum:
object.__setattr__(self, "default", self.minimum)
if (
(
self.minimum is not None
and self.default is not None
and self.minimum > self.default
)
or (
self.default is not None
and self.maximum is not None
and self.default > self.maximum
)
or (
self.minimum is not None
and self.maximum is not None
and self.minimum > self.maximum
)
):
raise ValueError(
f"{type(self).__name__} minimum ({self.minimum}), default ({self.default}), maximum ({self.maximum}) must be in sorted order"
)
def __getitem__(self, i):
fields = dataclasses.fields(self)
return getattr(self, fields[i].name)
def __len__(self):
return len(dataclasses.fields(self))
def _replace(self, **kwargs):
return dataclasses.replace(self, **kwargs)
def __repr__(self):
return (
f"({', '.join(format(v, 'g') if v is not None else 'None' for v in self)})"
)
@classmethod
def expand(
cls,
v: Union[
"AxisTriple",
float, # pin axis at single value, same as min==default==max
Tuple[float, float], # (min, max), restrict axis and keep default
Tuple[float, float, float], # (min, default, max)
],
) -> "AxisTriple":
"""Convert a single value or a tuple into an AxisTriple.
If the input is a single value, it is interpreted as a pin at that value.
If the input is a tuple, it is interpreted as (min, max) or (min, default, max).
"""
if isinstance(v, cls):
return v
if isinstance(v, (int, float)):
return cls(v, v, v)
try:
n = len(v)
except TypeError as e:
raise ValueError(
f"expected float, 2- or 3-tuple of floats; got {type(v)}: {v!r}"
) from e
default = None
if n == 2:
minimum, maximum = v
elif n >= 3:
return cls(*v)
else:
raise ValueError(f"expected sequence of 2 or 3; got {n}: {v!r}")
return cls(minimum, default, maximum)
def limitRangeAndPopulateDefaults(self, fvarTriple) -> "AxisTriple":
"""Return a new AxisTriple with the default value filled in.
Set default to fvar axis default if the latter is within the min/max range,
otherwise set default to the min or max value, whichever is closer to the
fvar axis default.
If the default value is already set, return self.
"""
minimum = self.minimum
if minimum is None:
minimum = fvarTriple[0]
default = self.default
if default is None:
default = fvarTriple[1]
maximum = self.maximum
if maximum is None:
maximum = fvarTriple[2]
minimum = max(minimum, fvarTriple[0])
maximum = max(maximum, fvarTriple[0])
minimum = min(minimum, fvarTriple[2])
maximum = min(maximum, fvarTriple[2])
default = max(minimum, min(maximum, default))
return AxisTriple(minimum, default, maximum)
@dataclasses.dataclass(frozen=True, order=True, repr=False)
class NormalizedAxisTriple(AxisTriple):
"""A triple of (min, default, max) normalized axis values."""
minimum: float
default: float
maximum: float
def __post_init__(self):
if self.default is None:
object.__setattr__(self, "default", max(self.minimum, min(self.maximum, 0)))
if not (-1.0 <= self.minimum <= self.default <= self.maximum <= 1.0):
raise ValueError(
"Normalized axis values not in -1..+1 range; got "
f"minimum={self.minimum:g}, default={self.default:g}, maximum={self.maximum:g})"
)
@dataclasses.dataclass(frozen=True, order=True, repr=False)
class NormalizedAxisTripleAndDistances(AxisTriple):
"""A triple of (min, default, max) normalized axis values,
with distances between min and default, and default and max,
in the *pre-normalized* space."""
minimum: float
default: float
maximum: float
distanceNegative: Optional[float] = 1
distancePositive: Optional[float] = 1
def __post_init__(self):
if self.default is None:
object.__setattr__(self, "default", max(self.minimum, min(self.maximum, 0)))
if not (-1.0 <= self.minimum <= self.default <= self.maximum <= 1.0):
raise ValueError(
"Normalized axis values not in -1..+1 range; got "
f"minimum={self.minimum:g}, default={self.default:g}, maximum={self.maximum:g})"
)
def reverse_negate(self):
v = self
return self.__class__(-v[2], -v[1], -v[0], v[4], v[3])
def renormalizeValue(self, v, extrapolate=True):
"""Renormalizes a normalized value v to the range of this axis,
considering the pre-normalized distances as well as the new
axis limits."""
lower, default, upper, distanceNegative, distancePositive = self
assert lower <= default <= upper
if not extrapolate:
v = max(lower, min(upper, v))
if v == default:
return 0
if default < 0:
return -self.reverse_negate().renormalizeValue(-v, extrapolate=extrapolate)
# default >= 0 and v != default
if v > default:
return (v - default) / (upper - default)
# v < default
if lower >= 0:
return (v - default) / (default - lower)
# lower < 0 and v < default
totalDistance = distanceNegative * -lower + distancePositive * default
if v >= 0:
vDistance = (default - v) * distancePositive
else:
vDistance = -v * distanceNegative + distancePositive * default
return -vDistance / totalDistance
class _BaseAxisLimits(Mapping[str, AxisTriple]):
def __getitem__(self, key: str) -> AxisTriple:
return self._data[key]
def __iter__(self) -> Iterable[str]:
return iter(self._data)
def __len__(self) -> int:
return len(self._data)
def __repr__(self) -> str:
return f"{type(self).__name__}({self._data!r})"
def __str__(self) -> str:
return str(self._data)
def defaultLocation(self) -> Dict[str, float]:
"""Return a dict of default axis values."""
return {k: v.default for k, v in self.items()}
def pinnedLocation(self) -> Dict[str, float]:
"""Return a location dict with only the pinned axes."""
return {k: v.default for k, v in self.items() if v.minimum == v.maximum}
class AxisLimits(_BaseAxisLimits):
"""Maps axis tags (str) to AxisTriple values."""
def __init__(self, *args, **kwargs):
self._data = data = {}
for k, v in dict(*args, **kwargs).items():
if v is None:
# will be filled in by limitAxesAndPopulateDefaults
data[k] = v
else:
try:
triple = AxisTriple.expand(v)
except ValueError as e:
raise ValueError(f"Invalid axis limits for {k!r}: {v!r}") from e
data[k] = triple
def limitAxesAndPopulateDefaults(self, varfont) -> "AxisLimits":
"""Return a new AxisLimits with defaults filled in from fvar table.
If all axis limits already have defaults, return self.
"""
fvar = varfont["fvar"]
fvarTriples = {
a.axisTag: (a.minValue, a.defaultValue, a.maxValue) for a in fvar.axes
}
newLimits = {}
for axisTag, triple in self.items():
fvarTriple = fvarTriples[axisTag]
default = fvarTriple[1]
if triple is None:
newLimits[axisTag] = AxisTriple(default, default, default)
else:
newLimits[axisTag] = triple.limitRangeAndPopulateDefaults(fvarTriple)
return type(self)(newLimits)
def normalize(self, varfont, usingAvar=True) -> "NormalizedAxisLimits":
"""Return a new NormalizedAxisLimits with normalized -1..0..+1 values.
If usingAvar is True, the avar table is used to warp the default normalization.
"""
fvar = varfont["fvar"]
badLimits = set(self.keys()).difference(a.axisTag for a in fvar.axes)
if badLimits:
raise ValueError("Cannot limit: {} not present in fvar".format(badLimits))
axes = {
a.axisTag: (a.minValue, a.defaultValue, a.maxValue)
for a in fvar.axes
if a.axisTag in self
}
avarSegments = {}
if usingAvar and "avar" in varfont:
avarSegments = varfont["avar"].segments
normalizedLimits = {}
for axis_tag, triple in axes.items():
distanceNegative = triple[1] - triple[0]
distancePositive = triple[2] - triple[1]
if self[axis_tag] is None:
normalizedLimits[axis_tag] = NormalizedAxisTripleAndDistances(
0, 0, 0, distanceNegative, distancePositive
)
continue
minV, defaultV, maxV = self[axis_tag]
if defaultV is None:
defaultV = triple[1]
avarMapping = avarSegments.get(axis_tag, None)
normalizedLimits[axis_tag] = NormalizedAxisTripleAndDistances(
*(normalize(v, triple, avarMapping) for v in (minV, defaultV, maxV)),
distanceNegative,
distancePositive,
)
return NormalizedAxisLimits(normalizedLimits)
class NormalizedAxisLimits(_BaseAxisLimits):
"""Maps axis tags (str) to NormalizedAxisTriple values."""
def __init__(self, *args, **kwargs):
self._data = data = {}
for k, v in dict(*args, **kwargs).items():
try:
triple = NormalizedAxisTripleAndDistances.expand(v)
except ValueError as e:
raise ValueError(f"Invalid axis limits for {k!r}: {v!r}") from e
data[k] = triple
class OverlapMode(IntEnum):
KEEP_AND_DONT_SET_FLAGS = 0
KEEP_AND_SET_FLAGS = 1
REMOVE = 2
REMOVE_AND_IGNORE_ERRORS = 3
def instantiateTupleVariationStore(
variations, axisLimits, origCoords=None, endPts=None
):
"""Instantiate TupleVariation list at the given location, or limit axes' min/max.
The 'variations' list of TupleVariation objects is modified in-place.
The 'axisLimits' (dict) maps axis tags (str) to NormalizedAxisTriple namedtuples
specifying (minimum, default, maximum) in the -1,0,+1 normalized space. Pinned axes
have minimum == default == maximum.
A 'full' instance (i.e. static font) is produced when all the axes are pinned to
single coordinates; a 'partial' instance (i.e. a less variable font) is produced
when some of the axes are omitted, or restricted with a new range.
Tuples that do not participate are kept as they are. Those that have 0 influence
at the given location are removed from the variation store.
Those that are fully instantiated (i.e. all their axes are being pinned) are also
removed from the variation store, their scaled deltas accummulated and returned, so
that they can be added by the caller to the default instance's coordinates.
Tuples that are only partially instantiated (i.e. not all the axes that they
participate in are being pinned) are kept in the store, and their deltas multiplied
by the scalar support of the axes to be pinned at the desired location.
Args:
variations: List[TupleVariation] from either 'gvar' or 'cvar'.
axisLimits: NormalizedAxisLimits: map from axis tags to (min, default, max)
normalized coordinates for the full or partial instance.
origCoords: GlyphCoordinates: default instance's coordinates for computing 'gvar'
inferred points (cf. table__g_l_y_f._getCoordinatesAndControls).
endPts: List[int]: indices of contour end points, for inferring 'gvar' deltas.
Returns:
List[float]: the overall delta adjustment after applicable deltas were summed.
"""
newVariations = changeTupleVariationsAxisLimits(variations, axisLimits)
mergedVariations = collections.OrderedDict()
for var in newVariations:
# compute inferred deltas only for gvar ('origCoords' is None for cvar)
if origCoords is not None:
var.calcInferredDeltas(origCoords, endPts)
# merge TupleVariations with overlapping "tents"
axes = frozenset(var.axes.items())
if axes in mergedVariations:
mergedVariations[axes] += var
else:
mergedVariations[axes] = var
# drop TupleVariation if all axes have been pinned (var.axes.items() is empty);
# its deltas will be added to the default instance's coordinates
defaultVar = mergedVariations.pop(frozenset(), None)
for var in mergedVariations.values():
var.roundDeltas()
variations[:] = list(mergedVariations.values())
return defaultVar.coordinates if defaultVar is not None else []
def changeTupleVariationsAxisLimits(variations, axisLimits):
for axisTag, axisLimit in sorted(axisLimits.items()):
newVariations = []
for var in variations:
newVariations.extend(changeTupleVariationAxisLimit(var, axisTag, axisLimit))
variations = newVariations
return variations
def changeTupleVariationAxisLimit(var, axisTag, axisLimit):
assert isinstance(axisLimit, NormalizedAxisTripleAndDistances)
# Skip when current axis is missing or peaks at 0 (i.e. doesn't participate)
lower, peak, upper = var.axes.get(axisTag, (-1, 0, 1))
if peak == 0:
# explicitly defined, no-op axes can be omitted
# https://github.com/fonttools/fonttools/issues/3453
if axisTag in var.axes:
del var.axes[axisTag]
return [var]
# Drop if the var 'tent' isn't well-formed
if not (lower <= peak <= upper) or (lower < 0 and upper > 0):
return []
if axisTag not in var.axes:
return [var]
tent = var.axes[axisTag]
solutions = solver.rebaseTent(tent, axisLimit)
out = []
for scalar, tent in solutions:
newVar = (
TupleVariation(var.axes, var.coordinates) if len(solutions) > 1 else var
)
if tent is None:
newVar.axes.pop(axisTag)
else:
assert tent[1] != 0, tent
newVar.axes[axisTag] = tent
newVar *= scalar
out.append(newVar)
return out
def _instantiateGvarGlyph(
glyphname, glyf, gvar, hMetrics, vMetrics, axisLimits, optimize=True
):
coordinates, ctrl = glyf._getCoordinatesAndControls(glyphname, hMetrics, vMetrics)
endPts = ctrl.endPts
# Not every glyph may have variations
tupleVarStore = gvar.variations.get(glyphname)
if tupleVarStore:
defaultDeltas = instantiateTupleVariationStore(
tupleVarStore, axisLimits, coordinates, endPts
)
if defaultDeltas:
coordinates += _g_l_y_f.GlyphCoordinates(defaultDeltas)
glyph = glyf[glyphname]
if glyph.isVarComposite():
for component in glyph.components:
newLocation = {}
for tag, loc in component.location.items():
if tag not in axisLimits:
newLocation[tag] = loc
continue
if component.flags & _g_l_y_f.VarComponentFlags.AXES_HAVE_VARIATION:
raise NotImplementedError(
"Instancing accross VarComposite axes with variation is not supported."
)
limits = axisLimits[tag]
loc = limits.renormalizeValue(loc, extrapolate=False)
newLocation[tag] = loc
component.location = newLocation
# _setCoordinates also sets the hmtx/vmtx advance widths and sidebearings from
# the four phantom points and glyph bounding boxes.
# We call it unconditionally even if a glyph has no variations or no deltas are
# applied at this location, in case the glyph's xMin and in turn its sidebearing
# have changed. E.g. a composite glyph has no deltas for the component's (x, y)
# offset nor for the 4 phantom points (e.g. it's monospaced). Thus its entry in
# gvar table is empty; however, the composite's base glyph may have deltas
# applied, hence the composite's bbox and left/top sidebearings may need updating
# in the instanced font.
glyf._setCoordinates(glyphname, coordinates, hMetrics, vMetrics)
if not tupleVarStore:
if glyphname in gvar.variations:
del gvar.variations[glyphname]
return
if optimize:
isComposite = glyf[glyphname].isComposite()
for var in tupleVarStore:
var.optimize(coordinates, endPts, isComposite=isComposite)
def instantiateGvarGlyph(varfont, glyphname, axisLimits, optimize=True):
"""Remove?
https://github.com/fonttools/fonttools/pull/2266"""
gvar = varfont["gvar"]
glyf = varfont["glyf"]
hMetrics = varfont["hmtx"].metrics
vMetrics = getattr(varfont.get("vmtx"), "metrics", None)
_instantiateGvarGlyph(
glyphname, glyf, gvar, hMetrics, vMetrics, axisLimits, optimize=optimize
)
def instantiateGvar(varfont, axisLimits, optimize=True):
log.info("Instantiating glyf/gvar tables")
gvar = varfont["gvar"]
glyf = varfont["glyf"]
hMetrics = varfont["hmtx"].metrics
vMetrics = getattr(varfont.get("vmtx"), "metrics", None)
# Get list of glyph names sorted by component depth.
# If a composite glyph is processed before its base glyph, the bounds may
# be calculated incorrectly because deltas haven't been applied to the
# base glyph yet.
glyphnames = sorted(
glyf.glyphOrder,
key=lambda name: (
(
glyf[name].getCompositeMaxpValues(glyf).maxComponentDepth
if glyf[name].isComposite() or glyf[name].isVarComposite()
else 0
),
name,
),
)
for glyphname in glyphnames:
_instantiateGvarGlyph(
glyphname, glyf, gvar, hMetrics, vMetrics, axisLimits, optimize=optimize
)
if not gvar.variations:
del varfont["gvar"]
def setCvarDeltas(cvt, deltas):
for i, delta in enumerate(deltas):
if delta:
cvt[i] += otRound(delta)
def instantiateCvar(varfont, axisLimits):
log.info("Instantiating cvt/cvar tables")
cvar = varfont["cvar"]
defaultDeltas = instantiateTupleVariationStore(cvar.variations, axisLimits)
if defaultDeltas:
setCvarDeltas(varfont["cvt "], defaultDeltas)
if not cvar.variations:
del varfont["cvar"]
def setMvarDeltas(varfont, deltas):
mvar = varfont["MVAR"].table
records = mvar.ValueRecord
for rec in records:
mvarTag = rec.ValueTag
if mvarTag not in MVAR_ENTRIES:
continue
tableTag, itemName = MVAR_ENTRIES[mvarTag]
delta = deltas[rec.VarIdx]
if delta != 0:
setattr(
varfont[tableTag],
itemName,
getattr(varfont[tableTag], itemName) + otRound(delta),
)
@contextmanager
def verticalMetricsKeptInSync(varfont):
"""Ensure hhea vertical metrics stay in sync with OS/2 ones after instancing.
When applying MVAR deltas to the OS/2 table, if the ascender, descender and
line gap change but they were the same as the respective hhea metrics in the
original font, this context manager ensures that hhea metrcs also get updated
accordingly.
The MVAR spec only has tags for the OS/2 metrics, but it is common in fonts
to have the hhea metrics be equal to those for compat reasons.
https://learn.microsoft.com/en-us/typography/opentype/spec/mvar
https://googlefonts.github.io/gf-guide/metrics.html#7-hhea-and-typo-metrics-should-be-equal
https://github.com/fonttools/fonttools/issues/3297
"""
current_os2_vmetrics = [
getattr(varfont["OS/2"], attr)
for attr in ("sTypoAscender", "sTypoDescender", "sTypoLineGap")
]
metrics_are_synced = current_os2_vmetrics == [
getattr(varfont["hhea"], attr) for attr in ("ascender", "descender", "lineGap")
]
yield metrics_are_synced
if metrics_are_synced:
new_os2_vmetrics = [
getattr(varfont["OS/2"], attr)
for attr in ("sTypoAscender", "sTypoDescender", "sTypoLineGap")
]
if current_os2_vmetrics != new_os2_vmetrics:
for attr, value in zip(
("ascender", "descender", "lineGap"), new_os2_vmetrics
):
setattr(varfont["hhea"], attr, value)
def instantiateMVAR(varfont, axisLimits):
log.info("Instantiating MVAR table")
mvar = varfont["MVAR"].table
fvarAxes = varfont["fvar"].axes
varStore = mvar.VarStore
defaultDeltas = instantiateItemVariationStore(varStore, fvarAxes, axisLimits)
with verticalMetricsKeptInSync(varfont):
setMvarDeltas(varfont, defaultDeltas)
if varStore.VarRegionList.Region:
varIndexMapping = varStore.optimize()
for rec in mvar.ValueRecord:
rec.VarIdx = varIndexMapping[rec.VarIdx]
else:
del varfont["MVAR"]
def _remapVarIdxMap(table, attrName, varIndexMapping, glyphOrder):
oldMapping = getattr(table, attrName).mapping
newMapping = [varIndexMapping[oldMapping[glyphName]] for glyphName in glyphOrder]
setattr(table, attrName, builder.buildVarIdxMap(newMapping, glyphOrder))
# TODO(anthrotype) Add support for HVAR/VVAR in CFF2
def _instantiateVHVAR(varfont, axisLimits, tableFields):
location = axisLimits.pinnedLocation()
tableTag = tableFields.tableTag
fvarAxes = varfont["fvar"].axes
# Deltas from gvar table have already been applied to the hmtx/vmtx. For full
# instances (i.e. all axes pinned), we can simply drop HVAR/VVAR and return
if set(location).issuperset(axis.axisTag for axis in fvarAxes):
log.info("Dropping %s table", tableTag)
del varfont[tableTag]
return
log.info("Instantiating %s table", tableTag)
vhvar = varfont[tableTag].table
varStore = vhvar.VarStore
# since deltas were already applied, the return value here is ignored
instantiateItemVariationStore(varStore, fvarAxes, axisLimits)
if varStore.VarRegionList.Region:
# Only re-optimize VarStore if the HVAR/VVAR already uses indirect AdvWidthMap
# or AdvHeightMap. If a direct, implicit glyphID->VariationIndex mapping is
# used for advances, skip re-optimizing and maintain original VariationIndex.
if getattr(vhvar, tableFields.advMapping):
varIndexMapping = varStore.optimize(use_NO_VARIATION_INDEX=False)
glyphOrder = varfont.getGlyphOrder()
_remapVarIdxMap(vhvar, tableFields.advMapping, varIndexMapping, glyphOrder)
if getattr(vhvar, tableFields.sb1): # left or top sidebearings
_remapVarIdxMap(vhvar, tableFields.sb1, varIndexMapping, glyphOrder)
if getattr(vhvar, tableFields.sb2): # right or bottom sidebearings
_remapVarIdxMap(vhvar, tableFields.sb2, varIndexMapping, glyphOrder)
if tableTag == "VVAR" and getattr(vhvar, tableFields.vOrigMapping):
_remapVarIdxMap(
vhvar, tableFields.vOrigMapping, varIndexMapping, glyphOrder
)
def instantiateHVAR(varfont, axisLimits):
return _instantiateVHVAR(varfont, axisLimits, varLib.HVAR_FIELDS)
def instantiateVVAR(varfont, axisLimits):
return _instantiateVHVAR(varfont, axisLimits, varLib.VVAR_FIELDS)
class _TupleVarStoreAdapter(object):
def __init__(self, regions, axisOrder, tupleVarData, itemCounts):
self.regions = regions
self.axisOrder = axisOrder
self.tupleVarData = tupleVarData
self.itemCounts = itemCounts
@classmethod
def fromItemVarStore(cls, itemVarStore, fvarAxes):
axisOrder = [axis.axisTag for axis in fvarAxes]
regions = [
region.get_support(fvarAxes) for region in itemVarStore.VarRegionList.Region
]
tupleVarData = []
itemCounts = []
for varData in itemVarStore.VarData:
variations = []
varDataRegions = (regions[i] for i in varData.VarRegionIndex)
for axes, coordinates in zip(varDataRegions, zip(*varData.Item)):
variations.append(TupleVariation(axes, list(coordinates)))
tupleVarData.append(variations)
itemCounts.append(varData.ItemCount)
return cls(regions, axisOrder, tupleVarData, itemCounts)
def rebuildRegions(self):
# Collect the set of all unique region axes from the current TupleVariations.
# We use an OrderedDict to de-duplicate regions while keeping the order.
uniqueRegions = collections.OrderedDict.fromkeys(
(
frozenset(var.axes.items())
for variations in self.tupleVarData
for var in variations
)
)
# Maintain the original order for the regions that pre-existed, appending
# the new regions at the end of the region list.
newRegions = []
for region in self.regions:
regionAxes = frozenset(region.items())
if regionAxes in uniqueRegions:
newRegions.append(region)
del uniqueRegions[regionAxes]
if uniqueRegions:
newRegions.extend(dict(region) for region in uniqueRegions)
self.regions = newRegions
def instantiate(self, axisLimits):
defaultDeltaArray = []
for variations, itemCount in zip(self.tupleVarData, self.itemCounts):
defaultDeltas = instantiateTupleVariationStore(variations, axisLimits)
if not defaultDeltas:
defaultDeltas = [0] * itemCount
defaultDeltaArray.append(defaultDeltas)
# rebuild regions whose axes were dropped or limited
self.rebuildRegions()
pinnedAxes = set(axisLimits.pinnedLocation())
self.axisOrder = [
axisTag for axisTag in self.axisOrder if axisTag not in pinnedAxes
]
return defaultDeltaArray
def asItemVarStore(self):
regionOrder = [frozenset(axes.items()) for axes in self.regions]
varDatas = []
for variations, itemCount in zip(self.tupleVarData, self.itemCounts):
if variations:
assert len(variations[0].coordinates) == itemCount
varRegionIndices = [
regionOrder.index(frozenset(var.axes.items())) for var in variations
]
varDataItems = list(zip(*(var.coordinates for var in variations)))
varDatas.append(
builder.buildVarData(varRegionIndices, varDataItems, optimize=False)
)
else:
varDatas.append(
builder.buildVarData([], [[] for _ in range(itemCount)])
)
regionList = builder.buildVarRegionList(self.regions, self.axisOrder)
itemVarStore = builder.buildVarStore(regionList, varDatas)
# remove unused regions from VarRegionList
itemVarStore.prune_regions()
return itemVarStore
def instantiateItemVariationStore(itemVarStore, fvarAxes, axisLimits):
"""Compute deltas at partial location, and update varStore in-place.
Remove regions in which all axes were instanced, or fall outside the new axis
limits. Scale the deltas of the remaining regions where only some of the axes
were instanced.
The number of VarData subtables, and the number of items within each, are
not modified, in order to keep the existing VariationIndex valid.
One may call VarStore.optimize() method after this to further optimize those.
Args:
varStore: An otTables.VarStore object (Item Variation Store)
fvarAxes: list of fvar's Axis objects
axisLimits: NormalizedAxisLimits: mapping axis tags to normalized
min/default/max axis coordinates. May not specify coordinates/ranges for
all the fvar axes.
Returns:
defaultDeltas: to be added to the default instance, of type dict of floats
keyed by VariationIndex compound values: i.e. (outer << 16) + inner.
"""
tupleVarStore = _TupleVarStoreAdapter.fromItemVarStore(itemVarStore, fvarAxes)
defaultDeltaArray = tupleVarStore.instantiate(axisLimits)
newItemVarStore = tupleVarStore.asItemVarStore()
itemVarStore.VarRegionList = newItemVarStore.VarRegionList
assert itemVarStore.VarDataCount == newItemVarStore.VarDataCount
itemVarStore.VarData = newItemVarStore.VarData
defaultDeltas = {
((major << 16) + minor): delta
for major, deltas in enumerate(defaultDeltaArray)
for minor, delta in enumerate(deltas)
}
defaultDeltas[itemVarStore.NO_VARIATION_INDEX] = 0
return defaultDeltas
def instantiateOTL(varfont, axisLimits):
# TODO(anthrotype) Support partial instancing of JSTF and BASE tables
if (
"GDEF" not in varfont
or varfont["GDEF"].table.Version < 0x00010003
or not varfont["GDEF"].table.VarStore
):
return
if "GPOS" in varfont:
msg = "Instantiating GDEF and GPOS tables"
else:
msg = "Instantiating GDEF table"
log.info(msg)
gdef = varfont["GDEF"].table
varStore = gdef.VarStore
fvarAxes = varfont["fvar"].axes
defaultDeltas = instantiateItemVariationStore(varStore, fvarAxes, axisLimits)
# When VF are built, big lookups may overflow and be broken into multiple
# subtables. MutatorMerger (which inherits from AligningMerger) reattaches
# them upon instancing, in case they can now fit a single subtable (if not,
# they will be split again upon compilation).
# This 'merger' also works as a 'visitor' that traverses the OTL tables and
# calls specific methods when instances of a given type are found.
# Specifically, it adds default deltas to GPOS Anchors/ValueRecords and GDEF
# LigatureCarets, and optionally deletes all VariationIndex tables if the
# VarStore is fully instanced.
merger = MutatorMerger(
varfont, defaultDeltas, deleteVariations=(not varStore.VarRegionList.Region)
)
merger.mergeTables(varfont, [varfont], ["GDEF", "GPOS"])
if varStore.VarRegionList.Region:
varIndexMapping = varStore.optimize()
gdef.remap_device_varidxes(varIndexMapping)
if "GPOS" in varfont:
varfont["GPOS"].table.remap_device_varidxes(varIndexMapping)
else:
# Downgrade GDEF.
del gdef.VarStore
gdef.Version = 0x00010002
if gdef.MarkGlyphSetsDef is None:
del gdef.MarkGlyphSetsDef
gdef.Version = 0x00010000
if not (
gdef.LigCaretList
or gdef.MarkAttachClassDef
or gdef.GlyphClassDef
or gdef.AttachList
or (gdef.Version >= 0x00010002 and gdef.MarkGlyphSetsDef)
):
del varfont["GDEF"]
def _isValidAvarSegmentMap(axisTag, segmentMap):
if not segmentMap:
return True
if not {(-1.0, -1.0), (0, 0), (1.0, 1.0)}.issubset(segmentMap.items()):