dviread.py 38 KB

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