You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

562 lines
16 KiB

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