dviread.py 41 KB

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