backend_ps.py 46 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348
  1. """
  2. A PostScript backend, which can produce both PostScript .ps and .eps.
  3. """
  4. import datetime
  5. from enum import Enum
  6. import glob
  7. from io import StringIO, TextIOWrapper
  8. import logging
  9. import math
  10. import os
  11. import pathlib
  12. import re
  13. import shutil
  14. from tempfile import TemporaryDirectory
  15. import time
  16. import numpy as np
  17. import matplotlib as mpl
  18. from matplotlib import cbook, _path
  19. from matplotlib import _text_layout
  20. from matplotlib.backend_bases import (
  21. _Backend, _check_savefig_extra_args, FigureCanvasBase, FigureManagerBase,
  22. GraphicsContextBase, RendererBase)
  23. from matplotlib.cbook import is_writable_file_like, file_requires_unicode
  24. from matplotlib.font_manager import is_opentype_cff_font, get_font
  25. from matplotlib.ft2font import LOAD_NO_HINTING
  26. from matplotlib._ttconv import convert_ttf_to_ps
  27. from matplotlib.mathtext import MathTextParser
  28. from matplotlib._mathtext_data import uni2type1
  29. from matplotlib.path import Path
  30. from matplotlib.texmanager import TexManager
  31. from matplotlib.transforms import Affine2D
  32. from matplotlib.backends.backend_mixed import MixedModeRenderer
  33. from . import _backend_pdf_ps
  34. _log = logging.getLogger(__name__)
  35. backend_version = 'Level II'
  36. debugPS = 0
  37. class PsBackendHelper:
  38. def __init__(self):
  39. self._cached = {}
  40. ps_backend_helper = PsBackendHelper()
  41. papersize = {'letter': (8.5, 11),
  42. 'legal': (8.5, 14),
  43. 'ledger': (11, 17),
  44. 'a0': (33.11, 46.81),
  45. 'a1': (23.39, 33.11),
  46. 'a2': (16.54, 23.39),
  47. 'a3': (11.69, 16.54),
  48. 'a4': (8.27, 11.69),
  49. 'a5': (5.83, 8.27),
  50. 'a6': (4.13, 5.83),
  51. 'a7': (2.91, 4.13),
  52. 'a8': (2.07, 2.91),
  53. 'a9': (1.457, 2.05),
  54. 'a10': (1.02, 1.457),
  55. 'b0': (40.55, 57.32),
  56. 'b1': (28.66, 40.55),
  57. 'b2': (20.27, 28.66),
  58. 'b3': (14.33, 20.27),
  59. 'b4': (10.11, 14.33),
  60. 'b5': (7.16, 10.11),
  61. 'b6': (5.04, 7.16),
  62. 'b7': (3.58, 5.04),
  63. 'b8': (2.51, 3.58),
  64. 'b9': (1.76, 2.51),
  65. 'b10': (1.26, 1.76)}
  66. def _get_papertype(w, h):
  67. for key, (pw, ph) in sorted(papersize.items(), reverse=True):
  68. if key.startswith('l'):
  69. continue
  70. if w < pw and h < ph:
  71. return key
  72. return 'a0'
  73. def _num_to_str(val):
  74. if isinstance(val, str):
  75. return val
  76. ival = int(val)
  77. if val == ival:
  78. return str(ival)
  79. s = "%1.3f" % val
  80. s = s.rstrip("0")
  81. s = s.rstrip(".")
  82. return s
  83. def _nums_to_str(*args):
  84. return ' '.join(map(_num_to_str, args))
  85. def quote_ps_string(s):
  86. """
  87. Quote dangerous characters of S for use in a PostScript string constant.
  88. """
  89. s = s.replace(b"\\", b"\\\\")
  90. s = s.replace(b"(", b"\\(")
  91. s = s.replace(b")", b"\\)")
  92. s = s.replace(b"'", b"\\251")
  93. s = s.replace(b"`", b"\\301")
  94. s = re.sub(br"[^ -~\n]", lambda x: br"\%03o" % ord(x.group()), s)
  95. return s.decode('ascii')
  96. def _move_path_to_path_or_stream(src, dst):
  97. """
  98. Move the contents of file at *src* to path-or-filelike *dst*.
  99. If *dst* is a path, the metadata of *src* are *not* copied.
  100. """
  101. if is_writable_file_like(dst):
  102. fh = (open(src, 'r', encoding='latin-1')
  103. if file_requires_unicode(dst)
  104. else open(src, 'rb'))
  105. with fh:
  106. shutil.copyfileobj(fh, dst)
  107. else:
  108. shutil.move(src, dst, copy_function=shutil.copyfile)
  109. class RendererPS(_backend_pdf_ps.RendererPDFPSBase):
  110. """
  111. The renderer handles all the drawing primitives using a graphics
  112. context instance that controls the colors/styles.
  113. """
  114. _afm_font_dir = cbook._get_data_path("fonts/afm")
  115. _use_afm_rc_name = "ps.useafm"
  116. def __init__(self, width, height, pswriter, imagedpi=72):
  117. # Although postscript itself is dpi independent, we need to inform the
  118. # image code about a requested dpi to generate high resolution images
  119. # and them scale them before embedding them.
  120. super().__init__(width, height)
  121. self._pswriter = pswriter
  122. if mpl.rcParams['text.usetex']:
  123. self.textcnt = 0
  124. self.psfrag = []
  125. self.imagedpi = imagedpi
  126. # current renderer state (None=uninitialised)
  127. self.color = None
  128. self.linewidth = None
  129. self.linejoin = None
  130. self.linecap = None
  131. self.linedash = None
  132. self.fontname = None
  133. self.fontsize = None
  134. self._hatches = {}
  135. self.image_magnification = imagedpi / 72
  136. self._clip_paths = {}
  137. self._path_collection_id = 0
  138. self._character_tracker = _backend_pdf_ps.CharacterTracker()
  139. self.mathtext_parser = MathTextParser("PS")
  140. @cbook.deprecated("3.3")
  141. @property
  142. def used_characters(self):
  143. return self._character_tracker.used_characters
  144. @cbook.deprecated("3.3")
  145. def track_characters(self, *args, **kwargs):
  146. """Keep track of which characters are required from each font."""
  147. self._character_tracker.track(*args, **kwargs)
  148. @cbook.deprecated("3.3")
  149. def merge_used_characters(self, *args, **kwargs):
  150. self._character_tracker.merge(*args, **kwargs)
  151. def set_color(self, r, g, b, store=True):
  152. if (r, g, b) != self.color:
  153. if r == g and r == b:
  154. self._pswriter.write("%1.3f setgray\n" % r)
  155. else:
  156. self._pswriter.write(
  157. "%1.3f %1.3f %1.3f setrgbcolor\n" % (r, g, b))
  158. if store:
  159. self.color = (r, g, b)
  160. def set_linewidth(self, linewidth, store=True):
  161. linewidth = float(linewidth)
  162. if linewidth != self.linewidth:
  163. self._pswriter.write("%1.3f setlinewidth\n" % linewidth)
  164. if store:
  165. self.linewidth = linewidth
  166. def set_linejoin(self, linejoin, store=True):
  167. if linejoin != self.linejoin:
  168. self._pswriter.write("%d setlinejoin\n" % linejoin)
  169. if store:
  170. self.linejoin = linejoin
  171. def set_linecap(self, linecap, store=True):
  172. if linecap != self.linecap:
  173. self._pswriter.write("%d setlinecap\n" % linecap)
  174. if store:
  175. self.linecap = linecap
  176. def set_linedash(self, offset, seq, store=True):
  177. if self.linedash is not None:
  178. oldo, oldseq = self.linedash
  179. if np.array_equal(seq, oldseq) and oldo == offset:
  180. return
  181. if seq is not None and len(seq):
  182. s = "[%s] %d setdash\n" % (_nums_to_str(*seq), offset)
  183. self._pswriter.write(s)
  184. else:
  185. self._pswriter.write("[] 0 setdash\n")
  186. if store:
  187. self.linedash = (offset, seq)
  188. def set_font(self, fontname, fontsize, store=True):
  189. if mpl.rcParams['ps.useafm']:
  190. return
  191. if (fontname, fontsize) != (self.fontname, self.fontsize):
  192. out = ("/%s findfont\n"
  193. "%1.3f scalefont\n"
  194. "setfont\n" % (fontname, fontsize))
  195. self._pswriter.write(out)
  196. if store:
  197. self.fontname = fontname
  198. self.fontsize = fontsize
  199. def create_hatch(self, hatch):
  200. sidelen = 72
  201. if hatch in self._hatches:
  202. return self._hatches[hatch]
  203. name = 'H%d' % len(self._hatches)
  204. linewidth = mpl.rcParams['hatch.linewidth']
  205. pageheight = self.height * 72
  206. self._pswriter.write(f"""\
  207. << /PatternType 1
  208. /PaintType 2
  209. /TilingType 2
  210. /BBox[0 0 {sidelen:d} {sidelen:d}]
  211. /XStep {sidelen:d}
  212. /YStep {sidelen:d}
  213. /PaintProc {{
  214. pop
  215. {linewidth:f} setlinewidth
  216. {self._convert_path(
  217. Path.hatch(hatch), Affine2D().scale(sidelen), simplify=False)}
  218. gsave
  219. fill
  220. grestore
  221. stroke
  222. }} bind
  223. >>
  224. matrix
  225. 0.0 {pageheight:f} translate
  226. makepattern
  227. /{name} exch def
  228. """)
  229. self._hatches[hatch] = name
  230. return name
  231. def get_image_magnification(self):
  232. """
  233. Get the factor by which to magnify images passed to draw_image.
  234. Allows a backend to have images at a different resolution to other
  235. artists.
  236. """
  237. return self.image_magnification
  238. def draw_image(self, gc, x, y, im, transform=None):
  239. # docstring inherited
  240. h, w = im.shape[:2]
  241. imagecmd = "false 3 colorimage"
  242. data = im[::-1, :, :3] # Vertically flipped rgb values.
  243. # data.tobytes().hex() has no spaces, so can be linewrapped by simply
  244. # splitting data every nchars. It's equivalent to textwrap.fill only
  245. # much faster.
  246. nchars = 128
  247. data = data.tobytes().hex()
  248. hexlines = "\n".join(
  249. [
  250. data[n * nchars:(n + 1) * nchars]
  251. for n in range(math.ceil(len(data) / nchars))
  252. ]
  253. )
  254. if transform is None:
  255. matrix = "1 0 0 1 0 0"
  256. xscale = w / self.image_magnification
  257. yscale = h / self.image_magnification
  258. else:
  259. matrix = " ".join(map(str, transform.frozen().to_values()))
  260. xscale = 1.0
  261. yscale = 1.0
  262. bbox = gc.get_clip_rectangle()
  263. clippath, clippath_trans = gc.get_clip_path()
  264. clip = []
  265. if bbox is not None:
  266. clip.append('%s clipbox' % _nums_to_str(*bbox.size, *bbox.p0))
  267. if clippath is not None:
  268. id = self._get_clip_path(clippath, clippath_trans)
  269. clip.append('%s' % id)
  270. clip = '\n'.join(clip)
  271. self._pswriter.write(f"""\
  272. gsave
  273. {clip}
  274. {x:f} {y:f} translate
  275. [{matrix}] concat
  276. {xscale:f} {yscale:f} scale
  277. /DataString {w:d} string def
  278. {w:d} {h:d} 8 [ {w:d} 0 0 -{h:d} 0 {h:d} ]
  279. {{
  280. currentfile DataString readhexstring pop
  281. }} bind {imagecmd}
  282. {hexlines}
  283. grestore
  284. """)
  285. def _convert_path(self, path, transform, clip=False, simplify=None):
  286. if clip:
  287. clip = (0.0, 0.0, self.width * 72.0, self.height * 72.0)
  288. else:
  289. clip = None
  290. return _path.convert_to_string(
  291. path, transform, clip, simplify, None,
  292. 6, [b'm', b'l', b'', b'c', b'cl'], True).decode('ascii')
  293. def _get_clip_path(self, clippath, clippath_transform):
  294. key = (clippath, id(clippath_transform))
  295. pid = self._clip_paths.get(key)
  296. if pid is None:
  297. pid = 'c%x' % len(self._clip_paths)
  298. clippath_bytes = self._convert_path(
  299. clippath, clippath_transform, simplify=False)
  300. self._pswriter.write(f"""\
  301. /{pid} {{
  302. {clippath_bytes}
  303. clip
  304. newpath
  305. }} bind def
  306. """)
  307. self._clip_paths[key] = pid
  308. return pid
  309. def draw_path(self, gc, path, transform, rgbFace=None):
  310. # docstring inherited
  311. clip = rgbFace is None and gc.get_hatch_path() is None
  312. simplify = path.should_simplify and clip
  313. ps = self._convert_path(path, transform, clip=clip, simplify=simplify)
  314. self._draw_ps(ps, gc, rgbFace)
  315. def draw_markers(
  316. self, gc, marker_path, marker_trans, path, trans, rgbFace=None):
  317. # docstring inherited
  318. if debugPS:
  319. self._pswriter.write('% draw_markers \n')
  320. ps_color = (
  321. None
  322. if _is_transparent(rgbFace)
  323. else '%1.3f setgray' % rgbFace[0]
  324. if rgbFace[0] == rgbFace[1] == rgbFace[2]
  325. else '%1.3f %1.3f %1.3f setrgbcolor' % rgbFace[:3])
  326. # construct the generic marker command:
  327. # don't want the translate to be global
  328. ps_cmd = ['/o {', 'gsave', 'newpath', 'translate']
  329. lw = gc.get_linewidth()
  330. alpha = (gc.get_alpha()
  331. if gc.get_forced_alpha() or len(gc.get_rgb()) == 3
  332. else gc.get_rgb()[3])
  333. stroke = lw > 0 and alpha > 0
  334. if stroke:
  335. ps_cmd.append('%.1f setlinewidth' % lw)
  336. jint = gc.get_joinstyle()
  337. ps_cmd.append('%d setlinejoin' % jint)
  338. cint = gc.get_capstyle()
  339. ps_cmd.append('%d setlinecap' % cint)
  340. ps_cmd.append(self._convert_path(marker_path, marker_trans,
  341. simplify=False))
  342. if rgbFace:
  343. if stroke:
  344. ps_cmd.append('gsave')
  345. if ps_color:
  346. ps_cmd.extend([ps_color, 'fill'])
  347. if stroke:
  348. ps_cmd.append('grestore')
  349. if stroke:
  350. ps_cmd.append('stroke')
  351. ps_cmd.extend(['grestore', '} bind def'])
  352. for vertices, code in path.iter_segments(
  353. trans,
  354. clip=(0, 0, self.width*72, self.height*72),
  355. simplify=False):
  356. if len(vertices):
  357. x, y = vertices[-2:]
  358. ps_cmd.append("%g %g o" % (x, y))
  359. ps = '\n'.join(ps_cmd)
  360. self._draw_ps(ps, gc, rgbFace, fill=False, stroke=False)
  361. def draw_path_collection(self, gc, master_transform, paths, all_transforms,
  362. offsets, offsetTrans, facecolors, edgecolors,
  363. linewidths, linestyles, antialiaseds, urls,
  364. offset_position):
  365. # Is the optimization worth it? Rough calculation:
  366. # cost of emitting a path in-line is
  367. # (len_path + 2) * uses_per_path
  368. # cost of definition+use is
  369. # (len_path + 3) + 3 * uses_per_path
  370. len_path = len(paths[0].vertices) if len(paths) > 0 else 0
  371. uses_per_path = self._iter_collection_uses_per_path(
  372. paths, all_transforms, offsets, facecolors, edgecolors)
  373. should_do_optimization = \
  374. len_path + 3 * uses_per_path + 3 < (len_path + 2) * uses_per_path
  375. if not should_do_optimization:
  376. return RendererBase.draw_path_collection(
  377. self, gc, master_transform, paths, all_transforms,
  378. offsets, offsetTrans, facecolors, edgecolors,
  379. linewidths, linestyles, antialiaseds, urls,
  380. offset_position)
  381. path_codes = []
  382. for i, (path, transform) in enumerate(self._iter_collection_raw_paths(
  383. master_transform, paths, all_transforms)):
  384. name = 'p%x_%x' % (self._path_collection_id, i)
  385. path_bytes = self._convert_path(path, transform, simplify=False)
  386. self._pswriter.write(f"""\
  387. /{name} {{
  388. newpath
  389. translate
  390. {path_bytes}
  391. }} bind def
  392. """)
  393. path_codes.append(name)
  394. for xo, yo, path_id, gc0, rgbFace in self._iter_collection(
  395. gc, master_transform, all_transforms, path_codes, offsets,
  396. offsetTrans, facecolors, edgecolors, linewidths, linestyles,
  397. antialiaseds, urls, offset_position):
  398. ps = "%g %g %s" % (xo, yo, path_id)
  399. self._draw_ps(ps, gc0, rgbFace)
  400. self._path_collection_id += 1
  401. @cbook._delete_parameter("3.3", "ismath")
  402. def draw_tex(self, gc, x, y, s, prop, angle, ismath='TeX!', mtext=None):
  403. # docstring inherited
  404. if not hasattr(self, "psfrag"):
  405. _log.warning(
  406. "The PS backend determines usetex status solely based on "
  407. "rcParams['text.usetex'] and does not support having "
  408. "usetex=True only for some elements; this element will thus "
  409. "be rendered as if usetex=False.")
  410. self.draw_text(gc, x, y, s, prop, angle, False, mtext)
  411. return
  412. w, h, bl = self.get_text_width_height_descent(s, prop, ismath="TeX")
  413. fontsize = prop.get_size_in_points()
  414. thetext = 'psmarker%d' % self.textcnt
  415. color = '%1.3f,%1.3f,%1.3f' % gc.get_rgb()[:3]
  416. fontcmd = {'sans-serif': r'{\sffamily %s}',
  417. 'monospace': r'{\ttfamily %s}'}.get(
  418. mpl.rcParams['font.family'][0], r'{\rmfamily %s}')
  419. s = fontcmd % s
  420. tex = r'\color[rgb]{%s} %s' % (color, s)
  421. corr = 0 # w/2*(fontsize-10)/10
  422. if dict.__getitem__(mpl.rcParams, 'text.latex.preview'):
  423. # use baseline alignment!
  424. pos = _nums_to_str(x-corr, y)
  425. self.psfrag.append(
  426. r'\psfrag{%s}[Bl][Bl][1][%f]{\fontsize{%f}{%f}%s}' % (
  427. thetext, angle, fontsize, fontsize*1.25, tex))
  428. else:
  429. # Stick to the bottom alignment.
  430. pos = _nums_to_str(x-corr, y-bl)
  431. self.psfrag.append(
  432. r'\psfrag{%s}[bl][bl][1][%f]{\fontsize{%f}{%f}%s}' % (
  433. thetext, angle, fontsize, fontsize*1.25, tex))
  434. self._pswriter.write(f"""\
  435. gsave
  436. {pos} moveto
  437. ({thetext})
  438. show
  439. grestore
  440. """)
  441. self.textcnt += 1
  442. def draw_text(self, gc, x, y, s, prop, angle, ismath=False, mtext=None):
  443. # docstring inherited
  444. if debugPS:
  445. self._pswriter.write("% text\n")
  446. if _is_transparent(gc.get_rgb()):
  447. return # Special handling for fully transparent.
  448. if ismath == 'TeX':
  449. return self.draw_tex(gc, x, y, s, prop, angle)
  450. elif ismath:
  451. return self.draw_mathtext(gc, x, y, s, prop, angle)
  452. elif mpl.rcParams['ps.useafm']:
  453. self.set_color(*gc.get_rgb())
  454. font = self._get_font_afm(prop)
  455. fontname = font.get_fontname()
  456. fontsize = prop.get_size_in_points()
  457. scale = 0.001 * fontsize
  458. thisx = 0
  459. thisy = font.get_str_bbox_and_descent(s)[4] * scale
  460. last_name = None
  461. lines = []
  462. for c in s:
  463. name = uni2type1.get(ord(c), f"uni{ord(c):04X}")
  464. try:
  465. width = font.get_width_from_char_name(name)
  466. except KeyError:
  467. name = 'question'
  468. width = font.get_width_char('?')
  469. if last_name is not None:
  470. kern = font.get_kern_dist_from_name(last_name, name)
  471. else:
  472. kern = 0
  473. last_name = name
  474. thisx += kern * scale
  475. lines.append('%f %f m /%s glyphshow' % (thisx, thisy, name))
  476. thisx += width * scale
  477. thetext = "\n".join(lines)
  478. self._pswriter.write(f"""\
  479. gsave
  480. /{fontname} findfont
  481. {fontsize} scalefont
  482. setfont
  483. {x:f} {y:f} translate
  484. {angle:f} rotate
  485. {thetext}
  486. grestore
  487. """)
  488. else:
  489. font = self._get_font_ttf(prop)
  490. font.set_text(s, 0, flags=LOAD_NO_HINTING)
  491. self._character_tracker.track(font, s)
  492. self.set_color(*gc.get_rgb())
  493. ps_name = (font.postscript_name
  494. .encode('ascii', 'replace').decode('ascii'))
  495. self.set_font(ps_name, prop.get_size_in_points())
  496. thetext = '\n'.join(
  497. '%f 0 m /%s glyphshow' % (x, font.get_glyph_name(glyph_idx))
  498. for glyph_idx, x in _text_layout.layout(s, font))
  499. self._pswriter.write(f"""\
  500. gsave
  501. {x:f} {y:f} translate
  502. {angle:f} rotate
  503. {thetext}
  504. grestore
  505. """)
  506. def new_gc(self):
  507. # docstring inherited
  508. return GraphicsContextPS()
  509. def draw_mathtext(self, gc, x, y, s, prop, angle):
  510. """Draw the math text using matplotlib.mathtext."""
  511. if debugPS:
  512. self._pswriter.write("% mathtext\n")
  513. width, height, descent, pswriter, used_characters = \
  514. self.mathtext_parser.parse(s, 72, prop)
  515. self._character_tracker.merge(used_characters)
  516. self.set_color(*gc.get_rgb())
  517. thetext = pswriter.getvalue()
  518. self._pswriter.write(f"""\
  519. gsave
  520. {x:f} {y:f} translate
  521. {angle:f} rotate
  522. {thetext}
  523. grestore
  524. """)
  525. def draw_gouraud_triangle(self, gc, points, colors, trans):
  526. self.draw_gouraud_triangles(gc, points.reshape((1, 3, 2)),
  527. colors.reshape((1, 3, 4)), trans)
  528. def draw_gouraud_triangles(self, gc, points, colors, trans):
  529. assert len(points) == len(colors)
  530. assert points.ndim == 3
  531. assert points.shape[1] == 3
  532. assert points.shape[2] == 2
  533. assert colors.ndim == 3
  534. assert colors.shape[1] == 3
  535. assert colors.shape[2] == 4
  536. shape = points.shape
  537. flat_points = points.reshape((shape[0] * shape[1], 2))
  538. flat_points = trans.transform(flat_points)
  539. flat_colors = colors.reshape((shape[0] * shape[1], 4))
  540. points_min = np.min(flat_points, axis=0) - (1 << 12)
  541. points_max = np.max(flat_points, axis=0) + (1 << 12)
  542. factor = np.ceil((2 ** 32 - 1) / (points_max - points_min))
  543. xmin, ymin = points_min
  544. xmax, ymax = points_max
  545. streamarr = np.empty(
  546. shape[0] * shape[1],
  547. dtype=[('flags', 'u1'), ('points', '2>u4'), ('colors', '3u1')])
  548. streamarr['flags'] = 0
  549. streamarr['points'] = (flat_points - points_min) * factor
  550. streamarr['colors'] = flat_colors[:, :3] * 255.0
  551. stream = quote_ps_string(streamarr.tobytes())
  552. self._pswriter.write(f"""\
  553. gsave
  554. << /ShadingType 4
  555. /ColorSpace [/DeviceRGB]
  556. /BitsPerCoordinate 32
  557. /BitsPerComponent 8
  558. /BitsPerFlag 8
  559. /AntiAlias true
  560. /Decode [ {xmin:f} {xmax:f} {ymin:f} {ymax:f} 0 1 0 1 0 1 ]
  561. /DataSource ({stream})
  562. >>
  563. shfill
  564. grestore
  565. """)
  566. def _draw_ps(self, ps, gc, rgbFace, fill=True, stroke=True, command=None):
  567. """
  568. Emit the PostScript snippet 'ps' with all the attributes from 'gc'
  569. applied. 'ps' must consist of PostScript commands to construct a path.
  570. The fill and/or stroke kwargs can be set to False if the
  571. 'ps' string already includes filling and/or stroking, in
  572. which case _draw_ps is just supplying properties and
  573. clipping.
  574. """
  575. # local variable eliminates all repeated attribute lookups
  576. write = self._pswriter.write
  577. if debugPS and command:
  578. write("% "+command+"\n")
  579. mightstroke = (gc.get_linewidth() > 0
  580. and not _is_transparent(gc.get_rgb()))
  581. if not mightstroke:
  582. stroke = False
  583. if _is_transparent(rgbFace):
  584. fill = False
  585. hatch = gc.get_hatch()
  586. if mightstroke:
  587. self.set_linewidth(gc.get_linewidth())
  588. jint = gc.get_joinstyle()
  589. self.set_linejoin(jint)
  590. cint = gc.get_capstyle()
  591. self.set_linecap(cint)
  592. self.set_linedash(*gc.get_dashes())
  593. self.set_color(*gc.get_rgb()[:3])
  594. write('gsave\n')
  595. cliprect = gc.get_clip_rectangle()
  596. if cliprect:
  597. write('%1.4g %1.4g %1.4g %1.4g clipbox\n'
  598. % (*cliprect.size, *cliprect.p0))
  599. clippath, clippath_trans = gc.get_clip_path()
  600. if clippath:
  601. id = self._get_clip_path(clippath, clippath_trans)
  602. write('%s\n' % id)
  603. # Jochen, is the strip necessary? - this could be a honking big string
  604. write(ps.strip())
  605. write("\n")
  606. if fill:
  607. if stroke or hatch:
  608. write("gsave\n")
  609. self.set_color(*rgbFace[:3], store=False)
  610. write("fill\n")
  611. if stroke or hatch:
  612. write("grestore\n")
  613. if hatch:
  614. hatch_name = self.create_hatch(hatch)
  615. write("gsave\n")
  616. write("%f %f %f " % gc.get_hatch_color()[:3])
  617. write("%s setpattern fill grestore\n" % hatch_name)
  618. if stroke:
  619. write("stroke\n")
  620. write("grestore\n")
  621. def _is_transparent(rgb_or_rgba):
  622. if rgb_or_rgba is None:
  623. return True # Consistent with rgbFace semantics.
  624. elif len(rgb_or_rgba) == 4:
  625. if rgb_or_rgba[3] == 0:
  626. return True
  627. if rgb_or_rgba[3] != 1:
  628. _log.warning(
  629. "The PostScript backend does not support transparency; "
  630. "partially transparent artists will be rendered opaque.")
  631. return False
  632. else: # len() == 3.
  633. return False
  634. class GraphicsContextPS(GraphicsContextBase):
  635. def get_capstyle(self):
  636. return {'butt': 0, 'round': 1, 'projecting': 2}[
  637. GraphicsContextBase.get_capstyle(self)]
  638. def get_joinstyle(self):
  639. return {'miter': 0, 'round': 1, 'bevel': 2}[
  640. GraphicsContextBase.get_joinstyle(self)]
  641. class _Orientation(Enum):
  642. portrait, landscape = range(2)
  643. def swap_if_landscape(self, shape):
  644. return shape[::-1] if self.name == "landscape" else shape
  645. class FigureCanvasPS(FigureCanvasBase):
  646. fixed_dpi = 72
  647. filetypes = {'ps': 'Postscript',
  648. 'eps': 'Encapsulated Postscript'}
  649. def get_default_filetype(self):
  650. return 'ps'
  651. def print_ps(self, outfile, *args, **kwargs):
  652. return self._print_ps(outfile, 'ps', *args, **kwargs)
  653. def print_eps(self, outfile, *args, **kwargs):
  654. return self._print_ps(outfile, 'eps', *args, **kwargs)
  655. def _print_ps(
  656. self, outfile, format, *args,
  657. dpi=72, metadata=None, papertype=None, orientation='portrait',
  658. **kwargs):
  659. self.figure.set_dpi(72) # Override the dpi kwarg
  660. dsc_comments = {}
  661. if isinstance(outfile, (str, os.PathLike)):
  662. dsc_comments["Title"] = \
  663. os.fspath(outfile).encode("ascii", "replace").decode("ascii")
  664. dsc_comments["Creator"] = (metadata or {}).get(
  665. "Creator",
  666. f"matplotlib version {mpl.__version__}, http://matplotlib.org/")
  667. # See https://reproducible-builds.org/specs/source-date-epoch/
  668. source_date_epoch = os.getenv("SOURCE_DATE_EPOCH")
  669. dsc_comments["CreationDate"] = (
  670. datetime.datetime.utcfromtimestamp(
  671. int(source_date_epoch)).strftime("%a %b %d %H:%M:%S %Y")
  672. if source_date_epoch
  673. else time.ctime())
  674. dsc_comments = "\n".join(
  675. f"%%{k}: {v}" for k, v in dsc_comments.items())
  676. if papertype is None:
  677. papertype = mpl.rcParams['ps.papersize']
  678. papertype = papertype.lower()
  679. cbook._check_in_list(['auto', *papersize], papertype=papertype)
  680. orientation = cbook._check_getitem(
  681. _Orientation, orientation=orientation.lower())
  682. printer = (self._print_figure_tex
  683. if mpl.rcParams['text.usetex'] else
  684. self._print_figure)
  685. printer(outfile, format, dpi=dpi, dsc_comments=dsc_comments,
  686. orientation=orientation, papertype=papertype, **kwargs)
  687. @_check_savefig_extra_args
  688. @cbook._delete_parameter("3.2", "dryrun")
  689. def _print_figure(
  690. self, outfile, format, *,
  691. dpi, dsc_comments, orientation, papertype,
  692. dryrun=False, bbox_inches_restore=None):
  693. """
  694. Render the figure to a filesystem path or a file-like object.
  695. Parameters are as for `.print_figure`, except that *dsc_comments* is a
  696. all string containing Document Structuring Convention comments,
  697. generated from the *metadata* parameter to `.print_figure`.
  698. """
  699. is_eps = format == 'eps'
  700. if isinstance(outfile, (str, os.PathLike)):
  701. outfile = os.fspath(outfile)
  702. passed_in_file_object = False
  703. elif is_writable_file_like(outfile):
  704. passed_in_file_object = True
  705. else:
  706. raise ValueError("outfile must be a path or a file-like object")
  707. # find the appropriate papertype
  708. width, height = self.figure.get_size_inches()
  709. if papertype == 'auto':
  710. papertype = _get_papertype(
  711. *orientation.swap_if_landscape((width, height)))
  712. paper_width, paper_height = orientation.swap_if_landscape(
  713. papersize[papertype])
  714. if mpl.rcParams['ps.usedistiller']:
  715. # distillers improperly clip eps files if pagesize is too small
  716. if width > paper_width or height > paper_height:
  717. papertype = _get_papertype(
  718. *orientation.swap_if_landscape(width, height))
  719. paper_width, paper_height = orientation.swap_if_landscape(
  720. papersize[papertype])
  721. # center the figure on the paper
  722. xo = 72 * 0.5 * (paper_width - width)
  723. yo = 72 * 0.5 * (paper_height - height)
  724. llx = xo
  725. lly = yo
  726. urx = llx + self.figure.bbox.width
  727. ury = lly + self.figure.bbox.height
  728. rotation = 0
  729. if orientation is _Orientation.landscape:
  730. llx, lly, urx, ury = lly, llx, ury, urx
  731. xo, yo = 72 * paper_height - yo, xo
  732. rotation = 90
  733. bbox = (llx, lly, urx, ury)
  734. if dryrun:
  735. class NullWriter:
  736. def write(self, *args, **kwargs):
  737. pass
  738. self._pswriter = NullWriter()
  739. else:
  740. self._pswriter = StringIO()
  741. # mixed mode rendering
  742. ps_renderer = RendererPS(width, height, self._pswriter, imagedpi=dpi)
  743. renderer = MixedModeRenderer(
  744. self.figure, width, height, dpi, ps_renderer,
  745. bbox_inches_restore=bbox_inches_restore)
  746. self.figure.draw(renderer)
  747. if dryrun: # return immediately if dryrun (tightbbox=True)
  748. return
  749. def print_figure_impl(fh):
  750. # write the PostScript headers
  751. if is_eps:
  752. print("%!PS-Adobe-3.0 EPSF-3.0", file=fh)
  753. else:
  754. print(f"%!PS-Adobe-3.0\n"
  755. f"%%DocumentPaperSizes: {papertype}\n"
  756. f"%%Pages: 1\n",
  757. end="", file=fh)
  758. print(f"{dsc_comments}\n"
  759. f"%%Orientation: {orientation.name}\n"
  760. f"%%BoundingBox: {bbox[0]} {bbox[1]} {bbox[2]} {bbox[3]}\n"
  761. f"%%EndComments\n",
  762. end="", file=fh)
  763. Ndict = len(psDefs)
  764. print("%%BeginProlog", file=fh)
  765. if not mpl.rcParams['ps.useafm']:
  766. Ndict += len(ps_renderer._character_tracker.used)
  767. print("/mpldict %d dict def" % Ndict, file=fh)
  768. print("mpldict begin", file=fh)
  769. print("\n".join(psDefs), file=fh)
  770. if not mpl.rcParams['ps.useafm']:
  771. for font_path, chars \
  772. in ps_renderer._character_tracker.used.items():
  773. if not chars:
  774. continue
  775. font = get_font(font_path)
  776. glyph_ids = [font.get_char_index(c) for c in chars]
  777. fonttype = mpl.rcParams['ps.fonttype']
  778. # Can't use more than 255 chars from a single Type 3 font.
  779. if len(glyph_ids) > 255:
  780. fonttype = 42
  781. # The ttf to ps (subsetting) support doesn't work for
  782. # OpenType fonts that are Postscript inside (like the STIX
  783. # fonts). This will simply turn that off to avoid errors.
  784. if is_opentype_cff_font(font_path):
  785. raise RuntimeError(
  786. "OpenType CFF fonts can not be saved using "
  787. "the internal Postscript backend at this "
  788. "time; consider using the Cairo backend")
  789. fh.flush()
  790. try:
  791. convert_ttf_to_ps(os.fsencode(font_path),
  792. fh, fonttype, glyph_ids)
  793. except RuntimeError:
  794. _log.warning("The PostScript backend does not "
  795. "currently support the selected font.")
  796. raise
  797. print("end", file=fh)
  798. print("%%EndProlog", file=fh)
  799. if not is_eps:
  800. print("%%Page: 1 1", file=fh)
  801. print("mpldict begin", file=fh)
  802. print("%s translate" % _nums_to_str(xo, yo), file=fh)
  803. if rotation:
  804. print("%d rotate" % rotation, file=fh)
  805. print("%s clipbox" % _nums_to_str(width*72, height*72, 0, 0),
  806. file=fh)
  807. # write the figure
  808. print(self._pswriter.getvalue(), file=fh)
  809. # write the trailer
  810. print("end", file=fh)
  811. print("showpage", file=fh)
  812. if not is_eps:
  813. print("%%EOF", file=fh)
  814. fh.flush()
  815. if mpl.rcParams['ps.usedistiller']:
  816. # We are going to use an external program to process the output.
  817. # Write to a temporary file.
  818. with TemporaryDirectory() as tmpdir:
  819. tmpfile = os.path.join(tmpdir, "tmp.ps")
  820. with open(tmpfile, 'w', encoding='latin-1') as fh:
  821. print_figure_impl(fh)
  822. if mpl.rcParams['ps.usedistiller'] == 'ghostscript':
  823. _try_distill(gs_distill,
  824. tmpfile, is_eps, ptype=papertype, bbox=bbox)
  825. elif mpl.rcParams['ps.usedistiller'] == 'xpdf':
  826. _try_distill(xpdf_distill,
  827. tmpfile, is_eps, ptype=papertype, bbox=bbox)
  828. _move_path_to_path_or_stream(tmpfile, outfile)
  829. else:
  830. # Write directly to outfile.
  831. if passed_in_file_object:
  832. requires_unicode = file_requires_unicode(outfile)
  833. if not requires_unicode:
  834. fh = TextIOWrapper(outfile, encoding="latin-1")
  835. # Prevent the TextIOWrapper from closing the underlying
  836. # file.
  837. fh.close = lambda: None
  838. else:
  839. fh = outfile
  840. print_figure_impl(fh)
  841. else:
  842. with open(outfile, 'w', encoding='latin-1') as fh:
  843. print_figure_impl(fh)
  844. @_check_savefig_extra_args
  845. @cbook._delete_parameter("3.2", "dryrun")
  846. def _print_figure_tex(
  847. self, outfile, format, *,
  848. dpi, dsc_comments, orientation, papertype,
  849. dryrun=False, bbox_inches_restore=None):
  850. """
  851. If :rc:`text.usetex` is True, a temporary pair of tex/eps files
  852. are created to allow tex to manage the text layout via the PSFrags
  853. package. These files are processed to yield the final ps or eps file.
  854. The rest of the behavior is as for `._print_figure`.
  855. """
  856. is_eps = format == 'eps'
  857. width, height = self.figure.get_size_inches()
  858. xo = 0
  859. yo = 0
  860. llx = xo
  861. lly = yo
  862. urx = llx + self.figure.bbox.width
  863. ury = lly + self.figure.bbox.height
  864. bbox = (llx, lly, urx, ury)
  865. if dryrun:
  866. class NullWriter:
  867. def write(self, *args, **kwargs):
  868. pass
  869. self._pswriter = NullWriter()
  870. else:
  871. self._pswriter = StringIO()
  872. # mixed mode rendering
  873. ps_renderer = RendererPS(width, height, self._pswriter, imagedpi=dpi)
  874. renderer = MixedModeRenderer(self.figure,
  875. width, height, dpi, ps_renderer,
  876. bbox_inches_restore=bbox_inches_restore)
  877. self.figure.draw(renderer)
  878. if dryrun: # return immediately if dryrun (tightbbox=True)
  879. return
  880. # write to a temp file, we'll move it to outfile when done
  881. with TemporaryDirectory() as tmpdir:
  882. tmpfile = os.path.join(tmpdir, "tmp.ps")
  883. pathlib.Path(tmpfile).write_text(
  884. f"""\
  885. %!PS-Adobe-3.0 EPSF-3.0
  886. {dsc_comments}
  887. %%BoundingBox: {bbox[0]} {bbox[1]} {bbox[2]} {bbox[3]}
  888. %%EndComments
  889. %%BeginProlog
  890. /mpldict {len(psDefs)} dict def
  891. mpldict begin
  892. {"".join(psDefs)}
  893. end
  894. %%EndProlog
  895. mpldict begin
  896. {_nums_to_str(xo, yo)} translate
  897. {_nums_to_str(width*72, height*72)} 0 0 clipbox
  898. {self._pswriter.getvalue()}
  899. end
  900. showpage
  901. """,
  902. encoding="latin-1")
  903. if orientation is _Orientation.landscape: # now, ready to rotate
  904. width, height = height, width
  905. bbox = (lly, llx, ury, urx)
  906. # set the paper size to the figure size if is_eps. The
  907. # resulting ps file has the given size with correct bounding
  908. # box so that there is no need to call 'pstoeps'
  909. if is_eps:
  910. paper_width, paper_height = orientation.swap_if_landscape(
  911. self.figure.get_size_inches())
  912. else:
  913. if papertype == 'auto':
  914. papertype = _get_papertype(width, height)
  915. paper_width, paper_height = papersize[papertype]
  916. texmanager = ps_renderer.get_texmanager()
  917. font_preamble = texmanager.get_font_preamble()
  918. custom_preamble = texmanager.get_custom_preamble()
  919. psfrag_rotated = convert_psfrags(tmpfile, ps_renderer.psfrag,
  920. font_preamble,
  921. custom_preamble, paper_width,
  922. paper_height,
  923. orientation.name)
  924. if (mpl.rcParams['ps.usedistiller'] == 'ghostscript'
  925. or mpl.rcParams['text.usetex']):
  926. _try_distill(gs_distill,
  927. tmpfile, is_eps, ptype=papertype, bbox=bbox,
  928. rotated=psfrag_rotated)
  929. elif mpl.rcParams['ps.usedistiller'] == 'xpdf':
  930. _try_distill(xpdf_distill,
  931. tmpfile, is_eps, ptype=papertype, bbox=bbox,
  932. rotated=psfrag_rotated)
  933. _move_path_to_path_or_stream(tmpfile, outfile)
  934. def convert_psfrags(tmpfile, psfrags, font_preamble, custom_preamble,
  935. paper_width, paper_height, orientation):
  936. """
  937. When we want to use the LaTeX backend with postscript, we write PSFrag tags
  938. to a temporary postscript file, each one marking a position for LaTeX to
  939. render some text. convert_psfrags generates a LaTeX document containing the
  940. commands to convert those tags to text. LaTeX/dvips produces the postscript
  941. file that includes the actual text.
  942. """
  943. with mpl.rc_context({
  944. "text.latex.preamble":
  945. mpl.rcParams["text.latex.preamble"] +
  946. r"\usepackage{psfrag,color}""\n"
  947. r"\usepackage[dvips]{graphicx}""\n"
  948. r"\geometry{papersize={%(width)sin,%(height)sin},"
  949. r"body={%(width)sin,%(height)sin},margin=0in}"
  950. % {"width": paper_width, "height": paper_height}
  951. }):
  952. dvifile = TexManager().make_dvi(
  953. "\n"
  954. r"\begin{figure}""\n"
  955. r" \centering\leavevmode""\n"
  956. r" %(psfrags)s""\n"
  957. r" \includegraphics*[angle=%(angle)s]{%(epsfile)s}""\n"
  958. r"\end{figure}"
  959. % {
  960. "psfrags": "\n".join(psfrags),
  961. "angle": 90 if orientation == 'landscape' else 0,
  962. "epsfile": pathlib.Path(tmpfile).resolve().as_posix(),
  963. },
  964. fontsize=10) # tex's default fontsize.
  965. with TemporaryDirectory() as tmpdir:
  966. psfile = os.path.join(tmpdir, "tmp.ps")
  967. cbook._check_and_log_subprocess(
  968. ['dvips', '-q', '-R0', '-o', psfile, dvifile], _log)
  969. shutil.move(psfile, tmpfile)
  970. # check if the dvips created a ps in landscape paper. Somehow,
  971. # above latex+dvips results in a ps file in a landscape mode for a
  972. # certain figure sizes (e.g., 8.3in, 5.8in which is a5). And the
  973. # bounding box of the final output got messed up. We check see if
  974. # the generated ps file is in landscape and return this
  975. # information. The return value is used in pstoeps step to recover
  976. # the correct bounding box. 2010-06-05 JJL
  977. with open(tmpfile) as fh:
  978. psfrag_rotated = "Landscape" in fh.read(1000)
  979. return psfrag_rotated
  980. def _try_distill(func, *args, **kwargs):
  981. try:
  982. func(*args, **kwargs)
  983. except mpl.ExecutableNotFoundError as exc:
  984. _log.warning("%s. Distillation step skipped.", exc)
  985. def gs_distill(tmpfile, eps=False, ptype='letter', bbox=None, rotated=False):
  986. """
  987. Use ghostscript's pswrite or epswrite device to distill a file.
  988. This yields smaller files without illegal encapsulated postscript
  989. operators. The output is low-level, converting text to outlines.
  990. """
  991. if eps:
  992. paper_option = "-dEPSCrop"
  993. else:
  994. paper_option = "-sPAPERSIZE=%s" % ptype
  995. psfile = tmpfile + '.ps'
  996. dpi = mpl.rcParams['ps.distiller.res']
  997. cbook._check_and_log_subprocess(
  998. [mpl._get_executable_info("gs").executable,
  999. "-dBATCH", "-dNOPAUSE", "-r%d" % dpi, "-sDEVICE=ps2write",
  1000. paper_option, "-sOutputFile=%s" % psfile, tmpfile],
  1001. _log)
  1002. os.remove(tmpfile)
  1003. shutil.move(psfile, tmpfile)
  1004. # While it is best if above steps preserve the original bounding
  1005. # box, there seem to be cases when it is not. For those cases,
  1006. # the original bbox can be restored during the pstoeps step.
  1007. if eps:
  1008. # For some versions of gs, above steps result in an ps file where the
  1009. # original bbox is no more correct. Do not adjust bbox for now.
  1010. pstoeps(tmpfile, bbox, rotated=rotated)
  1011. def xpdf_distill(tmpfile, eps=False, ptype='letter', bbox=None, rotated=False):
  1012. """
  1013. Use ghostscript's ps2pdf and xpdf's/poppler's pdftops to distill a file.
  1014. This yields smaller files without illegal encapsulated postscript
  1015. operators. This distiller is preferred, generating high-level postscript
  1016. output that treats text as text.
  1017. """
  1018. mpl._get_executable_info("gs") # Effectively checks for ps2pdf.
  1019. mpl._get_executable_info("pdftops")
  1020. pdffile = tmpfile + '.pdf'
  1021. psfile = tmpfile + '.ps'
  1022. # Pass options as `-foo#bar` instead of `-foo=bar` to keep Windows happy
  1023. # (https://www.ghostscript.com/doc/9.22/Use.htm#MS_Windows).
  1024. cbook._check_and_log_subprocess(
  1025. ["ps2pdf",
  1026. "-dAutoFilterColorImages#false",
  1027. "-dAutoFilterGrayImages#false",
  1028. "-sAutoRotatePages#None",
  1029. "-sGrayImageFilter#FlateEncode",
  1030. "-sColorImageFilter#FlateEncode",
  1031. "-dEPSCrop" if eps else "-sPAPERSIZE#%s" % ptype,
  1032. tmpfile, pdffile], _log)
  1033. cbook._check_and_log_subprocess(
  1034. ["pdftops", "-paper", "match", "-level2", pdffile, psfile], _log)
  1035. os.remove(tmpfile)
  1036. shutil.move(psfile, tmpfile)
  1037. if eps:
  1038. pstoeps(tmpfile)
  1039. for fname in glob.glob(tmpfile+'.*'):
  1040. os.remove(fname)
  1041. def get_bbox_header(lbrt, rotated=False):
  1042. """
  1043. Return a postscript header string for the given bbox lbrt=(l, b, r, t).
  1044. Optionally, return rotate command.
  1045. """
  1046. l, b, r, t = lbrt
  1047. if rotated:
  1048. rotate = "%.2f %.2f translate\n90 rotate" % (l+r, 0)
  1049. else:
  1050. rotate = ""
  1051. bbox_info = '%%%%BoundingBox: %d %d %d %d' % (l, b, np.ceil(r), np.ceil(t))
  1052. hires_bbox_info = '%%%%HiResBoundingBox: %.6f %.6f %.6f %.6f' % (
  1053. l, b, r, t)
  1054. return '\n'.join([bbox_info, hires_bbox_info]), rotate
  1055. def pstoeps(tmpfile, bbox=None, rotated=False):
  1056. """
  1057. Convert the postscript to encapsulated postscript. The bbox of
  1058. the eps file will be replaced with the given *bbox* argument. If
  1059. None, original bbox will be used.
  1060. """
  1061. # if rotated==True, the output eps file need to be rotated
  1062. if bbox:
  1063. bbox_info, rotate = get_bbox_header(bbox, rotated=rotated)
  1064. else:
  1065. bbox_info, rotate = None, None
  1066. epsfile = tmpfile + '.eps'
  1067. with open(epsfile, 'wb') as epsh, open(tmpfile, 'rb') as tmph:
  1068. write = epsh.write
  1069. # Modify the header:
  1070. for line in tmph:
  1071. if line.startswith(b'%!PS'):
  1072. write(b"%!PS-Adobe-3.0 EPSF-3.0\n")
  1073. if bbox:
  1074. write(bbox_info.encode('ascii') + b'\n')
  1075. elif line.startswith(b'%%EndComments'):
  1076. write(line)
  1077. write(b'%%BeginProlog\n'
  1078. b'save\n'
  1079. b'countdictstack\n'
  1080. b'mark\n'
  1081. b'newpath\n'
  1082. b'/showpage {} def\n'
  1083. b'/setpagedevice {pop} def\n'
  1084. b'%%EndProlog\n'
  1085. b'%%Page 1 1\n')
  1086. if rotate:
  1087. write(rotate.encode('ascii') + b'\n')
  1088. break
  1089. elif bbox and line.startswith((b'%%Bound', b'%%HiResBound',
  1090. b'%%DocumentMedia', b'%%Pages')):
  1091. pass
  1092. else:
  1093. write(line)
  1094. # Now rewrite the rest of the file, and modify the trailer.
  1095. # This is done in a second loop such that the header of the embedded
  1096. # eps file is not modified.
  1097. for line in tmph:
  1098. if line.startswith(b'%%EOF'):
  1099. write(b'cleartomark\n'
  1100. b'countdictstack\n'
  1101. b'exch sub { end } repeat\n'
  1102. b'restore\n'
  1103. b'showpage\n'
  1104. b'%%EOF\n')
  1105. elif line.startswith(b'%%PageBoundingBox'):
  1106. pass
  1107. else:
  1108. write(line)
  1109. os.remove(tmpfile)
  1110. shutil.move(epsfile, tmpfile)
  1111. FigureManagerPS = FigureManagerBase
  1112. # The following Python dictionary psDefs contains the entries for the
  1113. # PostScript dictionary mpldict. This dictionary implements most of
  1114. # the matplotlib primitives and some abbreviations.
  1115. #
  1116. # References:
  1117. # http://www.adobe.com/products/postscript/pdfs/PLRM.pdf
  1118. # http://www.mactech.com/articles/mactech/Vol.09/09.04/PostscriptTutorial/
  1119. # http://www.math.ubc.ca/people/faculty/cass/graphics/text/www/
  1120. #
  1121. # The usage comments use the notation of the operator summary
  1122. # in the PostScript Language reference manual.
  1123. psDefs = [
  1124. # x y *m* -
  1125. "/m { moveto } bind def",
  1126. # x y *l* -
  1127. "/l { lineto } bind def",
  1128. # x y *r* -
  1129. "/r { rlineto } bind def",
  1130. # x1 y1 x2 y2 x y *c* -
  1131. "/c { curveto } bind def",
  1132. # *closepath* -
  1133. "/cl { closepath } bind def",
  1134. # w h x y *box* -
  1135. """/box {
  1136. m
  1137. 1 index 0 r
  1138. 0 exch r
  1139. neg 0 r
  1140. cl
  1141. } bind def""",
  1142. # w h x y *clipbox* -
  1143. """/clipbox {
  1144. box
  1145. clip
  1146. newpath
  1147. } bind def""",
  1148. ]
  1149. @_Backend.export
  1150. class _BackendPS(_Backend):
  1151. FigureCanvas = FigureCanvasPS