afmLib.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437
  1. """Module for reading and writing AFM (Adobe Font Metrics) files.
  2. Note that this has been designed to read in AFM files generated by Fontographer
  3. and has not been tested on many other files. In particular, it does not
  4. implement the whole Adobe AFM specification [#f1]_ but, it should read most
  5. "common" AFM files.
  6. Here is an example of using `afmLib` to read, modify and write an AFM file:
  7. >>> from fontTools.afmLib import AFM
  8. >>> f = AFM("Tests/afmLib/data/TestAFM.afm")
  9. >>>
  10. >>> # Accessing a pair gets you the kern value
  11. >>> f[("V","A")]
  12. -60
  13. >>>
  14. >>> # Accessing a glyph name gets you metrics
  15. >>> f["A"]
  16. (65, 668, (8, -25, 660, 666))
  17. >>> # (charnum, width, bounding box)
  18. >>>
  19. >>> # Accessing an attribute gets you metadata
  20. >>> f.FontName
  21. 'TestFont-Regular'
  22. >>> f.FamilyName
  23. 'TestFont'
  24. >>> f.Weight
  25. 'Regular'
  26. >>> f.XHeight
  27. 500
  28. >>> f.Ascender
  29. 750
  30. >>>
  31. >>> # Attributes and items can also be set
  32. >>> f[("A","V")] = -150 # Tighten kerning
  33. >>> f.FontName = "TestFont Squished"
  34. >>>
  35. >>> # And the font written out again (remove the # in front)
  36. >>> #f.write("testfont-squished.afm")
  37. .. rubric:: Footnotes
  38. .. [#f1] `Adobe Technote 5004 <https://www.adobe.com/content/dam/acom/en/devnet/font/pdfs/5004.AFM_Spec.pdf>`_,
  39. Adobe Font Metrics File Format Specification.
  40. """
  41. import re
  42. # every single line starts with a "word"
  43. identifierRE = re.compile(r"^([A-Za-z]+).*")
  44. # regular expression to parse char lines
  45. charRE = re.compile(
  46. r"(-?\d+)" # charnum
  47. r"\s*;\s*WX\s+" # ; WX
  48. r"(-?\d+)" # width
  49. r"\s*;\s*N\s+" # ; N
  50. r"([.A-Za-z0-9_]+)" # charname
  51. r"\s*;\s*B\s+" # ; B
  52. r"(-?\d+)" # left
  53. r"\s+"
  54. r"(-?\d+)" # bottom
  55. r"\s+"
  56. r"(-?\d+)" # right
  57. r"\s+"
  58. r"(-?\d+)" # top
  59. r"\s*;\s*" # ;
  60. )
  61. # regular expression to parse kerning lines
  62. kernRE = re.compile(
  63. r"([.A-Za-z0-9_]+)" # leftchar
  64. r"\s+"
  65. r"([.A-Za-z0-9_]+)" # rightchar
  66. r"\s+"
  67. r"(-?\d+)" # value
  68. r"\s*"
  69. )
  70. # regular expressions to parse composite info lines of the form:
  71. # Aacute 2 ; PCC A 0 0 ; PCC acute 182 211 ;
  72. compositeRE = re.compile(
  73. r"([.A-Za-z0-9_]+)" r"\s+" r"(\d+)" r"\s*;\s*" # char name # number of parts
  74. )
  75. componentRE = re.compile(
  76. r"PCC\s+" # PPC
  77. r"([.A-Za-z0-9_]+)" # base char name
  78. r"\s+"
  79. r"(-?\d+)" # x offset
  80. r"\s+"
  81. r"(-?\d+)" # y offset
  82. r"\s*;\s*"
  83. )
  84. preferredAttributeOrder = [
  85. "FontName",
  86. "FullName",
  87. "FamilyName",
  88. "Weight",
  89. "ItalicAngle",
  90. "IsFixedPitch",
  91. "FontBBox",
  92. "UnderlinePosition",
  93. "UnderlineThickness",
  94. "Version",
  95. "Notice",
  96. "EncodingScheme",
  97. "CapHeight",
  98. "XHeight",
  99. "Ascender",
  100. "Descender",
  101. ]
  102. class error(Exception):
  103. pass
  104. class AFM(object):
  105. _attrs = None
  106. _keywords = [
  107. "StartFontMetrics",
  108. "EndFontMetrics",
  109. "StartCharMetrics",
  110. "EndCharMetrics",
  111. "StartKernData",
  112. "StartKernPairs",
  113. "EndKernPairs",
  114. "EndKernData",
  115. "StartComposites",
  116. "EndComposites",
  117. ]
  118. def __init__(self, path=None):
  119. """AFM file reader.
  120. Instantiating an object with a path name will cause the file to be opened,
  121. read, and parsed. Alternatively the path can be left unspecified, and a
  122. file can be parsed later with the :meth:`read` method."""
  123. self._attrs = {}
  124. self._chars = {}
  125. self._kerning = {}
  126. self._index = {}
  127. self._comments = []
  128. self._composites = {}
  129. if path is not None:
  130. self.read(path)
  131. def read(self, path):
  132. """Opens, reads and parses a file."""
  133. lines = readlines(path)
  134. for line in lines:
  135. if not line.strip():
  136. continue
  137. m = identifierRE.match(line)
  138. if m is None:
  139. raise error("syntax error in AFM file: " + repr(line))
  140. pos = m.regs[1][1]
  141. word = line[:pos]
  142. rest = line[pos:].strip()
  143. if word in self._keywords:
  144. continue
  145. if word == "C":
  146. self.parsechar(rest)
  147. elif word == "KPX":
  148. self.parsekernpair(rest)
  149. elif word == "CC":
  150. self.parsecomposite(rest)
  151. else:
  152. self.parseattr(word, rest)
  153. def parsechar(self, rest):
  154. m = charRE.match(rest)
  155. if m is None:
  156. raise error("syntax error in AFM file: " + repr(rest))
  157. things = []
  158. for fr, to in m.regs[1:]:
  159. things.append(rest[fr:to])
  160. charname = things[2]
  161. del things[2]
  162. charnum, width, l, b, r, t = (int(thing) for thing in things)
  163. self._chars[charname] = charnum, width, (l, b, r, t)
  164. def parsekernpair(self, rest):
  165. m = kernRE.match(rest)
  166. if m is None:
  167. raise error("syntax error in AFM file: " + repr(rest))
  168. things = []
  169. for fr, to in m.regs[1:]:
  170. things.append(rest[fr:to])
  171. leftchar, rightchar, value = things
  172. value = int(value)
  173. self._kerning[(leftchar, rightchar)] = value
  174. def parseattr(self, word, rest):
  175. if word == "FontBBox":
  176. l, b, r, t = [int(thing) for thing in rest.split()]
  177. self._attrs[word] = l, b, r, t
  178. elif word == "Comment":
  179. self._comments.append(rest)
  180. else:
  181. try:
  182. value = int(rest)
  183. except (ValueError, OverflowError):
  184. self._attrs[word] = rest
  185. else:
  186. self._attrs[word] = value
  187. def parsecomposite(self, rest):
  188. m = compositeRE.match(rest)
  189. if m is None:
  190. raise error("syntax error in AFM file: " + repr(rest))
  191. charname = m.group(1)
  192. ncomponents = int(m.group(2))
  193. rest = rest[m.regs[0][1] :]
  194. components = []
  195. while True:
  196. m = componentRE.match(rest)
  197. if m is None:
  198. raise error("syntax error in AFM file: " + repr(rest))
  199. basechar = m.group(1)
  200. xoffset = int(m.group(2))
  201. yoffset = int(m.group(3))
  202. components.append((basechar, xoffset, yoffset))
  203. rest = rest[m.regs[0][1] :]
  204. if not rest:
  205. break
  206. assert len(components) == ncomponents
  207. self._composites[charname] = components
  208. def write(self, path, sep="\r"):
  209. """Writes out an AFM font to the given path."""
  210. import time
  211. lines = [
  212. "StartFontMetrics 2.0",
  213. "Comment Generated by afmLib; at %s"
  214. % (time.strftime("%m/%d/%Y %H:%M:%S", time.localtime(time.time()))),
  215. ]
  216. # write comments, assuming (possibly wrongly!) they should
  217. # all appear at the top
  218. for comment in self._comments:
  219. lines.append("Comment " + comment)
  220. # write attributes, first the ones we know about, in
  221. # a preferred order
  222. attrs = self._attrs
  223. for attr in preferredAttributeOrder:
  224. if attr in attrs:
  225. value = attrs[attr]
  226. if attr == "FontBBox":
  227. value = "%s %s %s %s" % value
  228. lines.append(attr + " " + str(value))
  229. # then write the attributes we don't know about,
  230. # in alphabetical order
  231. items = sorted(attrs.items())
  232. for attr, value in items:
  233. if attr in preferredAttributeOrder:
  234. continue
  235. lines.append(attr + " " + str(value))
  236. # write char metrics
  237. lines.append("StartCharMetrics " + repr(len(self._chars)))
  238. items = [
  239. (charnum, (charname, width, box))
  240. for charname, (charnum, width, box) in self._chars.items()
  241. ]
  242. def myKey(a):
  243. """Custom key function to make sure unencoded chars (-1)
  244. end up at the end of the list after sorting."""
  245. if a[0] == -1:
  246. a = (0xFFFF,) + a[1:] # 0xffff is an arbitrary large number
  247. return a
  248. items.sort(key=myKey)
  249. for charnum, (charname, width, (l, b, r, t)) in items:
  250. lines.append(
  251. "C %d ; WX %d ; N %s ; B %d %d %d %d ;"
  252. % (charnum, width, charname, l, b, r, t)
  253. )
  254. lines.append("EndCharMetrics")
  255. # write kerning info
  256. lines.append("StartKernData")
  257. lines.append("StartKernPairs " + repr(len(self._kerning)))
  258. items = sorted(self._kerning.items())
  259. for (leftchar, rightchar), value in items:
  260. lines.append("KPX %s %s %d" % (leftchar, rightchar, value))
  261. lines.append("EndKernPairs")
  262. lines.append("EndKernData")
  263. if self._composites:
  264. composites = sorted(self._composites.items())
  265. lines.append("StartComposites %s" % len(self._composites))
  266. for charname, components in composites:
  267. line = "CC %s %s ;" % (charname, len(components))
  268. for basechar, xoffset, yoffset in components:
  269. line = line + " PCC %s %s %s ;" % (basechar, xoffset, yoffset)
  270. lines.append(line)
  271. lines.append("EndComposites")
  272. lines.append("EndFontMetrics")
  273. writelines(path, lines, sep)
  274. def has_kernpair(self, pair):
  275. """Returns `True` if the given glyph pair (specified as a tuple) exists
  276. in the kerning dictionary."""
  277. return pair in self._kerning
  278. def kernpairs(self):
  279. """Returns a list of all kern pairs in the kerning dictionary."""
  280. return list(self._kerning.keys())
  281. def has_char(self, char):
  282. """Returns `True` if the given glyph exists in the font."""
  283. return char in self._chars
  284. def chars(self):
  285. """Returns a list of all glyph names in the font."""
  286. return list(self._chars.keys())
  287. def comments(self):
  288. """Returns all comments from the file."""
  289. return self._comments
  290. def addComment(self, comment):
  291. """Adds a new comment to the file."""
  292. self._comments.append(comment)
  293. def addComposite(self, glyphName, components):
  294. """Specifies that the glyph `glyphName` is made up of the given components.
  295. The components list should be of the following form::
  296. [
  297. (glyphname, xOffset, yOffset),
  298. ...
  299. ]
  300. """
  301. self._composites[glyphName] = components
  302. def __getattr__(self, attr):
  303. if attr in self._attrs:
  304. return self._attrs[attr]
  305. else:
  306. raise AttributeError(attr)
  307. def __setattr__(self, attr, value):
  308. # all attrs *not* starting with "_" are consider to be AFM keywords
  309. if attr[:1] == "_":
  310. self.__dict__[attr] = value
  311. else:
  312. self._attrs[attr] = value
  313. def __delattr__(self, attr):
  314. # all attrs *not* starting with "_" are consider to be AFM keywords
  315. if attr[:1] == "_":
  316. try:
  317. del self.__dict__[attr]
  318. except KeyError:
  319. raise AttributeError(attr)
  320. else:
  321. try:
  322. del self._attrs[attr]
  323. except KeyError:
  324. raise AttributeError(attr)
  325. def __getitem__(self, key):
  326. if isinstance(key, tuple):
  327. # key is a tuple, return the kernpair
  328. return self._kerning[key]
  329. else:
  330. # return the metrics instead
  331. return self._chars[key]
  332. def __setitem__(self, key, value):
  333. if isinstance(key, tuple):
  334. # key is a tuple, set kernpair
  335. self._kerning[key] = value
  336. else:
  337. # set char metrics
  338. self._chars[key] = value
  339. def __delitem__(self, key):
  340. if isinstance(key, tuple):
  341. # key is a tuple, del kernpair
  342. del self._kerning[key]
  343. else:
  344. # del char metrics
  345. del self._chars[key]
  346. def __repr__(self):
  347. if hasattr(self, "FullName"):
  348. return "<AFM object for %s>" % self.FullName
  349. else:
  350. return "<AFM object at %x>" % id(self)
  351. def readlines(path):
  352. with open(path, "r", encoding="ascii") as f:
  353. data = f.read()
  354. return data.splitlines()
  355. def writelines(path, lines, sep="\r"):
  356. with open(path, "w", encoding="ascii", newline=sep) as f:
  357. f.write("\n".join(lines) + "\n")
  358. if __name__ == "__main__":
  359. import EasyDialogs
  360. path = EasyDialogs.AskFileForOpen()
  361. if path:
  362. afm = AFM(path)
  363. char = "A"
  364. if afm.has_char(char):
  365. print(afm[char]) # print charnum, width and boundingbox
  366. pair = ("A", "V")
  367. if afm.has_kernpair(pair):
  368. print(afm[pair]) # print kerning value for pair
  369. print(afm.Version) # various other afm entries have become attributes
  370. print(afm.Weight)
  371. # afm.comments() returns a list of all Comment lines found in the AFM
  372. print(afm.comments())
  373. # print afm.chars()
  374. # print afm.kernpairs()
  375. print(afm)
  376. afm.write(path + ".muck")