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.

1055 lines
36 KiB

4 years ago
  1. """
  2. A module for reading dvi files output by TeX. Several limitations make
  3. this not (currently) useful as a general-purpose dvi preprocessor, but
  4. it is currently used by the pdf backend for processing usetex text.
  5. Interface::
  6. with Dvi(filename, 72) as dvi:
  7. # iterate over pages:
  8. for page in dvi:
  9. w, h, d = page.width, page.height, page.descent
  10. for x, y, font, glyph, width in page.text:
  11. fontname = font.texname
  12. pointsize = font.size
  13. ...
  14. for x, y, height, width in page.boxes:
  15. ...
  16. """
  17. from collections import namedtuple
  18. import enum
  19. from functools import lru_cache, partial, wraps
  20. import logging
  21. import os
  22. import re
  23. import struct
  24. import subprocess
  25. import textwrap
  26. import numpy as np
  27. from matplotlib import cbook, rcParams
  28. _log = logging.getLogger(__name__)
  29. # Many dvi related files are looked for by external processes, require
  30. # additional parsing, and are used many times per rendering, which is why they
  31. # are cached using lru_cache().
  32. # Dvi is a bytecode format documented in
  33. # http://mirrors.ctan.org/systems/knuth/dist/texware/dvitype.web
  34. # http://texdoc.net/texmf-dist/doc/generic/knuth/texware/dvitype.pdf
  35. #
  36. # The file consists of a preamble, some number of pages, a postamble,
  37. # and a finale. Different opcodes are allowed in different contexts,
  38. # so the Dvi object has a parser state:
  39. #
  40. # pre: expecting the preamble
  41. # outer: between pages (followed by a page or the postamble,
  42. # also e.g. font definitions are allowed)
  43. # page: processing a page
  44. # post_post: state after the postamble (our current implementation
  45. # just stops reading)
  46. # finale: the finale (unimplemented in our current implementation)
  47. _dvistate = enum.Enum('DviState', 'pre outer inpage post_post finale')
  48. # The marks on a page consist of text and boxes. A page also has dimensions.
  49. Page = namedtuple('Page', 'text boxes height width descent')
  50. Text = namedtuple('Text', 'x y font glyph width')
  51. Box = namedtuple('Box', 'x y height width')
  52. # Opcode argument parsing
  53. #
  54. # Each of the following functions takes a Dvi object and delta,
  55. # which is the difference between the opcode and the minimum opcode
  56. # with the same meaning. Dvi opcodes often encode the number of
  57. # argument bytes in this delta.
  58. def _arg_raw(dvi, delta):
  59. """Return *delta* without reading anything more from the dvi file"""
  60. return delta
  61. def _arg(bytes, signed, dvi, _):
  62. """Read *bytes* bytes, returning the bytes interpreted as a
  63. signed integer if *signed* is true, unsigned otherwise."""
  64. return dvi._arg(bytes, signed)
  65. def _arg_slen(dvi, delta):
  66. """Signed, length *delta*
  67. Read *delta* bytes, returning None if *delta* is zero, and
  68. the bytes interpreted as a signed integer otherwise."""
  69. if delta == 0:
  70. return None
  71. return dvi._arg(delta, True)
  72. def _arg_slen1(dvi, delta):
  73. """Signed, length *delta*+1
  74. Read *delta*+1 bytes, returning the bytes interpreted as signed."""
  75. return dvi._arg(delta+1, True)
  76. def _arg_ulen1(dvi, delta):
  77. """Unsigned length *delta*+1
  78. Read *delta*+1 bytes, returning the bytes interpreted as unsigned."""
  79. return dvi._arg(delta+1, False)
  80. def _arg_olen1(dvi, delta):
  81. """Optionally signed, length *delta*+1
  82. Read *delta*+1 bytes, returning the bytes interpreted as
  83. unsigned integer for 0<=*delta*<3 and signed if *delta*==3."""
  84. return dvi._arg(delta + 1, delta == 3)
  85. _arg_mapping = dict(raw=_arg_raw,
  86. u1=partial(_arg, 1, False),
  87. u4=partial(_arg, 4, False),
  88. s4=partial(_arg, 4, True),
  89. slen=_arg_slen,
  90. olen1=_arg_olen1,
  91. slen1=_arg_slen1,
  92. ulen1=_arg_ulen1)
  93. def _dispatch(table, min, max=None, state=None, args=('raw',)):
  94. """Decorator for dispatch by opcode. Sets the values in *table*
  95. from *min* to *max* to this method, adds a check that the Dvi state
  96. matches *state* if not None, reads arguments from the file according
  97. to *args*.
  98. *table*
  99. the dispatch table to be filled in
  100. *min*
  101. minimum opcode for calling this function
  102. *max*
  103. maximum opcode for calling this function, None if only *min* is allowed
  104. *state*
  105. state of the Dvi object in which these opcodes are allowed
  106. *args*
  107. sequence of argument specifications:
  108. ``'raw'``: opcode minus minimum
  109. ``'u1'``: read one unsigned byte
  110. ``'u4'``: read four bytes, treat as an unsigned number
  111. ``'s4'``: read four bytes, treat as a signed number
  112. ``'slen'``: read (opcode - minimum) bytes, treat as signed
  113. ``'slen1'``: read (opcode - minimum + 1) bytes, treat as signed
  114. ``'ulen1'``: read (opcode - minimum + 1) bytes, treat as unsigned
  115. ``'olen1'``: read (opcode - minimum + 1) bytes, treat as unsigned
  116. if under four bytes, signed if four bytes
  117. """
  118. def decorate(method):
  119. get_args = [_arg_mapping[x] for x in args]
  120. @wraps(method)
  121. def wrapper(self, byte):
  122. if state is not None and self.state != state:
  123. raise ValueError("state precondition failed")
  124. return method(self, *[f(self, byte-min) for f in get_args])
  125. if max is None:
  126. table[min] = wrapper
  127. else:
  128. for i in range(min, max+1):
  129. assert table[i] is None
  130. table[i] = wrapper
  131. return wrapper
  132. return decorate
  133. class Dvi(object):
  134. """
  135. A reader for a dvi ("device-independent") file, as produced by TeX.
  136. The current implementation can only iterate through pages in order,
  137. and does not even attempt to verify the postamble.
  138. This class can be used as a context manager to close the underlying
  139. file upon exit. Pages can be read via iteration. Here is an overly
  140. simple way to extract text without trying to detect whitespace::
  141. >>> with matplotlib.dviread.Dvi('input.dvi', 72) as dvi:
  142. ... for page in dvi:
  143. ... print(''.join(chr(t.glyph) for t in page.text))
  144. """
  145. # dispatch table
  146. _dtable = [None] * 256
  147. _dispatch = partial(_dispatch, _dtable)
  148. def __init__(self, filename, dpi):
  149. """
  150. Read the data from the file named *filename* and convert
  151. TeX's internal units to units of *dpi* per inch.
  152. *dpi* only sets the units and does not limit the resolution.
  153. Use None to return TeX's internal units.
  154. """
  155. _log.debug('Dvi: %s', filename)
  156. self.file = open(filename, 'rb')
  157. self.dpi = dpi
  158. self.fonts = {}
  159. self.state = _dvistate.pre
  160. self.baseline = self._get_baseline(filename)
  161. def _get_baseline(self, filename):
  162. if rcParams['text.latex.preview']:
  163. base, ext = os.path.splitext(filename)
  164. baseline_filename = base + ".baseline"
  165. if os.path.exists(baseline_filename):
  166. with open(baseline_filename, 'rb') as fd:
  167. l = fd.read().split()
  168. height, depth, width = l
  169. return float(depth)
  170. return None
  171. def __enter__(self):
  172. """
  173. Context manager enter method, does nothing.
  174. """
  175. return self
  176. def __exit__(self, etype, evalue, etrace):
  177. """
  178. Context manager exit method, closes the underlying file if it is open.
  179. """
  180. self.close()
  181. def __iter__(self):
  182. """
  183. Iterate through the pages of the file.
  184. Yields
  185. ------
  186. Page
  187. Details of all the text and box objects on the page.
  188. The Page tuple contains lists of Text and Box tuples and
  189. the page dimensions, and the Text and Box tuples contain
  190. coordinates transformed into a standard Cartesian
  191. coordinate system at the dpi value given when initializing.
  192. The coordinates are floating point numbers, but otherwise
  193. precision is not lost and coordinate values are not clipped to
  194. integers.
  195. """
  196. while self._read():
  197. yield self._output()
  198. def close(self):
  199. """
  200. Close the underlying file if it is open.
  201. """
  202. if not self.file.closed:
  203. self.file.close()
  204. def _output(self):
  205. """
  206. Output the text and boxes belonging to the most recent page.
  207. page = dvi._output()
  208. """
  209. minx, miny, maxx, maxy = np.inf, np.inf, -np.inf, -np.inf
  210. maxy_pure = -np.inf
  211. for elt in self.text + self.boxes:
  212. if isinstance(elt, Box):
  213. x, y, h, w = elt
  214. e = 0 # zero depth
  215. else: # glyph
  216. x, y, font, g, w = elt
  217. h, e = font._height_depth_of(g)
  218. minx = min(minx, x)
  219. miny = min(miny, y - h)
  220. maxx = max(maxx, x + w)
  221. maxy = max(maxy, y + e)
  222. maxy_pure = max(maxy_pure, y)
  223. if self.dpi is None:
  224. # special case for ease of debugging: output raw dvi coordinates
  225. return Page(text=self.text, boxes=self.boxes,
  226. width=maxx-minx, height=maxy_pure-miny,
  227. descent=maxy-maxy_pure)
  228. # convert from TeX's "scaled points" to dpi units
  229. d = self.dpi / (72.27 * 2**16)
  230. if self.baseline is None:
  231. descent = (maxy - maxy_pure) * d
  232. else:
  233. descent = self.baseline
  234. text = [Text((x-minx)*d, (maxy-y)*d - descent, f, g, w*d)
  235. for (x, y, f, g, w) in self.text]
  236. boxes = [Box((x-minx)*d, (maxy-y)*d - descent, h*d, w*d)
  237. for (x, y, h, w) in self.boxes]
  238. return Page(text=text, boxes=boxes, width=(maxx-minx)*d,
  239. height=(maxy_pure-miny)*d, descent=descent)
  240. def _read(self):
  241. """
  242. Read one page from the file. Return True if successful,
  243. False if there were no more pages.
  244. """
  245. while True:
  246. byte = self.file.read(1)[0]
  247. self._dtable[byte](self, byte)
  248. if byte == 140: # end of page
  249. return True
  250. if self.state is _dvistate.post_post: # end of file
  251. self.close()
  252. return False
  253. def _arg(self, nbytes, signed=False):
  254. """
  255. Read and return an integer argument *nbytes* long.
  256. Signedness is determined by the *signed* keyword.
  257. """
  258. str = self.file.read(nbytes)
  259. value = str[0]
  260. if signed and value >= 0x80:
  261. value = value - 0x100
  262. for i in range(1, nbytes):
  263. value = 0x100*value + str[i]
  264. return value
  265. @_dispatch(min=0, max=127, state=_dvistate.inpage)
  266. def _set_char_immediate(self, char):
  267. self._put_char_real(char)
  268. self.h += self.fonts[self.f]._width_of(char)
  269. @_dispatch(min=128, max=131, state=_dvistate.inpage, args=('olen1',))
  270. def _set_char(self, char):
  271. self._put_char_real(char)
  272. self.h += self.fonts[self.f]._width_of(char)
  273. @_dispatch(132, state=_dvistate.inpage, args=('s4', 's4'))
  274. def _set_rule(self, a, b):
  275. self._put_rule_real(a, b)
  276. self.h += b
  277. @_dispatch(min=133, max=136, state=_dvistate.inpage, args=('olen1',))
  278. def _put_char(self, char):
  279. self._put_char_real(char)
  280. def _put_char_real(self, char):
  281. font = self.fonts[self.f]
  282. if font._vf is None:
  283. self.text.append(Text(self.h, self.v, font, char,
  284. font._width_of(char)))
  285. else:
  286. scale = font._scale
  287. for x, y, f, g, w in font._vf[char].text:
  288. newf = DviFont(scale=_mul2012(scale, f._scale),
  289. tfm=f._tfm, texname=f.texname, vf=f._vf)
  290. self.text.append(Text(self.h + _mul2012(x, scale),
  291. self.v + _mul2012(y, scale),
  292. newf, g, newf._width_of(g)))
  293. self.boxes.extend([Box(self.h + _mul2012(x, scale),
  294. self.v + _mul2012(y, scale),
  295. _mul2012(a, scale), _mul2012(b, scale))
  296. for x, y, a, b in font._vf[char].boxes])
  297. @_dispatch(137, state=_dvistate.inpage, args=('s4', 's4'))
  298. def _put_rule(self, a, b):
  299. self._put_rule_real(a, b)
  300. def _put_rule_real(self, a, b):
  301. if a > 0 and b > 0:
  302. self.boxes.append(Box(self.h, self.v, a, b))
  303. @_dispatch(138)
  304. def _nop(self, _):
  305. pass
  306. @_dispatch(139, state=_dvistate.outer, args=('s4',)*11)
  307. def _bop(self, c0, c1, c2, c3, c4, c5, c6, c7, c8, c9, p):
  308. self.state = _dvistate.inpage
  309. self.h, self.v, self.w, self.x, self.y, self.z = 0, 0, 0, 0, 0, 0
  310. self.stack = []
  311. self.text = [] # list of Text objects
  312. self.boxes = [] # list of Box objects
  313. @_dispatch(140, state=_dvistate.inpage)
  314. def _eop(self, _):
  315. self.state = _dvistate.outer
  316. del self.h, self.v, self.w, self.x, self.y, self.z, self.stack
  317. @_dispatch(141, state=_dvistate.inpage)
  318. def _push(self, _):
  319. self.stack.append((self.h, self.v, self.w, self.x, self.y, self.z))
  320. @_dispatch(142, state=_dvistate.inpage)
  321. def _pop(self, _):
  322. self.h, self.v, self.w, self.x, self.y, self.z = self.stack.pop()
  323. @_dispatch(min=143, max=146, state=_dvistate.inpage, args=('slen1',))
  324. def _right(self, b):
  325. self.h += b
  326. @_dispatch(min=147, max=151, state=_dvistate.inpage, args=('slen',))
  327. def _right_w(self, new_w):
  328. if new_w is not None:
  329. self.w = new_w
  330. self.h += self.w
  331. @_dispatch(min=152, max=156, state=_dvistate.inpage, args=('slen',))
  332. def _right_x(self, new_x):
  333. if new_x is not None:
  334. self.x = new_x
  335. self.h += self.x
  336. @_dispatch(min=157, max=160, state=_dvistate.inpage, args=('slen1',))
  337. def _down(self, a):
  338. self.v += a
  339. @_dispatch(min=161, max=165, state=_dvistate.inpage, args=('slen',))
  340. def _down_y(self, new_y):
  341. if new_y is not None:
  342. self.y = new_y
  343. self.v += self.y
  344. @_dispatch(min=166, max=170, state=_dvistate.inpage, args=('slen',))
  345. def _down_z(self, new_z):
  346. if new_z is not None:
  347. self.z = new_z
  348. self.v += self.z
  349. @_dispatch(min=171, max=234, state=_dvistate.inpage)
  350. def _fnt_num_immediate(self, k):
  351. self.f = k
  352. @_dispatch(min=235, max=238, state=_dvistate.inpage, args=('olen1',))
  353. def _fnt_num(self, new_f):
  354. self.f = new_f
  355. @_dispatch(min=239, max=242, args=('ulen1',))
  356. def _xxx(self, datalen):
  357. special = self.file.read(datalen)
  358. _log.debug(
  359. 'Dvi._xxx: encountered special: %s',
  360. ''.join([chr(ch) if 32 <= ch < 127 else '<%02x>' % ch
  361. for ch in special]))
  362. @_dispatch(min=243, max=246, args=('olen1', 'u4', 'u4', 'u4', 'u1', 'u1'))
  363. def _fnt_def(self, k, c, s, d, a, l):
  364. self._fnt_def_real(k, c, s, d, a, l)
  365. def _fnt_def_real(self, k, c, s, d, a, l):
  366. n = self.file.read(a + l)
  367. fontname = n[-l:].decode('ascii')
  368. tfm = _tfmfile(fontname)
  369. if tfm is None:
  370. raise FileNotFoundError("missing font metrics file: %s" % fontname)
  371. if c != 0 and tfm.checksum != 0 and c != tfm.checksum:
  372. raise ValueError('tfm checksum mismatch: %s' % n)
  373. vf = _vffile(fontname)
  374. self.fonts[k] = DviFont(scale=s, tfm=tfm, texname=n, vf=vf)
  375. @_dispatch(247, state=_dvistate.pre, args=('u1', 'u4', 'u4', 'u4', 'u1'))
  376. def _pre(self, i, num, den, mag, k):
  377. comment = self.file.read(k)
  378. if i != 2:
  379. raise ValueError("Unknown dvi format %d" % i)
  380. if num != 25400000 or den != 7227 * 2**16:
  381. raise ValueError("nonstandard units in dvi file")
  382. # meaning: TeX always uses those exact values, so it
  383. # should be enough for us to support those
  384. # (There are 72.27 pt to an inch so 7227 pt =
  385. # 7227 * 2**16 sp to 100 in. The numerator is multiplied
  386. # by 10^5 to get units of 10**-7 meters.)
  387. if mag != 1000:
  388. raise ValueError("nonstandard magnification in dvi file")
  389. # meaning: LaTeX seems to frown on setting \mag, so
  390. # I think we can assume this is constant
  391. self.state = _dvistate.outer
  392. @_dispatch(248, state=_dvistate.outer)
  393. def _post(self, _):
  394. self.state = _dvistate.post_post
  395. # TODO: actually read the postamble and finale?
  396. # currently post_post just triggers closing the file
  397. @_dispatch(249)
  398. def _post_post(self, _):
  399. raise NotImplementedError
  400. @_dispatch(min=250, max=255)
  401. def _malformed(self, offset):
  402. raise ValueError("unknown command: byte %d", 250 + offset)
  403. class DviFont(object):
  404. """
  405. Encapsulation of a font that a DVI file can refer to.
  406. This class holds a font's texname and size, supports comparison,
  407. and knows the widths of glyphs in the same units as the AFM file.
  408. There are also internal attributes (for use by dviread.py) that
  409. are *not* used for comparison.
  410. The size is in Adobe points (converted from TeX points).
  411. Parameters
  412. ----------
  413. scale : float
  414. Factor by which the font is scaled from its natural size.
  415. tfm : Tfm
  416. TeX font metrics for this font
  417. texname : bytes
  418. Name of the font as used internally by TeX and friends, as an
  419. ASCII bytestring. This is usually very different from any external
  420. font names, and :class:`dviread.PsfontsMap` can be used to find
  421. the external name of the font.
  422. vf : Vf
  423. A TeX "virtual font" file, or None if this font is not virtual.
  424. Attributes
  425. ----------
  426. texname : bytes
  427. size : float
  428. Size of the font in Adobe points, converted from the slightly
  429. smaller TeX points.
  430. widths : list
  431. Widths of glyphs in glyph-space units, typically 1/1000ths of
  432. the point size.
  433. """
  434. __slots__ = ('texname', 'size', 'widths', '_scale', '_vf', '_tfm')
  435. def __init__(self, scale, tfm, texname, vf):
  436. if not isinstance(texname, bytes):
  437. raise ValueError("texname must be a bytestring, got %s"
  438. % type(texname))
  439. self._scale, self._tfm, self.texname, self._vf = \
  440. scale, tfm, texname, vf
  441. self.size = scale * (72.0 / (72.27 * 2**16))
  442. try:
  443. nchars = max(tfm.width) + 1
  444. except ValueError:
  445. nchars = 0
  446. self.widths = [(1000*tfm.width.get(char, 0)) >> 20
  447. for char in range(nchars)]
  448. def __eq__(self, other):
  449. return self.__class__ == other.__class__ and \
  450. self.texname == other.texname and self.size == other.size
  451. def __ne__(self, other):
  452. return not self.__eq__(other)
  453. def _width_of(self, char):
  454. """
  455. Width of char in dvi units. For internal use by dviread.py.
  456. """
  457. width = self._tfm.width.get(char, None)
  458. if width is not None:
  459. return _mul2012(width, self._scale)
  460. _log.debug('No width for char %d in font %s.', char, self.texname)
  461. return 0
  462. def _height_depth_of(self, char):
  463. """
  464. Height and depth of char in dvi units. For internal use by dviread.py.
  465. """
  466. result = []
  467. for metric, name in ((self._tfm.height, "height"),
  468. (self._tfm.depth, "depth")):
  469. value = metric.get(char, None)
  470. if value is None:
  471. _log.debug('No %s for char %d in font %s',
  472. name, char, self.texname)
  473. result.append(0)
  474. else:
  475. result.append(_mul2012(value, self._scale))
  476. return result
  477. class Vf(Dvi):
  478. """
  479. A virtual font (\\*.vf file) containing subroutines for dvi files.
  480. Usage::
  481. vf = Vf(filename)
  482. glyph = vf[code]
  483. glyph.text, glyph.boxes, glyph.width
  484. Parameters
  485. ----------
  486. filename : string or bytestring
  487. Notes
  488. -----
  489. The virtual font format is a derivative of dvi:
  490. http://mirrors.ctan.org/info/knuth/virtual-fonts
  491. This class reuses some of the machinery of `Dvi`
  492. but replaces the `_read` loop and dispatch mechanism.
  493. """
  494. def __init__(self, filename):
  495. Dvi.__init__(self, filename, 0)
  496. try:
  497. self._first_font = None
  498. self._chars = {}
  499. self._read()
  500. finally:
  501. self.close()
  502. def __getitem__(self, code):
  503. return self._chars[code]
  504. def _read(self):
  505. """
  506. Read one page from the file. Return True if successful,
  507. False if there were no more pages.
  508. """
  509. packet_char, packet_ends = None, None
  510. packet_len, packet_width = None, None
  511. while True:
  512. byte = self.file.read(1)[0]
  513. # If we are in a packet, execute the dvi instructions
  514. if self.state is _dvistate.inpage:
  515. byte_at = self.file.tell()-1
  516. if byte_at == packet_ends:
  517. self._finalize_packet(packet_char, packet_width)
  518. packet_len, packet_char, packet_width = None, None, None
  519. # fall through to out-of-packet code
  520. elif byte_at > packet_ends:
  521. raise ValueError("Packet length mismatch in vf file")
  522. else:
  523. if byte in (139, 140) or byte >= 243:
  524. raise ValueError(
  525. "Inappropriate opcode %d in vf file" % byte)
  526. Dvi._dtable[byte](self, byte)
  527. continue
  528. # We are outside a packet
  529. if byte < 242: # a short packet (length given by byte)
  530. packet_len = byte
  531. packet_char, packet_width = self._arg(1), self._arg(3)
  532. packet_ends = self._init_packet(byte)
  533. self.state = _dvistate.inpage
  534. elif byte == 242: # a long packet
  535. packet_len, packet_char, packet_width = \
  536. [self._arg(x) for x in (4, 4, 4)]
  537. self._init_packet(packet_len)
  538. elif 243 <= byte <= 246:
  539. k = self._arg(byte - 242, byte == 246)
  540. c, s, d, a, l = [self._arg(x) for x in (4, 4, 4, 1, 1)]
  541. self._fnt_def_real(k, c, s, d, a, l)
  542. if self._first_font is None:
  543. self._first_font = k
  544. elif byte == 247: # preamble
  545. i, k = self._arg(1), self._arg(1)
  546. x = self.file.read(k)
  547. cs, ds = self._arg(4), self._arg(4)
  548. self._pre(i, x, cs, ds)
  549. elif byte == 248: # postamble (just some number of 248s)
  550. break
  551. else:
  552. raise ValueError("unknown vf opcode %d" % byte)
  553. def _init_packet(self, pl):
  554. if self.state != _dvistate.outer:
  555. raise ValueError("Misplaced packet in vf file")
  556. self.h, self.v, self.w, self.x, self.y, self.z = 0, 0, 0, 0, 0, 0
  557. self.stack, self.text, self.boxes = [], [], []
  558. self.f = self._first_font
  559. return self.file.tell() + pl
  560. def _finalize_packet(self, packet_char, packet_width):
  561. self._chars[packet_char] = Page(
  562. text=self.text, boxes=self.boxes, width=packet_width,
  563. height=None, descent=None)
  564. self.state = _dvistate.outer
  565. def _pre(self, i, x, cs, ds):
  566. if self.state is not _dvistate.pre:
  567. raise ValueError("pre command in middle of vf file")
  568. if i != 202:
  569. raise ValueError("Unknown vf format %d" % i)
  570. if len(x):
  571. _log.debug('vf file comment: %s', x)
  572. self.state = _dvistate.outer
  573. # cs = checksum, ds = design size
  574. def _fix2comp(num):
  575. """
  576. Convert from two's complement to negative.
  577. """
  578. assert 0 <= num < 2**32
  579. if num & 2**31:
  580. return num - 2**32
  581. else:
  582. return num
  583. def _mul2012(num1, num2):
  584. """
  585. Multiply two numbers in 20.12 fixed point format.
  586. """
  587. # Separated into a function because >> has surprising precedence
  588. return (num1*num2) >> 20
  589. class Tfm(object):
  590. """
  591. A TeX Font Metric file.
  592. This implementation covers only the bare minimum needed by the Dvi class.
  593. Parameters
  594. ----------
  595. filename : string or bytestring
  596. Attributes
  597. ----------
  598. checksum : int
  599. Used for verifying against the dvi file.
  600. design_size : int
  601. Design size of the font (unknown units)
  602. width, height, depth : dict
  603. Dimensions of each character, need to be scaled by the factor
  604. specified in the dvi file. These are dicts because indexing may
  605. not start from 0.
  606. """
  607. __slots__ = ('checksum', 'design_size', 'width', 'height', 'depth')
  608. def __init__(self, filename):
  609. _log.debug('opening tfm file %s', filename)
  610. with open(filename, 'rb') as file:
  611. header1 = file.read(24)
  612. lh, bc, ec, nw, nh, nd = \
  613. struct.unpack('!6H', header1[2:14])
  614. _log.debug('lh=%d, bc=%d, ec=%d, nw=%d, nh=%d, nd=%d',
  615. lh, bc, ec, nw, nh, nd)
  616. header2 = file.read(4*lh)
  617. self.checksum, self.design_size = \
  618. struct.unpack('!2I', header2[:8])
  619. # there is also encoding information etc.
  620. char_info = file.read(4*(ec-bc+1))
  621. widths = file.read(4*nw)
  622. heights = file.read(4*nh)
  623. depths = file.read(4*nd)
  624. self.width, self.height, self.depth = {}, {}, {}
  625. widths, heights, depths = \
  626. [struct.unpack('!%dI' % (len(x)/4), x)
  627. for x in (widths, heights, depths)]
  628. for idx, char in enumerate(range(bc, ec+1)):
  629. byte0 = char_info[4*idx]
  630. byte1 = char_info[4*idx+1]
  631. self.width[char] = _fix2comp(widths[byte0])
  632. self.height[char] = _fix2comp(heights[byte1 >> 4])
  633. self.depth[char] = _fix2comp(depths[byte1 & 0xf])
  634. PsFont = namedtuple('Font', 'texname psname effects encoding filename')
  635. class PsfontsMap(object):
  636. """
  637. A psfonts.map formatted file, mapping TeX fonts to PS fonts.
  638. Usage::
  639. >>> map = PsfontsMap(find_tex_file('pdftex.map'))
  640. >>> entry = map[b'ptmbo8r']
  641. >>> entry.texname
  642. b'ptmbo8r'
  643. >>> entry.psname
  644. b'Times-Bold'
  645. >>> entry.encoding
  646. '/usr/local/texlive/2008/texmf-dist/fonts/enc/dvips/base/8r.enc'
  647. >>> entry.effects
  648. {'slant': 0.16700000000000001}
  649. >>> entry.filename
  650. Parameters
  651. ----------
  652. filename : string or bytestring
  653. Notes
  654. -----
  655. For historical reasons, TeX knows many Type-1 fonts by different
  656. names than the outside world. (For one thing, the names have to
  657. fit in eight characters.) Also, TeX's native fonts are not Type-1
  658. but Metafont, which is nontrivial to convert to PostScript except
  659. as a bitmap. While high-quality conversions to Type-1 format exist
  660. and are shipped with modern TeX distributions, we need to know
  661. which Type-1 fonts are the counterparts of which native fonts. For
  662. these reasons a mapping is needed from internal font names to font
  663. file names.
  664. A texmf tree typically includes mapping files called e.g.
  665. :file:`psfonts.map`, :file:`pdftex.map`, or :file:`dvipdfm.map`.
  666. The file :file:`psfonts.map` is used by :program:`dvips`,
  667. :file:`pdftex.map` by :program:`pdfTeX`, and :file:`dvipdfm.map`
  668. by :program:`dvipdfm`. :file:`psfonts.map` might avoid embedding
  669. the 35 PostScript fonts (i.e., have no filename for them, as in
  670. the Times-Bold example above), while the pdf-related files perhaps
  671. only avoid the "Base 14" pdf fonts. But the user may have
  672. configured these files differently.
  673. """
  674. __slots__ = ('_font', '_filename')
  675. # Create a filename -> PsfontsMap cache, so that calling
  676. # `PsfontsMap(filename)` with the same filename a second time immediately
  677. # returns the same object.
  678. @lru_cache()
  679. def __new__(cls, filename):
  680. self = object.__new__(cls)
  681. self._font = {}
  682. self._filename = os.fsdecode(filename)
  683. with open(filename, 'rb') as file:
  684. self._parse(file)
  685. return self
  686. def __getitem__(self, texname):
  687. assert isinstance(texname, bytes)
  688. try:
  689. result = self._font[texname]
  690. except KeyError:
  691. fmt = ('A PostScript file for the font whose TeX name is "{0}" '
  692. 'could not be found in the file "{1}". The dviread module '
  693. 'can only handle fonts that have an associated PostScript '
  694. 'font file. '
  695. 'This problem can often be solved by installing '
  696. 'a suitable PostScript font package in your (TeX) '
  697. 'package manager.')
  698. msg = fmt.format(texname.decode('ascii'), self._filename)
  699. msg = textwrap.fill(msg, break_on_hyphens=False,
  700. break_long_words=False)
  701. _log.info(msg)
  702. raise
  703. fn, enc = result.filename, result.encoding
  704. if fn is not None and not fn.startswith(b'/'):
  705. fn = find_tex_file(fn)
  706. if enc is not None and not enc.startswith(b'/'):
  707. enc = find_tex_file(result.encoding)
  708. return result._replace(filename=fn, encoding=enc)
  709. def _parse(self, file):
  710. """
  711. Parse the font mapping file.
  712. The format is, AFAIK: texname fontname [effects and filenames]
  713. Effects are PostScript snippets like ".177 SlantFont",
  714. filenames begin with one or two less-than signs. A filename
  715. ending in enc is an encoding file, other filenames are font
  716. files. This can be overridden with a left bracket: <[foobar
  717. indicates an encoding file named foobar.
  718. There is some difference between <foo.pfb and <<bar.pfb in
  719. subsetting, but I have no example of << in my TeX installation.
  720. """
  721. # If the map file specifies multiple encodings for a font, we
  722. # follow pdfTeX in choosing the last one specified. Such
  723. # entries are probably mistakes but they have occurred.
  724. # http://tex.stackexchange.com/questions/10826/
  725. # http://article.gmane.org/gmane.comp.tex.pdftex/4914
  726. empty_re = re.compile(br'%|\s*$')
  727. word_re = re.compile(
  728. br'''(?x) (?:
  729. "<\[ (?P<enc1> [^"]+ )" | # quoted encoding marked by [
  730. "< (?P<enc2> [^"]+.enc)" | # quoted encoding, ends in .enc
  731. "<<? (?P<file1> [^"]+ )" | # quoted font file name
  732. " (?P<eff1> [^"]+ )" | # quoted effects or font name
  733. <\[ (?P<enc3> \S+ ) | # encoding marked by [
  734. < (?P<enc4> \S+ .enc) | # encoding, ends in .enc
  735. <<? (?P<file2> \S+ ) | # font file name
  736. (?P<eff2> \S+ ) # effects or font name
  737. )''')
  738. effects_re = re.compile(
  739. br'''(?x) (?P<slant> -?[0-9]*(?:\.[0-9]+)) \s* SlantFont
  740. | (?P<extend>-?[0-9]*(?:\.[0-9]+)) \s* ExtendFont''')
  741. lines = (line.strip()
  742. for line in file
  743. if not empty_re.match(line))
  744. for line in lines:
  745. effects, encoding, filename = b'', None, None
  746. words = word_re.finditer(line)
  747. # The named groups are mutually exclusive and are
  748. # referenced below at an estimated order of probability of
  749. # occurrence based on looking at my copy of pdftex.map.
  750. # The font names are probably unquoted:
  751. w = next(words)
  752. texname = w.group('eff2') or w.group('eff1')
  753. w = next(words)
  754. psname = w.group('eff2') or w.group('eff1')
  755. for w in words:
  756. # Any effects are almost always quoted:
  757. eff = w.group('eff1') or w.group('eff2')
  758. if eff:
  759. effects = eff
  760. continue
  761. # Encoding files usually have the .enc suffix
  762. # and almost never need quoting:
  763. enc = (w.group('enc4') or w.group('enc3') or
  764. w.group('enc2') or w.group('enc1'))
  765. if enc:
  766. if encoding is not None:
  767. _log.debug('Multiple encodings for %s = %s',
  768. texname, psname)
  769. encoding = enc
  770. continue
  771. # File names are probably unquoted:
  772. filename = w.group('file2') or w.group('file1')
  773. effects_dict = {}
  774. for match in effects_re.finditer(effects):
  775. slant = match.group('slant')
  776. if slant:
  777. effects_dict['slant'] = float(slant)
  778. else:
  779. effects_dict['extend'] = float(match.group('extend'))
  780. self._font[texname] = PsFont(
  781. texname=texname, psname=psname, effects=effects_dict,
  782. encoding=encoding, filename=filename)
  783. class Encoding(object):
  784. """
  785. Parses a \\*.enc file referenced from a psfonts.map style file.
  786. The format this class understands is a very limited subset of
  787. PostScript.
  788. Usage (subject to change)::
  789. for name in Encoding(filename):
  790. whatever(name)
  791. Parameters
  792. ----------
  793. filename : string or bytestring
  794. Attributes
  795. ----------
  796. encoding : list
  797. List of character names
  798. """
  799. __slots__ = ('encoding',)
  800. def __init__(self, filename):
  801. with open(filename, 'rb') as file:
  802. _log.debug('Parsing TeX encoding %s', filename)
  803. self.encoding = self._parse(file)
  804. _log.debug('Result: %s', self.encoding)
  805. def __iter__(self):
  806. yield from self.encoding
  807. @staticmethod
  808. def _parse(file):
  809. result = []
  810. lines = (line.split(b'%', 1)[0].strip() for line in file)
  811. data = b''.join(lines)
  812. beginning = data.find(b'[')
  813. if beginning < 0:
  814. raise ValueError("Cannot locate beginning of encoding in {}"
  815. .format(file))
  816. data = data[beginning:]
  817. end = data.find(b']')
  818. if end < 0:
  819. raise ValueError("Cannot locate end of encoding in {}"
  820. .format(file))
  821. data = data[:end]
  822. return re.findall(br'/([^][{}<>\s]+)', data)
  823. @lru_cache()
  824. def find_tex_file(filename, format=None):
  825. """
  826. Find a file in the texmf tree.
  827. Calls :program:`kpsewhich` which is an interface to the kpathsea
  828. library [1]_. Most existing TeX distributions on Unix-like systems use
  829. kpathsea. It is also available as part of MikTeX, a popular
  830. distribution on Windows.
  831. Parameters
  832. ----------
  833. filename : string or bytestring
  834. format : string or bytestring
  835. Used as the value of the `--format` option to :program:`kpsewhich`.
  836. Could be e.g. 'tfm' or 'vf' to limit the search to that type of files.
  837. References
  838. ----------
  839. .. [1] `Kpathsea documentation <http://www.tug.org/kpathsea/>`_
  840. The library that :program:`kpsewhich` is part of.
  841. """
  842. # we expect these to always be ascii encoded, but use utf-8
  843. # out of caution
  844. if isinstance(filename, bytes):
  845. filename = filename.decode('utf-8', errors='replace')
  846. if isinstance(format, bytes):
  847. format = format.decode('utf-8', errors='replace')
  848. cmd = ['kpsewhich']
  849. if format is not None:
  850. cmd += ['--format=' + format]
  851. cmd += [filename]
  852. _log.debug('find_tex_file(%s): %s', filename, cmd)
  853. pipe = subprocess.Popen(cmd, stdout=subprocess.PIPE)
  854. result = pipe.communicate()[0].rstrip()
  855. _log.debug('find_tex_file result: %s', result)
  856. return result.decode('ascii')
  857. @lru_cache()
  858. def _fontfile(cls, suffix, texname):
  859. filename = find_tex_file(texname + suffix)
  860. return cls(filename) if filename else None
  861. _tfmfile = partial(_fontfile, Tfm, ".tfm")
  862. _vffile = partial(_fontfile, Vf, ".vf")
  863. if __name__ == '__main__':
  864. import sys
  865. fname = sys.argv[1]
  866. try:
  867. dpi = float(sys.argv[2])
  868. except IndexError:
  869. dpi = None
  870. with Dvi(fname, dpi) as dvi:
  871. fontmap = PsfontsMap(find_tex_file('pdftex.map'))
  872. for page in dvi:
  873. print('=== new page ===')
  874. fPrev = None
  875. for x, y, f, c, w in page.text:
  876. if f != fPrev:
  877. print('font', f.texname, 'scaled', f._scale/pow(2.0, 20))
  878. fPrev = f
  879. print(x, y, c, 32 <= c < 128 and chr(c) or '.', w)
  880. for x, y, w, h in page.boxes:
  881. print(x, y, 'BOX', w, h)