Coverage for /home/martinb/.local/share/virtualenvs/camcops/lib/python3.6/site-packages/matplotlib/afm.py : 21%

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