fontBuilder.py 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993
  1. __all__ = ["FontBuilder"]
  2. """
  3. This module is *experimental*, meaning it still may evolve and change.
  4. The `FontBuilder` class is a convenient helper to construct working TTF or
  5. OTF fonts from scratch.
  6. Note that the various setup methods cannot be called in arbitrary order,
  7. due to various interdependencies between OpenType tables. Here is an order
  8. that works:
  9. fb = FontBuilder(...)
  10. fb.setupGlyphOrder(...)
  11. fb.setupCharacterMap(...)
  12. fb.setupGlyf(...) --or-- fb.setupCFF(...)
  13. fb.setupHorizontalMetrics(...)
  14. fb.setupHorizontalHeader()
  15. fb.setupNameTable(...)
  16. fb.setupOS2()
  17. fb.addOpenTypeFeatures(...)
  18. fb.setupPost()
  19. fb.save(...)
  20. Here is how to build a minimal TTF:
  21. ```python
  22. from fontTools.fontBuilder import FontBuilder
  23. from fontTools.pens.ttGlyphPen import TTGlyphPen
  24. def drawTestGlyph(pen):
  25. pen.moveTo((100, 100))
  26. pen.lineTo((100, 1000))
  27. pen.qCurveTo((200, 900), (400, 900), (500, 1000))
  28. pen.lineTo((500, 100))
  29. pen.closePath()
  30. fb = FontBuilder(1024, isTTF=True)
  31. fb.setupGlyphOrder([".notdef", ".null", "space", "A", "a"])
  32. fb.setupCharacterMap({32: "space", 65: "A", 97: "a"})
  33. advanceWidths = {".notdef": 600, "space": 500, "A": 600, "a": 600, ".null": 0}
  34. familyName = "HelloTestFont"
  35. styleName = "TotallyNormal"
  36. version = "0.1"
  37. nameStrings = dict(
  38. familyName=dict(en=familyName, nl="HalloTestFont"),
  39. styleName=dict(en=styleName, nl="TotaalNormaal"),
  40. uniqueFontIdentifier="fontBuilder: " + familyName + "." + styleName,
  41. fullName=familyName + "-" + styleName,
  42. psName=familyName + "-" + styleName,
  43. version="Version " + version,
  44. )
  45. pen = TTGlyphPen(None)
  46. drawTestGlyph(pen)
  47. glyph = pen.glyph()
  48. glyphs = {".notdef": glyph, "space": glyph, "A": glyph, "a": glyph, ".null": glyph}
  49. fb.setupGlyf(glyphs)
  50. metrics = {}
  51. glyphTable = fb.font["glyf"]
  52. for gn, advanceWidth in advanceWidths.items():
  53. metrics[gn] = (advanceWidth, glyphTable[gn].xMin)
  54. fb.setupHorizontalMetrics(metrics)
  55. fb.setupHorizontalHeader(ascent=824, descent=-200)
  56. fb.setupNameTable(nameStrings)
  57. fb.setupOS2(sTypoAscender=824, usWinAscent=824, usWinDescent=200)
  58. fb.setupPost()
  59. fb.save("test.ttf")
  60. ```
  61. And here's how to build a minimal OTF:
  62. ```python
  63. from fontTools.fontBuilder import FontBuilder
  64. from fontTools.pens.t2CharStringPen import T2CharStringPen
  65. def drawTestGlyph(pen):
  66. pen.moveTo((100, 100))
  67. pen.lineTo((100, 1000))
  68. pen.curveTo((200, 900), (400, 900), (500, 1000))
  69. pen.lineTo((500, 100))
  70. pen.closePath()
  71. fb = FontBuilder(1024, isTTF=False)
  72. fb.setupGlyphOrder([".notdef", ".null", "space", "A", "a"])
  73. fb.setupCharacterMap({32: "space", 65: "A", 97: "a"})
  74. advanceWidths = {".notdef": 600, "space": 500, "A": 600, "a": 600, ".null": 0}
  75. familyName = "HelloTestFont"
  76. styleName = "TotallyNormal"
  77. version = "0.1"
  78. nameStrings = dict(
  79. familyName=dict(en=familyName, nl="HalloTestFont"),
  80. styleName=dict(en=styleName, nl="TotaalNormaal"),
  81. uniqueFontIdentifier="fontBuilder: " + familyName + "." + styleName,
  82. fullName=familyName + "-" + styleName,
  83. psName=familyName + "-" + styleName,
  84. version="Version " + version,
  85. )
  86. pen = T2CharStringPen(600, None)
  87. drawTestGlyph(pen)
  88. charString = pen.getCharString()
  89. charStrings = {
  90. ".notdef": charString,
  91. "space": charString,
  92. "A": charString,
  93. "a": charString,
  94. ".null": charString,
  95. }
  96. fb.setupCFF(nameStrings["psName"], {"FullName": nameStrings["psName"]}, charStrings, {})
  97. lsb = {gn: cs.calcBounds(None)[0] for gn, cs in charStrings.items()}
  98. metrics = {}
  99. for gn, advanceWidth in advanceWidths.items():
  100. metrics[gn] = (advanceWidth, lsb[gn])
  101. fb.setupHorizontalMetrics(metrics)
  102. fb.setupHorizontalHeader(ascent=824, descent=200)
  103. fb.setupNameTable(nameStrings)
  104. fb.setupOS2(sTypoAscender=824, usWinAscent=824, usWinDescent=200)
  105. fb.setupPost()
  106. fb.save("test.otf")
  107. ```
  108. """
  109. from .ttLib import TTFont, newTable
  110. from .ttLib.tables._c_m_a_p import cmap_classes
  111. from .ttLib.tables._g_l_y_f import flagCubic
  112. from .ttLib.tables.O_S_2f_2 import Panose
  113. from .misc.timeTools import timestampNow
  114. import struct
  115. from collections import OrderedDict
  116. _headDefaults = dict(
  117. tableVersion=1.0,
  118. fontRevision=1.0,
  119. checkSumAdjustment=0,
  120. magicNumber=0x5F0F3CF5,
  121. flags=0x0003,
  122. unitsPerEm=1000,
  123. created=0,
  124. modified=0,
  125. xMin=0,
  126. yMin=0,
  127. xMax=0,
  128. yMax=0,
  129. macStyle=0,
  130. lowestRecPPEM=3,
  131. fontDirectionHint=2,
  132. indexToLocFormat=0,
  133. glyphDataFormat=0,
  134. )
  135. _maxpDefaultsTTF = dict(
  136. tableVersion=0x00010000,
  137. numGlyphs=0,
  138. maxPoints=0,
  139. maxContours=0,
  140. maxCompositePoints=0,
  141. maxCompositeContours=0,
  142. maxZones=2,
  143. maxTwilightPoints=0,
  144. maxStorage=0,
  145. maxFunctionDefs=0,
  146. maxInstructionDefs=0,
  147. maxStackElements=0,
  148. maxSizeOfInstructions=0,
  149. maxComponentElements=0,
  150. maxComponentDepth=0,
  151. )
  152. _maxpDefaultsOTF = dict(
  153. tableVersion=0x00005000,
  154. numGlyphs=0,
  155. )
  156. _postDefaults = dict(
  157. formatType=3.0,
  158. italicAngle=0,
  159. underlinePosition=0,
  160. underlineThickness=0,
  161. isFixedPitch=0,
  162. minMemType42=0,
  163. maxMemType42=0,
  164. minMemType1=0,
  165. maxMemType1=0,
  166. )
  167. _hheaDefaults = dict(
  168. tableVersion=0x00010000,
  169. ascent=0,
  170. descent=0,
  171. lineGap=0,
  172. advanceWidthMax=0,
  173. minLeftSideBearing=0,
  174. minRightSideBearing=0,
  175. xMaxExtent=0,
  176. caretSlopeRise=1,
  177. caretSlopeRun=0,
  178. caretOffset=0,
  179. reserved0=0,
  180. reserved1=0,
  181. reserved2=0,
  182. reserved3=0,
  183. metricDataFormat=0,
  184. numberOfHMetrics=0,
  185. )
  186. _vheaDefaults = dict(
  187. tableVersion=0x00010000,
  188. ascent=0,
  189. descent=0,
  190. lineGap=0,
  191. advanceHeightMax=0,
  192. minTopSideBearing=0,
  193. minBottomSideBearing=0,
  194. yMaxExtent=0,
  195. caretSlopeRise=0,
  196. caretSlopeRun=0,
  197. reserved0=0,
  198. reserved1=0,
  199. reserved2=0,
  200. reserved3=0,
  201. reserved4=0,
  202. metricDataFormat=0,
  203. numberOfVMetrics=0,
  204. )
  205. _nameIDs = dict(
  206. copyright=0,
  207. familyName=1,
  208. styleName=2,
  209. uniqueFontIdentifier=3,
  210. fullName=4,
  211. version=5,
  212. psName=6,
  213. trademark=7,
  214. manufacturer=8,
  215. designer=9,
  216. description=10,
  217. vendorURL=11,
  218. designerURL=12,
  219. licenseDescription=13,
  220. licenseInfoURL=14,
  221. # reserved = 15,
  222. typographicFamily=16,
  223. typographicSubfamily=17,
  224. compatibleFullName=18,
  225. sampleText=19,
  226. postScriptCIDFindfontName=20,
  227. wwsFamilyName=21,
  228. wwsSubfamilyName=22,
  229. lightBackgroundPalette=23,
  230. darkBackgroundPalette=24,
  231. variationsPostScriptNamePrefix=25,
  232. )
  233. # to insert in setupNameTable doc string:
  234. # print("\n".join(("%s (nameID %s)" % (k, v)) for k, v in sorted(_nameIDs.items(), key=lambda x: x[1])))
  235. _panoseDefaults = Panose()
  236. _OS2Defaults = dict(
  237. version=3,
  238. xAvgCharWidth=0,
  239. usWeightClass=400,
  240. usWidthClass=5,
  241. fsType=0x0004, # default: Preview & Print embedding
  242. ySubscriptXSize=0,
  243. ySubscriptYSize=0,
  244. ySubscriptXOffset=0,
  245. ySubscriptYOffset=0,
  246. ySuperscriptXSize=0,
  247. ySuperscriptYSize=0,
  248. ySuperscriptXOffset=0,
  249. ySuperscriptYOffset=0,
  250. yStrikeoutSize=0,
  251. yStrikeoutPosition=0,
  252. sFamilyClass=0,
  253. panose=_panoseDefaults,
  254. ulUnicodeRange1=0,
  255. ulUnicodeRange2=0,
  256. ulUnicodeRange3=0,
  257. ulUnicodeRange4=0,
  258. achVendID="????",
  259. fsSelection=0,
  260. usFirstCharIndex=0,
  261. usLastCharIndex=0,
  262. sTypoAscender=0,
  263. sTypoDescender=0,
  264. sTypoLineGap=0,
  265. usWinAscent=0,
  266. usWinDescent=0,
  267. ulCodePageRange1=0,
  268. ulCodePageRange2=0,
  269. sxHeight=0,
  270. sCapHeight=0,
  271. usDefaultChar=0, # .notdef
  272. usBreakChar=32, # space
  273. usMaxContext=0,
  274. usLowerOpticalPointSize=0,
  275. usUpperOpticalPointSize=0,
  276. )
  277. class FontBuilder(object):
  278. def __init__(self, unitsPerEm=None, font=None, isTTF=True, glyphDataFormat=0):
  279. """Initialize a FontBuilder instance.
  280. If the `font` argument is not given, a new `TTFont` will be
  281. constructed, and `unitsPerEm` must be given. If `isTTF` is True,
  282. the font will be a glyf-based TTF; if `isTTF` is False it will be
  283. a CFF-based OTF.
  284. The `glyphDataFormat` argument corresponds to the `head` table field
  285. that defines the format of the TrueType `glyf` table (default=0).
  286. TrueType glyphs historically can only contain quadratic splines and static
  287. components, but there's a proposal to add support for cubic Bezier curves as well
  288. as variable composites/components at
  289. https://github.com/harfbuzz/boring-expansion-spec/blob/main/glyf1.md
  290. You can experiment with the new features by setting `glyphDataFormat` to 1.
  291. A ValueError is raised if `glyphDataFormat` is left at 0 but glyphs are added
  292. that contain cubic splines or varcomposites. This is to prevent accidentally
  293. creating fonts that are incompatible with existing TrueType implementations.
  294. If `font` is given, it must be a `TTFont` instance and `unitsPerEm`
  295. must _not_ be given. The `isTTF` and `glyphDataFormat` arguments will be ignored.
  296. """
  297. if font is None:
  298. self.font = TTFont(recalcTimestamp=False)
  299. self.isTTF = isTTF
  300. now = timestampNow()
  301. assert unitsPerEm is not None
  302. self.setupHead(
  303. unitsPerEm=unitsPerEm,
  304. created=now,
  305. modified=now,
  306. glyphDataFormat=glyphDataFormat,
  307. )
  308. self.setupMaxp()
  309. else:
  310. assert unitsPerEm is None
  311. self.font = font
  312. self.isTTF = "glyf" in font
  313. def save(self, file):
  314. """Save the font. The 'file' argument can be either a pathname or a
  315. writable file object.
  316. """
  317. self.font.save(file)
  318. def _initTableWithValues(self, tableTag, defaults, values):
  319. table = self.font[tableTag] = newTable(tableTag)
  320. for k, v in defaults.items():
  321. setattr(table, k, v)
  322. for k, v in values.items():
  323. setattr(table, k, v)
  324. return table
  325. def _updateTableWithValues(self, tableTag, values):
  326. table = self.font[tableTag]
  327. for k, v in values.items():
  328. setattr(table, k, v)
  329. def setupHead(self, **values):
  330. """Create a new `head` table and initialize it with default values,
  331. which can be overridden by keyword arguments.
  332. """
  333. self._initTableWithValues("head", _headDefaults, values)
  334. def updateHead(self, **values):
  335. """Update the head table with the fields and values passed as
  336. keyword arguments.
  337. """
  338. self._updateTableWithValues("head", values)
  339. def setupGlyphOrder(self, glyphOrder):
  340. """Set the glyph order for the font."""
  341. self.font.setGlyphOrder(glyphOrder)
  342. def setupCharacterMap(self, cmapping, uvs=None, allowFallback=False):
  343. """Build the `cmap` table for the font. The `cmapping` argument should
  344. be a dict mapping unicode code points as integers to glyph names.
  345. The `uvs` argument, when passed, must be a list of tuples, describing
  346. Unicode Variation Sequences. These tuples have three elements:
  347. (unicodeValue, variationSelector, glyphName)
  348. `unicodeValue` and `variationSelector` are integer code points.
  349. `glyphName` may be None, to indicate this is the default variation.
  350. Text processors will then use the cmap to find the glyph name.
  351. Each Unicode Variation Sequence should be an officially supported
  352. sequence, but this is not policed.
  353. """
  354. subTables = []
  355. highestUnicode = max(cmapping) if cmapping else 0
  356. if highestUnicode > 0xFFFF:
  357. cmapping_3_1 = dict((k, v) for k, v in cmapping.items() if k < 0x10000)
  358. subTable_3_10 = buildCmapSubTable(cmapping, 12, 3, 10)
  359. subTables.append(subTable_3_10)
  360. else:
  361. cmapping_3_1 = cmapping
  362. format = 4
  363. subTable_3_1 = buildCmapSubTable(cmapping_3_1, format, 3, 1)
  364. try:
  365. subTable_3_1.compile(self.font)
  366. except struct.error:
  367. # format 4 overflowed, fall back to format 12
  368. if not allowFallback:
  369. raise ValueError(
  370. "cmap format 4 subtable overflowed; sort glyph order by unicode to fix."
  371. )
  372. format = 12
  373. subTable_3_1 = buildCmapSubTable(cmapping_3_1, format, 3, 1)
  374. subTables.append(subTable_3_1)
  375. subTable_0_3 = buildCmapSubTable(cmapping_3_1, format, 0, 3)
  376. subTables.append(subTable_0_3)
  377. if uvs is not None:
  378. uvsDict = {}
  379. for unicodeValue, variationSelector, glyphName in uvs:
  380. if cmapping.get(unicodeValue) == glyphName:
  381. # this is a default variation
  382. glyphName = None
  383. if variationSelector not in uvsDict:
  384. uvsDict[variationSelector] = []
  385. uvsDict[variationSelector].append((unicodeValue, glyphName))
  386. uvsSubTable = buildCmapSubTable({}, 14, 0, 5)
  387. uvsSubTable.uvsDict = uvsDict
  388. subTables.append(uvsSubTable)
  389. self.font["cmap"] = newTable("cmap")
  390. self.font["cmap"].tableVersion = 0
  391. self.font["cmap"].tables = subTables
  392. def setupNameTable(self, nameStrings, windows=True, mac=True):
  393. """Create the `name` table for the font. The `nameStrings` argument must
  394. be a dict, mapping nameIDs or descriptive names for the nameIDs to name
  395. record values. A value is either a string, or a dict, mapping language codes
  396. to strings, to allow localized name table entries.
  397. By default, both Windows (platformID=3) and Macintosh (platformID=1) name
  398. records are added, unless any of `windows` or `mac` arguments is False.
  399. The following descriptive names are available for nameIDs:
  400. copyright (nameID 0)
  401. familyName (nameID 1)
  402. styleName (nameID 2)
  403. uniqueFontIdentifier (nameID 3)
  404. fullName (nameID 4)
  405. version (nameID 5)
  406. psName (nameID 6)
  407. trademark (nameID 7)
  408. manufacturer (nameID 8)
  409. designer (nameID 9)
  410. description (nameID 10)
  411. vendorURL (nameID 11)
  412. designerURL (nameID 12)
  413. licenseDescription (nameID 13)
  414. licenseInfoURL (nameID 14)
  415. typographicFamily (nameID 16)
  416. typographicSubfamily (nameID 17)
  417. compatibleFullName (nameID 18)
  418. sampleText (nameID 19)
  419. postScriptCIDFindfontName (nameID 20)
  420. wwsFamilyName (nameID 21)
  421. wwsSubfamilyName (nameID 22)
  422. lightBackgroundPalette (nameID 23)
  423. darkBackgroundPalette (nameID 24)
  424. variationsPostScriptNamePrefix (nameID 25)
  425. """
  426. nameTable = self.font["name"] = newTable("name")
  427. nameTable.names = []
  428. for nameName, nameValue in nameStrings.items():
  429. if isinstance(nameName, int):
  430. nameID = nameName
  431. else:
  432. nameID = _nameIDs[nameName]
  433. if isinstance(nameValue, str):
  434. nameValue = dict(en=nameValue)
  435. nameTable.addMultilingualName(
  436. nameValue, ttFont=self.font, nameID=nameID, windows=windows, mac=mac
  437. )
  438. def setupOS2(self, **values):
  439. """Create a new `OS/2` table and initialize it with default values,
  440. which can be overridden by keyword arguments.
  441. """
  442. self._initTableWithValues("OS/2", _OS2Defaults, values)
  443. if "xAvgCharWidth" not in values:
  444. assert (
  445. "hmtx" in self.font
  446. ), "the 'hmtx' table must be setup before the 'OS/2' table"
  447. self.font["OS/2"].recalcAvgCharWidth(self.font)
  448. if not (
  449. "ulUnicodeRange1" in values
  450. or "ulUnicodeRange2" in values
  451. or "ulUnicodeRange3" in values
  452. or "ulUnicodeRange3" in values
  453. ):
  454. assert (
  455. "cmap" in self.font
  456. ), "the 'cmap' table must be setup before the 'OS/2' table"
  457. self.font["OS/2"].recalcUnicodeRanges(self.font)
  458. def setupCFF(self, psName, fontInfo, charStringsDict, privateDict):
  459. from .cffLib import (
  460. CFFFontSet,
  461. TopDictIndex,
  462. TopDict,
  463. CharStrings,
  464. GlobalSubrsIndex,
  465. PrivateDict,
  466. )
  467. assert not self.isTTF
  468. self.font.sfntVersion = "OTTO"
  469. fontSet = CFFFontSet()
  470. fontSet.major = 1
  471. fontSet.minor = 0
  472. fontSet.otFont = self.font
  473. fontSet.fontNames = [psName]
  474. fontSet.topDictIndex = TopDictIndex()
  475. globalSubrs = GlobalSubrsIndex()
  476. fontSet.GlobalSubrs = globalSubrs
  477. private = PrivateDict()
  478. for key, value in privateDict.items():
  479. setattr(private, key, value)
  480. fdSelect = None
  481. fdArray = None
  482. topDict = TopDict()
  483. topDict.charset = self.font.getGlyphOrder()
  484. topDict.Private = private
  485. topDict.GlobalSubrs = fontSet.GlobalSubrs
  486. for key, value in fontInfo.items():
  487. setattr(topDict, key, value)
  488. if "FontMatrix" not in fontInfo:
  489. scale = 1 / self.font["head"].unitsPerEm
  490. topDict.FontMatrix = [scale, 0, 0, scale, 0, 0]
  491. charStrings = CharStrings(
  492. None, topDict.charset, globalSubrs, private, fdSelect, fdArray
  493. )
  494. for glyphName, charString in charStringsDict.items():
  495. charString.private = private
  496. charString.globalSubrs = globalSubrs
  497. charStrings[glyphName] = charString
  498. topDict.CharStrings = charStrings
  499. fontSet.topDictIndex.append(topDict)
  500. self.font["CFF "] = newTable("CFF ")
  501. self.font["CFF "].cff = fontSet
  502. def setupCFF2(self, charStringsDict, fdArrayList=None, regions=None):
  503. from .cffLib import (
  504. CFFFontSet,
  505. TopDictIndex,
  506. TopDict,
  507. CharStrings,
  508. GlobalSubrsIndex,
  509. PrivateDict,
  510. FDArrayIndex,
  511. FontDict,
  512. )
  513. assert not self.isTTF
  514. self.font.sfntVersion = "OTTO"
  515. fontSet = CFFFontSet()
  516. fontSet.major = 2
  517. fontSet.minor = 0
  518. cff2GetGlyphOrder = self.font.getGlyphOrder
  519. fontSet.topDictIndex = TopDictIndex(None, cff2GetGlyphOrder, None)
  520. globalSubrs = GlobalSubrsIndex()
  521. fontSet.GlobalSubrs = globalSubrs
  522. if fdArrayList is None:
  523. fdArrayList = [{}]
  524. fdSelect = None
  525. fdArray = FDArrayIndex()
  526. fdArray.strings = None
  527. fdArray.GlobalSubrs = globalSubrs
  528. for privateDict in fdArrayList:
  529. fontDict = FontDict()
  530. fontDict.setCFF2(True)
  531. private = PrivateDict()
  532. for key, value in privateDict.items():
  533. setattr(private, key, value)
  534. fontDict.Private = private
  535. fdArray.append(fontDict)
  536. topDict = TopDict()
  537. topDict.cff2GetGlyphOrder = cff2GetGlyphOrder
  538. topDict.FDArray = fdArray
  539. scale = 1 / self.font["head"].unitsPerEm
  540. topDict.FontMatrix = [scale, 0, 0, scale, 0, 0]
  541. private = fdArray[0].Private
  542. charStrings = CharStrings(None, None, globalSubrs, private, fdSelect, fdArray)
  543. for glyphName, charString in charStringsDict.items():
  544. charString.private = private
  545. charString.globalSubrs = globalSubrs
  546. charStrings[glyphName] = charString
  547. topDict.CharStrings = charStrings
  548. fontSet.topDictIndex.append(topDict)
  549. self.font["CFF2"] = newTable("CFF2")
  550. self.font["CFF2"].cff = fontSet
  551. if regions:
  552. self.setupCFF2Regions(regions)
  553. def setupCFF2Regions(self, regions):
  554. from .varLib.builder import buildVarRegionList, buildVarData, buildVarStore
  555. from .cffLib import VarStoreData
  556. assert "fvar" in self.font, "fvar must to be set up first"
  557. assert "CFF2" in self.font, "CFF2 must to be set up first"
  558. axisTags = [a.axisTag for a in self.font["fvar"].axes]
  559. varRegionList = buildVarRegionList(regions, axisTags)
  560. varData = buildVarData(list(range(len(regions))), None, optimize=False)
  561. varStore = buildVarStore(varRegionList, [varData])
  562. vstore = VarStoreData(otVarStore=varStore)
  563. topDict = self.font["CFF2"].cff.topDictIndex[0]
  564. topDict.VarStore = vstore
  565. for fontDict in topDict.FDArray:
  566. fontDict.Private.vstore = vstore
  567. def setupGlyf(self, glyphs, calcGlyphBounds=True, validateGlyphFormat=True):
  568. """Create the `glyf` table from a dict, that maps glyph names
  569. to `fontTools.ttLib.tables._g_l_y_f.Glyph` objects, for example
  570. as made by `fontTools.pens.ttGlyphPen.TTGlyphPen`.
  571. If `calcGlyphBounds` is True, the bounds of all glyphs will be
  572. calculated. Only pass False if your glyph objects already have
  573. their bounding box values set.
  574. If `validateGlyphFormat` is True, raise ValueError if any of the glyphs contains
  575. cubic curves or is a variable composite but head.glyphDataFormat=0.
  576. Set it to False to skip the check if you know in advance all the glyphs are
  577. compatible with the specified glyphDataFormat.
  578. """
  579. assert self.isTTF
  580. if validateGlyphFormat and self.font["head"].glyphDataFormat == 0:
  581. for name, g in glyphs.items():
  582. if g.isVarComposite():
  583. raise ValueError(
  584. f"Glyph {name!r} is a variable composite, but glyphDataFormat=0"
  585. )
  586. elif g.numberOfContours > 0 and any(f & flagCubic for f in g.flags):
  587. raise ValueError(
  588. f"Glyph {name!r} has cubic Bezier outlines, but glyphDataFormat=0; "
  589. "either convert to quadratics with cu2qu or set glyphDataFormat=1."
  590. )
  591. self.font["loca"] = newTable("loca")
  592. self.font["glyf"] = newTable("glyf")
  593. self.font["glyf"].glyphs = glyphs
  594. if hasattr(self.font, "glyphOrder"):
  595. self.font["glyf"].glyphOrder = self.font.glyphOrder
  596. if calcGlyphBounds:
  597. self.calcGlyphBounds()
  598. def setupFvar(self, axes, instances):
  599. """Adds an font variations table to the font.
  600. Args:
  601. axes (list): See below.
  602. instances (list): See below.
  603. ``axes`` should be a list of axes, with each axis either supplied as
  604. a py:class:`.designspaceLib.AxisDescriptor` object, or a tuple in the
  605. format ```tupletag, minValue, defaultValue, maxValue, name``.
  606. The ``name`` is either a string, or a dict, mapping language codes
  607. to strings, to allow localized name table entries.
  608. ```instances`` should be a list of instances, with each instance either
  609. supplied as a py:class:`.designspaceLib.InstanceDescriptor` object, or a
  610. dict with keys ``location`` (mapping of axis tags to float values),
  611. ``stylename`` and (optionally) ``postscriptfontname``.
  612. The ``stylename`` is either a string, or a dict, mapping language codes
  613. to strings, to allow localized name table entries.
  614. """
  615. addFvar(self.font, axes, instances)
  616. def setupAvar(self, axes, mappings=None):
  617. """Adds an axis variations table to the font.
  618. Args:
  619. axes (list): A list of py:class:`.designspaceLib.AxisDescriptor` objects.
  620. """
  621. from .varLib import _add_avar
  622. if "fvar" not in self.font:
  623. raise KeyError("'fvar' table is missing; can't add 'avar'.")
  624. axisTags = [axis.axisTag for axis in self.font["fvar"].axes]
  625. axes = OrderedDict(enumerate(axes)) # Only values are used
  626. _add_avar(self.font, axes, mappings, axisTags)
  627. def setupGvar(self, variations):
  628. gvar = self.font["gvar"] = newTable("gvar")
  629. gvar.version = 1
  630. gvar.reserved = 0
  631. gvar.variations = variations
  632. def calcGlyphBounds(self):
  633. """Calculate the bounding boxes of all glyphs in the `glyf` table.
  634. This is usually not called explicitly by client code.
  635. """
  636. glyphTable = self.font["glyf"]
  637. for glyph in glyphTable.glyphs.values():
  638. glyph.recalcBounds(glyphTable)
  639. def setupHorizontalMetrics(self, metrics):
  640. """Create a new `hmtx` table, for horizontal metrics.
  641. The `metrics` argument must be a dict, mapping glyph names to
  642. `(width, leftSidebearing)` tuples.
  643. """
  644. self.setupMetrics("hmtx", metrics)
  645. def setupVerticalMetrics(self, metrics):
  646. """Create a new `vmtx` table, for horizontal metrics.
  647. The `metrics` argument must be a dict, mapping glyph names to
  648. `(height, topSidebearing)` tuples.
  649. """
  650. self.setupMetrics("vmtx", metrics)
  651. def setupMetrics(self, tableTag, metrics):
  652. """See `setupHorizontalMetrics()` and `setupVerticalMetrics()`."""
  653. assert tableTag in ("hmtx", "vmtx")
  654. mtxTable = self.font[tableTag] = newTable(tableTag)
  655. roundedMetrics = {}
  656. for gn in metrics:
  657. w, lsb = metrics[gn]
  658. roundedMetrics[gn] = int(round(w)), int(round(lsb))
  659. mtxTable.metrics = roundedMetrics
  660. def setupHorizontalHeader(self, **values):
  661. """Create a new `hhea` table initialize it with default values,
  662. which can be overridden by keyword arguments.
  663. """
  664. self._initTableWithValues("hhea", _hheaDefaults, values)
  665. def setupVerticalHeader(self, **values):
  666. """Create a new `vhea` table initialize it with default values,
  667. which can be overridden by keyword arguments.
  668. """
  669. self._initTableWithValues("vhea", _vheaDefaults, values)
  670. def setupVerticalOrigins(self, verticalOrigins, defaultVerticalOrigin=None):
  671. """Create a new `VORG` table. The `verticalOrigins` argument must be
  672. a dict, mapping glyph names to vertical origin values.
  673. The `defaultVerticalOrigin` argument should be the most common vertical
  674. origin value. If omitted, this value will be derived from the actual
  675. values in the `verticalOrigins` argument.
  676. """
  677. if defaultVerticalOrigin is None:
  678. # find the most frequent vorg value
  679. bag = {}
  680. for gn in verticalOrigins:
  681. vorg = verticalOrigins[gn]
  682. if vorg not in bag:
  683. bag[vorg] = 1
  684. else:
  685. bag[vorg] += 1
  686. defaultVerticalOrigin = sorted(
  687. bag, key=lambda vorg: bag[vorg], reverse=True
  688. )[0]
  689. self._initTableWithValues(
  690. "VORG",
  691. {},
  692. dict(VOriginRecords={}, defaultVertOriginY=defaultVerticalOrigin),
  693. )
  694. vorgTable = self.font["VORG"]
  695. vorgTable.majorVersion = 1
  696. vorgTable.minorVersion = 0
  697. for gn in verticalOrigins:
  698. vorgTable[gn] = verticalOrigins[gn]
  699. def setupPost(self, keepGlyphNames=True, **values):
  700. """Create a new `post` table and initialize it with default values,
  701. which can be overridden by keyword arguments.
  702. """
  703. isCFF2 = "CFF2" in self.font
  704. postTable = self._initTableWithValues("post", _postDefaults, values)
  705. if (self.isTTF or isCFF2) and keepGlyphNames:
  706. postTable.formatType = 2.0
  707. postTable.extraNames = []
  708. postTable.mapping = {}
  709. else:
  710. postTable.formatType = 3.0
  711. def setupMaxp(self):
  712. """Create a new `maxp` table. This is called implicitly by FontBuilder
  713. itself and is usually not called by client code.
  714. """
  715. if self.isTTF:
  716. defaults = _maxpDefaultsTTF
  717. else:
  718. defaults = _maxpDefaultsOTF
  719. self._initTableWithValues("maxp", defaults, {})
  720. def setupDummyDSIG(self):
  721. """This adds an empty DSIG table to the font to make some MS applications
  722. happy. This does not properly sign the font.
  723. """
  724. values = dict(
  725. ulVersion=1,
  726. usFlag=0,
  727. usNumSigs=0,
  728. signatureRecords=[],
  729. )
  730. self._initTableWithValues("DSIG", {}, values)
  731. def addOpenTypeFeatures(self, features, filename=None, tables=None, debug=False):
  732. """Add OpenType features to the font from a string containing
  733. Feature File syntax.
  734. The `filename` argument is used in error messages and to determine
  735. where to look for "include" files.
  736. The optional `tables` argument can be a list of OTL tables tags to
  737. build, allowing the caller to only build selected OTL tables. See
  738. `fontTools.feaLib` for details.
  739. The optional `debug` argument controls whether to add source debugging
  740. information to the font in the `Debg` table.
  741. """
  742. from .feaLib.builder import addOpenTypeFeaturesFromString
  743. addOpenTypeFeaturesFromString(
  744. self.font, features, filename=filename, tables=tables, debug=debug
  745. )
  746. def addFeatureVariations(self, conditionalSubstitutions, featureTag="rvrn"):
  747. """Add conditional substitutions to a Variable Font.
  748. See `fontTools.varLib.featureVars.addFeatureVariations`.
  749. """
  750. from .varLib import featureVars
  751. if "fvar" not in self.font:
  752. raise KeyError("'fvar' table is missing; can't add FeatureVariations.")
  753. featureVars.addFeatureVariations(
  754. self.font, conditionalSubstitutions, featureTag=featureTag
  755. )
  756. def setupCOLR(
  757. self,
  758. colorLayers,
  759. version=None,
  760. varStore=None,
  761. varIndexMap=None,
  762. clipBoxes=None,
  763. allowLayerReuse=True,
  764. ):
  765. """Build new COLR table using color layers dictionary.
  766. Cf. `fontTools.colorLib.builder.buildCOLR`.
  767. """
  768. from fontTools.colorLib.builder import buildCOLR
  769. glyphMap = self.font.getReverseGlyphMap()
  770. self.font["COLR"] = buildCOLR(
  771. colorLayers,
  772. version=version,
  773. glyphMap=glyphMap,
  774. varStore=varStore,
  775. varIndexMap=varIndexMap,
  776. clipBoxes=clipBoxes,
  777. allowLayerReuse=allowLayerReuse,
  778. )
  779. def setupCPAL(
  780. self,
  781. palettes,
  782. paletteTypes=None,
  783. paletteLabels=None,
  784. paletteEntryLabels=None,
  785. ):
  786. """Build new CPAL table using list of palettes.
  787. Optionally build CPAL v1 table using paletteTypes, paletteLabels and
  788. paletteEntryLabels.
  789. Cf. `fontTools.colorLib.builder.buildCPAL`.
  790. """
  791. from fontTools.colorLib.builder import buildCPAL
  792. self.font["CPAL"] = buildCPAL(
  793. palettes,
  794. paletteTypes=paletteTypes,
  795. paletteLabels=paletteLabels,
  796. paletteEntryLabels=paletteEntryLabels,
  797. nameTable=self.font.get("name"),
  798. )
  799. def setupStat(self, axes, locations=None, elidedFallbackName=2):
  800. """Build a new 'STAT' table.
  801. See `fontTools.otlLib.builder.buildStatTable` for details about
  802. the arguments.
  803. """
  804. from .otlLib.builder import buildStatTable
  805. buildStatTable(self.font, axes, locations, elidedFallbackName)
  806. def buildCmapSubTable(cmapping, format, platformID, platEncID):
  807. subTable = cmap_classes[format](format)
  808. subTable.cmap = cmapping
  809. subTable.platformID = platformID
  810. subTable.platEncID = platEncID
  811. subTable.language = 0
  812. return subTable
  813. def addFvar(font, axes, instances):
  814. from .ttLib.tables._f_v_a_r import Axis, NamedInstance
  815. assert axes
  816. fvar = newTable("fvar")
  817. nameTable = font["name"]
  818. for axis_def in axes:
  819. axis = Axis()
  820. if isinstance(axis_def, tuple):
  821. (
  822. axis.axisTag,
  823. axis.minValue,
  824. axis.defaultValue,
  825. axis.maxValue,
  826. name,
  827. ) = axis_def
  828. else:
  829. (axis.axisTag, axis.minValue, axis.defaultValue, axis.maxValue, name) = (
  830. axis_def.tag,
  831. axis_def.minimum,
  832. axis_def.default,
  833. axis_def.maximum,
  834. axis_def.name,
  835. )
  836. if axis_def.hidden:
  837. axis.flags = 0x0001 # HIDDEN_AXIS
  838. if isinstance(name, str):
  839. name = dict(en=name)
  840. axis.axisNameID = nameTable.addMultilingualName(name, ttFont=font)
  841. fvar.axes.append(axis)
  842. for instance in instances:
  843. if isinstance(instance, dict):
  844. coordinates = instance["location"]
  845. name = instance["stylename"]
  846. psname = instance.get("postscriptfontname")
  847. else:
  848. coordinates = instance.location
  849. name = instance.localisedStyleName or instance.styleName
  850. psname = instance.postScriptFontName
  851. if isinstance(name, str):
  852. name = dict(en=name)
  853. inst = NamedInstance()
  854. inst.subfamilyNameID = nameTable.addMultilingualName(name, ttFont=font)
  855. if psname is not None:
  856. inst.postscriptNameID = nameTable.addName(psname)
  857. inst.coordinates = coordinates
  858. fvar.instances.append(inst)
  859. font["fvar"] = fvar