afmLib.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440
  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_]+)" # char name
  74. r"\s+"
  75. r"(\d+)" # number of parts
  76. r"\s*;\s*"
  77. )
  78. componentRE = re.compile(
  79. r"PCC\s+" # PPC
  80. r"([.A-Za-z0-9_]+)" # base char name
  81. r"\s+"
  82. r"(-?\d+)" # x offset
  83. r"\s+"
  84. r"(-?\d+)" # y offset
  85. r"\s*;\s*"
  86. )
  87. preferredAttributeOrder = [
  88. "FontName",
  89. "FullName",
  90. "FamilyName",
  91. "Weight",
  92. "ItalicAngle",
  93. "IsFixedPitch",
  94. "FontBBox",
  95. "UnderlinePosition",
  96. "UnderlineThickness",
  97. "Version",
  98. "Notice",
  99. "EncodingScheme",
  100. "CapHeight",
  101. "XHeight",
  102. "Ascender",
  103. "Descender",
  104. ]
  105. class error(Exception):
  106. pass
  107. class AFM(object):
  108. _attrs = None
  109. _keywords = [
  110. "StartFontMetrics",
  111. "EndFontMetrics",
  112. "StartCharMetrics",
  113. "EndCharMetrics",
  114. "StartKernData",
  115. "StartKernPairs",
  116. "EndKernPairs",
  117. "EndKernData",
  118. "StartComposites",
  119. "EndComposites",
  120. ]
  121. def __init__(self, path=None):
  122. """AFM file reader.
  123. Instantiating an object with a path name will cause the file to be opened,
  124. read, and parsed. Alternatively the path can be left unspecified, and a
  125. file can be parsed later with the :meth:`read` method."""
  126. self._attrs = {}
  127. self._chars = {}
  128. self._kerning = {}
  129. self._index = {}
  130. self._comments = []
  131. self._composites = {}
  132. if path is not None:
  133. self.read(path)
  134. def read(self, path):
  135. """Opens, reads and parses a file."""
  136. lines = readlines(path)
  137. for line in lines:
  138. if not line.strip():
  139. continue
  140. m = identifierRE.match(line)
  141. if m is None:
  142. raise error("syntax error in AFM file: " + repr(line))
  143. pos = m.regs[1][1]
  144. word = line[:pos]
  145. rest = line[pos:].strip()
  146. if word in self._keywords:
  147. continue
  148. if word == "C":
  149. self.parsechar(rest)
  150. elif word == "KPX":
  151. self.parsekernpair(rest)
  152. elif word == "CC":
  153. self.parsecomposite(rest)
  154. else:
  155. self.parseattr(word, rest)
  156. def parsechar(self, rest):
  157. m = charRE.match(rest)
  158. if m is None:
  159. raise error("syntax error in AFM file: " + repr(rest))
  160. things = []
  161. for fr, to in m.regs[1:]:
  162. things.append(rest[fr:to])
  163. charname = things[2]
  164. del things[2]
  165. charnum, width, l, b, r, t = (int(thing) for thing in things)
  166. self._chars[charname] = charnum, width, (l, b, r, t)
  167. def parsekernpair(self, rest):
  168. m = kernRE.match(rest)
  169. if m is None:
  170. raise error("syntax error in AFM file: " + repr(rest))
  171. things = []
  172. for fr, to in m.regs[1:]:
  173. things.append(rest[fr:to])
  174. leftchar, rightchar, value = things
  175. value = int(value)
  176. self._kerning[(leftchar, rightchar)] = value
  177. def parseattr(self, word, rest):
  178. if word == "FontBBox":
  179. l, b, r, t = [int(thing) for thing in rest.split()]
  180. self._attrs[word] = l, b, r, t
  181. elif word == "Comment":
  182. self._comments.append(rest)
  183. else:
  184. try:
  185. value = int(rest)
  186. except (ValueError, OverflowError):
  187. self._attrs[word] = rest
  188. else:
  189. self._attrs[word] = value
  190. def parsecomposite(self, rest):
  191. m = compositeRE.match(rest)
  192. if m is None:
  193. raise error("syntax error in AFM file: " + repr(rest))
  194. charname = m.group(1)
  195. ncomponents = int(m.group(2))
  196. rest = rest[m.regs[0][1] :]
  197. components = []
  198. while True:
  199. m = componentRE.match(rest)
  200. if m is None:
  201. raise error("syntax error in AFM file: " + repr(rest))
  202. basechar = m.group(1)
  203. xoffset = int(m.group(2))
  204. yoffset = int(m.group(3))
  205. components.append((basechar, xoffset, yoffset))
  206. rest = rest[m.regs[0][1] :]
  207. if not rest:
  208. break
  209. assert len(components) == ncomponents
  210. self._composites[charname] = components
  211. def write(self, path, sep="\r"):
  212. """Writes out an AFM font to the given path."""
  213. import time
  214. lines = [
  215. "StartFontMetrics 2.0",
  216. "Comment Generated by afmLib; at %s"
  217. % (time.strftime("%m/%d/%Y %H:%M:%S", time.localtime(time.time()))),
  218. ]
  219. # write comments, assuming (possibly wrongly!) they should
  220. # all appear at the top
  221. for comment in self._comments:
  222. lines.append("Comment " + comment)
  223. # write attributes, first the ones we know about, in
  224. # a preferred order
  225. attrs = self._attrs
  226. for attr in preferredAttributeOrder:
  227. if attr in attrs:
  228. value = attrs[attr]
  229. if attr == "FontBBox":
  230. value = "%s %s %s %s" % value
  231. lines.append(attr + " " + str(value))
  232. # then write the attributes we don't know about,
  233. # in alphabetical order
  234. items = sorted(attrs.items())
  235. for attr, value in items:
  236. if attr in preferredAttributeOrder:
  237. continue
  238. lines.append(attr + " " + str(value))
  239. # write char metrics
  240. lines.append("StartCharMetrics " + repr(len(self._chars)))
  241. items = [
  242. (charnum, (charname, width, box))
  243. for charname, (charnum, width, box) in self._chars.items()
  244. ]
  245. def myKey(a):
  246. """Custom key function to make sure unencoded chars (-1)
  247. end up at the end of the list after sorting."""
  248. if a[0] == -1:
  249. a = (0xFFFF,) + a[1:] # 0xffff is an arbitrary large number
  250. return a
  251. items.sort(key=myKey)
  252. for charnum, (charname, width, (l, b, r, t)) in items:
  253. lines.append(
  254. "C %d ; WX %d ; N %s ; B %d %d %d %d ;"
  255. % (charnum, width, charname, l, b, r, t)
  256. )
  257. lines.append("EndCharMetrics")
  258. # write kerning info
  259. lines.append("StartKernData")
  260. lines.append("StartKernPairs " + repr(len(self._kerning)))
  261. items = sorted(self._kerning.items())
  262. for (leftchar, rightchar), value in items:
  263. lines.append("KPX %s %s %d" % (leftchar, rightchar, value))
  264. lines.append("EndKernPairs")
  265. lines.append("EndKernData")
  266. if self._composites:
  267. composites = sorted(self._composites.items())
  268. lines.append("StartComposites %s" % len(self._composites))
  269. for charname, components in composites:
  270. line = "CC %s %s ;" % (charname, len(components))
  271. for basechar, xoffset, yoffset in components:
  272. line = line + " PCC %s %s %s ;" % (basechar, xoffset, yoffset)
  273. lines.append(line)
  274. lines.append("EndComposites")
  275. lines.append("EndFontMetrics")
  276. writelines(path, lines, sep)
  277. def has_kernpair(self, pair):
  278. """Returns `True` if the given glyph pair (specified as a tuple) exists
  279. in the kerning dictionary."""
  280. return pair in self._kerning
  281. def kernpairs(self):
  282. """Returns a list of all kern pairs in the kerning dictionary."""
  283. return list(self._kerning.keys())
  284. def has_char(self, char):
  285. """Returns `True` if the given glyph exists in the font."""
  286. return char in self._chars
  287. def chars(self):
  288. """Returns a list of all glyph names in the font."""
  289. return list(self._chars.keys())
  290. def comments(self):
  291. """Returns all comments from the file."""
  292. return self._comments
  293. def addComment(self, comment):
  294. """Adds a new comment to the file."""
  295. self._comments.append(comment)
  296. def addComposite(self, glyphName, components):
  297. """Specifies that the glyph `glyphName` is made up of the given components.
  298. The components list should be of the following form::
  299. [
  300. (glyphname, xOffset, yOffset),
  301. ...
  302. ]
  303. """
  304. self._composites[glyphName] = components
  305. def __getattr__(self, attr):
  306. if attr in self._attrs:
  307. return self._attrs[attr]
  308. else:
  309. raise AttributeError(attr)
  310. def __setattr__(self, attr, value):
  311. # all attrs *not* starting with "_" are consider to be AFM keywords
  312. if attr[:1] == "_":
  313. self.__dict__[attr] = value
  314. else:
  315. self._attrs[attr] = value
  316. def __delattr__(self, attr):
  317. # all attrs *not* starting with "_" are consider to be AFM keywords
  318. if attr[:1] == "_":
  319. try:
  320. del self.__dict__[attr]
  321. except KeyError:
  322. raise AttributeError(attr)
  323. else:
  324. try:
  325. del self._attrs[attr]
  326. except KeyError:
  327. raise AttributeError(attr)
  328. def __getitem__(self, key):
  329. if isinstance(key, tuple):
  330. # key is a tuple, return the kernpair
  331. return self._kerning[key]
  332. else:
  333. # return the metrics instead
  334. return self._chars[key]
  335. def __setitem__(self, key, value):
  336. if isinstance(key, tuple):
  337. # key is a tuple, set kernpair
  338. self._kerning[key] = value
  339. else:
  340. # set char metrics
  341. self._chars[key] = value
  342. def __delitem__(self, key):
  343. if isinstance(key, tuple):
  344. # key is a tuple, del kernpair
  345. del self._kerning[key]
  346. else:
  347. # del char metrics
  348. del self._chars[key]
  349. def __repr__(self):
  350. if hasattr(self, "FullName"):
  351. return "<AFM object for %s>" % self.FullName
  352. else:
  353. return "<AFM object at %x>" % id(self)
  354. def readlines(path):
  355. with open(path, "r", encoding="ascii") as f:
  356. data = f.read()
  357. return data.splitlines()
  358. def writelines(path, lines, sep="\r"):
  359. with open(path, "w", encoding="ascii", newline=sep) as f:
  360. f.write("\n".join(lines) + "\n")
  361. if __name__ == "__main__":
  362. import EasyDialogs
  363. path = EasyDialogs.AskFileForOpen()
  364. if path:
  365. afm = AFM(path)
  366. char = "A"
  367. if afm.has_char(char):
  368. print(afm[char]) # print charnum, width and boundingbox
  369. pair = ("A", "V")
  370. if afm.has_kernpair(pair):
  371. print(afm[pair]) # print kerning value for pair
  372. print(afm.Version) # various other afm entries have become attributes
  373. print(afm.Weight)
  374. # afm.comments() returns a list of all Comment lines found in the AFM
  375. print(afm.comments())
  376. # print afm.chars()
  377. # print afm.kernpairs()
  378. print(afm)
  379. afm.write(path + ".muck")