_afm.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532
  1. """
  2. A python interface to Adobe Font Metrics Files.
  3. Although a number of other Python implementations exist, and may be more
  4. complete than this, it was decided not to go with them because they were
  5. either:
  6. 1) copyrighted or used a non-BSD compatible license
  7. 2) had too many dependencies and a free standing lib was needed
  8. 3) did more than needed and it was easier to write afresh rather than
  9. figure out how to get just what was needed.
  10. It is pretty easy to use, and has no external dependencies:
  11. >>> import matplotlib as mpl
  12. >>> from pathlib import Path
  13. >>> afm_path = Path(mpl.get_data_path(), 'fonts', 'afm', 'ptmr8a.afm')
  14. >>>
  15. >>> from matplotlib.afm import AFM
  16. >>> with afm_path.open('rb') as fh:
  17. ... afm = AFM(fh)
  18. >>> afm.string_width_height('What the heck?')
  19. (6220.0, 694)
  20. >>> afm.get_fontname()
  21. 'Times-Roman'
  22. >>> afm.get_kern_dist('A', 'f')
  23. 0
  24. >>> afm.get_kern_dist('A', 'y')
  25. -92.0
  26. >>> afm.get_bbox_char('!')
  27. [130, -9, 238, 676]
  28. As in the Adobe Font Metrics File Format Specification, all dimensions
  29. are given in units of 1/1000 of the scale factor (point size) of the font
  30. being used.
  31. """
  32. from collections import namedtuple
  33. import logging
  34. import re
  35. from ._mathtext_data import uni2type1
  36. _log = logging.getLogger(__name__)
  37. def _to_int(x):
  38. # Some AFM files have floats where we are expecting ints -- there is
  39. # probably a better way to handle this (support floats, round rather than
  40. # truncate). But I don't know what the best approach is now and this
  41. # change to _to_int should at least prevent Matplotlib from crashing on
  42. # these. JDH (2009-11-06)
  43. return int(float(x))
  44. def _to_float(x):
  45. # Some AFM files use "," instead of "." as decimal separator -- this
  46. # shouldn't be ambiguous (unless someone is wicked enough to use "," as
  47. # thousands separator...).
  48. if isinstance(x, bytes):
  49. # Encoding doesn't really matter -- if we have codepoints >127 the call
  50. # to float() will error anyways.
  51. x = x.decode('latin-1')
  52. return float(x.replace(',', '.'))
  53. def _to_str(x):
  54. return x.decode('utf8')
  55. def _to_list_of_ints(s):
  56. s = s.replace(b',', b' ')
  57. return [_to_int(val) for val in s.split()]
  58. def _to_list_of_floats(s):
  59. return [_to_float(val) for val in s.split()]
  60. def _to_bool(s):
  61. if s.lower().strip() in (b'false', b'0', b'no'):
  62. return False
  63. else:
  64. return True
  65. def _parse_header(fh):
  66. """
  67. Read the font metrics header (up to the char metrics) and returns
  68. a dictionary mapping *key* to *val*. *val* will be converted to the
  69. appropriate python type as necessary; e.g.:
  70. * 'False'->False
  71. * '0'->0
  72. * '-168 -218 1000 898'-> [-168, -218, 1000, 898]
  73. Dictionary keys are
  74. StartFontMetrics, FontName, FullName, FamilyName, Weight,
  75. ItalicAngle, IsFixedPitch, FontBBox, UnderlinePosition,
  76. UnderlineThickness, Version, Notice, EncodingScheme, CapHeight,
  77. XHeight, Ascender, Descender, StartCharMetrics
  78. """
  79. header_converters = {
  80. b'StartFontMetrics': _to_float,
  81. b'FontName': _to_str,
  82. b'FullName': _to_str,
  83. b'FamilyName': _to_str,
  84. b'Weight': _to_str,
  85. b'ItalicAngle': _to_float,
  86. b'IsFixedPitch': _to_bool,
  87. b'FontBBox': _to_list_of_ints,
  88. b'UnderlinePosition': _to_float,
  89. b'UnderlineThickness': _to_float,
  90. b'Version': _to_str,
  91. # Some AFM files have non-ASCII characters (which are not allowed by
  92. # the spec). Given that there is actually no public API to even access
  93. # this field, just return it as straight bytes.
  94. b'Notice': lambda x: x,
  95. b'EncodingScheme': _to_str,
  96. b'CapHeight': _to_float, # Is the second version a mistake, or
  97. b'Capheight': _to_float, # do some AFM files contain 'Capheight'? -JKS
  98. b'XHeight': _to_float,
  99. b'Ascender': _to_float,
  100. b'Descender': _to_float,
  101. b'StdHW': _to_float,
  102. b'StdVW': _to_float,
  103. b'StartCharMetrics': _to_int,
  104. b'CharacterSet': _to_str,
  105. b'Characters': _to_int,
  106. }
  107. d = {}
  108. first_line = True
  109. for line in fh:
  110. line = line.rstrip()
  111. if line.startswith(b'Comment'):
  112. continue
  113. lst = line.split(b' ', 1)
  114. key = lst[0]
  115. if first_line:
  116. # AFM spec, Section 4: The StartFontMetrics keyword
  117. # [followed by a version number] must be the first line in
  118. # the file, and the EndFontMetrics keyword must be the
  119. # last non-empty line in the file. We just check the
  120. # first header entry.
  121. if key != b'StartFontMetrics':
  122. raise RuntimeError('Not an AFM file')
  123. first_line = False
  124. if len(lst) == 2:
  125. val = lst[1]
  126. else:
  127. val = b''
  128. try:
  129. converter = header_converters[key]
  130. except KeyError:
  131. _log.error("Found an unknown keyword in AFM header (was %r)", key)
  132. continue
  133. try:
  134. d[key] = converter(val)
  135. except ValueError:
  136. _log.error('Value error parsing header in AFM: %s, %s', key, val)
  137. continue
  138. if key == b'StartCharMetrics':
  139. break
  140. else:
  141. raise RuntimeError('Bad parse')
  142. return d
  143. CharMetrics = namedtuple('CharMetrics', 'width, name, bbox')
  144. CharMetrics.__doc__ = """
  145. Represents the character metrics of a single character.
  146. Notes
  147. -----
  148. The fields do currently only describe a subset of character metrics
  149. information defined in the AFM standard.
  150. """
  151. CharMetrics.width.__doc__ = """The character width (WX)."""
  152. CharMetrics.name.__doc__ = """The character name (N)."""
  153. CharMetrics.bbox.__doc__ = """
  154. The bbox of the character (B) as a tuple (*llx*, *lly*, *urx*, *ury*)."""
  155. def _parse_char_metrics(fh):
  156. """
  157. Parse the given filehandle for character metrics information and return
  158. the information as dicts.
  159. It is assumed that the file cursor is on the line behind
  160. 'StartCharMetrics'.
  161. Returns
  162. -------
  163. ascii_d : dict
  164. A mapping "ASCII num of the character" to `.CharMetrics`.
  165. name_d : dict
  166. A mapping "character name" to `.CharMetrics`.
  167. Notes
  168. -----
  169. This function is incomplete per the standard, but thus far parses
  170. all the sample afm files tried.
  171. """
  172. required_keys = {'C', 'WX', 'N', 'B'}
  173. ascii_d = {}
  174. name_d = {}
  175. for line in fh:
  176. # We are defensively letting values be utf8. The spec requires
  177. # ascii, but there are non-compliant fonts in circulation
  178. line = _to_str(line.rstrip()) # Convert from byte-literal
  179. if line.startswith('EndCharMetrics'):
  180. return ascii_d, name_d
  181. # Split the metric line into a dictionary, keyed by metric identifiers
  182. vals = dict(s.strip().split(' ', 1) for s in line.split(';') if s)
  183. # There may be other metrics present, but only these are needed
  184. if not required_keys.issubset(vals):
  185. raise RuntimeError('Bad char metrics line: %s' % line)
  186. num = _to_int(vals['C'])
  187. wx = _to_float(vals['WX'])
  188. name = vals['N']
  189. bbox = _to_list_of_floats(vals['B'])
  190. bbox = list(map(int, bbox))
  191. metrics = CharMetrics(wx, name, bbox)
  192. # Workaround: If the character name is 'Euro', give it the
  193. # corresponding character code, according to WinAnsiEncoding (see PDF
  194. # Reference).
  195. if name == 'Euro':
  196. num = 128
  197. elif name == 'minus':
  198. num = ord("\N{MINUS SIGN}") # 0x2212
  199. if num != -1:
  200. ascii_d[num] = metrics
  201. name_d[name] = metrics
  202. raise RuntimeError('Bad parse')
  203. def _parse_kern_pairs(fh):
  204. """
  205. Return a kern pairs dictionary; keys are (*char1*, *char2*) tuples and
  206. values are the kern pair value. For example, a kern pairs line like
  207. ``KPX A y -50``
  208. will be represented as::
  209. d[ ('A', 'y') ] = -50
  210. """
  211. line = next(fh)
  212. if not line.startswith(b'StartKernPairs'):
  213. raise RuntimeError('Bad start of kern pairs data: %s' % line)
  214. d = {}
  215. for line in fh:
  216. line = line.rstrip()
  217. if not line:
  218. continue
  219. if line.startswith(b'EndKernPairs'):
  220. next(fh) # EndKernData
  221. return d
  222. vals = line.split()
  223. if len(vals) != 4 or vals[0] != b'KPX':
  224. raise RuntimeError('Bad kern pairs line: %s' % line)
  225. c1, c2, val = _to_str(vals[1]), _to_str(vals[2]), _to_float(vals[3])
  226. d[(c1, c2)] = val
  227. raise RuntimeError('Bad kern pairs parse')
  228. CompositePart = namedtuple('CompositePart', 'name, dx, dy')
  229. CompositePart.__doc__ = """
  230. Represents the information on a composite element of a composite char."""
  231. CompositePart.name.__doc__ = """Name of the part, e.g. 'acute'."""
  232. CompositePart.dx.__doc__ = """x-displacement of the part from the origin."""
  233. CompositePart.dy.__doc__ = """y-displacement of the part from the origin."""
  234. def _parse_composites(fh):
  235. """
  236. Parse the given filehandle for composites information return them as a
  237. dict.
  238. It is assumed that the file cursor is on the line behind 'StartComposites'.
  239. Returns
  240. -------
  241. dict
  242. A dict mapping composite character names to a parts list. The parts
  243. list is a list of `.CompositePart` entries describing the parts of
  244. the composite.
  245. Examples
  246. --------
  247. A composite definition line::
  248. CC Aacute 2 ; PCC A 0 0 ; PCC acute 160 170 ;
  249. will be represented as::
  250. composites['Aacute'] = [CompositePart(name='A', dx=0, dy=0),
  251. CompositePart(name='acute', dx=160, dy=170)]
  252. """
  253. composites = {}
  254. for line in fh:
  255. line = line.rstrip()
  256. if not line:
  257. continue
  258. if line.startswith(b'EndComposites'):
  259. return composites
  260. vals = line.split(b';')
  261. cc = vals[0].split()
  262. name, _num_parts = cc[1], _to_int(cc[2])
  263. pccParts = []
  264. for s in vals[1:-1]:
  265. pcc = s.split()
  266. part = CompositePart(pcc[1], _to_float(pcc[2]), _to_float(pcc[3]))
  267. pccParts.append(part)
  268. composites[name] = pccParts
  269. raise RuntimeError('Bad composites parse')
  270. def _parse_optional(fh):
  271. """
  272. Parse the optional fields for kern pair data and composites.
  273. Returns
  274. -------
  275. kern_data : dict
  276. A dict containing kerning information. May be empty.
  277. See `._parse_kern_pairs`.
  278. composites : dict
  279. A dict containing composite information. May be empty.
  280. See `._parse_composites`.
  281. """
  282. optional = {
  283. b'StartKernData': _parse_kern_pairs,
  284. b'StartComposites': _parse_composites,
  285. }
  286. d = {b'StartKernData': {},
  287. b'StartComposites': {}}
  288. for line in fh:
  289. line = line.rstrip()
  290. if not line:
  291. continue
  292. key = line.split()[0]
  293. if key in optional:
  294. d[key] = optional[key](fh)
  295. return d[b'StartKernData'], d[b'StartComposites']
  296. class AFM:
  297. def __init__(self, fh):
  298. """Parse the AFM file in file object *fh*."""
  299. self._header = _parse_header(fh)
  300. self._metrics, self._metrics_by_name = _parse_char_metrics(fh)
  301. self._kern, self._composite = _parse_optional(fh)
  302. def get_bbox_char(self, c, isord=False):
  303. if not isord:
  304. c = ord(c)
  305. return self._metrics[c].bbox
  306. def string_width_height(self, s):
  307. """
  308. Return the string width (including kerning) and string height
  309. as a (*w*, *h*) tuple.
  310. """
  311. if not len(s):
  312. return 0, 0
  313. total_width = 0
  314. namelast = None
  315. miny = 1e9
  316. maxy = 0
  317. for c in s:
  318. if c == '\n':
  319. continue
  320. wx, name, bbox = self._metrics[ord(c)]
  321. total_width += wx + self._kern.get((namelast, name), 0)
  322. l, b, w, h = bbox
  323. miny = min(miny, b)
  324. maxy = max(maxy, b + h)
  325. namelast = name
  326. return total_width, maxy - miny
  327. def get_str_bbox_and_descent(self, s):
  328. """Return the string bounding box and the maximal descent."""
  329. if not len(s):
  330. return 0, 0, 0, 0, 0
  331. total_width = 0
  332. namelast = None
  333. miny = 1e9
  334. maxy = 0
  335. left = 0
  336. if not isinstance(s, str):
  337. s = _to_str(s)
  338. for c in s:
  339. if c == '\n':
  340. continue
  341. name = uni2type1.get(ord(c), f"uni{ord(c):04X}")
  342. try:
  343. wx, _, bbox = self._metrics_by_name[name]
  344. except KeyError:
  345. name = 'question'
  346. wx, _, bbox = self._metrics_by_name[name]
  347. total_width += wx + self._kern.get((namelast, name), 0)
  348. l, b, w, h = bbox
  349. left = min(left, l)
  350. miny = min(miny, b)
  351. maxy = max(maxy, b + h)
  352. namelast = name
  353. return left, miny, total_width, maxy - miny, -miny
  354. def get_str_bbox(self, s):
  355. """Return the string bounding box."""
  356. return self.get_str_bbox_and_descent(s)[:4]
  357. def get_name_char(self, c, isord=False):
  358. """Get the name of the character, i.e., ';' is 'semicolon'."""
  359. if not isord:
  360. c = ord(c)
  361. return self._metrics[c].name
  362. def get_width_char(self, c, isord=False):
  363. """
  364. Get the width of the character from the character metric WX field.
  365. """
  366. if not isord:
  367. c = ord(c)
  368. return self._metrics[c].width
  369. def get_width_from_char_name(self, name):
  370. """Get the width of the character from a type1 character name."""
  371. return self._metrics_by_name[name].width
  372. def get_height_char(self, c, isord=False):
  373. """Get the bounding box (ink) height of character *c* (space is 0)."""
  374. if not isord:
  375. c = ord(c)
  376. return self._metrics[c].bbox[-1]
  377. def get_kern_dist(self, c1, c2):
  378. """
  379. Return the kerning pair distance (possibly 0) for chars *c1* and *c2*.
  380. """
  381. name1, name2 = self.get_name_char(c1), self.get_name_char(c2)
  382. return self.get_kern_dist_from_name(name1, name2)
  383. def get_kern_dist_from_name(self, name1, name2):
  384. """
  385. Return the kerning pair distance (possibly 0) for chars
  386. *name1* and *name2*.
  387. """
  388. return self._kern.get((name1, name2), 0)
  389. def get_fontname(self):
  390. """Return the font name, e.g., 'Times-Roman'."""
  391. return self._header[b'FontName']
  392. @property
  393. def postscript_name(self): # For consistency with FT2Font.
  394. return self.get_fontname()
  395. def get_fullname(self):
  396. """Return the font full name, e.g., 'Times-Roman'."""
  397. name = self._header.get(b'FullName')
  398. if name is None: # use FontName as a substitute
  399. name = self._header[b'FontName']
  400. return name
  401. def get_familyname(self):
  402. """Return the font family name, e.g., 'Times'."""
  403. name = self._header.get(b'FamilyName')
  404. if name is not None:
  405. return name
  406. # FamilyName not specified so we'll make a guess
  407. name = self.get_fullname()
  408. extras = (r'(?i)([ -](regular|plain|italic|oblique|bold|semibold|'
  409. r'light|ultralight|extra|condensed))+$')
  410. return re.sub(extras, '', name)
  411. @property
  412. def family_name(self):
  413. """The font family name, e.g., 'Times'."""
  414. return self.get_familyname()
  415. def get_weight(self):
  416. """Return the font weight, e.g., 'Bold' or 'Roman'."""
  417. return self._header[b'Weight']
  418. def get_angle(self):
  419. """Return the fontangle as float."""
  420. return self._header[b'ItalicAngle']
  421. def get_capheight(self):
  422. """Return the cap height as float."""
  423. return self._header[b'CapHeight']
  424. def get_xheight(self):
  425. """Return the xheight as float."""
  426. return self._header[b'XHeight']
  427. def get_underline_thickness(self):
  428. """Return the underline thickness as float."""
  429. return self._header[b'UnderlineThickness']
  430. def get_horizontal_stem_width(self):
  431. """
  432. Return the standard horizontal stem width as float, or *None* if
  433. not specified in AFM file.
  434. """
  435. return self._header.get(b'StdHW', None)
  436. def get_vertical_stem_width(self):
  437. """
  438. Return the standard vertical stem width as float, or *None* if
  439. not specified in AFM file.
  440. """
  441. return self._header.get(b'StdVW', None)