fonttools 4.60.2__cp311-cp311-win32.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- fontTools/__init__.py +8 -0
- fontTools/__main__.py +35 -0
- fontTools/afmLib.py +439 -0
- fontTools/agl.py +5233 -0
- fontTools/annotations.py +30 -0
- fontTools/cffLib/CFF2ToCFF.py +258 -0
- fontTools/cffLib/CFFToCFF2.py +305 -0
- fontTools/cffLib/__init__.py +3694 -0
- fontTools/cffLib/specializer.py +927 -0
- fontTools/cffLib/transforms.py +495 -0
- fontTools/cffLib/width.py +210 -0
- fontTools/colorLib/__init__.py +0 -0
- fontTools/colorLib/builder.py +664 -0
- fontTools/colorLib/errors.py +2 -0
- fontTools/colorLib/geometry.py +143 -0
- fontTools/colorLib/table_builder.py +223 -0
- fontTools/colorLib/unbuilder.py +81 -0
- fontTools/config/__init__.py +90 -0
- fontTools/cu2qu/__init__.py +15 -0
- fontTools/cu2qu/__main__.py +6 -0
- fontTools/cu2qu/benchmark.py +54 -0
- fontTools/cu2qu/cli.py +198 -0
- fontTools/cu2qu/cu2qu.c +15817 -0
- fontTools/cu2qu/cu2qu.cp311-win32.pyd +0 -0
- fontTools/cu2qu/cu2qu.py +563 -0
- fontTools/cu2qu/errors.py +77 -0
- fontTools/cu2qu/ufo.py +363 -0
- fontTools/designspaceLib/__init__.py +3343 -0
- fontTools/designspaceLib/__main__.py +6 -0
- fontTools/designspaceLib/split.py +475 -0
- fontTools/designspaceLib/statNames.py +260 -0
- fontTools/designspaceLib/types.py +147 -0
- fontTools/encodings/MacRoman.py +258 -0
- fontTools/encodings/StandardEncoding.py +258 -0
- fontTools/encodings/__init__.py +1 -0
- fontTools/encodings/codecs.py +135 -0
- fontTools/feaLib/__init__.py +4 -0
- fontTools/feaLib/__main__.py +78 -0
- fontTools/feaLib/ast.py +2143 -0
- fontTools/feaLib/builder.py +1814 -0
- fontTools/feaLib/error.py +22 -0
- fontTools/feaLib/lexer.c +17029 -0
- fontTools/feaLib/lexer.cp311-win32.pyd +0 -0
- fontTools/feaLib/lexer.py +287 -0
- fontTools/feaLib/location.py +12 -0
- fontTools/feaLib/lookupDebugInfo.py +12 -0
- fontTools/feaLib/parser.py +2394 -0
- fontTools/feaLib/variableScalar.py +118 -0
- fontTools/fontBuilder.py +1014 -0
- fontTools/help.py +36 -0
- fontTools/merge/__init__.py +248 -0
- fontTools/merge/__main__.py +6 -0
- fontTools/merge/base.py +81 -0
- fontTools/merge/cmap.py +173 -0
- fontTools/merge/layout.py +526 -0
- fontTools/merge/options.py +85 -0
- fontTools/merge/tables.py +352 -0
- fontTools/merge/unicode.py +78 -0
- fontTools/merge/util.py +143 -0
- fontTools/misc/__init__.py +1 -0
- fontTools/misc/arrayTools.py +424 -0
- fontTools/misc/bezierTools.c +39731 -0
- fontTools/misc/bezierTools.cp311-win32.pyd +0 -0
- fontTools/misc/bezierTools.py +1500 -0
- fontTools/misc/classifyTools.py +170 -0
- fontTools/misc/cliTools.py +53 -0
- fontTools/misc/configTools.py +349 -0
- fontTools/misc/cython.py +27 -0
- fontTools/misc/dictTools.py +83 -0
- fontTools/misc/eexec.py +119 -0
- fontTools/misc/encodingTools.py +72 -0
- fontTools/misc/enumTools.py +23 -0
- fontTools/misc/etree.py +456 -0
- fontTools/misc/filenames.py +245 -0
- fontTools/misc/filesystem/__init__.py +68 -0
- fontTools/misc/filesystem/_base.py +134 -0
- fontTools/misc/filesystem/_copy.py +45 -0
- fontTools/misc/filesystem/_errors.py +54 -0
- fontTools/misc/filesystem/_info.py +75 -0
- fontTools/misc/filesystem/_osfs.py +164 -0
- fontTools/misc/filesystem/_path.py +67 -0
- fontTools/misc/filesystem/_subfs.py +92 -0
- fontTools/misc/filesystem/_tempfs.py +34 -0
- fontTools/misc/filesystem/_tools.py +34 -0
- fontTools/misc/filesystem/_walk.py +55 -0
- fontTools/misc/filesystem/_zipfs.py +204 -0
- fontTools/misc/fixedTools.py +253 -0
- fontTools/misc/intTools.py +25 -0
- fontTools/misc/iterTools.py +12 -0
- fontTools/misc/lazyTools.py +42 -0
- fontTools/misc/loggingTools.py +543 -0
- fontTools/misc/macCreatorType.py +56 -0
- fontTools/misc/macRes.py +261 -0
- fontTools/misc/plistlib/__init__.py +681 -0
- fontTools/misc/plistlib/py.typed +0 -0
- fontTools/misc/psCharStrings.py +1511 -0
- fontTools/misc/psLib.py +398 -0
- fontTools/misc/psOperators.py +572 -0
- fontTools/misc/py23.py +96 -0
- fontTools/misc/roundTools.py +110 -0
- fontTools/misc/sstruct.py +227 -0
- fontTools/misc/symfont.py +242 -0
- fontTools/misc/testTools.py +233 -0
- fontTools/misc/textTools.py +156 -0
- fontTools/misc/timeTools.py +88 -0
- fontTools/misc/transform.py +516 -0
- fontTools/misc/treeTools.py +45 -0
- fontTools/misc/vector.py +147 -0
- fontTools/misc/visitor.py +158 -0
- fontTools/misc/xmlReader.py +188 -0
- fontTools/misc/xmlWriter.py +231 -0
- fontTools/mtiLib/__init__.py +1400 -0
- fontTools/mtiLib/__main__.py +5 -0
- fontTools/otlLib/__init__.py +1 -0
- fontTools/otlLib/builder.py +3465 -0
- fontTools/otlLib/error.py +11 -0
- fontTools/otlLib/maxContextCalc.py +96 -0
- fontTools/otlLib/optimize/__init__.py +53 -0
- fontTools/otlLib/optimize/__main__.py +6 -0
- fontTools/otlLib/optimize/gpos.py +439 -0
- fontTools/pens/__init__.py +1 -0
- fontTools/pens/areaPen.py +52 -0
- fontTools/pens/basePen.py +475 -0
- fontTools/pens/boundsPen.py +98 -0
- fontTools/pens/cairoPen.py +26 -0
- fontTools/pens/cocoaPen.py +26 -0
- fontTools/pens/cu2quPen.py +325 -0
- fontTools/pens/explicitClosingLinePen.py +101 -0
- fontTools/pens/filterPen.py +433 -0
- fontTools/pens/freetypePen.py +462 -0
- fontTools/pens/hashPointPen.py +89 -0
- fontTools/pens/momentsPen.c +13378 -0
- fontTools/pens/momentsPen.cp311-win32.pyd +0 -0
- fontTools/pens/momentsPen.py +879 -0
- fontTools/pens/perimeterPen.py +69 -0
- fontTools/pens/pointInsidePen.py +192 -0
- fontTools/pens/pointPen.py +643 -0
- fontTools/pens/qtPen.py +29 -0
- fontTools/pens/qu2cuPen.py +105 -0
- fontTools/pens/quartzPen.py +43 -0
- fontTools/pens/recordingPen.py +335 -0
- fontTools/pens/reportLabPen.py +79 -0
- fontTools/pens/reverseContourPen.py +96 -0
- fontTools/pens/roundingPen.py +130 -0
- fontTools/pens/statisticsPen.py +312 -0
- fontTools/pens/svgPathPen.py +310 -0
- fontTools/pens/t2CharStringPen.py +88 -0
- fontTools/pens/teePen.py +55 -0
- fontTools/pens/transformPen.py +115 -0
- fontTools/pens/ttGlyphPen.py +335 -0
- fontTools/pens/wxPen.py +29 -0
- fontTools/qu2cu/__init__.py +15 -0
- fontTools/qu2cu/__main__.py +7 -0
- fontTools/qu2cu/benchmark.py +56 -0
- fontTools/qu2cu/cli.py +125 -0
- fontTools/qu2cu/qu2cu.c +16682 -0
- fontTools/qu2cu/qu2cu.cp311-win32.pyd +0 -0
- fontTools/qu2cu/qu2cu.py +405 -0
- fontTools/subset/__init__.py +4096 -0
- fontTools/subset/__main__.py +6 -0
- fontTools/subset/cff.py +184 -0
- fontTools/subset/svg.py +253 -0
- fontTools/subset/util.py +25 -0
- fontTools/svgLib/__init__.py +3 -0
- fontTools/svgLib/path/__init__.py +65 -0
- fontTools/svgLib/path/arc.py +154 -0
- fontTools/svgLib/path/parser.py +322 -0
- fontTools/svgLib/path/shapes.py +183 -0
- fontTools/t1Lib/__init__.py +648 -0
- fontTools/tfmLib.py +460 -0
- fontTools/ttLib/__init__.py +30 -0
- fontTools/ttLib/__main__.py +148 -0
- fontTools/ttLib/macUtils.py +54 -0
- fontTools/ttLib/removeOverlaps.py +395 -0
- fontTools/ttLib/reorderGlyphs.py +285 -0
- fontTools/ttLib/scaleUpem.py +436 -0
- fontTools/ttLib/sfnt.py +661 -0
- fontTools/ttLib/standardGlyphOrder.py +271 -0
- fontTools/ttLib/tables/B_A_S_E_.py +14 -0
- fontTools/ttLib/tables/BitmapGlyphMetrics.py +64 -0
- fontTools/ttLib/tables/C_B_D_T_.py +113 -0
- fontTools/ttLib/tables/C_B_L_C_.py +19 -0
- fontTools/ttLib/tables/C_F_F_.py +61 -0
- fontTools/ttLib/tables/C_F_F__2.py +26 -0
- fontTools/ttLib/tables/C_O_L_R_.py +165 -0
- fontTools/ttLib/tables/C_P_A_L_.py +305 -0
- fontTools/ttLib/tables/D_S_I_G_.py +158 -0
- fontTools/ttLib/tables/D__e_b_g.py +35 -0
- fontTools/ttLib/tables/DefaultTable.py +49 -0
- fontTools/ttLib/tables/E_B_D_T_.py +835 -0
- fontTools/ttLib/tables/E_B_L_C_.py +718 -0
- fontTools/ttLib/tables/F_F_T_M_.py +52 -0
- fontTools/ttLib/tables/F__e_a_t.py +149 -0
- fontTools/ttLib/tables/G_D_E_F_.py +13 -0
- fontTools/ttLib/tables/G_M_A_P_.py +148 -0
- fontTools/ttLib/tables/G_P_K_G_.py +133 -0
- fontTools/ttLib/tables/G_P_O_S_.py +14 -0
- fontTools/ttLib/tables/G_S_U_B_.py +13 -0
- fontTools/ttLib/tables/G_V_A_R_.py +5 -0
- fontTools/ttLib/tables/G__l_a_t.py +235 -0
- fontTools/ttLib/tables/G__l_o_c.py +85 -0
- fontTools/ttLib/tables/H_V_A_R_.py +13 -0
- fontTools/ttLib/tables/J_S_T_F_.py +13 -0
- fontTools/ttLib/tables/L_T_S_H_.py +58 -0
- fontTools/ttLib/tables/M_A_T_H_.py +13 -0
- fontTools/ttLib/tables/M_E_T_A_.py +352 -0
- fontTools/ttLib/tables/M_V_A_R_.py +13 -0
- fontTools/ttLib/tables/O_S_2f_2.py +752 -0
- fontTools/ttLib/tables/S_I_N_G_.py +99 -0
- fontTools/ttLib/tables/S_T_A_T_.py +15 -0
- fontTools/ttLib/tables/S_V_G_.py +223 -0
- fontTools/ttLib/tables/S__i_l_f.py +1040 -0
- fontTools/ttLib/tables/S__i_l_l.py +92 -0
- fontTools/ttLib/tables/T_S_I_B_.py +13 -0
- fontTools/ttLib/tables/T_S_I_C_.py +14 -0
- fontTools/ttLib/tables/T_S_I_D_.py +13 -0
- fontTools/ttLib/tables/T_S_I_J_.py +13 -0
- fontTools/ttLib/tables/T_S_I_P_.py +13 -0
- fontTools/ttLib/tables/T_S_I_S_.py +13 -0
- fontTools/ttLib/tables/T_S_I_V_.py +26 -0
- fontTools/ttLib/tables/T_S_I__0.py +70 -0
- fontTools/ttLib/tables/T_S_I__1.py +163 -0
- fontTools/ttLib/tables/T_S_I__2.py +17 -0
- fontTools/ttLib/tables/T_S_I__3.py +22 -0
- fontTools/ttLib/tables/T_S_I__5.py +60 -0
- fontTools/ttLib/tables/T_T_F_A_.py +14 -0
- fontTools/ttLib/tables/TupleVariation.py +884 -0
- fontTools/ttLib/tables/V_A_R_C_.py +12 -0
- fontTools/ttLib/tables/V_D_M_X_.py +249 -0
- fontTools/ttLib/tables/V_O_R_G_.py +165 -0
- fontTools/ttLib/tables/V_V_A_R_.py +13 -0
- fontTools/ttLib/tables/__init__.py +98 -0
- fontTools/ttLib/tables/_a_n_k_r.py +15 -0
- fontTools/ttLib/tables/_a_v_a_r.py +193 -0
- fontTools/ttLib/tables/_b_s_l_n.py +15 -0
- fontTools/ttLib/tables/_c_i_d_g.py +24 -0
- fontTools/ttLib/tables/_c_m_a_p.py +1591 -0
- fontTools/ttLib/tables/_c_v_a_r.py +94 -0
- fontTools/ttLib/tables/_c_v_t.py +56 -0
- fontTools/ttLib/tables/_f_e_a_t.py +15 -0
- fontTools/ttLib/tables/_f_p_g_m.py +62 -0
- fontTools/ttLib/tables/_f_v_a_r.py +261 -0
- fontTools/ttLib/tables/_g_a_s_p.py +63 -0
- fontTools/ttLib/tables/_g_c_i_d.py +13 -0
- fontTools/ttLib/tables/_g_l_y_f.py +2311 -0
- fontTools/ttLib/tables/_g_v_a_r.py +340 -0
- fontTools/ttLib/tables/_h_d_m_x.py +127 -0
- fontTools/ttLib/tables/_h_e_a_d.py +130 -0
- fontTools/ttLib/tables/_h_h_e_a.py +147 -0
- fontTools/ttLib/tables/_h_m_t_x.py +164 -0
- fontTools/ttLib/tables/_k_e_r_n.py +289 -0
- fontTools/ttLib/tables/_l_c_a_r.py +13 -0
- fontTools/ttLib/tables/_l_o_c_a.py +70 -0
- fontTools/ttLib/tables/_l_t_a_g.py +72 -0
- fontTools/ttLib/tables/_m_a_x_p.py +147 -0
- fontTools/ttLib/tables/_m_e_t_a.py +112 -0
- fontTools/ttLib/tables/_m_o_r_t.py +14 -0
- fontTools/ttLib/tables/_m_o_r_x.py +15 -0
- fontTools/ttLib/tables/_n_a_m_e.py +1242 -0
- fontTools/ttLib/tables/_o_p_b_d.py +14 -0
- fontTools/ttLib/tables/_p_o_s_t.py +319 -0
- fontTools/ttLib/tables/_p_r_e_p.py +16 -0
- fontTools/ttLib/tables/_p_r_o_p.py +12 -0
- fontTools/ttLib/tables/_s_b_i_x.py +129 -0
- fontTools/ttLib/tables/_t_r_a_k.py +332 -0
- fontTools/ttLib/tables/_v_h_e_a.py +139 -0
- fontTools/ttLib/tables/_v_m_t_x.py +19 -0
- fontTools/ttLib/tables/asciiTable.py +20 -0
- fontTools/ttLib/tables/grUtils.py +92 -0
- fontTools/ttLib/tables/otBase.py +1458 -0
- fontTools/ttLib/tables/otConverters.py +2068 -0
- fontTools/ttLib/tables/otData.py +6400 -0
- fontTools/ttLib/tables/otTables.py +2703 -0
- fontTools/ttLib/tables/otTraverse.py +163 -0
- fontTools/ttLib/tables/sbixGlyph.py +149 -0
- fontTools/ttLib/tables/sbixStrike.py +177 -0
- fontTools/ttLib/tables/table_API_readme.txt +91 -0
- fontTools/ttLib/tables/ttProgram.py +594 -0
- fontTools/ttLib/ttCollection.py +125 -0
- fontTools/ttLib/ttFont.py +1148 -0
- fontTools/ttLib/ttGlyphSet.py +490 -0
- fontTools/ttLib/ttVisitor.py +32 -0
- fontTools/ttLib/woff2.py +1680 -0
- fontTools/ttx.py +479 -0
- fontTools/ufoLib/__init__.py +2575 -0
- fontTools/ufoLib/converters.py +407 -0
- fontTools/ufoLib/errors.py +30 -0
- fontTools/ufoLib/etree.py +6 -0
- fontTools/ufoLib/filenames.py +356 -0
- fontTools/ufoLib/glifLib.py +2120 -0
- fontTools/ufoLib/kerning.py +141 -0
- fontTools/ufoLib/plistlib.py +47 -0
- fontTools/ufoLib/pointPen.py +6 -0
- fontTools/ufoLib/utils.py +107 -0
- fontTools/ufoLib/validators.py +1208 -0
- fontTools/unicode.py +50 -0
- fontTools/unicodedata/Blocks.py +817 -0
- fontTools/unicodedata/Mirrored.py +446 -0
- fontTools/unicodedata/OTTags.py +50 -0
- fontTools/unicodedata/ScriptExtensions.py +832 -0
- fontTools/unicodedata/Scripts.py +3639 -0
- fontTools/unicodedata/__init__.py +306 -0
- fontTools/varLib/__init__.py +1600 -0
- fontTools/varLib/__main__.py +6 -0
- fontTools/varLib/avar/__init__.py +0 -0
- fontTools/varLib/avar/__main__.py +72 -0
- fontTools/varLib/avar/build.py +79 -0
- fontTools/varLib/avar/map.py +108 -0
- fontTools/varLib/avar/plan.py +1004 -0
- fontTools/varLib/avar/unbuild.py +271 -0
- fontTools/varLib/avarPlanner.py +8 -0
- fontTools/varLib/builder.py +215 -0
- fontTools/varLib/cff.py +631 -0
- fontTools/varLib/errors.py +219 -0
- fontTools/varLib/featureVars.py +703 -0
- fontTools/varLib/hvar.py +113 -0
- fontTools/varLib/instancer/__init__.py +2052 -0
- fontTools/varLib/instancer/__main__.py +5 -0
- fontTools/varLib/instancer/featureVars.py +190 -0
- fontTools/varLib/instancer/names.py +388 -0
- fontTools/varLib/instancer/solver.py +309 -0
- fontTools/varLib/interpolatable.py +1209 -0
- fontTools/varLib/interpolatableHelpers.py +399 -0
- fontTools/varLib/interpolatablePlot.py +1269 -0
- fontTools/varLib/interpolatableTestContourOrder.py +82 -0
- fontTools/varLib/interpolatableTestStartingPoint.py +107 -0
- fontTools/varLib/interpolate_layout.py +124 -0
- fontTools/varLib/iup.c +19815 -0
- fontTools/varLib/iup.cp311-win32.pyd +0 -0
- fontTools/varLib/iup.py +490 -0
- fontTools/varLib/merger.py +1717 -0
- fontTools/varLib/models.py +642 -0
- fontTools/varLib/multiVarStore.py +253 -0
- fontTools/varLib/mutator.py +529 -0
- fontTools/varLib/mvar.py +40 -0
- fontTools/varLib/plot.py +238 -0
- fontTools/varLib/stat.py +149 -0
- fontTools/varLib/varStore.py +739 -0
- fontTools/voltLib/__init__.py +5 -0
- fontTools/voltLib/__main__.py +206 -0
- fontTools/voltLib/ast.py +452 -0
- fontTools/voltLib/error.py +12 -0
- fontTools/voltLib/lexer.py +99 -0
- fontTools/voltLib/parser.py +664 -0
- fontTools/voltLib/voltToFea.py +911 -0
- fonttools-4.60.2.data/data/share/man/man1/ttx.1 +225 -0
- fonttools-4.60.2.dist-info/METADATA +2250 -0
- fonttools-4.60.2.dist-info/RECORD +353 -0
- fonttools-4.60.2.dist-info/WHEEL +5 -0
- fonttools-4.60.2.dist-info/entry_points.txt +5 -0
- fonttools-4.60.2.dist-info/licenses/LICENSE +21 -0
- fonttools-4.60.2.dist-info/licenses/LICENSE.external +388 -0
- fonttools-4.60.2.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,1600 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Module for dealing with 'gvar'-style font variations, also known as run-time
|
|
3
|
+
interpolation.
|
|
4
|
+
|
|
5
|
+
The ideas here are very similar to MutatorMath. There is even code to read
|
|
6
|
+
MutatorMath .designspace files in the varLib.designspace module.
|
|
7
|
+
|
|
8
|
+
For now, if you run this file on a designspace file, it tries to find
|
|
9
|
+
ttf-interpolatable files for the masters and build a variable-font from
|
|
10
|
+
them. Such ttf-interpolatable and designspace files can be generated from
|
|
11
|
+
a Glyphs source, eg., using noto-source as an example:
|
|
12
|
+
|
|
13
|
+
.. code-block:: sh
|
|
14
|
+
|
|
15
|
+
$ fontmake -o ttf-interpolatable -g NotoSansArabic-MM.glyphs
|
|
16
|
+
|
|
17
|
+
Then you can make a variable-font this way:
|
|
18
|
+
|
|
19
|
+
.. code-block:: sh
|
|
20
|
+
|
|
21
|
+
$ fonttools varLib master_ufo/NotoSansArabic.designspace
|
|
22
|
+
|
|
23
|
+
API *will* change in near future.
|
|
24
|
+
"""
|
|
25
|
+
|
|
26
|
+
from typing import List
|
|
27
|
+
from fontTools.misc.vector import Vector
|
|
28
|
+
from fontTools.misc.roundTools import noRound, otRound
|
|
29
|
+
from fontTools.misc.fixedTools import floatToFixed as fl2fi
|
|
30
|
+
from fontTools.misc.textTools import Tag, tostr
|
|
31
|
+
from fontTools.ttLib import TTFont, newTable
|
|
32
|
+
from fontTools.ttLib.tables._f_v_a_r import Axis, NamedInstance
|
|
33
|
+
from fontTools.ttLib.tables._g_l_y_f import (
|
|
34
|
+
GlyphCoordinates,
|
|
35
|
+
dropImpliedOnCurvePoints,
|
|
36
|
+
USE_MY_METRICS,
|
|
37
|
+
)
|
|
38
|
+
from fontTools.ttLib.tables.ttProgram import Program
|
|
39
|
+
from fontTools.ttLib.tables.TupleVariation import TupleVariation
|
|
40
|
+
from fontTools.ttLib.tables import otTables as ot
|
|
41
|
+
from fontTools.ttLib.tables.otBase import OTTableWriter
|
|
42
|
+
from fontTools.varLib import builder, models, varStore
|
|
43
|
+
from fontTools.varLib.merger import VariationMerger, COLRVariationMerger
|
|
44
|
+
from fontTools.varLib.mvar import MVAR_ENTRIES
|
|
45
|
+
from fontTools.varLib.iup import iup_delta_optimize
|
|
46
|
+
from fontTools.varLib.featureVars import addFeatureVariations
|
|
47
|
+
from fontTools.designspaceLib import DesignSpaceDocument, InstanceDescriptor
|
|
48
|
+
from fontTools.designspaceLib.split import splitInterpolable, splitVariableFonts
|
|
49
|
+
from fontTools.varLib.stat import buildVFStatTable
|
|
50
|
+
from fontTools.colorLib.builder import buildColrV1
|
|
51
|
+
from fontTools.colorLib.unbuilder import unbuildColrV1
|
|
52
|
+
from functools import partial
|
|
53
|
+
from collections import OrderedDict, defaultdict, namedtuple
|
|
54
|
+
import os.path
|
|
55
|
+
import logging
|
|
56
|
+
from copy import deepcopy
|
|
57
|
+
from pprint import pformat
|
|
58
|
+
from re import fullmatch
|
|
59
|
+
from .errors import VarLibError, VarLibValidationError
|
|
60
|
+
|
|
61
|
+
log = logging.getLogger("fontTools.varLib")
|
|
62
|
+
|
|
63
|
+
# This is a lib key for the designspace document. The value should be
|
|
64
|
+
# a comma-separated list of OpenType feature tag(s), to be used as the
|
|
65
|
+
# FeatureVariations feature.
|
|
66
|
+
# If present, the DesignSpace <rules processing="..."> flag is ignored.
|
|
67
|
+
FEAVAR_FEATURETAG_LIB_KEY = "com.github.fonttools.varLib.featureVarsFeatureTag"
|
|
68
|
+
|
|
69
|
+
#
|
|
70
|
+
# Creation routines
|
|
71
|
+
#
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def _add_fvar(font, axes, instances: List[InstanceDescriptor]):
|
|
75
|
+
"""
|
|
76
|
+
Add 'fvar' table to font.
|
|
77
|
+
|
|
78
|
+
axes is an ordered dictionary of DesignspaceAxis objects.
|
|
79
|
+
|
|
80
|
+
instances is list of dictionary objects with 'location', 'stylename',
|
|
81
|
+
and possibly 'postscriptfontname' entries.
|
|
82
|
+
"""
|
|
83
|
+
|
|
84
|
+
assert axes
|
|
85
|
+
assert isinstance(axes, OrderedDict)
|
|
86
|
+
|
|
87
|
+
log.info("Generating fvar")
|
|
88
|
+
|
|
89
|
+
fvar = newTable("fvar")
|
|
90
|
+
nameTable = font["name"]
|
|
91
|
+
|
|
92
|
+
# if there are not currently any mac names don't add them here, that's inconsistent
|
|
93
|
+
# https://github.com/fonttools/fonttools/issues/683
|
|
94
|
+
macNames = any(nr.platformID == 1 for nr in getattr(nameTable, "names", ()))
|
|
95
|
+
|
|
96
|
+
# we have all the best ways to express mac names
|
|
97
|
+
platforms = ((3, 1, 0x409),)
|
|
98
|
+
if macNames:
|
|
99
|
+
platforms = ((1, 0, 0),) + platforms
|
|
100
|
+
|
|
101
|
+
for a in axes.values():
|
|
102
|
+
axis = Axis()
|
|
103
|
+
axis.axisTag = Tag(a.tag)
|
|
104
|
+
# TODO Skip axes that have no variation.
|
|
105
|
+
axis.minValue, axis.defaultValue, axis.maxValue = (
|
|
106
|
+
a.minimum,
|
|
107
|
+
a.default,
|
|
108
|
+
a.maximum,
|
|
109
|
+
)
|
|
110
|
+
axis.axisNameID = nameTable.addMultilingualName(
|
|
111
|
+
a.labelNames, font, minNameID=256, mac=macNames
|
|
112
|
+
)
|
|
113
|
+
axis.flags = int(a.hidden)
|
|
114
|
+
fvar.axes.append(axis)
|
|
115
|
+
|
|
116
|
+
default_coordinates = {axis.axisTag: axis.defaultValue for axis in fvar.axes}
|
|
117
|
+
|
|
118
|
+
for instance in instances:
|
|
119
|
+
# Filter out discrete axis locations
|
|
120
|
+
coordinates = {
|
|
121
|
+
name: value for name, value in instance.location.items() if name in axes
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
if "en" not in instance.localisedStyleName:
|
|
125
|
+
if not instance.styleName:
|
|
126
|
+
raise VarLibValidationError(
|
|
127
|
+
f"Instance at location '{coordinates}' must have a default English "
|
|
128
|
+
"style name ('stylename' attribute on the instance element or a "
|
|
129
|
+
"stylename element with an 'xml:lang=\"en\"' attribute)."
|
|
130
|
+
)
|
|
131
|
+
localisedStyleName = dict(instance.localisedStyleName)
|
|
132
|
+
localisedStyleName["en"] = tostr(instance.styleName)
|
|
133
|
+
else:
|
|
134
|
+
localisedStyleName = instance.localisedStyleName
|
|
135
|
+
|
|
136
|
+
psname = instance.postScriptFontName
|
|
137
|
+
|
|
138
|
+
inst = NamedInstance()
|
|
139
|
+
inst.coordinates = {
|
|
140
|
+
axes[k].tag: axes[k].map_backward(v) for k, v in coordinates.items()
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
subfamilyNameID = nameTable.findMultilingualName(
|
|
144
|
+
localisedStyleName, windows=True, mac=macNames
|
|
145
|
+
)
|
|
146
|
+
if subfamilyNameID in {2, 17} and inst.coordinates == default_coordinates:
|
|
147
|
+
# Instances can only reuse an existing name ID 2 or 17 if they are at the
|
|
148
|
+
# default location across all axes, see:
|
|
149
|
+
# https://github.com/fonttools/fonttools/issues/3825.
|
|
150
|
+
inst.subfamilyNameID = subfamilyNameID
|
|
151
|
+
else:
|
|
152
|
+
inst.subfamilyNameID = nameTable.addMultilingualName(
|
|
153
|
+
localisedStyleName, windows=True, mac=macNames, minNameID=256
|
|
154
|
+
)
|
|
155
|
+
|
|
156
|
+
if psname is not None:
|
|
157
|
+
psname = tostr(psname)
|
|
158
|
+
inst.postscriptNameID = nameTable.addName(psname, platforms=platforms)
|
|
159
|
+
fvar.instances.append(inst)
|
|
160
|
+
|
|
161
|
+
assert "fvar" not in font
|
|
162
|
+
font["fvar"] = fvar
|
|
163
|
+
|
|
164
|
+
return fvar
|
|
165
|
+
|
|
166
|
+
|
|
167
|
+
def _add_avar(font, axes, mappings, axisTags):
|
|
168
|
+
"""
|
|
169
|
+
Add 'avar' table to font.
|
|
170
|
+
|
|
171
|
+
axes is an ordered dictionary of AxisDescriptor objects.
|
|
172
|
+
"""
|
|
173
|
+
|
|
174
|
+
assert axes
|
|
175
|
+
assert isinstance(axes, OrderedDict)
|
|
176
|
+
|
|
177
|
+
log.info("Generating avar")
|
|
178
|
+
|
|
179
|
+
avar = newTable("avar")
|
|
180
|
+
|
|
181
|
+
interesting = False
|
|
182
|
+
vals_triples = {}
|
|
183
|
+
for axis in axes.values():
|
|
184
|
+
# Currently, some rasterizers require that the default value maps
|
|
185
|
+
# (-1 to -1, 0 to 0, and 1 to 1) be present for all the segment
|
|
186
|
+
# maps, even when the default normalization mapping for the axis
|
|
187
|
+
# was not modified.
|
|
188
|
+
# https://github.com/googlei18n/fontmake/issues/295
|
|
189
|
+
# https://github.com/fonttools/fonttools/issues/1011
|
|
190
|
+
# TODO(anthrotype) revert this (and 19c4b37) when issue is fixed
|
|
191
|
+
curve = avar.segments[axis.tag] = {-1.0: -1.0, 0.0: 0.0, 1.0: 1.0}
|
|
192
|
+
|
|
193
|
+
keys_triple = (axis.minimum, axis.default, axis.maximum)
|
|
194
|
+
vals_triple = tuple(axis.map_forward(v) for v in keys_triple)
|
|
195
|
+
vals_triples[axis.tag] = vals_triple
|
|
196
|
+
|
|
197
|
+
if not axis.map:
|
|
198
|
+
continue
|
|
199
|
+
|
|
200
|
+
items = sorted(axis.map)
|
|
201
|
+
keys = [item[0] for item in items]
|
|
202
|
+
vals = [item[1] for item in items]
|
|
203
|
+
|
|
204
|
+
# Current avar requirements. We don't have to enforce
|
|
205
|
+
# these on the designer and can deduce some ourselves,
|
|
206
|
+
# but for now just enforce them.
|
|
207
|
+
if axis.minimum != min(keys):
|
|
208
|
+
raise VarLibValidationError(
|
|
209
|
+
f"Axis '{axis.name}': there must be a mapping for the axis minimum "
|
|
210
|
+
f"value {axis.minimum} and it must be the lowest input mapping value."
|
|
211
|
+
)
|
|
212
|
+
if axis.maximum != max(keys):
|
|
213
|
+
raise VarLibValidationError(
|
|
214
|
+
f"Axis '{axis.name}': there must be a mapping for the axis maximum "
|
|
215
|
+
f"value {axis.maximum} and it must be the highest input mapping value."
|
|
216
|
+
)
|
|
217
|
+
if axis.default not in keys:
|
|
218
|
+
raise VarLibValidationError(
|
|
219
|
+
f"Axis '{axis.name}': there must be a mapping for the axis default "
|
|
220
|
+
f"value {axis.default}."
|
|
221
|
+
)
|
|
222
|
+
# No duplicate input values (output values can be >= their preceeding value).
|
|
223
|
+
if len(set(keys)) != len(keys):
|
|
224
|
+
raise VarLibValidationError(
|
|
225
|
+
f"Axis '{axis.name}': All axis mapping input='...' values must be "
|
|
226
|
+
"unique, but we found duplicates."
|
|
227
|
+
)
|
|
228
|
+
# Ascending values
|
|
229
|
+
if sorted(vals) != vals:
|
|
230
|
+
raise VarLibValidationError(
|
|
231
|
+
f"Axis '{axis.name}': mapping output values must be in ascending order."
|
|
232
|
+
)
|
|
233
|
+
|
|
234
|
+
keys = [models.normalizeValue(v, keys_triple) for v in keys]
|
|
235
|
+
vals = [models.normalizeValue(v, vals_triple) for v in vals]
|
|
236
|
+
|
|
237
|
+
if all(k == v for k, v in zip(keys, vals)):
|
|
238
|
+
continue
|
|
239
|
+
interesting = True
|
|
240
|
+
|
|
241
|
+
curve.update(zip(keys, vals))
|
|
242
|
+
|
|
243
|
+
assert 0.0 in curve and curve[0.0] == 0.0
|
|
244
|
+
assert -1.0 not in curve or curve[-1.0] == -1.0
|
|
245
|
+
assert +1.0 not in curve or curve[+1.0] == +1.0
|
|
246
|
+
# curve.update({-1.0: -1.0, 0.0: 0.0, 1.0: 1.0})
|
|
247
|
+
|
|
248
|
+
if mappings:
|
|
249
|
+
interesting = True
|
|
250
|
+
|
|
251
|
+
inputLocations = [
|
|
252
|
+
{
|
|
253
|
+
axes[name].tag: models.normalizeValue(v, vals_triples[axes[name].tag])
|
|
254
|
+
for name, v in mapping.inputLocation.items()
|
|
255
|
+
}
|
|
256
|
+
for mapping in mappings
|
|
257
|
+
]
|
|
258
|
+
outputLocations = [
|
|
259
|
+
{
|
|
260
|
+
axes[name].tag: models.normalizeValue(v, vals_triples[axes[name].tag])
|
|
261
|
+
for name, v in mapping.outputLocation.items()
|
|
262
|
+
}
|
|
263
|
+
for mapping in mappings
|
|
264
|
+
]
|
|
265
|
+
assert len(inputLocations) == len(outputLocations)
|
|
266
|
+
|
|
267
|
+
# If base-master is missing, insert it at zero location.
|
|
268
|
+
if not any(all(v == 0 for k, v in loc.items()) for loc in inputLocations):
|
|
269
|
+
inputLocations.insert(0, {})
|
|
270
|
+
outputLocations.insert(0, {})
|
|
271
|
+
|
|
272
|
+
model = models.VariationModel(inputLocations, axisTags)
|
|
273
|
+
storeBuilder = varStore.OnlineVarStoreBuilder(axisTags)
|
|
274
|
+
storeBuilder.setModel(model)
|
|
275
|
+
varIdxes = {}
|
|
276
|
+
for tag in axisTags:
|
|
277
|
+
masterValues = []
|
|
278
|
+
for vo, vi in zip(outputLocations, inputLocations):
|
|
279
|
+
if tag not in vo:
|
|
280
|
+
masterValues.append(0)
|
|
281
|
+
continue
|
|
282
|
+
v = vo[tag] - vi.get(tag, 0)
|
|
283
|
+
masterValues.append(fl2fi(v, 14))
|
|
284
|
+
varIdxes[tag] = storeBuilder.storeMasters(masterValues)[1]
|
|
285
|
+
|
|
286
|
+
store = storeBuilder.finish()
|
|
287
|
+
optimized = store.optimize()
|
|
288
|
+
varIdxes = {axis: optimized[value] for axis, value in varIdxes.items()}
|
|
289
|
+
|
|
290
|
+
varIdxMap = builder.buildDeltaSetIndexMap(varIdxes[t] for t in axisTags)
|
|
291
|
+
|
|
292
|
+
avar.majorVersion = 2
|
|
293
|
+
avar.table = ot.avar()
|
|
294
|
+
avar.table.VarIdxMap = varIdxMap
|
|
295
|
+
avar.table.VarStore = store
|
|
296
|
+
|
|
297
|
+
assert "avar" not in font
|
|
298
|
+
if not interesting:
|
|
299
|
+
log.info("No need for avar")
|
|
300
|
+
avar = None
|
|
301
|
+
else:
|
|
302
|
+
font["avar"] = avar
|
|
303
|
+
|
|
304
|
+
return avar
|
|
305
|
+
|
|
306
|
+
|
|
307
|
+
def _add_stat(font):
|
|
308
|
+
# Note: this function only gets called by old code that calls `build()`
|
|
309
|
+
# directly. Newer code that wants to benefit from STAT data from the
|
|
310
|
+
# designspace should call `build_many()`
|
|
311
|
+
|
|
312
|
+
if "STAT" in font:
|
|
313
|
+
return
|
|
314
|
+
|
|
315
|
+
from ..otlLib.builder import buildStatTable
|
|
316
|
+
|
|
317
|
+
fvarTable = font["fvar"]
|
|
318
|
+
axes = [dict(tag=a.axisTag, name=a.axisNameID) for a in fvarTable.axes]
|
|
319
|
+
buildStatTable(font, axes)
|
|
320
|
+
|
|
321
|
+
|
|
322
|
+
_MasterData = namedtuple("_MasterData", ["glyf", "hMetrics", "vMetrics"])
|
|
323
|
+
|
|
324
|
+
|
|
325
|
+
def _add_gvar(font, masterModel, master_ttfs, tolerance=0.5, optimize=True):
|
|
326
|
+
if tolerance < 0:
|
|
327
|
+
raise ValueError("`tolerance` must be a positive number.")
|
|
328
|
+
|
|
329
|
+
log.info("Generating gvar")
|
|
330
|
+
assert "gvar" not in font
|
|
331
|
+
gvar = font["gvar"] = newTable("gvar")
|
|
332
|
+
glyf = font["glyf"]
|
|
333
|
+
defaultMasterIndex = masterModel.reverseMapping[0]
|
|
334
|
+
|
|
335
|
+
master_datas = [
|
|
336
|
+
_MasterData(
|
|
337
|
+
m["glyf"], m["hmtx"].metrics, getattr(m.get("vmtx"), "metrics", None)
|
|
338
|
+
)
|
|
339
|
+
for m in master_ttfs
|
|
340
|
+
]
|
|
341
|
+
|
|
342
|
+
for glyph in font.getGlyphOrder():
|
|
343
|
+
log.debug("building gvar for glyph '%s'", glyph)
|
|
344
|
+
|
|
345
|
+
allData = [
|
|
346
|
+
m.glyf._getCoordinatesAndControls(glyph, m.hMetrics, m.vMetrics)
|
|
347
|
+
for m in master_datas
|
|
348
|
+
]
|
|
349
|
+
|
|
350
|
+
if allData[defaultMasterIndex][1].numberOfContours != 0:
|
|
351
|
+
# If the default master is not empty, interpret empty non-default masters
|
|
352
|
+
# as missing glyphs from a sparse master
|
|
353
|
+
allData = [
|
|
354
|
+
d if d is not None and d[1].numberOfContours != 0 else None
|
|
355
|
+
for d in allData
|
|
356
|
+
]
|
|
357
|
+
|
|
358
|
+
model, allData = masterModel.getSubModel(allData)
|
|
359
|
+
|
|
360
|
+
allCoords = [d[0] for d in allData]
|
|
361
|
+
allControls = [d[1] for d in allData]
|
|
362
|
+
control = allControls[0]
|
|
363
|
+
if not models.allEqual(allControls):
|
|
364
|
+
log.warning("glyph %s has incompatible masters; skipping" % glyph)
|
|
365
|
+
continue
|
|
366
|
+
del allControls
|
|
367
|
+
|
|
368
|
+
# Update gvar
|
|
369
|
+
gvar.variations[glyph] = []
|
|
370
|
+
deltas = model.getDeltas(
|
|
371
|
+
allCoords, round=partial(GlyphCoordinates.__round__, round=round)
|
|
372
|
+
)
|
|
373
|
+
supports = model.supports
|
|
374
|
+
assert len(deltas) == len(supports)
|
|
375
|
+
|
|
376
|
+
# Prepare for IUP optimization
|
|
377
|
+
origCoords = deltas[0]
|
|
378
|
+
endPts = control.endPts
|
|
379
|
+
|
|
380
|
+
for i, (delta, support) in enumerate(zip(deltas[1:], supports[1:])):
|
|
381
|
+
if all(v == 0 for v in delta.array):
|
|
382
|
+
continue
|
|
383
|
+
var = TupleVariation(support, delta)
|
|
384
|
+
if optimize:
|
|
385
|
+
delta_opt = iup_delta_optimize(
|
|
386
|
+
delta, origCoords, endPts, tolerance=tolerance
|
|
387
|
+
)
|
|
388
|
+
|
|
389
|
+
if None in delta_opt:
|
|
390
|
+
# Use "optimized" version only if smaller...
|
|
391
|
+
var_opt = TupleVariation(support, delta_opt)
|
|
392
|
+
|
|
393
|
+
axis_tags = sorted(
|
|
394
|
+
support.keys()
|
|
395
|
+
) # Shouldn't matter that this is different from fvar...?
|
|
396
|
+
tupleData, auxData = var.compile(axis_tags)
|
|
397
|
+
unoptimized_len = len(tupleData) + len(auxData)
|
|
398
|
+
tupleData, auxData = var_opt.compile(axis_tags)
|
|
399
|
+
optimized_len = len(tupleData) + len(auxData)
|
|
400
|
+
|
|
401
|
+
if optimized_len < unoptimized_len:
|
|
402
|
+
var = var_opt
|
|
403
|
+
|
|
404
|
+
gvar.variations[glyph].append(var)
|
|
405
|
+
|
|
406
|
+
|
|
407
|
+
def _remove_TTHinting(font):
|
|
408
|
+
for tag in ("cvar", "cvt ", "fpgm", "prep"):
|
|
409
|
+
if tag in font:
|
|
410
|
+
del font[tag]
|
|
411
|
+
maxp = font["maxp"]
|
|
412
|
+
for attr in (
|
|
413
|
+
"maxTwilightPoints",
|
|
414
|
+
"maxStorage",
|
|
415
|
+
"maxFunctionDefs",
|
|
416
|
+
"maxInstructionDefs",
|
|
417
|
+
"maxStackElements",
|
|
418
|
+
"maxSizeOfInstructions",
|
|
419
|
+
):
|
|
420
|
+
setattr(maxp, attr, 0)
|
|
421
|
+
maxp.maxZones = 1
|
|
422
|
+
font["glyf"].removeHinting()
|
|
423
|
+
# TODO: Modify gasp table to deactivate gridfitting for all ranges?
|
|
424
|
+
|
|
425
|
+
|
|
426
|
+
def _merge_TTHinting(font, masterModel, master_ttfs):
|
|
427
|
+
log.info("Merging TT hinting")
|
|
428
|
+
assert "cvar" not in font
|
|
429
|
+
|
|
430
|
+
# Check that the existing hinting is compatible
|
|
431
|
+
|
|
432
|
+
# fpgm and prep table
|
|
433
|
+
|
|
434
|
+
for tag in ("fpgm", "prep"):
|
|
435
|
+
all_pgms = [m[tag].program for m in master_ttfs if tag in m]
|
|
436
|
+
if not all_pgms:
|
|
437
|
+
continue
|
|
438
|
+
font_pgm = getattr(font.get(tag), "program", None)
|
|
439
|
+
if any(pgm != font_pgm for pgm in all_pgms):
|
|
440
|
+
log.warning(
|
|
441
|
+
"Masters have incompatible %s tables, hinting is discarded." % tag
|
|
442
|
+
)
|
|
443
|
+
_remove_TTHinting(font)
|
|
444
|
+
return
|
|
445
|
+
|
|
446
|
+
# glyf table
|
|
447
|
+
|
|
448
|
+
font_glyf = font["glyf"]
|
|
449
|
+
master_glyfs = [m["glyf"] for m in master_ttfs]
|
|
450
|
+
for name, glyph in font_glyf.glyphs.items():
|
|
451
|
+
all_pgms = [getattr(glyf.get(name), "program", None) for glyf in master_glyfs]
|
|
452
|
+
if not any(all_pgms):
|
|
453
|
+
continue
|
|
454
|
+
glyph.expand(font_glyf)
|
|
455
|
+
font_pgm = getattr(glyph, "program", None)
|
|
456
|
+
if any(pgm != font_pgm for pgm in all_pgms if pgm):
|
|
457
|
+
log.warning(
|
|
458
|
+
"Masters have incompatible glyph programs in glyph '%s', hinting is discarded."
|
|
459
|
+
% name
|
|
460
|
+
)
|
|
461
|
+
# TODO Only drop hinting from this glyph.
|
|
462
|
+
_remove_TTHinting(font)
|
|
463
|
+
return
|
|
464
|
+
|
|
465
|
+
# cvt table
|
|
466
|
+
|
|
467
|
+
all_cvs = [Vector(m["cvt "].values) if "cvt " in m else None for m in master_ttfs]
|
|
468
|
+
|
|
469
|
+
nonNone_cvs = models.nonNone(all_cvs)
|
|
470
|
+
if not nonNone_cvs:
|
|
471
|
+
# There is no cvt table to make a cvar table from, we're done here.
|
|
472
|
+
return
|
|
473
|
+
|
|
474
|
+
if not models.allEqual(len(c) for c in nonNone_cvs):
|
|
475
|
+
log.warning("Masters have incompatible cvt tables, hinting is discarded.")
|
|
476
|
+
_remove_TTHinting(font)
|
|
477
|
+
return
|
|
478
|
+
|
|
479
|
+
variations = []
|
|
480
|
+
deltas, supports = masterModel.getDeltasAndSupports(
|
|
481
|
+
all_cvs, round=round
|
|
482
|
+
) # builtin round calls into Vector.__round__, which uses builtin round as we like
|
|
483
|
+
for i, (delta, support) in enumerate(zip(deltas[1:], supports[1:])):
|
|
484
|
+
if all(v == 0 for v in delta):
|
|
485
|
+
continue
|
|
486
|
+
var = TupleVariation(support, delta)
|
|
487
|
+
variations.append(var)
|
|
488
|
+
|
|
489
|
+
# We can build the cvar table now.
|
|
490
|
+
if variations:
|
|
491
|
+
cvar = font["cvar"] = newTable("cvar")
|
|
492
|
+
cvar.version = 1
|
|
493
|
+
cvar.variations = variations
|
|
494
|
+
|
|
495
|
+
|
|
496
|
+
def _has_inconsistent_use_my_metrics_flag(
|
|
497
|
+
master_glyf, glyph_name, flagged_components, expected_num_components
|
|
498
|
+
) -> bool:
|
|
499
|
+
master_glyph = master_glyf.get(glyph_name)
|
|
500
|
+
# 'sparse' glyph master doesn't contribute. Besides when components don't match
|
|
501
|
+
# the VF build is going to fail anyway, so be lenient here.
|
|
502
|
+
if (
|
|
503
|
+
master_glyph is not None
|
|
504
|
+
and master_glyph.isComposite()
|
|
505
|
+
and len(master_glyph.components) == expected_num_components
|
|
506
|
+
):
|
|
507
|
+
for i, base_glyph in flagged_components:
|
|
508
|
+
comp = master_glyph.components[i]
|
|
509
|
+
if comp.glyphName != base_glyph:
|
|
510
|
+
break
|
|
511
|
+
if not (comp.flags & USE_MY_METRICS):
|
|
512
|
+
return True
|
|
513
|
+
return False
|
|
514
|
+
|
|
515
|
+
|
|
516
|
+
def _unset_inconsistent_use_my_metrics_flags(vf, master_fonts):
|
|
517
|
+
"""Clear USE_MY_METRICS on composite components if inconsistent across masters.
|
|
518
|
+
|
|
519
|
+
If a composite glyph's component has USE_MY_METRICS set differently among
|
|
520
|
+
the masters, the flag is removed from the variable font's glyf table so that
|
|
521
|
+
advance widths are not determined by that single component's phantom points.
|
|
522
|
+
"""
|
|
523
|
+
glyf = vf["glyf"]
|
|
524
|
+
master_glyfs = [m["glyf"] for m in master_fonts if "glyf" in m]
|
|
525
|
+
if not master_glyfs:
|
|
526
|
+
# Should not happen: at least the base master (as copied into vf) has glyf
|
|
527
|
+
return
|
|
528
|
+
|
|
529
|
+
for glyph_name in glyf.keys():
|
|
530
|
+
glyph = glyf[glyph_name]
|
|
531
|
+
if not glyph.isComposite():
|
|
532
|
+
continue
|
|
533
|
+
|
|
534
|
+
# collect indices of component(s) that carry the USE_MY_METRICS flag.
|
|
535
|
+
# This is supposed to be 1 component per composite, but you never know.
|
|
536
|
+
flagged_components = [
|
|
537
|
+
(i, comp.glyphName)
|
|
538
|
+
for i, comp in enumerate(glyph.components)
|
|
539
|
+
if (comp.flags & USE_MY_METRICS)
|
|
540
|
+
]
|
|
541
|
+
if not flagged_components:
|
|
542
|
+
# Nothing to fix
|
|
543
|
+
continue
|
|
544
|
+
|
|
545
|
+
# Verify that for all master glyf tables that contribute this glyph, the
|
|
546
|
+
# corresponding component (same glyphName and index) also carries USE_MY_METRICS
|
|
547
|
+
# and unset the flag if not.
|
|
548
|
+
expected_num_components = len(glyph.components)
|
|
549
|
+
if any(
|
|
550
|
+
_has_inconsistent_use_my_metrics_flag(
|
|
551
|
+
master_glyf, glyph_name, flagged_components, expected_num_components
|
|
552
|
+
)
|
|
553
|
+
for master_glyf in master_glyfs
|
|
554
|
+
):
|
|
555
|
+
comp_names = [name for _, name in flagged_components]
|
|
556
|
+
log.info(
|
|
557
|
+
"Composite glyph '%s' has inconsistent USE_MY_METRICS flags across "
|
|
558
|
+
"masters; clearing the flag on component%s %s",
|
|
559
|
+
glyph_name,
|
|
560
|
+
"s" if len(comp_names) > 1 else "",
|
|
561
|
+
comp_names if len(comp_names) > 1 else comp_names[0],
|
|
562
|
+
)
|
|
563
|
+
for i, _ in flagged_components:
|
|
564
|
+
glyph.components[i].flags &= ~USE_MY_METRICS
|
|
565
|
+
|
|
566
|
+
|
|
567
|
+
_MetricsFields = namedtuple(
|
|
568
|
+
"_MetricsFields",
|
|
569
|
+
[
|
|
570
|
+
"tableTag",
|
|
571
|
+
"metricsTag",
|
|
572
|
+
"sb1",
|
|
573
|
+
"sb2",
|
|
574
|
+
"advMapping",
|
|
575
|
+
"vOrigMapping",
|
|
576
|
+
"phantomIndex",
|
|
577
|
+
],
|
|
578
|
+
)
|
|
579
|
+
|
|
580
|
+
HVAR_FIELDS = _MetricsFields(
|
|
581
|
+
tableTag="HVAR",
|
|
582
|
+
metricsTag="hmtx",
|
|
583
|
+
sb1="LsbMap",
|
|
584
|
+
sb2="RsbMap",
|
|
585
|
+
advMapping="AdvWidthMap",
|
|
586
|
+
vOrigMapping=None,
|
|
587
|
+
phantomIndex=0,
|
|
588
|
+
)
|
|
589
|
+
|
|
590
|
+
VVAR_FIELDS = _MetricsFields(
|
|
591
|
+
tableTag="VVAR",
|
|
592
|
+
metricsTag="vmtx",
|
|
593
|
+
sb1="TsbMap",
|
|
594
|
+
sb2="BsbMap",
|
|
595
|
+
advMapping="AdvHeightMap",
|
|
596
|
+
vOrigMapping="VOrgMap",
|
|
597
|
+
phantomIndex=1,
|
|
598
|
+
)
|
|
599
|
+
|
|
600
|
+
|
|
601
|
+
def _add_HVAR(font, masterModel, master_ttfs, axisTags):
|
|
602
|
+
getAdvanceMetrics = partial(
|
|
603
|
+
_get_advance_metrics, font, masterModel, master_ttfs, axisTags, HVAR_FIELDS
|
|
604
|
+
)
|
|
605
|
+
_add_VHVAR(font, axisTags, HVAR_FIELDS, getAdvanceMetrics)
|
|
606
|
+
|
|
607
|
+
|
|
608
|
+
def _add_VVAR(font, masterModel, master_ttfs, axisTags):
|
|
609
|
+
getAdvanceMetrics = partial(
|
|
610
|
+
_get_advance_metrics, font, masterModel, master_ttfs, axisTags, VVAR_FIELDS
|
|
611
|
+
)
|
|
612
|
+
_add_VHVAR(font, axisTags, VVAR_FIELDS, getAdvanceMetrics)
|
|
613
|
+
|
|
614
|
+
|
|
615
|
+
def _add_VHVAR(font, axisTags, tableFields, getAdvanceMetrics):
|
|
616
|
+
tableTag = tableFields.tableTag
|
|
617
|
+
assert tableTag not in font
|
|
618
|
+
glyphOrder = font.getGlyphOrder()
|
|
619
|
+
log.info("Generating " + tableTag)
|
|
620
|
+
VHVAR = newTable(tableTag)
|
|
621
|
+
tableClass = getattr(ot, tableTag)
|
|
622
|
+
vhvar = VHVAR.table = tableClass()
|
|
623
|
+
vhvar.Version = 0x00010000
|
|
624
|
+
|
|
625
|
+
vhAdvanceDeltasAndSupports, vOrigDeltasAndSupports = getAdvanceMetrics()
|
|
626
|
+
|
|
627
|
+
if vOrigDeltasAndSupports:
|
|
628
|
+
singleModel = False
|
|
629
|
+
else:
|
|
630
|
+
singleModel = models.allEqual(
|
|
631
|
+
id(v[1]) for v in vhAdvanceDeltasAndSupports.values()
|
|
632
|
+
)
|
|
633
|
+
|
|
634
|
+
directStore = None
|
|
635
|
+
if singleModel:
|
|
636
|
+
# Build direct mapping
|
|
637
|
+
supports = next(iter(vhAdvanceDeltasAndSupports.values()))[1][1:]
|
|
638
|
+
varTupleList = builder.buildVarRegionList(supports, axisTags)
|
|
639
|
+
varTupleIndexes = list(range(len(supports)))
|
|
640
|
+
varData = builder.buildVarData(varTupleIndexes, [], optimize=False)
|
|
641
|
+
for glyphName in glyphOrder:
|
|
642
|
+
varData.addItem(vhAdvanceDeltasAndSupports[glyphName][0], round=noRound)
|
|
643
|
+
varData.optimize()
|
|
644
|
+
directStore = builder.buildVarStore(varTupleList, [varData])
|
|
645
|
+
# remove unused regions from VarRegionList
|
|
646
|
+
directStore.prune_regions()
|
|
647
|
+
|
|
648
|
+
# Build optimized indirect mapping
|
|
649
|
+
storeBuilder = varStore.OnlineVarStoreBuilder(axisTags)
|
|
650
|
+
advMapping = {}
|
|
651
|
+
for glyphName in glyphOrder:
|
|
652
|
+
deltas, supports = vhAdvanceDeltasAndSupports[glyphName]
|
|
653
|
+
storeBuilder.setSupports(supports)
|
|
654
|
+
advMapping[glyphName] = storeBuilder.storeDeltas(deltas, round=noRound)
|
|
655
|
+
|
|
656
|
+
if vOrigDeltasAndSupports:
|
|
657
|
+
vOrigMap = {}
|
|
658
|
+
for glyphName in glyphOrder:
|
|
659
|
+
deltas, supports = vOrigDeltasAndSupports[glyphName]
|
|
660
|
+
storeBuilder.setSupports(supports)
|
|
661
|
+
vOrigMap[glyphName] = storeBuilder.storeDeltas(deltas, round=noRound)
|
|
662
|
+
|
|
663
|
+
indirectStore = storeBuilder.finish()
|
|
664
|
+
mapping2 = indirectStore.optimize(use_NO_VARIATION_INDEX=False)
|
|
665
|
+
advMapping = [mapping2[advMapping[g]] for g in glyphOrder]
|
|
666
|
+
advanceMapping = builder.buildVarIdxMap(advMapping, glyphOrder)
|
|
667
|
+
|
|
668
|
+
if vOrigDeltasAndSupports:
|
|
669
|
+
vOrigMap = [mapping2[vOrigMap[g]] for g in glyphOrder]
|
|
670
|
+
|
|
671
|
+
useDirect = False
|
|
672
|
+
vOrigMapping = None
|
|
673
|
+
if directStore:
|
|
674
|
+
# Compile both, see which is more compact
|
|
675
|
+
|
|
676
|
+
writer = OTTableWriter()
|
|
677
|
+
directStore.compile(writer, font)
|
|
678
|
+
directSize = len(writer.getAllData())
|
|
679
|
+
|
|
680
|
+
writer = OTTableWriter()
|
|
681
|
+
indirectStore.compile(writer, font)
|
|
682
|
+
advanceMapping.compile(writer, font)
|
|
683
|
+
indirectSize = len(writer.getAllData())
|
|
684
|
+
|
|
685
|
+
useDirect = directSize < indirectSize
|
|
686
|
+
|
|
687
|
+
if useDirect:
|
|
688
|
+
metricsStore = directStore
|
|
689
|
+
advanceMapping = None
|
|
690
|
+
else:
|
|
691
|
+
metricsStore = indirectStore
|
|
692
|
+
if vOrigDeltasAndSupports:
|
|
693
|
+
vOrigMapping = builder.buildVarIdxMap(vOrigMap, glyphOrder)
|
|
694
|
+
|
|
695
|
+
vhvar.VarStore = metricsStore
|
|
696
|
+
setattr(vhvar, tableFields.advMapping, advanceMapping)
|
|
697
|
+
if vOrigMapping is not None:
|
|
698
|
+
setattr(vhvar, tableFields.vOrigMapping, vOrigMapping)
|
|
699
|
+
setattr(vhvar, tableFields.sb1, None)
|
|
700
|
+
setattr(vhvar, tableFields.sb2, None)
|
|
701
|
+
|
|
702
|
+
font[tableTag] = VHVAR
|
|
703
|
+
return
|
|
704
|
+
|
|
705
|
+
|
|
706
|
+
def _get_advance_metrics(font, masterModel, master_ttfs, axisTags, tableFields):
|
|
707
|
+
tableTag = tableFields.tableTag
|
|
708
|
+
glyphOrder = font.getGlyphOrder()
|
|
709
|
+
|
|
710
|
+
# Build list of source font advance widths for each glyph
|
|
711
|
+
metricsTag = tableFields.metricsTag
|
|
712
|
+
advMetricses = [m[metricsTag].metrics for m in master_ttfs]
|
|
713
|
+
|
|
714
|
+
# Build list of source font vertical origin coords for each glyph
|
|
715
|
+
if tableTag == "VVAR" and "VORG" in master_ttfs[0]:
|
|
716
|
+
vOrigMetricses = [m["VORG"].VOriginRecords for m in master_ttfs]
|
|
717
|
+
defaultYOrigs = [m["VORG"].defaultVertOriginY for m in master_ttfs]
|
|
718
|
+
vOrigMetricses = list(zip(vOrigMetricses, defaultYOrigs))
|
|
719
|
+
else:
|
|
720
|
+
vOrigMetricses = None
|
|
721
|
+
|
|
722
|
+
vhAdvanceDeltasAndSupports = {}
|
|
723
|
+
vOrigDeltasAndSupports = {}
|
|
724
|
+
# HACK: we treat width 65535 as a sentinel value to signal that a glyph
|
|
725
|
+
# from a non-default master should not participate in computing {H,V}VAR,
|
|
726
|
+
# as if it were missing. Allows to variate other glyph-related data independently
|
|
727
|
+
# from glyph metrics
|
|
728
|
+
sparse_advance = 0xFFFF
|
|
729
|
+
for glyph in glyphOrder:
|
|
730
|
+
vhAdvances = [
|
|
731
|
+
(
|
|
732
|
+
metrics[glyph][0]
|
|
733
|
+
if glyph in metrics and metrics[glyph][0] != sparse_advance
|
|
734
|
+
else None
|
|
735
|
+
)
|
|
736
|
+
for metrics in advMetricses
|
|
737
|
+
]
|
|
738
|
+
vhAdvanceDeltasAndSupports[glyph] = masterModel.getDeltasAndSupports(
|
|
739
|
+
vhAdvances, round=round
|
|
740
|
+
)
|
|
741
|
+
|
|
742
|
+
if vOrigMetricses:
|
|
743
|
+
for glyph in glyphOrder:
|
|
744
|
+
# We need to supply a vOrigs tuple with non-None default values
|
|
745
|
+
# for each glyph. vOrigMetricses contains values only for those
|
|
746
|
+
# glyphs which have a non-default vOrig.
|
|
747
|
+
vOrigs = [
|
|
748
|
+
metrics[glyph] if glyph in metrics else defaultVOrig
|
|
749
|
+
for metrics, defaultVOrig in vOrigMetricses
|
|
750
|
+
]
|
|
751
|
+
vOrigDeltasAndSupports[glyph] = masterModel.getDeltasAndSupports(
|
|
752
|
+
vOrigs, round=round
|
|
753
|
+
)
|
|
754
|
+
|
|
755
|
+
return vhAdvanceDeltasAndSupports, vOrigDeltasAndSupports
|
|
756
|
+
|
|
757
|
+
|
|
758
|
+
def _add_MVAR(font, masterModel, master_ttfs, axisTags):
|
|
759
|
+
log.info("Generating MVAR")
|
|
760
|
+
|
|
761
|
+
store_builder = varStore.OnlineVarStoreBuilder(axisTags)
|
|
762
|
+
|
|
763
|
+
records = []
|
|
764
|
+
lastTableTag = None
|
|
765
|
+
fontTable = None
|
|
766
|
+
tables = None
|
|
767
|
+
# HACK: we need to special-case post.underlineThickness and .underlinePosition
|
|
768
|
+
# and unilaterally/arbitrarily define a sentinel value to distinguish the case
|
|
769
|
+
# when a post table is present in a given master simply because that's where
|
|
770
|
+
# the glyph names in TrueType must be stored, but the underline values are not
|
|
771
|
+
# meant to be used for building MVAR's deltas. The value of -0x8000 (-36768)
|
|
772
|
+
# the minimum FWord (int16) value, was chosen for its unlikelyhood to appear
|
|
773
|
+
# in real-world underline position/thickness values.
|
|
774
|
+
specialTags = {"unds": -0x8000, "undo": -0x8000}
|
|
775
|
+
|
|
776
|
+
for tag, (tableTag, itemName) in sorted(MVAR_ENTRIES.items(), key=lambda kv: kv[1]):
|
|
777
|
+
# For each tag, fetch the associated table from all fonts (or not when we are
|
|
778
|
+
# still looking at a tag from the same tables) and set up the variation model
|
|
779
|
+
# for them.
|
|
780
|
+
if tableTag != lastTableTag:
|
|
781
|
+
tables = fontTable = None
|
|
782
|
+
if tableTag in font:
|
|
783
|
+
fontTable = font[tableTag]
|
|
784
|
+
tables = []
|
|
785
|
+
for master in master_ttfs:
|
|
786
|
+
if tableTag not in master or (
|
|
787
|
+
tag in specialTags
|
|
788
|
+
and getattr(master[tableTag], itemName) == specialTags[tag]
|
|
789
|
+
):
|
|
790
|
+
tables.append(None)
|
|
791
|
+
else:
|
|
792
|
+
tables.append(master[tableTag])
|
|
793
|
+
model, tables = masterModel.getSubModel(tables)
|
|
794
|
+
store_builder.setModel(model)
|
|
795
|
+
lastTableTag = tableTag
|
|
796
|
+
|
|
797
|
+
if tables is None: # Tag not applicable to the master font.
|
|
798
|
+
continue
|
|
799
|
+
|
|
800
|
+
# TODO support gasp entries
|
|
801
|
+
|
|
802
|
+
master_values = [getattr(table, itemName) for table in tables]
|
|
803
|
+
if models.allEqual(master_values):
|
|
804
|
+
base, varIdx = master_values[0], None
|
|
805
|
+
else:
|
|
806
|
+
base, varIdx = store_builder.storeMasters(master_values)
|
|
807
|
+
setattr(fontTable, itemName, base)
|
|
808
|
+
|
|
809
|
+
if varIdx is None:
|
|
810
|
+
continue
|
|
811
|
+
log.info(" %s: %s.%s %s", tag, tableTag, itemName, master_values)
|
|
812
|
+
rec = ot.MetricsValueRecord()
|
|
813
|
+
rec.ValueTag = tag
|
|
814
|
+
rec.VarIdx = varIdx
|
|
815
|
+
records.append(rec)
|
|
816
|
+
|
|
817
|
+
assert "MVAR" not in font
|
|
818
|
+
if records:
|
|
819
|
+
store = store_builder.finish()
|
|
820
|
+
# Optimize
|
|
821
|
+
mapping = store.optimize()
|
|
822
|
+
for rec in records:
|
|
823
|
+
rec.VarIdx = mapping[rec.VarIdx]
|
|
824
|
+
|
|
825
|
+
MVAR = font["MVAR"] = newTable("MVAR")
|
|
826
|
+
mvar = MVAR.table = ot.MVAR()
|
|
827
|
+
mvar.Version = 0x00010000
|
|
828
|
+
mvar.Reserved = 0
|
|
829
|
+
mvar.VarStore = store
|
|
830
|
+
# XXX these should not be hard-coded but computed automatically
|
|
831
|
+
mvar.ValueRecordSize = 8
|
|
832
|
+
mvar.ValueRecordCount = len(records)
|
|
833
|
+
mvar.ValueRecord = sorted(records, key=lambda r: r.ValueTag)
|
|
834
|
+
|
|
835
|
+
|
|
836
|
+
def _add_BASE(font, masterModel, master_ttfs, axisTags):
|
|
837
|
+
log.info("Generating BASE")
|
|
838
|
+
|
|
839
|
+
merger = VariationMerger(masterModel, axisTags, font)
|
|
840
|
+
merger.mergeTables(font, master_ttfs, ["BASE"])
|
|
841
|
+
store = merger.store_builder.finish()
|
|
842
|
+
|
|
843
|
+
if not store:
|
|
844
|
+
return
|
|
845
|
+
base = font["BASE"].table
|
|
846
|
+
assert base.Version == 0x00010000
|
|
847
|
+
base.Version = 0x00010001
|
|
848
|
+
base.VarStore = store
|
|
849
|
+
|
|
850
|
+
|
|
851
|
+
def _merge_OTL(font, model, master_fonts, axisTags):
|
|
852
|
+
otl_tags = ["GSUB", "GDEF", "GPOS"]
|
|
853
|
+
if not any(tag in font for tag in otl_tags):
|
|
854
|
+
return
|
|
855
|
+
|
|
856
|
+
log.info("Merging OpenType Layout tables")
|
|
857
|
+
merger = VariationMerger(model, axisTags, font)
|
|
858
|
+
|
|
859
|
+
merger.mergeTables(font, master_fonts, otl_tags)
|
|
860
|
+
store = merger.store_builder.finish()
|
|
861
|
+
if not store:
|
|
862
|
+
return
|
|
863
|
+
try:
|
|
864
|
+
GDEF = font["GDEF"].table
|
|
865
|
+
assert GDEF.Version <= 0x00010002
|
|
866
|
+
except KeyError:
|
|
867
|
+
font["GDEF"] = newTable("GDEF")
|
|
868
|
+
GDEFTable = font["GDEF"] = newTable("GDEF")
|
|
869
|
+
GDEF = GDEFTable.table = ot.GDEF()
|
|
870
|
+
GDEF.GlyphClassDef = None
|
|
871
|
+
GDEF.AttachList = None
|
|
872
|
+
GDEF.LigCaretList = None
|
|
873
|
+
GDEF.MarkAttachClassDef = None
|
|
874
|
+
GDEF.MarkGlyphSetsDef = None
|
|
875
|
+
|
|
876
|
+
GDEF.Version = 0x00010003
|
|
877
|
+
GDEF.VarStore = store
|
|
878
|
+
|
|
879
|
+
# Optimize
|
|
880
|
+
varidx_map = store.optimize()
|
|
881
|
+
GDEF.remap_device_varidxes(varidx_map)
|
|
882
|
+
if "GPOS" in font:
|
|
883
|
+
font["GPOS"].table.remap_device_varidxes(varidx_map)
|
|
884
|
+
|
|
885
|
+
|
|
886
|
+
def _add_GSUB_feature_variations(
|
|
887
|
+
font, axes, internal_axis_supports, rules, featureTags
|
|
888
|
+
):
|
|
889
|
+
def normalize(name, value):
|
|
890
|
+
return models.normalizeLocation({name: value}, internal_axis_supports)[name]
|
|
891
|
+
|
|
892
|
+
log.info("Generating GSUB FeatureVariations")
|
|
893
|
+
|
|
894
|
+
axis_tags = {name: axis.tag for name, axis in axes.items()}
|
|
895
|
+
|
|
896
|
+
conditional_subs = []
|
|
897
|
+
for rule in rules:
|
|
898
|
+
region = []
|
|
899
|
+
for conditions in rule.conditionSets:
|
|
900
|
+
space = {}
|
|
901
|
+
for condition in conditions:
|
|
902
|
+
axis_name = condition["name"]
|
|
903
|
+
if condition["minimum"] is not None:
|
|
904
|
+
minimum = normalize(axis_name, condition["minimum"])
|
|
905
|
+
else:
|
|
906
|
+
minimum = -1.0
|
|
907
|
+
if condition["maximum"] is not None:
|
|
908
|
+
maximum = normalize(axis_name, condition["maximum"])
|
|
909
|
+
else:
|
|
910
|
+
maximum = 1.0
|
|
911
|
+
tag = axis_tags[axis_name]
|
|
912
|
+
space[tag] = (minimum, maximum)
|
|
913
|
+
region.append(space)
|
|
914
|
+
|
|
915
|
+
subs = {k: v for k, v in rule.subs}
|
|
916
|
+
|
|
917
|
+
conditional_subs.append((region, subs))
|
|
918
|
+
|
|
919
|
+
addFeatureVariations(font, conditional_subs, featureTags)
|
|
920
|
+
|
|
921
|
+
|
|
922
|
+
_DesignSpaceData = namedtuple(
|
|
923
|
+
"_DesignSpaceData",
|
|
924
|
+
[
|
|
925
|
+
"axes",
|
|
926
|
+
"axisMappings",
|
|
927
|
+
"internal_axis_supports",
|
|
928
|
+
"base_idx",
|
|
929
|
+
"normalized_master_locs",
|
|
930
|
+
"masters",
|
|
931
|
+
"instances",
|
|
932
|
+
"rules",
|
|
933
|
+
"rulesProcessingLast",
|
|
934
|
+
"lib",
|
|
935
|
+
],
|
|
936
|
+
)
|
|
937
|
+
|
|
938
|
+
|
|
939
|
+
def _add_CFF2(varFont, model, master_fonts):
|
|
940
|
+
from .cff import merge_region_fonts
|
|
941
|
+
|
|
942
|
+
glyphOrder = varFont.getGlyphOrder()
|
|
943
|
+
if "CFF2" not in varFont:
|
|
944
|
+
from fontTools.cffLib.CFFToCFF2 import convertCFFToCFF2
|
|
945
|
+
|
|
946
|
+
convertCFFToCFF2(varFont)
|
|
947
|
+
|
|
948
|
+
ordered_fonts_list = model.reorderMasters(master_fonts, model.reverseMapping)
|
|
949
|
+
# re-ordering the master list simplifies building the CFF2 data item lists.
|
|
950
|
+
merge_region_fonts(varFont, model, ordered_fonts_list, glyphOrder)
|
|
951
|
+
|
|
952
|
+
|
|
953
|
+
def _add_COLR(font, model, master_fonts, axisTags, colr_layer_reuse=True):
|
|
954
|
+
merger = COLRVariationMerger(
|
|
955
|
+
model, axisTags, font, allowLayerReuse=colr_layer_reuse
|
|
956
|
+
)
|
|
957
|
+
merger.mergeTables(font, master_fonts)
|
|
958
|
+
store = merger.store_builder.finish()
|
|
959
|
+
|
|
960
|
+
colr = font["COLR"].table
|
|
961
|
+
if store:
|
|
962
|
+
mapping = store.optimize()
|
|
963
|
+
colr.VarStore = store
|
|
964
|
+
varIdxes = [mapping[v] for v in merger.varIdxes]
|
|
965
|
+
colr.VarIndexMap = builder.buildDeltaSetIndexMap(varIdxes)
|
|
966
|
+
|
|
967
|
+
|
|
968
|
+
def load_designspace(designspace, log_enabled=True, *, require_sources=True):
|
|
969
|
+
# TODO: remove this and always assume 'designspace' is a DesignSpaceDocument,
|
|
970
|
+
# never a file path, as that's already handled by caller
|
|
971
|
+
if hasattr(designspace, "sources"): # Assume a DesignspaceDocument
|
|
972
|
+
ds = designspace
|
|
973
|
+
else: # Assume a file path
|
|
974
|
+
ds = DesignSpaceDocument.fromfile(designspace)
|
|
975
|
+
|
|
976
|
+
masters = ds.sources
|
|
977
|
+
if require_sources and not masters:
|
|
978
|
+
raise VarLibValidationError("Designspace must have at least one source.")
|
|
979
|
+
instances = ds.instances
|
|
980
|
+
|
|
981
|
+
# TODO: Use fontTools.designspaceLib.tagForAxisName instead.
|
|
982
|
+
standard_axis_map = OrderedDict(
|
|
983
|
+
[
|
|
984
|
+
("weight", ("wght", {"en": "Weight"})),
|
|
985
|
+
("width", ("wdth", {"en": "Width"})),
|
|
986
|
+
("slant", ("slnt", {"en": "Slant"})),
|
|
987
|
+
("optical", ("opsz", {"en": "Optical Size"})),
|
|
988
|
+
("italic", ("ital", {"en": "Italic"})),
|
|
989
|
+
]
|
|
990
|
+
)
|
|
991
|
+
|
|
992
|
+
# Setup axes
|
|
993
|
+
if not ds.axes:
|
|
994
|
+
raise VarLibValidationError(f"Designspace must have at least one axis.")
|
|
995
|
+
|
|
996
|
+
axes = OrderedDict()
|
|
997
|
+
for axis_index, axis in enumerate(ds.axes):
|
|
998
|
+
axis_name = axis.name
|
|
999
|
+
if not axis_name:
|
|
1000
|
+
if not axis.tag:
|
|
1001
|
+
raise VarLibValidationError(f"Axis at index {axis_index} needs a tag.")
|
|
1002
|
+
axis_name = axis.name = axis.tag
|
|
1003
|
+
|
|
1004
|
+
if axis_name in standard_axis_map:
|
|
1005
|
+
if axis.tag is None:
|
|
1006
|
+
axis.tag = standard_axis_map[axis_name][0]
|
|
1007
|
+
if not axis.labelNames:
|
|
1008
|
+
axis.labelNames.update(standard_axis_map[axis_name][1])
|
|
1009
|
+
else:
|
|
1010
|
+
if not axis.tag:
|
|
1011
|
+
raise VarLibValidationError(f"Axis at index {axis_index} needs a tag.")
|
|
1012
|
+
if not axis.labelNames:
|
|
1013
|
+
axis.labelNames["en"] = tostr(axis_name)
|
|
1014
|
+
|
|
1015
|
+
axes[axis_name] = axis
|
|
1016
|
+
if log_enabled:
|
|
1017
|
+
log.info("Axes:\n%s", pformat([axis.asdict() for axis in axes.values()]))
|
|
1018
|
+
|
|
1019
|
+
axisMappings = ds.axisMappings
|
|
1020
|
+
if axisMappings and log_enabled:
|
|
1021
|
+
log.info("Mappings:\n%s", pformat(axisMappings))
|
|
1022
|
+
|
|
1023
|
+
# Check all master and instance locations are valid and fill in defaults
|
|
1024
|
+
for obj in masters + instances:
|
|
1025
|
+
obj_name = obj.name or obj.styleName or ""
|
|
1026
|
+
loc = obj.getFullDesignLocation(ds)
|
|
1027
|
+
obj.designLocation = loc
|
|
1028
|
+
if loc is None:
|
|
1029
|
+
raise VarLibValidationError(
|
|
1030
|
+
f"Source or instance '{obj_name}' has no location."
|
|
1031
|
+
)
|
|
1032
|
+
for axis_name in loc.keys():
|
|
1033
|
+
if axis_name not in axes:
|
|
1034
|
+
raise VarLibValidationError(
|
|
1035
|
+
f"Location axis '{axis_name}' unknown for '{obj_name}'."
|
|
1036
|
+
)
|
|
1037
|
+
for axis_name, axis in axes.items():
|
|
1038
|
+
v = axis.map_backward(loc[axis_name])
|
|
1039
|
+
if not (axis.minimum <= v <= axis.maximum):
|
|
1040
|
+
raise VarLibValidationError(
|
|
1041
|
+
f"Source or instance '{obj_name}' has out-of-range location "
|
|
1042
|
+
f"for axis '{axis_name}': is mapped to {v} but must be in "
|
|
1043
|
+
f"mapped range [{axis.minimum}..{axis.maximum}] (NOTE: all "
|
|
1044
|
+
"values are in user-space)."
|
|
1045
|
+
)
|
|
1046
|
+
|
|
1047
|
+
# Normalize master locations
|
|
1048
|
+
|
|
1049
|
+
internal_master_locs = [o.getFullDesignLocation(ds) for o in masters]
|
|
1050
|
+
if log_enabled:
|
|
1051
|
+
log.info("Internal master locations:\n%s", pformat(internal_master_locs))
|
|
1052
|
+
|
|
1053
|
+
# TODO This mapping should ideally be moved closer to logic in _add_fvar/avar
|
|
1054
|
+
internal_axis_supports = {}
|
|
1055
|
+
for axis in axes.values():
|
|
1056
|
+
triple = (axis.minimum, axis.default, axis.maximum)
|
|
1057
|
+
internal_axis_supports[axis.name] = [axis.map_forward(v) for v in triple]
|
|
1058
|
+
if log_enabled:
|
|
1059
|
+
log.info("Internal axis supports:\n%s", pformat(internal_axis_supports))
|
|
1060
|
+
|
|
1061
|
+
normalized_master_locs = [
|
|
1062
|
+
models.normalizeLocation(m, internal_axis_supports)
|
|
1063
|
+
for m in internal_master_locs
|
|
1064
|
+
]
|
|
1065
|
+
if log_enabled:
|
|
1066
|
+
log.info("Normalized master locations:\n%s", pformat(normalized_master_locs))
|
|
1067
|
+
|
|
1068
|
+
# Find base master
|
|
1069
|
+
base_idx = None
|
|
1070
|
+
for i, m in enumerate(normalized_master_locs):
|
|
1071
|
+
if all(v == 0 for v in m.values()):
|
|
1072
|
+
if base_idx is not None:
|
|
1073
|
+
raise VarLibValidationError(
|
|
1074
|
+
"More than one base master found in Designspace."
|
|
1075
|
+
)
|
|
1076
|
+
base_idx = i
|
|
1077
|
+
if require_sources and base_idx is None:
|
|
1078
|
+
raise VarLibValidationError(
|
|
1079
|
+
"Base master not found; no master at default location?"
|
|
1080
|
+
)
|
|
1081
|
+
if log_enabled:
|
|
1082
|
+
log.info("Index of base master: %s", base_idx)
|
|
1083
|
+
|
|
1084
|
+
return _DesignSpaceData(
|
|
1085
|
+
axes,
|
|
1086
|
+
axisMappings,
|
|
1087
|
+
internal_axis_supports,
|
|
1088
|
+
base_idx,
|
|
1089
|
+
normalized_master_locs,
|
|
1090
|
+
masters,
|
|
1091
|
+
instances,
|
|
1092
|
+
ds.rules,
|
|
1093
|
+
ds.rulesProcessingLast,
|
|
1094
|
+
ds.lib,
|
|
1095
|
+
)
|
|
1096
|
+
|
|
1097
|
+
|
|
1098
|
+
# https://docs.microsoft.com/en-us/typography/opentype/spec/os2#uswidthclass
|
|
1099
|
+
WDTH_VALUE_TO_OS2_WIDTH_CLASS = {
|
|
1100
|
+
50: 1,
|
|
1101
|
+
62.5: 2,
|
|
1102
|
+
75: 3,
|
|
1103
|
+
87.5: 4,
|
|
1104
|
+
100: 5,
|
|
1105
|
+
112.5: 6,
|
|
1106
|
+
125: 7,
|
|
1107
|
+
150: 8,
|
|
1108
|
+
200: 9,
|
|
1109
|
+
}
|
|
1110
|
+
|
|
1111
|
+
|
|
1112
|
+
def set_default_weight_width_slant(font, location):
|
|
1113
|
+
if "OS/2" in font:
|
|
1114
|
+
if "wght" in location:
|
|
1115
|
+
weight_class = otRound(max(1, min(location["wght"], 1000)))
|
|
1116
|
+
if font["OS/2"].usWeightClass != weight_class:
|
|
1117
|
+
log.info("Setting OS/2.usWeightClass = %s", weight_class)
|
|
1118
|
+
font["OS/2"].usWeightClass = weight_class
|
|
1119
|
+
|
|
1120
|
+
if "wdth" in location:
|
|
1121
|
+
# map 'wdth' axis (50..200) to OS/2.usWidthClass (1..9), rounding to closest
|
|
1122
|
+
widthValue = min(max(location["wdth"], 50), 200)
|
|
1123
|
+
widthClass = otRound(
|
|
1124
|
+
models.piecewiseLinearMap(widthValue, WDTH_VALUE_TO_OS2_WIDTH_CLASS)
|
|
1125
|
+
)
|
|
1126
|
+
if font["OS/2"].usWidthClass != widthClass:
|
|
1127
|
+
log.info("Setting OS/2.usWidthClass = %s", widthClass)
|
|
1128
|
+
font["OS/2"].usWidthClass = widthClass
|
|
1129
|
+
|
|
1130
|
+
if "slnt" in location and "post" in font:
|
|
1131
|
+
italicAngle = max(-90, min(location["slnt"], 90))
|
|
1132
|
+
if font["post"].italicAngle != italicAngle:
|
|
1133
|
+
log.info("Setting post.italicAngle = %s", italicAngle)
|
|
1134
|
+
font["post"].italicAngle = italicAngle
|
|
1135
|
+
|
|
1136
|
+
|
|
1137
|
+
def drop_implied_oncurve_points(*masters: TTFont) -> int:
|
|
1138
|
+
"""Drop impliable on-curve points from all the simple glyphs in masters.
|
|
1139
|
+
|
|
1140
|
+
In TrueType glyf outlines, on-curve points can be implied when they are located
|
|
1141
|
+
exactly at the midpoint of the line connecting two consecutive off-curve points.
|
|
1142
|
+
|
|
1143
|
+
The input masters' glyf tables are assumed to contain same-named glyphs that are
|
|
1144
|
+
interpolatable. Oncurve points are only dropped if they can be implied for all
|
|
1145
|
+
the masters. The fonts are modified in-place.
|
|
1146
|
+
|
|
1147
|
+
Args:
|
|
1148
|
+
masters: The TTFont(s) to modify
|
|
1149
|
+
|
|
1150
|
+
Returns:
|
|
1151
|
+
The total number of points that were dropped if any.
|
|
1152
|
+
|
|
1153
|
+
Reference:
|
|
1154
|
+
https://developer.apple.com/fonts/TrueType-Reference-Manual/RM01/Chap1.html
|
|
1155
|
+
"""
|
|
1156
|
+
|
|
1157
|
+
count = 0
|
|
1158
|
+
glyph_masters = defaultdict(list)
|
|
1159
|
+
# multiple DS source may point to the same TTFont object and we want to
|
|
1160
|
+
# avoid processing the same glyph twice as they are modified in-place
|
|
1161
|
+
for font in {id(m): m for m in masters}.values():
|
|
1162
|
+
glyf = font["glyf"]
|
|
1163
|
+
for glyphName in glyf.keys():
|
|
1164
|
+
glyph_masters[glyphName].append(glyf[glyphName])
|
|
1165
|
+
count = 0
|
|
1166
|
+
for glyphName, glyphs in glyph_masters.items():
|
|
1167
|
+
try:
|
|
1168
|
+
dropped = dropImpliedOnCurvePoints(*glyphs)
|
|
1169
|
+
except ValueError as e:
|
|
1170
|
+
# we don't fail for incompatible glyphs in _add_gvar so we shouldn't here
|
|
1171
|
+
log.warning("Failed to drop implied oncurves for %r: %s", glyphName, e)
|
|
1172
|
+
else:
|
|
1173
|
+
count += len(dropped)
|
|
1174
|
+
return count
|
|
1175
|
+
|
|
1176
|
+
|
|
1177
|
+
def build_many(
|
|
1178
|
+
designspace: DesignSpaceDocument,
|
|
1179
|
+
master_finder=lambda s: s,
|
|
1180
|
+
exclude=[],
|
|
1181
|
+
optimize=True,
|
|
1182
|
+
skip_vf=lambda vf_name: False,
|
|
1183
|
+
colr_layer_reuse=True,
|
|
1184
|
+
drop_implied_oncurves=False,
|
|
1185
|
+
):
|
|
1186
|
+
"""
|
|
1187
|
+
Build variable fonts from a designspace file, version 5 which can define
|
|
1188
|
+
several VFs, or version 4 which has implicitly one VF covering the whole doc.
|
|
1189
|
+
|
|
1190
|
+
If master_finder is set, it should be a callable that takes master
|
|
1191
|
+
filename as found in designspace file and map it to master font
|
|
1192
|
+
binary as to be opened (eg. .ttf or .otf).
|
|
1193
|
+
|
|
1194
|
+
skip_vf can be used to skip building some of the variable fonts defined in
|
|
1195
|
+
the input designspace. It's a predicate that takes as argument the name
|
|
1196
|
+
of the variable font and returns `bool`.
|
|
1197
|
+
|
|
1198
|
+
Always returns a Dict[str, TTFont] keyed by VariableFontDescriptor.name
|
|
1199
|
+
"""
|
|
1200
|
+
res = {}
|
|
1201
|
+
# varLib.build (used further below) by default only builds an incomplete 'STAT'
|
|
1202
|
+
# with an empty AxisValueArray--unless the VF inherited 'STAT' from its base master.
|
|
1203
|
+
# Designspace version 5 can also be used to define 'STAT' labels or customize
|
|
1204
|
+
# axes ordering, etc. To avoid overwriting a pre-existing 'STAT' or redoing the
|
|
1205
|
+
# same work twice, here we check if designspace contains any 'STAT' info before
|
|
1206
|
+
# proceeding to call buildVFStatTable for each VF.
|
|
1207
|
+
# https://github.com/fonttools/fonttools/pull/3024
|
|
1208
|
+
# https://github.com/fonttools/fonttools/issues/3045
|
|
1209
|
+
doBuildStatFromDSv5 = (
|
|
1210
|
+
"STAT" not in exclude
|
|
1211
|
+
and designspace.formatTuple >= (5, 0)
|
|
1212
|
+
and (
|
|
1213
|
+
any(a.axisLabels or a.axisOrdering is not None for a in designspace.axes)
|
|
1214
|
+
or designspace.locationLabels
|
|
1215
|
+
)
|
|
1216
|
+
)
|
|
1217
|
+
for _location, subDoc in splitInterpolable(designspace):
|
|
1218
|
+
for name, vfDoc in splitVariableFonts(subDoc):
|
|
1219
|
+
if skip_vf(name):
|
|
1220
|
+
log.debug(f"Skipping variable TTF font: {name}")
|
|
1221
|
+
continue
|
|
1222
|
+
vf = build(
|
|
1223
|
+
vfDoc,
|
|
1224
|
+
master_finder,
|
|
1225
|
+
exclude=exclude,
|
|
1226
|
+
optimize=optimize,
|
|
1227
|
+
colr_layer_reuse=colr_layer_reuse,
|
|
1228
|
+
drop_implied_oncurves=drop_implied_oncurves,
|
|
1229
|
+
)[0]
|
|
1230
|
+
if doBuildStatFromDSv5:
|
|
1231
|
+
buildVFStatTable(vf, designspace, name)
|
|
1232
|
+
res[name] = vf
|
|
1233
|
+
return res
|
|
1234
|
+
|
|
1235
|
+
|
|
1236
|
+
def build(
|
|
1237
|
+
designspace,
|
|
1238
|
+
master_finder=lambda s: s,
|
|
1239
|
+
exclude=[],
|
|
1240
|
+
optimize=True,
|
|
1241
|
+
colr_layer_reuse=True,
|
|
1242
|
+
drop_implied_oncurves=False,
|
|
1243
|
+
):
|
|
1244
|
+
"""
|
|
1245
|
+
Build variation font from a designspace file.
|
|
1246
|
+
|
|
1247
|
+
If master_finder is set, it should be a callable that takes master
|
|
1248
|
+
filename as found in designspace file and map it to master font
|
|
1249
|
+
binary as to be opened (eg. .ttf or .otf).
|
|
1250
|
+
"""
|
|
1251
|
+
if hasattr(designspace, "sources"): # Assume a DesignspaceDocument
|
|
1252
|
+
pass
|
|
1253
|
+
else: # Assume a file path
|
|
1254
|
+
designspace = DesignSpaceDocument.fromfile(designspace)
|
|
1255
|
+
|
|
1256
|
+
ds = load_designspace(designspace)
|
|
1257
|
+
log.info("Building variable font")
|
|
1258
|
+
|
|
1259
|
+
log.info("Loading master fonts")
|
|
1260
|
+
master_fonts = load_masters(designspace, master_finder)
|
|
1261
|
+
|
|
1262
|
+
# TODO: 'master_ttfs' is unused except for return value, remove later
|
|
1263
|
+
master_ttfs = []
|
|
1264
|
+
for master in master_fonts:
|
|
1265
|
+
try:
|
|
1266
|
+
master_ttfs.append(master.reader.file.name)
|
|
1267
|
+
except AttributeError:
|
|
1268
|
+
master_ttfs.append(None) # in-memory fonts have no path
|
|
1269
|
+
|
|
1270
|
+
if drop_implied_oncurves and "glyf" in master_fonts[ds.base_idx]:
|
|
1271
|
+
drop_count = drop_implied_oncurve_points(*master_fonts)
|
|
1272
|
+
log.info(
|
|
1273
|
+
"Dropped %s on-curve points from simple glyphs in the 'glyf' table",
|
|
1274
|
+
drop_count,
|
|
1275
|
+
)
|
|
1276
|
+
|
|
1277
|
+
# Copy the base master to work from it
|
|
1278
|
+
vf = deepcopy(master_fonts[ds.base_idx])
|
|
1279
|
+
|
|
1280
|
+
if "DSIG" in vf:
|
|
1281
|
+
del vf["DSIG"]
|
|
1282
|
+
|
|
1283
|
+
# Clear USE_MY_METRICS composite flags if set inconsistently across masters.
|
|
1284
|
+
if "glyf" in vf:
|
|
1285
|
+
_unset_inconsistent_use_my_metrics_flags(vf, master_fonts)
|
|
1286
|
+
|
|
1287
|
+
# TODO append masters as named-instances as well; needs .designspace change.
|
|
1288
|
+
fvar = _add_fvar(vf, ds.axes, ds.instances)
|
|
1289
|
+
if "STAT" not in exclude:
|
|
1290
|
+
_add_stat(vf)
|
|
1291
|
+
|
|
1292
|
+
# Map from axis names to axis tags...
|
|
1293
|
+
normalized_master_locs = [
|
|
1294
|
+
{ds.axes[k].tag: v for k, v in loc.items()} for loc in ds.normalized_master_locs
|
|
1295
|
+
]
|
|
1296
|
+
# From here on, we use fvar axes only
|
|
1297
|
+
axisTags = [axis.axisTag for axis in fvar.axes]
|
|
1298
|
+
|
|
1299
|
+
# Assume single-model for now.
|
|
1300
|
+
model = models.VariationModel(normalized_master_locs, axisOrder=axisTags)
|
|
1301
|
+
assert 0 == model.mapping[ds.base_idx]
|
|
1302
|
+
|
|
1303
|
+
log.info("Building variations tables")
|
|
1304
|
+
if "avar" not in exclude:
|
|
1305
|
+
_add_avar(vf, ds.axes, ds.axisMappings, axisTags)
|
|
1306
|
+
if "BASE" not in exclude and "BASE" in vf:
|
|
1307
|
+
_add_BASE(vf, model, master_fonts, axisTags)
|
|
1308
|
+
if "MVAR" not in exclude:
|
|
1309
|
+
_add_MVAR(vf, model, master_fonts, axisTags)
|
|
1310
|
+
if "HVAR" not in exclude:
|
|
1311
|
+
_add_HVAR(vf, model, master_fonts, axisTags)
|
|
1312
|
+
if "VVAR" not in exclude and "vmtx" in vf:
|
|
1313
|
+
_add_VVAR(vf, model, master_fonts, axisTags)
|
|
1314
|
+
if "GDEF" not in exclude or "GPOS" not in exclude:
|
|
1315
|
+
_merge_OTL(vf, model, master_fonts, axisTags)
|
|
1316
|
+
if "gvar" not in exclude and "glyf" in vf:
|
|
1317
|
+
_add_gvar(vf, model, master_fonts, optimize=optimize)
|
|
1318
|
+
if "cvar" not in exclude and "glyf" in vf:
|
|
1319
|
+
_merge_TTHinting(vf, model, master_fonts)
|
|
1320
|
+
if "GSUB" not in exclude and ds.rules:
|
|
1321
|
+
featureTags = _feature_variations_tags(ds)
|
|
1322
|
+
_add_GSUB_feature_variations(
|
|
1323
|
+
vf, ds.axes, ds.internal_axis_supports, ds.rules, featureTags
|
|
1324
|
+
)
|
|
1325
|
+
if "CFF2" not in exclude and ("CFF " in vf or "CFF2" in vf):
|
|
1326
|
+
_add_CFF2(vf, model, master_fonts)
|
|
1327
|
+
if "post" in vf:
|
|
1328
|
+
# set 'post' to format 2 to keep the glyph names dropped from CFF2
|
|
1329
|
+
post = vf["post"]
|
|
1330
|
+
if post.formatType != 2.0:
|
|
1331
|
+
post.formatType = 2.0
|
|
1332
|
+
post.extraNames = []
|
|
1333
|
+
post.mapping = {}
|
|
1334
|
+
if "COLR" not in exclude and "COLR" in vf and vf["COLR"].version > 0:
|
|
1335
|
+
_add_COLR(vf, model, master_fonts, axisTags, colr_layer_reuse)
|
|
1336
|
+
|
|
1337
|
+
set_default_weight_width_slant(
|
|
1338
|
+
vf, location={axis.axisTag: axis.defaultValue for axis in vf["fvar"].axes}
|
|
1339
|
+
)
|
|
1340
|
+
|
|
1341
|
+
for tag in exclude:
|
|
1342
|
+
if tag in vf:
|
|
1343
|
+
del vf[tag]
|
|
1344
|
+
|
|
1345
|
+
# TODO: Only return vf for 4.0+, the rest is unused.
|
|
1346
|
+
return vf, model, master_ttfs
|
|
1347
|
+
|
|
1348
|
+
|
|
1349
|
+
def _open_font(path, master_finder=lambda s: s):
|
|
1350
|
+
# load TTFont masters from given 'path': this can be either a .TTX or an
|
|
1351
|
+
# OpenType binary font; or if neither of these, try use the 'master_finder'
|
|
1352
|
+
# callable to resolve the path to a valid .TTX or OpenType font binary.
|
|
1353
|
+
from fontTools.ttx import guessFileType
|
|
1354
|
+
|
|
1355
|
+
master_path = os.path.normpath(path)
|
|
1356
|
+
tp = guessFileType(master_path)
|
|
1357
|
+
if tp is None:
|
|
1358
|
+
# not an OpenType binary/ttx, fall back to the master finder.
|
|
1359
|
+
master_path = master_finder(master_path)
|
|
1360
|
+
tp = guessFileType(master_path)
|
|
1361
|
+
if tp in ("TTX", "OTX"):
|
|
1362
|
+
font = TTFont()
|
|
1363
|
+
font.importXML(master_path)
|
|
1364
|
+
elif tp in ("TTF", "OTF", "WOFF", "WOFF2"):
|
|
1365
|
+
font = TTFont(master_path)
|
|
1366
|
+
else:
|
|
1367
|
+
raise VarLibValidationError("Invalid master path: %r" % master_path)
|
|
1368
|
+
return font
|
|
1369
|
+
|
|
1370
|
+
|
|
1371
|
+
def load_masters(designspace, master_finder=lambda s: s):
|
|
1372
|
+
"""Ensure that all SourceDescriptor.font attributes have an appropriate TTFont
|
|
1373
|
+
object loaded, or else open TTFont objects from the SourceDescriptor.path
|
|
1374
|
+
attributes.
|
|
1375
|
+
|
|
1376
|
+
The paths can point to either an OpenType font, a TTX file, or a UFO. In the
|
|
1377
|
+
latter case, use the provided master_finder callable to map from UFO paths to
|
|
1378
|
+
the respective master font binaries (e.g. .ttf, .otf or .ttx).
|
|
1379
|
+
|
|
1380
|
+
Return list of master TTFont objects in the same order they are listed in the
|
|
1381
|
+
DesignSpaceDocument.
|
|
1382
|
+
"""
|
|
1383
|
+
for master in designspace.sources:
|
|
1384
|
+
# If a SourceDescriptor has a layer name, demand that the compiled TTFont
|
|
1385
|
+
# be supplied by the caller. This spares us from modifying MasterFinder.
|
|
1386
|
+
if master.layerName and master.font is None:
|
|
1387
|
+
raise VarLibValidationError(
|
|
1388
|
+
f"Designspace source '{master.name or '<Unknown>'}' specified a "
|
|
1389
|
+
"layer name but lacks the required TTFont object in the 'font' "
|
|
1390
|
+
"attribute."
|
|
1391
|
+
)
|
|
1392
|
+
|
|
1393
|
+
return designspace.loadSourceFonts(_open_font, master_finder=master_finder)
|
|
1394
|
+
|
|
1395
|
+
|
|
1396
|
+
class MasterFinder(object):
|
|
1397
|
+
def __init__(self, template):
|
|
1398
|
+
self.template = template
|
|
1399
|
+
|
|
1400
|
+
def __call__(self, src_path):
|
|
1401
|
+
fullname = os.path.abspath(src_path)
|
|
1402
|
+
dirname, basename = os.path.split(fullname)
|
|
1403
|
+
stem, ext = os.path.splitext(basename)
|
|
1404
|
+
path = self.template.format(
|
|
1405
|
+
fullname=fullname,
|
|
1406
|
+
dirname=dirname,
|
|
1407
|
+
basename=basename,
|
|
1408
|
+
stem=stem,
|
|
1409
|
+
ext=ext,
|
|
1410
|
+
)
|
|
1411
|
+
return os.path.normpath(path)
|
|
1412
|
+
|
|
1413
|
+
|
|
1414
|
+
def _feature_variations_tags(ds):
|
|
1415
|
+
raw_tags = ds.lib.get(
|
|
1416
|
+
FEAVAR_FEATURETAG_LIB_KEY,
|
|
1417
|
+
"rclt" if ds.rulesProcessingLast else "rvrn",
|
|
1418
|
+
)
|
|
1419
|
+
return sorted({t.strip() for t in raw_tags.split(",")})
|
|
1420
|
+
|
|
1421
|
+
|
|
1422
|
+
def addGSUBFeatureVariations(vf, designspace, featureTags=(), *, log_enabled=False):
|
|
1423
|
+
"""Add GSUB FeatureVariations table to variable font, based on DesignSpace rules.
|
|
1424
|
+
|
|
1425
|
+
Args:
|
|
1426
|
+
vf: A TTFont object representing the variable font.
|
|
1427
|
+
designspace: A DesignSpaceDocument object.
|
|
1428
|
+
featureTags: Optional feature tag(s) to use for the FeatureVariations records.
|
|
1429
|
+
If unset, the key 'com.github.fonttools.varLib.featureVarsFeatureTag' is
|
|
1430
|
+
looked up in the DS <lib> and used; otherwise the default is 'rclt' if
|
|
1431
|
+
the <rules processing="last"> attribute is set, else 'rvrn'.
|
|
1432
|
+
See <https://fonttools.readthedocs.io/en/latest/designspaceLib/xml.html#rules-element>
|
|
1433
|
+
log_enabled: If True, log info about DS axes and sources. Default is False, as
|
|
1434
|
+
the same info may have already been logged as part of varLib.build.
|
|
1435
|
+
"""
|
|
1436
|
+
ds = load_designspace(designspace, log_enabled=log_enabled)
|
|
1437
|
+
if not ds.rules:
|
|
1438
|
+
return
|
|
1439
|
+
if not featureTags:
|
|
1440
|
+
featureTags = _feature_variations_tags(ds)
|
|
1441
|
+
_add_GSUB_feature_variations(
|
|
1442
|
+
vf, ds.axes, ds.internal_axis_supports, ds.rules, featureTags
|
|
1443
|
+
)
|
|
1444
|
+
|
|
1445
|
+
|
|
1446
|
+
def main(args=None):
|
|
1447
|
+
"""Build variable fonts from a designspace file and masters"""
|
|
1448
|
+
from argparse import ArgumentParser
|
|
1449
|
+
from fontTools import configLogger
|
|
1450
|
+
|
|
1451
|
+
parser = ArgumentParser(prog="varLib", description=main.__doc__)
|
|
1452
|
+
parser.add_argument("designspace")
|
|
1453
|
+
output_group = parser.add_mutually_exclusive_group()
|
|
1454
|
+
output_group.add_argument(
|
|
1455
|
+
"-o", metavar="OUTPUTFILE", dest="outfile", default=None, help="output file"
|
|
1456
|
+
)
|
|
1457
|
+
output_group.add_argument(
|
|
1458
|
+
"-d",
|
|
1459
|
+
"--output-dir",
|
|
1460
|
+
metavar="OUTPUTDIR",
|
|
1461
|
+
default=None,
|
|
1462
|
+
help="output dir (default: same as input designspace file)",
|
|
1463
|
+
)
|
|
1464
|
+
parser.add_argument(
|
|
1465
|
+
"-x",
|
|
1466
|
+
metavar="TAG",
|
|
1467
|
+
dest="exclude",
|
|
1468
|
+
action="append",
|
|
1469
|
+
default=[],
|
|
1470
|
+
help="exclude table",
|
|
1471
|
+
)
|
|
1472
|
+
parser.add_argument(
|
|
1473
|
+
"--disable-iup",
|
|
1474
|
+
dest="optimize",
|
|
1475
|
+
action="store_false",
|
|
1476
|
+
help="do not perform IUP optimization",
|
|
1477
|
+
)
|
|
1478
|
+
parser.add_argument(
|
|
1479
|
+
"--no-colr-layer-reuse",
|
|
1480
|
+
dest="colr_layer_reuse",
|
|
1481
|
+
action="store_false",
|
|
1482
|
+
help="do not rebuild variable COLR table to optimize COLR layer reuse",
|
|
1483
|
+
)
|
|
1484
|
+
parser.add_argument(
|
|
1485
|
+
"--drop-implied-oncurves",
|
|
1486
|
+
action="store_true",
|
|
1487
|
+
help=(
|
|
1488
|
+
"drop on-curve points that can be implied when exactly in the middle of "
|
|
1489
|
+
"two off-curve points (only applies to TrueType fonts)"
|
|
1490
|
+
),
|
|
1491
|
+
)
|
|
1492
|
+
parser.add_argument(
|
|
1493
|
+
"--master-finder",
|
|
1494
|
+
default="master_ttf_interpolatable/{stem}.ttf",
|
|
1495
|
+
help=(
|
|
1496
|
+
"templated string used for finding binary font "
|
|
1497
|
+
"files given the source file names defined in the "
|
|
1498
|
+
"designspace document. The following special strings "
|
|
1499
|
+
"are defined: {fullname} is the absolute source file "
|
|
1500
|
+
"name; {basename} is the file name without its "
|
|
1501
|
+
"directory; {stem} is the basename without the file "
|
|
1502
|
+
"extension; {ext} is the source file extension; "
|
|
1503
|
+
"{dirname} is the directory of the absolute file "
|
|
1504
|
+
'name. The default value is "%(default)s".'
|
|
1505
|
+
),
|
|
1506
|
+
)
|
|
1507
|
+
parser.add_argument(
|
|
1508
|
+
"--variable-fonts",
|
|
1509
|
+
default=".*",
|
|
1510
|
+
metavar="VF_NAME",
|
|
1511
|
+
help=(
|
|
1512
|
+
"Filter the list of variable fonts produced from the input "
|
|
1513
|
+
"Designspace v5 file. By default all listed variable fonts are "
|
|
1514
|
+
"generated. To generate a specific variable font (or variable fonts) "
|
|
1515
|
+
'that match a given "name" attribute, you can pass as argument '
|
|
1516
|
+
"the full name or a regular expression. E.g.: --variable-fonts "
|
|
1517
|
+
'"MyFontVF_WeightOnly"; or --variable-fonts "MyFontVFItalic_.*".'
|
|
1518
|
+
),
|
|
1519
|
+
)
|
|
1520
|
+
logging_group = parser.add_mutually_exclusive_group(required=False)
|
|
1521
|
+
logging_group.add_argument(
|
|
1522
|
+
"-v", "--verbose", action="store_true", help="Run more verbosely."
|
|
1523
|
+
)
|
|
1524
|
+
logging_group.add_argument(
|
|
1525
|
+
"-q", "--quiet", action="store_true", help="Turn verbosity off."
|
|
1526
|
+
)
|
|
1527
|
+
options = parser.parse_args(args)
|
|
1528
|
+
|
|
1529
|
+
configLogger(
|
|
1530
|
+
level=("DEBUG" if options.verbose else "ERROR" if options.quiet else "INFO")
|
|
1531
|
+
)
|
|
1532
|
+
|
|
1533
|
+
designspace_filename = options.designspace
|
|
1534
|
+
designspace = DesignSpaceDocument.fromfile(designspace_filename)
|
|
1535
|
+
|
|
1536
|
+
vf_descriptors = designspace.getVariableFonts()
|
|
1537
|
+
if not vf_descriptors:
|
|
1538
|
+
parser.error(f"No variable fonts in given designspace {designspace.path!r}")
|
|
1539
|
+
|
|
1540
|
+
vfs_to_build = []
|
|
1541
|
+
for vf in vf_descriptors:
|
|
1542
|
+
# Skip variable fonts that do not match the user's inclusion regex if given.
|
|
1543
|
+
if not fullmatch(options.variable_fonts, vf.name):
|
|
1544
|
+
continue
|
|
1545
|
+
vfs_to_build.append(vf)
|
|
1546
|
+
|
|
1547
|
+
if not vfs_to_build:
|
|
1548
|
+
parser.error(f"No variable fonts matching {options.variable_fonts!r}")
|
|
1549
|
+
|
|
1550
|
+
if options.outfile is not None and len(vfs_to_build) > 1:
|
|
1551
|
+
parser.error(
|
|
1552
|
+
"can't specify -o because there are multiple VFs to build; "
|
|
1553
|
+
"use --output-dir, or select a single VF with --variable-fonts"
|
|
1554
|
+
)
|
|
1555
|
+
|
|
1556
|
+
output_dir = options.output_dir
|
|
1557
|
+
if output_dir is None:
|
|
1558
|
+
output_dir = os.path.dirname(designspace_filename)
|
|
1559
|
+
|
|
1560
|
+
vf_name_to_output_path = {}
|
|
1561
|
+
if len(vfs_to_build) == 1 and options.outfile is not None:
|
|
1562
|
+
vf_name_to_output_path[vfs_to_build[0].name] = options.outfile
|
|
1563
|
+
else:
|
|
1564
|
+
for vf in vfs_to_build:
|
|
1565
|
+
if vf.filename is not None:
|
|
1566
|
+
# Only use basename to prevent path traversal attacks
|
|
1567
|
+
filename = os.path.basename(vf.filename)
|
|
1568
|
+
else:
|
|
1569
|
+
filename = vf.name + ".{ext}"
|
|
1570
|
+
vf_name_to_output_path[vf.name] = os.path.join(output_dir, filename)
|
|
1571
|
+
|
|
1572
|
+
finder = MasterFinder(options.master_finder)
|
|
1573
|
+
|
|
1574
|
+
vfs = build_many(
|
|
1575
|
+
designspace,
|
|
1576
|
+
finder,
|
|
1577
|
+
exclude=options.exclude,
|
|
1578
|
+
optimize=options.optimize,
|
|
1579
|
+
colr_layer_reuse=options.colr_layer_reuse,
|
|
1580
|
+
drop_implied_oncurves=options.drop_implied_oncurves,
|
|
1581
|
+
)
|
|
1582
|
+
|
|
1583
|
+
for vf_name, vf in vfs.items():
|
|
1584
|
+
ext = "otf" if vf.sfntVersion == "OTTO" else "ttf"
|
|
1585
|
+
output_path = vf_name_to_output_path[vf_name].format(ext=ext)
|
|
1586
|
+
output_dir = os.path.dirname(output_path)
|
|
1587
|
+
if output_dir:
|
|
1588
|
+
os.makedirs(output_dir, exist_ok=True)
|
|
1589
|
+
log.info("Saving variation font %s", output_path)
|
|
1590
|
+
vf.save(output_path)
|
|
1591
|
+
|
|
1592
|
+
|
|
1593
|
+
if __name__ == "__main__":
|
|
1594
|
+
import sys
|
|
1595
|
+
|
|
1596
|
+
if len(sys.argv) > 1:
|
|
1597
|
+
sys.exit(main())
|
|
1598
|
+
import doctest
|
|
1599
|
+
|
|
1600
|
+
sys.exit(doctest.testmod().failed)
|