backend_ps.py 49 KB

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