dviread.py 42 KB

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