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.
Files changed (353) hide show
  1. fontTools/__init__.py +8 -0
  2. fontTools/__main__.py +35 -0
  3. fontTools/afmLib.py +439 -0
  4. fontTools/agl.py +5233 -0
  5. fontTools/annotations.py +30 -0
  6. fontTools/cffLib/CFF2ToCFF.py +258 -0
  7. fontTools/cffLib/CFFToCFF2.py +305 -0
  8. fontTools/cffLib/__init__.py +3694 -0
  9. fontTools/cffLib/specializer.py +927 -0
  10. fontTools/cffLib/transforms.py +495 -0
  11. fontTools/cffLib/width.py +210 -0
  12. fontTools/colorLib/__init__.py +0 -0
  13. fontTools/colorLib/builder.py +664 -0
  14. fontTools/colorLib/errors.py +2 -0
  15. fontTools/colorLib/geometry.py +143 -0
  16. fontTools/colorLib/table_builder.py +223 -0
  17. fontTools/colorLib/unbuilder.py +81 -0
  18. fontTools/config/__init__.py +90 -0
  19. fontTools/cu2qu/__init__.py +15 -0
  20. fontTools/cu2qu/__main__.py +6 -0
  21. fontTools/cu2qu/benchmark.py +54 -0
  22. fontTools/cu2qu/cli.py +198 -0
  23. fontTools/cu2qu/cu2qu.c +15817 -0
  24. fontTools/cu2qu/cu2qu.cp311-win32.pyd +0 -0
  25. fontTools/cu2qu/cu2qu.py +563 -0
  26. fontTools/cu2qu/errors.py +77 -0
  27. fontTools/cu2qu/ufo.py +363 -0
  28. fontTools/designspaceLib/__init__.py +3343 -0
  29. fontTools/designspaceLib/__main__.py +6 -0
  30. fontTools/designspaceLib/split.py +475 -0
  31. fontTools/designspaceLib/statNames.py +260 -0
  32. fontTools/designspaceLib/types.py +147 -0
  33. fontTools/encodings/MacRoman.py +258 -0
  34. fontTools/encodings/StandardEncoding.py +258 -0
  35. fontTools/encodings/__init__.py +1 -0
  36. fontTools/encodings/codecs.py +135 -0
  37. fontTools/feaLib/__init__.py +4 -0
  38. fontTools/feaLib/__main__.py +78 -0
  39. fontTools/feaLib/ast.py +2143 -0
  40. fontTools/feaLib/builder.py +1814 -0
  41. fontTools/feaLib/error.py +22 -0
  42. fontTools/feaLib/lexer.c +17029 -0
  43. fontTools/feaLib/lexer.cp311-win32.pyd +0 -0
  44. fontTools/feaLib/lexer.py +287 -0
  45. fontTools/feaLib/location.py +12 -0
  46. fontTools/feaLib/lookupDebugInfo.py +12 -0
  47. fontTools/feaLib/parser.py +2394 -0
  48. fontTools/feaLib/variableScalar.py +118 -0
  49. fontTools/fontBuilder.py +1014 -0
  50. fontTools/help.py +36 -0
  51. fontTools/merge/__init__.py +248 -0
  52. fontTools/merge/__main__.py +6 -0
  53. fontTools/merge/base.py +81 -0
  54. fontTools/merge/cmap.py +173 -0
  55. fontTools/merge/layout.py +526 -0
  56. fontTools/merge/options.py +85 -0
  57. fontTools/merge/tables.py +352 -0
  58. fontTools/merge/unicode.py +78 -0
  59. fontTools/merge/util.py +143 -0
  60. fontTools/misc/__init__.py +1 -0
  61. fontTools/misc/arrayTools.py +424 -0
  62. fontTools/misc/bezierTools.c +39731 -0
  63. fontTools/misc/bezierTools.cp311-win32.pyd +0 -0
  64. fontTools/misc/bezierTools.py +1500 -0
  65. fontTools/misc/classifyTools.py +170 -0
  66. fontTools/misc/cliTools.py +53 -0
  67. fontTools/misc/configTools.py +349 -0
  68. fontTools/misc/cython.py +27 -0
  69. fontTools/misc/dictTools.py +83 -0
  70. fontTools/misc/eexec.py +119 -0
  71. fontTools/misc/encodingTools.py +72 -0
  72. fontTools/misc/enumTools.py +23 -0
  73. fontTools/misc/etree.py +456 -0
  74. fontTools/misc/filenames.py +245 -0
  75. fontTools/misc/filesystem/__init__.py +68 -0
  76. fontTools/misc/filesystem/_base.py +134 -0
  77. fontTools/misc/filesystem/_copy.py +45 -0
  78. fontTools/misc/filesystem/_errors.py +54 -0
  79. fontTools/misc/filesystem/_info.py +75 -0
  80. fontTools/misc/filesystem/_osfs.py +164 -0
  81. fontTools/misc/filesystem/_path.py +67 -0
  82. fontTools/misc/filesystem/_subfs.py +92 -0
  83. fontTools/misc/filesystem/_tempfs.py +34 -0
  84. fontTools/misc/filesystem/_tools.py +34 -0
  85. fontTools/misc/filesystem/_walk.py +55 -0
  86. fontTools/misc/filesystem/_zipfs.py +204 -0
  87. fontTools/misc/fixedTools.py +253 -0
  88. fontTools/misc/intTools.py +25 -0
  89. fontTools/misc/iterTools.py +12 -0
  90. fontTools/misc/lazyTools.py +42 -0
  91. fontTools/misc/loggingTools.py +543 -0
  92. fontTools/misc/macCreatorType.py +56 -0
  93. fontTools/misc/macRes.py +261 -0
  94. fontTools/misc/plistlib/__init__.py +681 -0
  95. fontTools/misc/plistlib/py.typed +0 -0
  96. fontTools/misc/psCharStrings.py +1511 -0
  97. fontTools/misc/psLib.py +398 -0
  98. fontTools/misc/psOperators.py +572 -0
  99. fontTools/misc/py23.py +96 -0
  100. fontTools/misc/roundTools.py +110 -0
  101. fontTools/misc/sstruct.py +227 -0
  102. fontTools/misc/symfont.py +242 -0
  103. fontTools/misc/testTools.py +233 -0
  104. fontTools/misc/textTools.py +156 -0
  105. fontTools/misc/timeTools.py +88 -0
  106. fontTools/misc/transform.py +516 -0
  107. fontTools/misc/treeTools.py +45 -0
  108. fontTools/misc/vector.py +147 -0
  109. fontTools/misc/visitor.py +158 -0
  110. fontTools/misc/xmlReader.py +188 -0
  111. fontTools/misc/xmlWriter.py +231 -0
  112. fontTools/mtiLib/__init__.py +1400 -0
  113. fontTools/mtiLib/__main__.py +5 -0
  114. fontTools/otlLib/__init__.py +1 -0
  115. fontTools/otlLib/builder.py +3465 -0
  116. fontTools/otlLib/error.py +11 -0
  117. fontTools/otlLib/maxContextCalc.py +96 -0
  118. fontTools/otlLib/optimize/__init__.py +53 -0
  119. fontTools/otlLib/optimize/__main__.py +6 -0
  120. fontTools/otlLib/optimize/gpos.py +439 -0
  121. fontTools/pens/__init__.py +1 -0
  122. fontTools/pens/areaPen.py +52 -0
  123. fontTools/pens/basePen.py +475 -0
  124. fontTools/pens/boundsPen.py +98 -0
  125. fontTools/pens/cairoPen.py +26 -0
  126. fontTools/pens/cocoaPen.py +26 -0
  127. fontTools/pens/cu2quPen.py +325 -0
  128. fontTools/pens/explicitClosingLinePen.py +101 -0
  129. fontTools/pens/filterPen.py +433 -0
  130. fontTools/pens/freetypePen.py +462 -0
  131. fontTools/pens/hashPointPen.py +89 -0
  132. fontTools/pens/momentsPen.c +13378 -0
  133. fontTools/pens/momentsPen.cp311-win32.pyd +0 -0
  134. fontTools/pens/momentsPen.py +879 -0
  135. fontTools/pens/perimeterPen.py +69 -0
  136. fontTools/pens/pointInsidePen.py +192 -0
  137. fontTools/pens/pointPen.py +643 -0
  138. fontTools/pens/qtPen.py +29 -0
  139. fontTools/pens/qu2cuPen.py +105 -0
  140. fontTools/pens/quartzPen.py +43 -0
  141. fontTools/pens/recordingPen.py +335 -0
  142. fontTools/pens/reportLabPen.py +79 -0
  143. fontTools/pens/reverseContourPen.py +96 -0
  144. fontTools/pens/roundingPen.py +130 -0
  145. fontTools/pens/statisticsPen.py +312 -0
  146. fontTools/pens/svgPathPen.py +310 -0
  147. fontTools/pens/t2CharStringPen.py +88 -0
  148. fontTools/pens/teePen.py +55 -0
  149. fontTools/pens/transformPen.py +115 -0
  150. fontTools/pens/ttGlyphPen.py +335 -0
  151. fontTools/pens/wxPen.py +29 -0
  152. fontTools/qu2cu/__init__.py +15 -0
  153. fontTools/qu2cu/__main__.py +7 -0
  154. fontTools/qu2cu/benchmark.py +56 -0
  155. fontTools/qu2cu/cli.py +125 -0
  156. fontTools/qu2cu/qu2cu.c +16682 -0
  157. fontTools/qu2cu/qu2cu.cp311-win32.pyd +0 -0
  158. fontTools/qu2cu/qu2cu.py +405 -0
  159. fontTools/subset/__init__.py +4096 -0
  160. fontTools/subset/__main__.py +6 -0
  161. fontTools/subset/cff.py +184 -0
  162. fontTools/subset/svg.py +253 -0
  163. fontTools/subset/util.py +25 -0
  164. fontTools/svgLib/__init__.py +3 -0
  165. fontTools/svgLib/path/__init__.py +65 -0
  166. fontTools/svgLib/path/arc.py +154 -0
  167. fontTools/svgLib/path/parser.py +322 -0
  168. fontTools/svgLib/path/shapes.py +183 -0
  169. fontTools/t1Lib/__init__.py +648 -0
  170. fontTools/tfmLib.py +460 -0
  171. fontTools/ttLib/__init__.py +30 -0
  172. fontTools/ttLib/__main__.py +148 -0
  173. fontTools/ttLib/macUtils.py +54 -0
  174. fontTools/ttLib/removeOverlaps.py +395 -0
  175. fontTools/ttLib/reorderGlyphs.py +285 -0
  176. fontTools/ttLib/scaleUpem.py +436 -0
  177. fontTools/ttLib/sfnt.py +661 -0
  178. fontTools/ttLib/standardGlyphOrder.py +271 -0
  179. fontTools/ttLib/tables/B_A_S_E_.py +14 -0
  180. fontTools/ttLib/tables/BitmapGlyphMetrics.py +64 -0
  181. fontTools/ttLib/tables/C_B_D_T_.py +113 -0
  182. fontTools/ttLib/tables/C_B_L_C_.py +19 -0
  183. fontTools/ttLib/tables/C_F_F_.py +61 -0
  184. fontTools/ttLib/tables/C_F_F__2.py +26 -0
  185. fontTools/ttLib/tables/C_O_L_R_.py +165 -0
  186. fontTools/ttLib/tables/C_P_A_L_.py +305 -0
  187. fontTools/ttLib/tables/D_S_I_G_.py +158 -0
  188. fontTools/ttLib/tables/D__e_b_g.py +35 -0
  189. fontTools/ttLib/tables/DefaultTable.py +49 -0
  190. fontTools/ttLib/tables/E_B_D_T_.py +835 -0
  191. fontTools/ttLib/tables/E_B_L_C_.py +718 -0
  192. fontTools/ttLib/tables/F_F_T_M_.py +52 -0
  193. fontTools/ttLib/tables/F__e_a_t.py +149 -0
  194. fontTools/ttLib/tables/G_D_E_F_.py +13 -0
  195. fontTools/ttLib/tables/G_M_A_P_.py +148 -0
  196. fontTools/ttLib/tables/G_P_K_G_.py +133 -0
  197. fontTools/ttLib/tables/G_P_O_S_.py +14 -0
  198. fontTools/ttLib/tables/G_S_U_B_.py +13 -0
  199. fontTools/ttLib/tables/G_V_A_R_.py +5 -0
  200. fontTools/ttLib/tables/G__l_a_t.py +235 -0
  201. fontTools/ttLib/tables/G__l_o_c.py +85 -0
  202. fontTools/ttLib/tables/H_V_A_R_.py +13 -0
  203. fontTools/ttLib/tables/J_S_T_F_.py +13 -0
  204. fontTools/ttLib/tables/L_T_S_H_.py +58 -0
  205. fontTools/ttLib/tables/M_A_T_H_.py +13 -0
  206. fontTools/ttLib/tables/M_E_T_A_.py +352 -0
  207. fontTools/ttLib/tables/M_V_A_R_.py +13 -0
  208. fontTools/ttLib/tables/O_S_2f_2.py +752 -0
  209. fontTools/ttLib/tables/S_I_N_G_.py +99 -0
  210. fontTools/ttLib/tables/S_T_A_T_.py +15 -0
  211. fontTools/ttLib/tables/S_V_G_.py +223 -0
  212. fontTools/ttLib/tables/S__i_l_f.py +1040 -0
  213. fontTools/ttLib/tables/S__i_l_l.py +92 -0
  214. fontTools/ttLib/tables/T_S_I_B_.py +13 -0
  215. fontTools/ttLib/tables/T_S_I_C_.py +14 -0
  216. fontTools/ttLib/tables/T_S_I_D_.py +13 -0
  217. fontTools/ttLib/tables/T_S_I_J_.py +13 -0
  218. fontTools/ttLib/tables/T_S_I_P_.py +13 -0
  219. fontTools/ttLib/tables/T_S_I_S_.py +13 -0
  220. fontTools/ttLib/tables/T_S_I_V_.py +26 -0
  221. fontTools/ttLib/tables/T_S_I__0.py +70 -0
  222. fontTools/ttLib/tables/T_S_I__1.py +163 -0
  223. fontTools/ttLib/tables/T_S_I__2.py +17 -0
  224. fontTools/ttLib/tables/T_S_I__3.py +22 -0
  225. fontTools/ttLib/tables/T_S_I__5.py +60 -0
  226. fontTools/ttLib/tables/T_T_F_A_.py +14 -0
  227. fontTools/ttLib/tables/TupleVariation.py +884 -0
  228. fontTools/ttLib/tables/V_A_R_C_.py +12 -0
  229. fontTools/ttLib/tables/V_D_M_X_.py +249 -0
  230. fontTools/ttLib/tables/V_O_R_G_.py +165 -0
  231. fontTools/ttLib/tables/V_V_A_R_.py +13 -0
  232. fontTools/ttLib/tables/__init__.py +98 -0
  233. fontTools/ttLib/tables/_a_n_k_r.py +15 -0
  234. fontTools/ttLib/tables/_a_v_a_r.py +193 -0
  235. fontTools/ttLib/tables/_b_s_l_n.py +15 -0
  236. fontTools/ttLib/tables/_c_i_d_g.py +24 -0
  237. fontTools/ttLib/tables/_c_m_a_p.py +1591 -0
  238. fontTools/ttLib/tables/_c_v_a_r.py +94 -0
  239. fontTools/ttLib/tables/_c_v_t.py +56 -0
  240. fontTools/ttLib/tables/_f_e_a_t.py +15 -0
  241. fontTools/ttLib/tables/_f_p_g_m.py +62 -0
  242. fontTools/ttLib/tables/_f_v_a_r.py +261 -0
  243. fontTools/ttLib/tables/_g_a_s_p.py +63 -0
  244. fontTools/ttLib/tables/_g_c_i_d.py +13 -0
  245. fontTools/ttLib/tables/_g_l_y_f.py +2311 -0
  246. fontTools/ttLib/tables/_g_v_a_r.py +340 -0
  247. fontTools/ttLib/tables/_h_d_m_x.py +127 -0
  248. fontTools/ttLib/tables/_h_e_a_d.py +130 -0
  249. fontTools/ttLib/tables/_h_h_e_a.py +147 -0
  250. fontTools/ttLib/tables/_h_m_t_x.py +164 -0
  251. fontTools/ttLib/tables/_k_e_r_n.py +289 -0
  252. fontTools/ttLib/tables/_l_c_a_r.py +13 -0
  253. fontTools/ttLib/tables/_l_o_c_a.py +70 -0
  254. fontTools/ttLib/tables/_l_t_a_g.py +72 -0
  255. fontTools/ttLib/tables/_m_a_x_p.py +147 -0
  256. fontTools/ttLib/tables/_m_e_t_a.py +112 -0
  257. fontTools/ttLib/tables/_m_o_r_t.py +14 -0
  258. fontTools/ttLib/tables/_m_o_r_x.py +15 -0
  259. fontTools/ttLib/tables/_n_a_m_e.py +1242 -0
  260. fontTools/ttLib/tables/_o_p_b_d.py +14 -0
  261. fontTools/ttLib/tables/_p_o_s_t.py +319 -0
  262. fontTools/ttLib/tables/_p_r_e_p.py +16 -0
  263. fontTools/ttLib/tables/_p_r_o_p.py +12 -0
  264. fontTools/ttLib/tables/_s_b_i_x.py +129 -0
  265. fontTools/ttLib/tables/_t_r_a_k.py +332 -0
  266. fontTools/ttLib/tables/_v_h_e_a.py +139 -0
  267. fontTools/ttLib/tables/_v_m_t_x.py +19 -0
  268. fontTools/ttLib/tables/asciiTable.py +20 -0
  269. fontTools/ttLib/tables/grUtils.py +92 -0
  270. fontTools/ttLib/tables/otBase.py +1458 -0
  271. fontTools/ttLib/tables/otConverters.py +2068 -0
  272. fontTools/ttLib/tables/otData.py +6400 -0
  273. fontTools/ttLib/tables/otTables.py +2703 -0
  274. fontTools/ttLib/tables/otTraverse.py +163 -0
  275. fontTools/ttLib/tables/sbixGlyph.py +149 -0
  276. fontTools/ttLib/tables/sbixStrike.py +177 -0
  277. fontTools/ttLib/tables/table_API_readme.txt +91 -0
  278. fontTools/ttLib/tables/ttProgram.py +594 -0
  279. fontTools/ttLib/ttCollection.py +125 -0
  280. fontTools/ttLib/ttFont.py +1148 -0
  281. fontTools/ttLib/ttGlyphSet.py +490 -0
  282. fontTools/ttLib/ttVisitor.py +32 -0
  283. fontTools/ttLib/woff2.py +1680 -0
  284. fontTools/ttx.py +479 -0
  285. fontTools/ufoLib/__init__.py +2575 -0
  286. fontTools/ufoLib/converters.py +407 -0
  287. fontTools/ufoLib/errors.py +30 -0
  288. fontTools/ufoLib/etree.py +6 -0
  289. fontTools/ufoLib/filenames.py +356 -0
  290. fontTools/ufoLib/glifLib.py +2120 -0
  291. fontTools/ufoLib/kerning.py +141 -0
  292. fontTools/ufoLib/plistlib.py +47 -0
  293. fontTools/ufoLib/pointPen.py +6 -0
  294. fontTools/ufoLib/utils.py +107 -0
  295. fontTools/ufoLib/validators.py +1208 -0
  296. fontTools/unicode.py +50 -0
  297. fontTools/unicodedata/Blocks.py +817 -0
  298. fontTools/unicodedata/Mirrored.py +446 -0
  299. fontTools/unicodedata/OTTags.py +50 -0
  300. fontTools/unicodedata/ScriptExtensions.py +832 -0
  301. fontTools/unicodedata/Scripts.py +3639 -0
  302. fontTools/unicodedata/__init__.py +306 -0
  303. fontTools/varLib/__init__.py +1600 -0
  304. fontTools/varLib/__main__.py +6 -0
  305. fontTools/varLib/avar/__init__.py +0 -0
  306. fontTools/varLib/avar/__main__.py +72 -0
  307. fontTools/varLib/avar/build.py +79 -0
  308. fontTools/varLib/avar/map.py +108 -0
  309. fontTools/varLib/avar/plan.py +1004 -0
  310. fontTools/varLib/avar/unbuild.py +271 -0
  311. fontTools/varLib/avarPlanner.py +8 -0
  312. fontTools/varLib/builder.py +215 -0
  313. fontTools/varLib/cff.py +631 -0
  314. fontTools/varLib/errors.py +219 -0
  315. fontTools/varLib/featureVars.py +703 -0
  316. fontTools/varLib/hvar.py +113 -0
  317. fontTools/varLib/instancer/__init__.py +2052 -0
  318. fontTools/varLib/instancer/__main__.py +5 -0
  319. fontTools/varLib/instancer/featureVars.py +190 -0
  320. fontTools/varLib/instancer/names.py +388 -0
  321. fontTools/varLib/instancer/solver.py +309 -0
  322. fontTools/varLib/interpolatable.py +1209 -0
  323. fontTools/varLib/interpolatableHelpers.py +399 -0
  324. fontTools/varLib/interpolatablePlot.py +1269 -0
  325. fontTools/varLib/interpolatableTestContourOrder.py +82 -0
  326. fontTools/varLib/interpolatableTestStartingPoint.py +107 -0
  327. fontTools/varLib/interpolate_layout.py +124 -0
  328. fontTools/varLib/iup.c +19815 -0
  329. fontTools/varLib/iup.cp311-win32.pyd +0 -0
  330. fontTools/varLib/iup.py +490 -0
  331. fontTools/varLib/merger.py +1717 -0
  332. fontTools/varLib/models.py +642 -0
  333. fontTools/varLib/multiVarStore.py +253 -0
  334. fontTools/varLib/mutator.py +529 -0
  335. fontTools/varLib/mvar.py +40 -0
  336. fontTools/varLib/plot.py +238 -0
  337. fontTools/varLib/stat.py +149 -0
  338. fontTools/varLib/varStore.py +739 -0
  339. fontTools/voltLib/__init__.py +5 -0
  340. fontTools/voltLib/__main__.py +206 -0
  341. fontTools/voltLib/ast.py +452 -0
  342. fontTools/voltLib/error.py +12 -0
  343. fontTools/voltLib/lexer.py +99 -0
  344. fontTools/voltLib/parser.py +664 -0
  345. fontTools/voltLib/voltToFea.py +911 -0
  346. fonttools-4.60.2.data/data/share/man/man1/ttx.1 +225 -0
  347. fonttools-4.60.2.dist-info/METADATA +2250 -0
  348. fonttools-4.60.2.dist-info/RECORD +353 -0
  349. fonttools-4.60.2.dist-info/WHEEL +5 -0
  350. fonttools-4.60.2.dist-info/entry_points.txt +5 -0
  351. fonttools-4.60.2.dist-info/licenses/LICENSE +21 -0
  352. fonttools-4.60.2.dist-info/licenses/LICENSE.external +388 -0
  353. fonttools-4.60.2.dist-info/top_level.txt +1 -0
@@ -0,0 +1,1014 @@
1
+ __all__ = ["FontBuilder"]
2
+
3
+ """
4
+ This module is *experimental*, meaning it still may evolve and change.
5
+
6
+ The `FontBuilder` class is a convenient helper to construct working TTF or
7
+ OTF fonts from scratch.
8
+
9
+ Note that the various setup methods cannot be called in arbitrary order,
10
+ due to various interdependencies between OpenType tables. Here is an order
11
+ that works:
12
+
13
+ fb = FontBuilder(...)
14
+ fb.setupGlyphOrder(...)
15
+ fb.setupCharacterMap(...)
16
+ fb.setupGlyf(...) --or-- fb.setupCFF(...)
17
+ fb.setupHorizontalMetrics(...)
18
+ fb.setupHorizontalHeader()
19
+ fb.setupNameTable(...)
20
+ fb.setupOS2()
21
+ fb.addOpenTypeFeatures(...)
22
+ fb.setupPost()
23
+ fb.save(...)
24
+
25
+ Here is how to build a minimal TTF:
26
+
27
+ ```python
28
+ from fontTools.fontBuilder import FontBuilder
29
+ from fontTools.pens.ttGlyphPen import TTGlyphPen
30
+
31
+
32
+ def drawTestGlyph(pen):
33
+ pen.moveTo((100, 100))
34
+ pen.lineTo((100, 1000))
35
+ pen.qCurveTo((200, 900), (400, 900), (500, 1000))
36
+ pen.lineTo((500, 100))
37
+ pen.closePath()
38
+
39
+
40
+ fb = FontBuilder(1024, isTTF=True)
41
+ fb.setupGlyphOrder([".notdef", ".null", "space", "A", "a"])
42
+ fb.setupCharacterMap({32: "space", 65: "A", 97: "a"})
43
+ advanceWidths = {".notdef": 600, "space": 500, "A": 600, "a": 600, ".null": 0}
44
+
45
+ familyName = "HelloTestFont"
46
+ styleName = "TotallyNormal"
47
+ version = "0.1"
48
+
49
+ nameStrings = dict(
50
+ familyName=dict(en=familyName, nl="HalloTestFont"),
51
+ styleName=dict(en=styleName, nl="TotaalNormaal"),
52
+ uniqueFontIdentifier="fontBuilder: " + familyName + "." + styleName,
53
+ fullName=familyName + "-" + styleName,
54
+ psName=familyName + "-" + styleName,
55
+ version="Version " + version,
56
+ )
57
+
58
+ pen = TTGlyphPen(None)
59
+ drawTestGlyph(pen)
60
+ glyph = pen.glyph()
61
+ glyphs = {".notdef": glyph, "space": glyph, "A": glyph, "a": glyph, ".null": glyph}
62
+ fb.setupGlyf(glyphs)
63
+ metrics = {}
64
+ glyphTable = fb.font["glyf"]
65
+ for gn, advanceWidth in advanceWidths.items():
66
+ metrics[gn] = (advanceWidth, glyphTable[gn].xMin)
67
+ fb.setupHorizontalMetrics(metrics)
68
+ fb.setupHorizontalHeader(ascent=824, descent=-200)
69
+ fb.setupNameTable(nameStrings)
70
+ fb.setupOS2(sTypoAscender=824, usWinAscent=824, usWinDescent=200)
71
+ fb.setupPost()
72
+ fb.save("test.ttf")
73
+ ```
74
+
75
+ And here's how to build a minimal OTF:
76
+
77
+ ```python
78
+ from fontTools.fontBuilder import FontBuilder
79
+ from fontTools.pens.t2CharStringPen import T2CharStringPen
80
+
81
+
82
+ def drawTestGlyph(pen):
83
+ pen.moveTo((100, 100))
84
+ pen.lineTo((100, 1000))
85
+ pen.curveTo((200, 900), (400, 900), (500, 1000))
86
+ pen.lineTo((500, 100))
87
+ pen.closePath()
88
+
89
+
90
+ fb = FontBuilder(1024, isTTF=False)
91
+ fb.setupGlyphOrder([".notdef", ".null", "space", "A", "a"])
92
+ fb.setupCharacterMap({32: "space", 65: "A", 97: "a"})
93
+ advanceWidths = {".notdef": 600, "space": 500, "A": 600, "a": 600, ".null": 0}
94
+
95
+ familyName = "HelloTestFont"
96
+ styleName = "TotallyNormal"
97
+ version = "0.1"
98
+
99
+ nameStrings = dict(
100
+ familyName=dict(en=familyName, nl="HalloTestFont"),
101
+ styleName=dict(en=styleName, nl="TotaalNormaal"),
102
+ uniqueFontIdentifier="fontBuilder: " + familyName + "." + styleName,
103
+ fullName=familyName + "-" + styleName,
104
+ psName=familyName + "-" + styleName,
105
+ version="Version " + version,
106
+ )
107
+
108
+ pen = T2CharStringPen(600, None)
109
+ drawTestGlyph(pen)
110
+ charString = pen.getCharString()
111
+ charStrings = {
112
+ ".notdef": charString,
113
+ "space": charString,
114
+ "A": charString,
115
+ "a": charString,
116
+ ".null": charString,
117
+ }
118
+ fb.setupCFF(nameStrings["psName"], {"FullName": nameStrings["psName"]}, charStrings, {})
119
+ lsb = {gn: cs.calcBounds(None)[0] for gn, cs in charStrings.items()}
120
+ metrics = {}
121
+ for gn, advanceWidth in advanceWidths.items():
122
+ metrics[gn] = (advanceWidth, lsb[gn])
123
+ fb.setupHorizontalMetrics(metrics)
124
+ fb.setupHorizontalHeader(ascent=824, descent=200)
125
+ fb.setupNameTable(nameStrings)
126
+ fb.setupOS2(sTypoAscender=824, usWinAscent=824, usWinDescent=200)
127
+ fb.setupPost()
128
+ fb.save("test.otf")
129
+ ```
130
+ """
131
+
132
+ from .ttLib import TTFont, newTable
133
+ from .ttLib.tables._c_m_a_p import cmap_classes
134
+ from .ttLib.tables._g_l_y_f import flagCubic
135
+ from .ttLib.tables.O_S_2f_2 import Panose
136
+ from .misc.timeTools import timestampNow
137
+ import struct
138
+ from collections import OrderedDict
139
+
140
+
141
+ _headDefaults = dict(
142
+ tableVersion=1.0,
143
+ fontRevision=1.0,
144
+ checkSumAdjustment=0,
145
+ magicNumber=0x5F0F3CF5,
146
+ flags=0x0003,
147
+ unitsPerEm=1000,
148
+ created=0,
149
+ modified=0,
150
+ xMin=0,
151
+ yMin=0,
152
+ xMax=0,
153
+ yMax=0,
154
+ macStyle=0,
155
+ lowestRecPPEM=3,
156
+ fontDirectionHint=2,
157
+ indexToLocFormat=0,
158
+ glyphDataFormat=0,
159
+ )
160
+
161
+ _maxpDefaultsTTF = dict(
162
+ tableVersion=0x00010000,
163
+ numGlyphs=0,
164
+ maxPoints=0,
165
+ maxContours=0,
166
+ maxCompositePoints=0,
167
+ maxCompositeContours=0,
168
+ maxZones=2,
169
+ maxTwilightPoints=0,
170
+ maxStorage=0,
171
+ maxFunctionDefs=0,
172
+ maxInstructionDefs=0,
173
+ maxStackElements=0,
174
+ maxSizeOfInstructions=0,
175
+ maxComponentElements=0,
176
+ maxComponentDepth=0,
177
+ )
178
+ _maxpDefaultsOTF = dict(
179
+ tableVersion=0x00005000,
180
+ numGlyphs=0,
181
+ )
182
+
183
+ _postDefaults = dict(
184
+ formatType=3.0,
185
+ italicAngle=0,
186
+ underlinePosition=0,
187
+ underlineThickness=0,
188
+ isFixedPitch=0,
189
+ minMemType42=0,
190
+ maxMemType42=0,
191
+ minMemType1=0,
192
+ maxMemType1=0,
193
+ )
194
+
195
+ _hheaDefaults = dict(
196
+ tableVersion=0x00010000,
197
+ ascent=0,
198
+ descent=0,
199
+ lineGap=0,
200
+ advanceWidthMax=0,
201
+ minLeftSideBearing=0,
202
+ minRightSideBearing=0,
203
+ xMaxExtent=0,
204
+ caretSlopeRise=1,
205
+ caretSlopeRun=0,
206
+ caretOffset=0,
207
+ reserved0=0,
208
+ reserved1=0,
209
+ reserved2=0,
210
+ reserved3=0,
211
+ metricDataFormat=0,
212
+ numberOfHMetrics=0,
213
+ )
214
+
215
+ _vheaDefaults = dict(
216
+ tableVersion=0x00010000,
217
+ ascent=0,
218
+ descent=0,
219
+ lineGap=0,
220
+ advanceHeightMax=0,
221
+ minTopSideBearing=0,
222
+ minBottomSideBearing=0,
223
+ yMaxExtent=0,
224
+ caretSlopeRise=0,
225
+ caretSlopeRun=0,
226
+ reserved0=0,
227
+ reserved1=0,
228
+ reserved2=0,
229
+ reserved3=0,
230
+ reserved4=0,
231
+ metricDataFormat=0,
232
+ numberOfVMetrics=0,
233
+ )
234
+
235
+ _nameIDs = dict(
236
+ copyright=0,
237
+ familyName=1,
238
+ styleName=2,
239
+ uniqueFontIdentifier=3,
240
+ fullName=4,
241
+ version=5,
242
+ psName=6,
243
+ trademark=7,
244
+ manufacturer=8,
245
+ designer=9,
246
+ description=10,
247
+ vendorURL=11,
248
+ designerURL=12,
249
+ licenseDescription=13,
250
+ licenseInfoURL=14,
251
+ # reserved = 15,
252
+ typographicFamily=16,
253
+ typographicSubfamily=17,
254
+ compatibleFullName=18,
255
+ sampleText=19,
256
+ postScriptCIDFindfontName=20,
257
+ wwsFamilyName=21,
258
+ wwsSubfamilyName=22,
259
+ lightBackgroundPalette=23,
260
+ darkBackgroundPalette=24,
261
+ variationsPostScriptNamePrefix=25,
262
+ )
263
+
264
+ # to insert in setupNameTable doc string:
265
+ # print("\n".join(("%s (nameID %s)" % (k, v)) for k, v in sorted(_nameIDs.items(), key=lambda x: x[1])))
266
+
267
+ _panoseDefaults = Panose()
268
+
269
+ _OS2Defaults = dict(
270
+ version=3,
271
+ xAvgCharWidth=0,
272
+ usWeightClass=400,
273
+ usWidthClass=5,
274
+ fsType=0x0004, # default: Preview & Print embedding
275
+ ySubscriptXSize=0,
276
+ ySubscriptYSize=0,
277
+ ySubscriptXOffset=0,
278
+ ySubscriptYOffset=0,
279
+ ySuperscriptXSize=0,
280
+ ySuperscriptYSize=0,
281
+ ySuperscriptXOffset=0,
282
+ ySuperscriptYOffset=0,
283
+ yStrikeoutSize=0,
284
+ yStrikeoutPosition=0,
285
+ sFamilyClass=0,
286
+ panose=_panoseDefaults,
287
+ ulUnicodeRange1=0,
288
+ ulUnicodeRange2=0,
289
+ ulUnicodeRange3=0,
290
+ ulUnicodeRange4=0,
291
+ achVendID="????",
292
+ fsSelection=0,
293
+ usFirstCharIndex=0,
294
+ usLastCharIndex=0,
295
+ sTypoAscender=0,
296
+ sTypoDescender=0,
297
+ sTypoLineGap=0,
298
+ usWinAscent=0,
299
+ usWinDescent=0,
300
+ ulCodePageRange1=0,
301
+ ulCodePageRange2=0,
302
+ sxHeight=0,
303
+ sCapHeight=0,
304
+ usDefaultChar=0, # .notdef
305
+ usBreakChar=32, # space
306
+ usMaxContext=0,
307
+ usLowerOpticalPointSize=0,
308
+ usUpperOpticalPointSize=0,
309
+ )
310
+
311
+
312
+ class FontBuilder(object):
313
+ def __init__(self, unitsPerEm=None, font=None, isTTF=True, glyphDataFormat=0):
314
+ """Initialize a FontBuilder instance.
315
+
316
+ If the `font` argument is not given, a new `TTFont` will be
317
+ constructed, and `unitsPerEm` must be given. If `isTTF` is True,
318
+ the font will be a glyf-based TTF; if `isTTF` is False it will be
319
+ a CFF-based OTF.
320
+
321
+ The `glyphDataFormat` argument corresponds to the `head` table field
322
+ that defines the format of the TrueType `glyf` table (default=0).
323
+ TrueType glyphs historically can only contain quadratic splines and static
324
+ components, but there's a proposal to add support for cubic Bezier curves as well
325
+ as variable composites/components at
326
+ https://github.com/harfbuzz/boring-expansion-spec/blob/main/glyf1.md
327
+ You can experiment with the new features by setting `glyphDataFormat` to 1.
328
+ A ValueError is raised if `glyphDataFormat` is left at 0 but glyphs are added
329
+ that contain cubic splines or varcomposites. This is to prevent accidentally
330
+ creating fonts that are incompatible with existing TrueType implementations.
331
+
332
+ If `font` is given, it must be a `TTFont` instance and `unitsPerEm`
333
+ must _not_ be given. The `isTTF` and `glyphDataFormat` arguments will be ignored.
334
+ """
335
+ if font is None:
336
+ self.font = TTFont(recalcTimestamp=False)
337
+ self.isTTF = isTTF
338
+ now = timestampNow()
339
+ assert unitsPerEm is not None
340
+ self.setupHead(
341
+ unitsPerEm=unitsPerEm,
342
+ created=now,
343
+ modified=now,
344
+ glyphDataFormat=glyphDataFormat,
345
+ )
346
+ self.setupMaxp()
347
+ else:
348
+ assert unitsPerEm is None
349
+ self.font = font
350
+ self.isTTF = "glyf" in font
351
+
352
+ def save(self, file):
353
+ """Save the font. The 'file' argument can be either a pathname or a
354
+ writable file object.
355
+ """
356
+ self.font.save(file)
357
+
358
+ def _initTableWithValues(self, tableTag, defaults, values):
359
+ table = self.font[tableTag] = newTable(tableTag)
360
+ for k, v in defaults.items():
361
+ setattr(table, k, v)
362
+ for k, v in values.items():
363
+ setattr(table, k, v)
364
+ return table
365
+
366
+ def _updateTableWithValues(self, tableTag, values):
367
+ table = self.font[tableTag]
368
+ for k, v in values.items():
369
+ setattr(table, k, v)
370
+
371
+ def setupHead(self, **values):
372
+ """Create a new `head` table and initialize it with default values,
373
+ which can be overridden by keyword arguments.
374
+ """
375
+ self._initTableWithValues("head", _headDefaults, values)
376
+
377
+ def updateHead(self, **values):
378
+ """Update the head table with the fields and values passed as
379
+ keyword arguments.
380
+ """
381
+ self._updateTableWithValues("head", values)
382
+
383
+ def setupGlyphOrder(self, glyphOrder):
384
+ """Set the glyph order for the font."""
385
+ self.font.setGlyphOrder(glyphOrder)
386
+
387
+ def setupCharacterMap(self, cmapping, uvs=None, allowFallback=False):
388
+ """Build the `cmap` table for the font. The `cmapping` argument should
389
+ be a dict mapping unicode code points as integers to glyph names.
390
+
391
+ The `uvs` argument, when passed, must be a list of tuples, describing
392
+ Unicode Variation Sequences. These tuples have three elements:
393
+ (unicodeValue, variationSelector, glyphName)
394
+ `unicodeValue` and `variationSelector` are integer code points.
395
+ `glyphName` may be None, to indicate this is the default variation.
396
+ Text processors will then use the cmap to find the glyph name.
397
+ Each Unicode Variation Sequence should be an officially supported
398
+ sequence, but this is not policed.
399
+ """
400
+ subTables = []
401
+ highestUnicode = max(cmapping) if cmapping else 0
402
+ if highestUnicode > 0xFFFF:
403
+ cmapping_3_1 = dict((k, v) for k, v in cmapping.items() if k < 0x10000)
404
+ subTable_3_10 = buildCmapSubTable(cmapping, 12, 3, 10)
405
+ subTables.append(subTable_3_10)
406
+ else:
407
+ cmapping_3_1 = cmapping
408
+ format = 4
409
+ subTable_3_1 = buildCmapSubTable(cmapping_3_1, format, 3, 1)
410
+ try:
411
+ subTable_3_1.compile(self.font)
412
+ except struct.error:
413
+ # format 4 overflowed, fall back to format 12
414
+ if not allowFallback:
415
+ raise ValueError(
416
+ "cmap format 4 subtable overflowed; sort glyph order by unicode to fix."
417
+ )
418
+ format = 12
419
+ subTable_3_1 = buildCmapSubTable(cmapping_3_1, format, 3, 1)
420
+ subTables.append(subTable_3_1)
421
+ subTable_0_3 = buildCmapSubTable(cmapping_3_1, format, 0, 3)
422
+ subTables.append(subTable_0_3)
423
+
424
+ if uvs is not None:
425
+ uvsDict = {}
426
+ for unicodeValue, variationSelector, glyphName in uvs:
427
+ if cmapping.get(unicodeValue) == glyphName:
428
+ # this is a default variation
429
+ glyphName = None
430
+ if variationSelector not in uvsDict:
431
+ uvsDict[variationSelector] = []
432
+ uvsDict[variationSelector].append((unicodeValue, glyphName))
433
+ uvsSubTable = buildCmapSubTable({}, 14, 0, 5)
434
+ uvsSubTable.uvsDict = uvsDict
435
+ subTables.append(uvsSubTable)
436
+
437
+ self.font["cmap"] = newTable("cmap")
438
+ self.font["cmap"].tableVersion = 0
439
+ self.font["cmap"].tables = subTables
440
+
441
+ def setupNameTable(self, nameStrings, windows=True, mac=True):
442
+ """Create the `name` table for the font. The `nameStrings` argument must
443
+ be a dict, mapping nameIDs or descriptive names for the nameIDs to name
444
+ record values. A value is either a string, or a dict, mapping language codes
445
+ to strings, to allow localized name table entries.
446
+
447
+ By default, both Windows (platformID=3) and Macintosh (platformID=1) name
448
+ records are added, unless any of `windows` or `mac` arguments is False.
449
+
450
+ The following descriptive names are available for nameIDs:
451
+
452
+ copyright (nameID 0)
453
+ familyName (nameID 1)
454
+ styleName (nameID 2)
455
+ uniqueFontIdentifier (nameID 3)
456
+ fullName (nameID 4)
457
+ version (nameID 5)
458
+ psName (nameID 6)
459
+ trademark (nameID 7)
460
+ manufacturer (nameID 8)
461
+ designer (nameID 9)
462
+ description (nameID 10)
463
+ vendorURL (nameID 11)
464
+ designerURL (nameID 12)
465
+ licenseDescription (nameID 13)
466
+ licenseInfoURL (nameID 14)
467
+ typographicFamily (nameID 16)
468
+ typographicSubfamily (nameID 17)
469
+ compatibleFullName (nameID 18)
470
+ sampleText (nameID 19)
471
+ postScriptCIDFindfontName (nameID 20)
472
+ wwsFamilyName (nameID 21)
473
+ wwsSubfamilyName (nameID 22)
474
+ lightBackgroundPalette (nameID 23)
475
+ darkBackgroundPalette (nameID 24)
476
+ variationsPostScriptNamePrefix (nameID 25)
477
+ """
478
+ nameTable = self.font["name"] = newTable("name")
479
+ nameTable.names = []
480
+
481
+ for nameName, nameValue in nameStrings.items():
482
+ if isinstance(nameName, int):
483
+ nameID = nameName
484
+ else:
485
+ nameID = _nameIDs[nameName]
486
+ if isinstance(nameValue, str):
487
+ nameValue = dict(en=nameValue)
488
+ nameTable.addMultilingualName(
489
+ nameValue, ttFont=self.font, nameID=nameID, windows=windows, mac=mac
490
+ )
491
+
492
+ def setupOS2(self, **values):
493
+ """Create a new `OS/2` table and initialize it with default values,
494
+ which can be overridden by keyword arguments.
495
+ """
496
+ self._initTableWithValues("OS/2", _OS2Defaults, values)
497
+ if "xAvgCharWidth" not in values:
498
+ assert (
499
+ "hmtx" in self.font
500
+ ), "the 'hmtx' table must be setup before the 'OS/2' table"
501
+ self.font["OS/2"].recalcAvgCharWidth(self.font)
502
+ if not (
503
+ "ulUnicodeRange1" in values
504
+ or "ulUnicodeRange2" in values
505
+ or "ulUnicodeRange3" in values
506
+ or "ulUnicodeRange3" in values
507
+ ):
508
+ assert (
509
+ "cmap" in self.font
510
+ ), "the 'cmap' table must be setup before the 'OS/2' table"
511
+ self.font["OS/2"].recalcUnicodeRanges(self.font)
512
+
513
+ def setupCFF(self, psName, fontInfo, charStringsDict, privateDict):
514
+ from .cffLib import (
515
+ CFFFontSet,
516
+ TopDictIndex,
517
+ TopDict,
518
+ CharStrings,
519
+ GlobalSubrsIndex,
520
+ PrivateDict,
521
+ )
522
+
523
+ assert not self.isTTF
524
+ self.font.sfntVersion = "OTTO"
525
+ fontSet = CFFFontSet()
526
+ fontSet.major = 1
527
+ fontSet.minor = 0
528
+ fontSet.otFont = self.font
529
+ fontSet.fontNames = [psName]
530
+ fontSet.topDictIndex = TopDictIndex()
531
+
532
+ globalSubrs = GlobalSubrsIndex()
533
+ fontSet.GlobalSubrs = globalSubrs
534
+ private = PrivateDict()
535
+ for key, value in privateDict.items():
536
+ setattr(private, key, value)
537
+ fdSelect = None
538
+ fdArray = None
539
+
540
+ topDict = TopDict()
541
+ topDict.charset = self.font.getGlyphOrder()
542
+ topDict.Private = private
543
+ topDict.GlobalSubrs = fontSet.GlobalSubrs
544
+ for key, value in fontInfo.items():
545
+ setattr(topDict, key, value)
546
+ if "FontMatrix" not in fontInfo:
547
+ scale = 1 / self.font["head"].unitsPerEm
548
+ topDict.FontMatrix = [scale, 0, 0, scale, 0, 0]
549
+
550
+ charStrings = CharStrings(
551
+ None, topDict.charset, globalSubrs, private, fdSelect, fdArray
552
+ )
553
+ for glyphName, charString in charStringsDict.items():
554
+ charString.private = private
555
+ charString.globalSubrs = globalSubrs
556
+ charStrings[glyphName] = charString
557
+ topDict.CharStrings = charStrings
558
+
559
+ fontSet.topDictIndex.append(topDict)
560
+
561
+ self.font["CFF "] = newTable("CFF ")
562
+ self.font["CFF "].cff = fontSet
563
+
564
+ def setupCFF2(self, charStringsDict, fdArrayList=None, regions=None):
565
+ from .cffLib import (
566
+ CFFFontSet,
567
+ TopDictIndex,
568
+ TopDict,
569
+ CharStrings,
570
+ GlobalSubrsIndex,
571
+ PrivateDict,
572
+ FDArrayIndex,
573
+ FontDict,
574
+ )
575
+
576
+ assert not self.isTTF
577
+ self.font.sfntVersion = "OTTO"
578
+ fontSet = CFFFontSet()
579
+ fontSet.major = 2
580
+ fontSet.minor = 0
581
+
582
+ cff2GetGlyphOrder = self.font.getGlyphOrder
583
+ fontSet.topDictIndex = TopDictIndex(None, cff2GetGlyphOrder, None)
584
+
585
+ globalSubrs = GlobalSubrsIndex()
586
+ fontSet.GlobalSubrs = globalSubrs
587
+
588
+ if fdArrayList is None:
589
+ fdArrayList = [{}]
590
+ fdSelect = None
591
+ fdArray = FDArrayIndex()
592
+ fdArray.strings = None
593
+ fdArray.GlobalSubrs = globalSubrs
594
+ for privateDict in fdArrayList:
595
+ fontDict = FontDict()
596
+ fontDict.setCFF2(True)
597
+ private = PrivateDict()
598
+ for key, value in privateDict.items():
599
+ setattr(private, key, value)
600
+ fontDict.Private = private
601
+ fdArray.append(fontDict)
602
+
603
+ topDict = TopDict()
604
+ topDict.cff2GetGlyphOrder = cff2GetGlyphOrder
605
+ topDict.FDArray = fdArray
606
+ scale = 1 / self.font["head"].unitsPerEm
607
+ topDict.FontMatrix = [scale, 0, 0, scale, 0, 0]
608
+
609
+ private = fdArray[0].Private
610
+ charStrings = CharStrings(None, None, globalSubrs, private, fdSelect, fdArray)
611
+ for glyphName, charString in charStringsDict.items():
612
+ charString.private = private
613
+ charString.globalSubrs = globalSubrs
614
+ charStrings[glyphName] = charString
615
+ topDict.CharStrings = charStrings
616
+
617
+ fontSet.topDictIndex.append(topDict)
618
+
619
+ self.font["CFF2"] = newTable("CFF2")
620
+ self.font["CFF2"].cff = fontSet
621
+
622
+ if regions:
623
+ self.setupCFF2Regions(regions)
624
+
625
+ def setupCFF2Regions(self, regions):
626
+ from .varLib.builder import buildVarRegionList, buildVarData, buildVarStore
627
+ from .cffLib import VarStoreData
628
+
629
+ assert "fvar" in self.font, "fvar must to be set up first"
630
+ assert "CFF2" in self.font, "CFF2 must to be set up first"
631
+ axisTags = [a.axisTag for a in self.font["fvar"].axes]
632
+ varRegionList = buildVarRegionList(regions, axisTags)
633
+ varData = buildVarData(list(range(len(regions))), None, optimize=False)
634
+ varStore = buildVarStore(varRegionList, [varData])
635
+ vstore = VarStoreData(otVarStore=varStore)
636
+ topDict = self.font["CFF2"].cff.topDictIndex[0]
637
+ topDict.VarStore = vstore
638
+ for fontDict in topDict.FDArray:
639
+ fontDict.Private.vstore = vstore
640
+
641
+ def setupGlyf(self, glyphs, calcGlyphBounds=True, validateGlyphFormat=True):
642
+ """Create the `glyf` table from a dict, that maps glyph names
643
+ to `fontTools.ttLib.tables._g_l_y_f.Glyph` objects, for example
644
+ as made by `fontTools.pens.ttGlyphPen.TTGlyphPen`.
645
+
646
+ If `calcGlyphBounds` is True, the bounds of all glyphs will be
647
+ calculated. Only pass False if your glyph objects already have
648
+ their bounding box values set.
649
+
650
+ If `validateGlyphFormat` is True, raise ValueError if any of the glyphs contains
651
+ cubic curves or is a variable composite but head.glyphDataFormat=0.
652
+ Set it to False to skip the check if you know in advance all the glyphs are
653
+ compatible with the specified glyphDataFormat.
654
+ """
655
+ assert self.isTTF
656
+
657
+ if validateGlyphFormat and self.font["head"].glyphDataFormat == 0:
658
+ for name, g in glyphs.items():
659
+ if g.numberOfContours > 0 and any(f & flagCubic for f in g.flags):
660
+ raise ValueError(
661
+ f"Glyph {name!r} has cubic Bezier outlines, but glyphDataFormat=0; "
662
+ "either convert to quadratics with cu2qu or set glyphDataFormat=1."
663
+ )
664
+
665
+ self.font["loca"] = newTable("loca")
666
+ self.font["glyf"] = newTable("glyf")
667
+ self.font["glyf"].glyphs = glyphs
668
+ if hasattr(self.font, "glyphOrder"):
669
+ self.font["glyf"].glyphOrder = self.font.glyphOrder
670
+ if calcGlyphBounds:
671
+ self.calcGlyphBounds()
672
+
673
+ def setupFvar(self, axes, instances):
674
+ """Adds an font variations table to the font.
675
+
676
+ Args:
677
+ axes (list): See below.
678
+ instances (list): See below.
679
+
680
+ ``axes`` should be a list of axes, with each axis either supplied as
681
+ a py:class:`.designspaceLib.AxisDescriptor` object, or a tuple in the
682
+ format ```tupletag, minValue, defaultValue, maxValue, name``.
683
+ The ``name`` is either a string, or a dict, mapping language codes
684
+ to strings, to allow localized name table entries.
685
+
686
+ ```instances`` should be a list of instances, with each instance either
687
+ supplied as a py:class:`.designspaceLib.InstanceDescriptor` object, or a
688
+ dict with keys ``location`` (mapping of axis tags to float values),
689
+ ``stylename`` and (optionally) ``postscriptfontname``.
690
+ The ``stylename`` is either a string, or a dict, mapping language codes
691
+ to strings, to allow localized name table entries.
692
+ """
693
+
694
+ addFvar(self.font, axes, instances)
695
+
696
+ def setupAvar(self, axes, mappings=None):
697
+ """Adds an axis variations table to the font.
698
+
699
+ Args:
700
+ axes (list): A list of py:class:`.designspaceLib.AxisDescriptor` objects.
701
+ """
702
+ from .varLib import _add_avar
703
+
704
+ if "fvar" not in self.font:
705
+ raise KeyError("'fvar' table is missing; can't add 'avar'.")
706
+
707
+ axisTags = [axis.axisTag for axis in self.font["fvar"].axes]
708
+ axes = OrderedDict(enumerate(axes)) # Only values are used
709
+ _add_avar(self.font, axes, mappings, axisTags)
710
+
711
+ def setupGvar(self, variations):
712
+ gvar = self.font["gvar"] = newTable("gvar")
713
+ gvar.version = 1
714
+ gvar.reserved = 0
715
+ gvar.variations = variations
716
+
717
+ def setupGVAR(self, variations):
718
+ gvar = self.font["GVAR"] = newTable("GVAR")
719
+ gvar.version = 1
720
+ gvar.reserved = 0
721
+ gvar.variations = variations
722
+
723
+ def calcGlyphBounds(self):
724
+ """Calculate the bounding boxes of all glyphs in the `glyf` table.
725
+ This is usually not called explicitly by client code.
726
+ """
727
+ glyphTable = self.font["glyf"]
728
+ for glyph in glyphTable.glyphs.values():
729
+ glyph.recalcBounds(glyphTable)
730
+
731
+ def setupHorizontalMetrics(self, metrics):
732
+ """Create a new `hmtx` table, for horizontal metrics.
733
+
734
+ The `metrics` argument must be a dict, mapping glyph names to
735
+ `(width, leftSidebearing)` tuples.
736
+ """
737
+ self.setupMetrics("hmtx", metrics)
738
+
739
+ def setupVerticalMetrics(self, metrics):
740
+ """Create a new `vmtx` table, for horizontal metrics.
741
+
742
+ The `metrics` argument must be a dict, mapping glyph names to
743
+ `(height, topSidebearing)` tuples.
744
+ """
745
+ self.setupMetrics("vmtx", metrics)
746
+
747
+ def setupMetrics(self, tableTag, metrics):
748
+ """See `setupHorizontalMetrics()` and `setupVerticalMetrics()`."""
749
+ assert tableTag in ("hmtx", "vmtx")
750
+ mtxTable = self.font[tableTag] = newTable(tableTag)
751
+ roundedMetrics = {}
752
+ for gn in metrics:
753
+ w, lsb = metrics[gn]
754
+ roundedMetrics[gn] = int(round(w)), int(round(lsb))
755
+ mtxTable.metrics = roundedMetrics
756
+
757
+ def setupHorizontalHeader(self, **values):
758
+ """Create a new `hhea` table initialize it with default values,
759
+ which can be overridden by keyword arguments.
760
+ """
761
+ self._initTableWithValues("hhea", _hheaDefaults, values)
762
+
763
+ def setupVerticalHeader(self, **values):
764
+ """Create a new `vhea` table initialize it with default values,
765
+ which can be overridden by keyword arguments.
766
+ """
767
+ self._initTableWithValues("vhea", _vheaDefaults, values)
768
+
769
+ def setupVerticalOrigins(self, verticalOrigins, defaultVerticalOrigin=None):
770
+ """Create a new `VORG` table. The `verticalOrigins` argument must be
771
+ a dict, mapping glyph names to vertical origin values.
772
+
773
+ The `defaultVerticalOrigin` argument should be the most common vertical
774
+ origin value. If omitted, this value will be derived from the actual
775
+ values in the `verticalOrigins` argument.
776
+ """
777
+ if defaultVerticalOrigin is None:
778
+ # find the most frequent vorg value
779
+ bag = {}
780
+ for gn in verticalOrigins:
781
+ vorg = verticalOrigins[gn]
782
+ if vorg not in bag:
783
+ bag[vorg] = 1
784
+ else:
785
+ bag[vorg] += 1
786
+ defaultVerticalOrigin = sorted(
787
+ bag, key=lambda vorg: bag[vorg], reverse=True
788
+ )[0]
789
+ self._initTableWithValues(
790
+ "VORG",
791
+ {},
792
+ dict(VOriginRecords={}, defaultVertOriginY=defaultVerticalOrigin),
793
+ )
794
+ vorgTable = self.font["VORG"]
795
+ vorgTable.majorVersion = 1
796
+ vorgTable.minorVersion = 0
797
+ for gn in verticalOrigins:
798
+ vorgTable[gn] = verticalOrigins[gn]
799
+
800
+ def setupPost(self, keepGlyphNames=True, **values):
801
+ """Create a new `post` table and initialize it with default values,
802
+ which can be overridden by keyword arguments.
803
+ """
804
+ isCFF2 = "CFF2" in self.font
805
+ postTable = self._initTableWithValues("post", _postDefaults, values)
806
+ if (self.isTTF or isCFF2) and keepGlyphNames:
807
+ postTable.formatType = 2.0
808
+ postTable.extraNames = []
809
+ postTable.mapping = {}
810
+ else:
811
+ postTable.formatType = 3.0
812
+
813
+ def setupMaxp(self):
814
+ """Create a new `maxp` table. This is called implicitly by FontBuilder
815
+ itself and is usually not called by client code.
816
+ """
817
+ if self.isTTF:
818
+ defaults = _maxpDefaultsTTF
819
+ else:
820
+ defaults = _maxpDefaultsOTF
821
+ self._initTableWithValues("maxp", defaults, {})
822
+
823
+ def setupDummyDSIG(self):
824
+ """This adds an empty DSIG table to the font to make some MS applications
825
+ happy. This does not properly sign the font.
826
+ """
827
+ values = dict(
828
+ ulVersion=1,
829
+ usFlag=0,
830
+ usNumSigs=0,
831
+ signatureRecords=[],
832
+ )
833
+ self._initTableWithValues("DSIG", {}, values)
834
+
835
+ def addOpenTypeFeatures(self, features, filename=None, tables=None, debug=False):
836
+ """Add OpenType features to the font from a string containing
837
+ Feature File syntax.
838
+
839
+ The `filename` argument is used in error messages and to determine
840
+ where to look for "include" files.
841
+
842
+ The optional `tables` argument can be a list of OTL tables tags to
843
+ build, allowing the caller to only build selected OTL tables. See
844
+ `fontTools.feaLib` for details.
845
+
846
+ The optional `debug` argument controls whether to add source debugging
847
+ information to the font in the `Debg` table.
848
+ """
849
+ from .feaLib.builder import addOpenTypeFeaturesFromString
850
+
851
+ addOpenTypeFeaturesFromString(
852
+ self.font, features, filename=filename, tables=tables, debug=debug
853
+ )
854
+
855
+ def addFeatureVariations(self, conditionalSubstitutions, featureTag="rvrn"):
856
+ """Add conditional substitutions to a Variable Font.
857
+
858
+ See `fontTools.varLib.featureVars.addFeatureVariations`.
859
+ """
860
+ from .varLib import featureVars
861
+
862
+ if "fvar" not in self.font:
863
+ raise KeyError("'fvar' table is missing; can't add FeatureVariations.")
864
+
865
+ featureVars.addFeatureVariations(
866
+ self.font, conditionalSubstitutions, featureTag=featureTag
867
+ )
868
+
869
+ def setupCOLR(
870
+ self,
871
+ colorLayers,
872
+ version=None,
873
+ varStore=None,
874
+ varIndexMap=None,
875
+ clipBoxes=None,
876
+ allowLayerReuse=True,
877
+ ):
878
+ """Build new COLR table using color layers dictionary.
879
+
880
+ Cf. `fontTools.colorLib.builder.buildCOLR`.
881
+ """
882
+ from fontTools.colorLib.builder import buildCOLR
883
+
884
+ glyphMap = self.font.getReverseGlyphMap()
885
+ self.font["COLR"] = buildCOLR(
886
+ colorLayers,
887
+ version=version,
888
+ glyphMap=glyphMap,
889
+ varStore=varStore,
890
+ varIndexMap=varIndexMap,
891
+ clipBoxes=clipBoxes,
892
+ allowLayerReuse=allowLayerReuse,
893
+ )
894
+
895
+ def setupCPAL(
896
+ self,
897
+ palettes,
898
+ paletteTypes=None,
899
+ paletteLabels=None,
900
+ paletteEntryLabels=None,
901
+ ):
902
+ """Build new CPAL table using list of palettes.
903
+
904
+ Optionally build CPAL v1 table using paletteTypes, paletteLabels and
905
+ paletteEntryLabels.
906
+
907
+ Cf. `fontTools.colorLib.builder.buildCPAL`.
908
+ """
909
+ from fontTools.colorLib.builder import buildCPAL
910
+
911
+ self.font["CPAL"] = buildCPAL(
912
+ palettes,
913
+ paletteTypes=paletteTypes,
914
+ paletteLabels=paletteLabels,
915
+ paletteEntryLabels=paletteEntryLabels,
916
+ nameTable=self.font.get("name"),
917
+ )
918
+
919
+ def setupStat(self, axes, locations=None, elidedFallbackName=2):
920
+ """Build a new 'STAT' table.
921
+
922
+ See `fontTools.otlLib.builder.buildStatTable` for details about
923
+ the arguments.
924
+ """
925
+ from .otlLib.builder import buildStatTable
926
+
927
+ assert "name" in self.font, "name must to be set up first"
928
+
929
+ buildStatTable(
930
+ self.font,
931
+ axes,
932
+ locations,
933
+ elidedFallbackName,
934
+ macNames=any(nr.platformID == 1 for nr in self.font["name"].names),
935
+ )
936
+
937
+
938
+ def buildCmapSubTable(cmapping, format, platformID, platEncID):
939
+ subTable = cmap_classes[format](format)
940
+ subTable.cmap = cmapping
941
+ subTable.platformID = platformID
942
+ subTable.platEncID = platEncID
943
+ subTable.language = 0
944
+ return subTable
945
+
946
+
947
+ def addFvar(font, axes, instances):
948
+ from .ttLib.tables._f_v_a_r import Axis, NamedInstance
949
+
950
+ assert axes
951
+
952
+ fvar = newTable("fvar")
953
+ nameTable = font["name"]
954
+
955
+ # if there are not currently any mac names don't add them here, that's inconsistent
956
+ # https://github.com/fonttools/fonttools/issues/683
957
+ macNames = any(nr.platformID == 1 for nr in getattr(nameTable, "names", ()))
958
+
959
+ # we have all the best ways to express mac names
960
+ platforms = ((3, 1, 0x409),)
961
+ if macNames:
962
+ platforms = ((1, 0, 0),) + platforms
963
+
964
+ for axis_def in axes:
965
+ axis = Axis()
966
+
967
+ if isinstance(axis_def, tuple):
968
+ (
969
+ axis.axisTag,
970
+ axis.minValue,
971
+ axis.defaultValue,
972
+ axis.maxValue,
973
+ name,
974
+ ) = axis_def
975
+ else:
976
+ (axis.axisTag, axis.minValue, axis.defaultValue, axis.maxValue, name) = (
977
+ axis_def.tag,
978
+ axis_def.minimum,
979
+ axis_def.default,
980
+ axis_def.maximum,
981
+ axis_def.name,
982
+ )
983
+ if axis_def.hidden:
984
+ axis.flags = 0x0001 # HIDDEN_AXIS
985
+
986
+ if isinstance(name, str):
987
+ name = dict(en=name)
988
+
989
+ axis.axisNameID = nameTable.addMultilingualName(name, ttFont=font, mac=macNames)
990
+ fvar.axes.append(axis)
991
+
992
+ for instance in instances:
993
+ if isinstance(instance, dict):
994
+ coordinates = instance["location"]
995
+ name = instance["stylename"]
996
+ psname = instance.get("postscriptfontname")
997
+ else:
998
+ coordinates = instance.location
999
+ name = instance.localisedStyleName or instance.styleName
1000
+ psname = instance.postScriptFontName
1001
+
1002
+ if isinstance(name, str):
1003
+ name = dict(en=name)
1004
+
1005
+ inst = NamedInstance()
1006
+ inst.subfamilyNameID = nameTable.addMultilingualName(
1007
+ name, ttFont=font, mac=macNames
1008
+ )
1009
+ if psname is not None:
1010
+ inst.postscriptNameID = nameTable.addName(psname, platforms=platforms)
1011
+ inst.coordinates = coordinates
1012
+ fvar.instances.append(inst)
1013
+
1014
+ font["fvar"] = fvar