Skip to content

Commit

Permalink
Merge pull request matplotlib#10532 from anntzer/py3pgf
Browse files Browse the repository at this point in the history
Py3fy backend_pgf.
  • Loading branch information
timhoffm authored Mar 5, 2018
2 parents 2898bfa + 879b2e9 commit 862e693
Show file tree
Hide file tree
Showing 6 changed files with 35 additions and 45 deletions.
3 changes: 3 additions & 0 deletions doc/api/next_api_changes/2018-02-15-AL-deprecations.rst
Original file line number Diff line number Diff line change
Expand Up @@ -13,3 +13,6 @@ The following functions and classes are deprecated:
- ``cbook.is_numlike`` (use ``isinstance(..., numbers.Number)`` instead),
- ``mathtext.unichr_safe`` (use ``chr`` instead),
- ``texmanager.dvipng_hack_alpha``,

The following rcParams are deprecated:
- ``pgf.debug`` (the pgf backend relies on logging),
2 changes: 1 addition & 1 deletion lib/matplotlib/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -812,7 +812,7 @@ def gen_candidates():

_deprecated_ignore_map = {'nbagg.transparent': 'figure.facecolor'}

_obsolete_set = {'plugins.directory', 'text.dvipnghack'}
_obsolete_set = {'pgf.debug', 'plugins.directory', 'text.dvipnghack'}

# The following may use a value of None to suppress the warning.
# do NOT include in _all_deprecated
Expand Down
70 changes: 30 additions & 40 deletions lib/matplotlib/backends/backend_pgf.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,7 @@
from __future__ import (absolute_import, division, print_function,
unicode_literals)

import six

import atexit
import codecs
import errno
import logging
import math
import os
import re
Expand All @@ -27,6 +23,8 @@
from matplotlib.figure import Figure
from matplotlib._pylab_helpers import Gcf

_log = logging.getLogger(__name__)


###############################################################################

Expand Down Expand Up @@ -193,10 +191,9 @@ def make_pdf_to_png_converter():
tools_available = []
# check for pdftocairo
try:
subprocess.check_output(
["pdftocairo", "-v"], stderr=subprocess.STDOUT)
subprocess.check_output(["pdftocairo", "-v"], stderr=subprocess.STDOUT)
tools_available.append("pdftocairo")
except:
except OSError:
pass
# check for ghostscript
gs, ver = mpl.checkdep_ghostscript()
Expand All @@ -212,7 +209,7 @@ def cairo_convert(pdffile, pngfile, dpi):
return cairo_convert
elif "gs" in tools_available:
def gs_convert(pdffile, pngfile, dpi):
cmd = [str(gs),
cmd = [gs,
'-dQUIET', '-dSAFER', '-dBATCH', '-dNOPAUSE', '-dNOPROMPT',
'-dUseCIEColor', '-dTextAlphaBits=4',
'-dGraphicsAlphaBits=4', '-dDOINTERPOLATE',
Expand All @@ -226,11 +223,11 @@ def gs_convert(pdffile, pngfile, dpi):

class LatexError(Exception):
def __init__(self, message, latex_output=""):
Exception.__init__(self, message)
super().__init__(message)
self.latex_output = latex_output


class LatexManagerFactory(object):
class LatexManagerFactory:
previous_instance = None

@staticmethod
Expand All @@ -242,18 +239,16 @@ def get_latex_manager():
# Check if the previous instance of LatexManager can be reused.
if (prev and prev.latex_header == latex_header
and prev.texcommand == texcommand):
if rcParams["pgf.debug"]:
print("reusing LatexManager")
_log.debug("reusing LatexManager")
return prev
else:
if rcParams["pgf.debug"]:
print("creating LatexManager")
_log.debug("creating LatexManager")
new_inst = LatexManager()
LatexManagerFactory.previous_instance = new_inst
return new_inst


class LatexManager(object):
class LatexManager:
"""
The LatexManager opens an instance of the LaTeX application for
determining the metrics of text elements. The LaTeX environment can be
Expand Down Expand Up @@ -306,7 +301,6 @@ def __init__(self):
# store references for __del__
self._os_path = os.path
self._shutil = shutil
self._debug = rcParams["pgf.debug"]

# create a tmp directory for running latex, remember to cleanup
self.tmpdir = tempfile.mkdtemp(prefix="mpl_pgf_lm_")
Expand All @@ -317,26 +311,24 @@ def __init__(self):
self.latex_header = LatexManager._build_latex_header()
latex_end = "\n\\makeatletter\n\\@@end\n"
try:
latex = subprocess.Popen([str(self.texcommand), "-halt-on-error"],
latex = subprocess.Popen([self.texcommand, "-halt-on-error"],
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
cwd=self.tmpdir)
except OSError as e:
if e.errno == errno.ENOENT:
raise RuntimeError(
"Latex command not found. Install %r or change "
"pgf.texsystem to the desired command." % self.texcommand)
else:
raise RuntimeError(
"Error starting process %r" % self.texcommand)
except FileNotFoundError:
raise RuntimeError(
"Latex command not found. Install %r or change "
"pgf.texsystem to the desired command." % self.texcommand)
except OSError:
raise RuntimeError("Error starting process %r" % self.texcommand)
test_input = self.latex_header + latex_end
stdout, stderr = latex.communicate(test_input.encode("utf-8"))
if latex.returncode != 0:
raise LatexError("LaTeX returned an error, probably missing font "
"or error in preamble:\n%s" % stdout)

# open LaTeX process for real work
latex = subprocess.Popen([str(self.texcommand), "-halt-on-error"],
latex = subprocess.Popen([self.texcommand, "-halt-on-error"],
stdin=subprocess.PIPE, stdout=subprocess.PIPE,
cwd=self.tmpdir)
self.latex = latex
Expand Down Expand Up @@ -366,8 +358,7 @@ def _cleanup(self):
sys.stderr.write("error deleting tmp directory %s\n" % self.tmpdir)

def __del__(self):
if self._debug:
print("deleting LatexManager")
_log.debug("deleting LatexManager")
self._cleanup()

def get_width_height_descent(self, text, prop):
Expand Down Expand Up @@ -787,7 +778,7 @@ class GraphicsContextPgf(GraphicsContextBase):
########################################################################


class TmpDirCleaner(object):
class TmpDirCleaner:
remaining_tmpdirs = set()

@staticmethod
Expand All @@ -797,10 +788,10 @@ def add(tmpdir):
@staticmethod
def cleanup_remaining_tmpdirs():
for tmpdir in TmpDirCleaner.remaining_tmpdirs:
try:
shutil.rmtree(tmpdir)
except:
sys.stderr.write("error deleting tmp directory %s\n" % tmpdir)
shutil.rmtree(
tmpdir,
onerror=lambda *args: print("error deleting tmp directory %s"
% tmpdir, file=sys.stderr))


class FigureCanvasPgf(FigureCanvasBase):
Expand Down Expand Up @@ -879,7 +870,7 @@ def print_pgf(self, fname_or_fh, *args, **kwargs):
return

# figure out where the pgf is to be written to
if isinstance(fname_or_fh, six.string_types):
if isinstance(fname_or_fh, str):
with codecs.open(fname_or_fh, "w", encoding="utf-8") as fh:
self._print_pgf_to_fh(fh, *args, **kwargs)
elif is_writable_file_like(fname_or_fh):
Expand Down Expand Up @@ -918,7 +909,7 @@ def _print_pdf_to_fh(self, fh, *args, **kwargs):
fh_tex.write(latexcode)

texcommand = get_texcommand()
cmdargs = [str(texcommand), "-interaction=nonstopmode",
cmdargs = [texcommand, "-interaction=nonstopmode",
"-halt-on-error", "figure.tex"]
try:
subprocess.check_output(
Expand Down Expand Up @@ -946,7 +937,7 @@ def print_pdf(self, fname_or_fh, *args, **kwargs):
return

# figure out where the pdf is to be written to
if isinstance(fname_or_fh, six.string_types):
if isinstance(fname_or_fh, str):
with open(fname_or_fh, "wb") as fh:
self._print_pdf_to_fh(fh, *args, **kwargs)
elif is_writable_file_like(fname_or_fh):
Expand Down Expand Up @@ -982,7 +973,7 @@ def print_png(self, fname_or_fh, *args, **kwargs):
self._print_pgf_to_fh(None, *args, **kwargs)
return

if isinstance(fname_or_fh, six.string_types):
if isinstance(fname_or_fh, str):
with open(fname_or_fh, "wb") as fh:
self._print_png_to_fh(fh, *args, **kwargs)
elif is_writable_file_like(fname_or_fh):
Expand All @@ -995,8 +986,7 @@ def get_renderer(self):


class FigureManagerPgf(FigureManagerBase):
def __init__(self, *args):
FigureManagerBase.__init__(self, *args)
pass


@_Backend.export
Expand Down
1 change: 0 additions & 1 deletion lib/matplotlib/mpl-data/stylelib/_classic_test.mplstyle
Original file line number Diff line number Diff line change
Expand Up @@ -441,7 +441,6 @@ pdf.inheritcolor : False
pdf.use14corefonts : False

# pgf backend params
pgf.debug : False
pgf.texsystem : xelatex
pgf.rcfonts : True
pgf.preamble :
Expand Down
1 change: 0 additions & 1 deletion lib/matplotlib/mpl-data/stylelib/classic.mplstyle
Original file line number Diff line number Diff line change
Expand Up @@ -443,7 +443,6 @@ pdf.inheritcolor : False
pdf.use14corefonts : False

# pgf backend params
pgf.debug : False
pgf.texsystem : xelatex
pgf.rcfonts : True
pgf.preamble :
Expand Down
3 changes: 1 addition & 2 deletions matplotlibrc.template
Original file line number Diff line number Diff line change
Expand Up @@ -565,9 +565,8 @@ backend : $TEMPLATE_BACKEND
## instead of uuid4
### pgf parameter
#pgf.rcfonts : True
#pgf.preamble :
#pgf.preamble :
#pgf.texsystem : xelatex
#pgf.debug : False

### docstring params
##docstring.hardcopy = False ## set this when you want to generate hardcopy docstring
Expand Down

0 comments on commit 862e693

Please sign in to comment.