Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit dc7a06c

Browse files
committed
backend_ps cleanup.
Dedupe some code between backend_ps and backend_bases (the edgecolor and facecolor handling -- see changelog), as well as between the non-tex and tex cases (by formatting the header metadata ("dsc_comments") earlier). Also simplify a bit papersize handling in usetex case.
1 parent 430723d commit dc7a06c

File tree

2 files changed

+52
-104
lines changed

2 files changed

+52
-104
lines changed
Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
`.FigureCanvasPS.print_ps` and `.FigureCanvasPS.print_eps` no longer apply edgecolor and facecolor
2+
``````````````````````````````````````````````````````````````````````````````````````````````````
3+
4+
These methods now assume that the figure edge and facecolor have been correctly
5+
applied by `.FigureCanvasBase.print_figure`, as they are normally called
6+
through it.
7+
8+
This behavior is consistent with other figure saving methods
9+
(`.FigureCanvasAgg.print_png`, `.FigureCanvasPdf.print_pdf`,
10+
`.FigureCanvasSVG.print_svg`).

lib/matplotlib/backends/backend_ps.py

Lines changed: 42 additions & 104 deletions
Original file line numberDiff line numberDiff line change
@@ -831,10 +831,29 @@ def print_ps(self, outfile, *args, **kwargs):
831831
def print_eps(self, outfile, *args, **kwargs):
832832
return self._print_ps(outfile, 'eps', *args, **kwargs)
833833

834-
def _print_ps(self, outfile, format, *args,
835-
papertype=None, dpi=72, facecolor='w', edgecolor='w',
836-
orientation='portrait',
837-
**kwargs):
834+
def _print_ps(
835+
self, outfile, format, *args,
836+
dpi=72, metadata=None, papertype=None, orientation='portrait',
837+
**kwargs):
838+
839+
self.figure.set_dpi(72) # Override the dpi kwarg
840+
841+
dsc_comments = {}
842+
if isinstance(outfile, (str, os.PathLike)):
843+
dsc_comments["Title"] = \
844+
os.fspath(outfile).encode("ascii", "replace").decode("ascii")
845+
dsc_comments["Creator"] = (metadata or {}).get(
846+
"Creator",
847+
f"matplotlib version {__version__}, http://matplotlib.org/")
848+
source_date_epoch = os.getenv("SOURCE_DATE_EPOCH")
849+
dsc_comments["CreationDate"] = (
850+
datetime.datetime.utcfromtimestamp(
851+
int(source_date_epoch)).strftime("%a %b %d %H:%M:%S %Y")
852+
if source_date_epoch
853+
else time.ctime())
854+
dsc_comments = "\n".join(
855+
f"%%{k}: {v}" for k, v in dsc_comments.items())
856+
838857
if papertype is None:
839858
papertype = rcParams['ps.papersize']
840859
papertype = papertype.lower()
@@ -843,42 +862,29 @@ def _print_ps(self, outfile, format, *args,
843862
orientation = cbook._check_getitem(
844863
_Orientation, orientation=orientation.lower())
845864

846-
self.figure.set_dpi(72) # Override the dpi kwarg
847-
848865
printer = (self._print_figure_tex
849866
if rcParams['text.usetex'] else
850867
self._print_figure)
851-
printer(outfile, format, dpi, facecolor, edgecolor,
852-
orientation, papertype, **kwargs)
868+
printer(outfile, format, dpi=dpi, dsc_comments=dsc_comments,
869+
orientation=orientation, papertype=papertype, **kwargs)
853870

854871
@cbook._delete_parameter("3.2", "dryrun")
855872
def _print_figure(
856-
self, outfile, format, dpi, facecolor, edgecolor,
857-
orientation, papertype, *,
858-
metadata=None, dryrun=False, bbox_inches_restore=None, **kwargs):
873+
self, outfile, format, *,
874+
dpi, dsc_comments, orientation, papertype,
875+
dryrun=False, bbox_inches_restore=None, **kwargs):
859876
"""
860-
Render the figure to hardcopy. Set the figure patch face and
861-
edge colors. This is useful because some of the GUIs have a
862-
gray figure face color background and you'll probably want to
863-
override this on hardcopy
864-
865-
If outfile is a string, it is interpreted as a file name.
866-
If the extension matches .ep* write encapsulated postscript,
867-
otherwise write a stand-alone PostScript file.
868-
869-
If outfile is a file object, a stand-alone PostScript file is
870-
written into this file object.
877+
Render the figure to a filesystem path or a file-like object.
871878
872-
metadata must be a dictionary. Currently, only the value for
873-
the key 'Creator' is used.
879+
Parameters are as for `.print_figure`, except that *dsc_comments* is a
880+
all string containing Document Structuring Convention comments,
881+
generated from the *metadata* parameter to `.print_figure`.
874882
"""
875883
is_eps = format == 'eps'
876884
if isinstance(outfile, (str, os.PathLike)):
877-
outfile = title = os.fspath(outfile)
878-
title = title.encode("ascii", "replace").decode("ascii")
885+
outfile = os.fspath(outfile)
879886
passed_in_file_object = False
880887
elif is_writable_file_like(outfile):
881-
title = None
882888
passed_in_file_object = True
883889
else:
884890
raise ValueError("outfile must be a path or a file-like object")
@@ -915,12 +921,6 @@ def _print_figure(
915921
rotation = 90
916922
bbox = (llx, lly, urx, ury)
917923

918-
# generate PostScript code for the figure and store it in a string
919-
origfacecolor = self.figure.get_facecolor()
920-
origedgecolor = self.figure.get_edgecolor()
921-
self.figure.set_facecolor(facecolor)
922-
self.figure.set_edgecolor(edgecolor)
923-
924924
if dryrun:
925925
class NullWriter:
926926
def write(self, *args, **kwargs):
@@ -941,16 +941,6 @@ def write(self, *args, **kwargs):
941941
if dryrun: # return immediately if dryrun (tightbbox=True)
942942
return
943943

944-
self.figure.set_facecolor(origfacecolor)
945-
self.figure.set_edgecolor(origedgecolor)
946-
947-
# check for custom metadata
948-
if metadata is not None and 'Creator' in metadata:
949-
creator_str = metadata['Creator']
950-
else:
951-
creator_str = "matplotlib version " + __version__ + \
952-
", http://matplotlib.org/"
953-
954944
def print_figure_impl(fh):
955945
# write the PostScript headers
956946
if is_eps:
@@ -960,18 +950,7 @@ def print_figure_impl(fh):
960950
f"%%DocumentPaperSizes: {papertype}\n"
961951
f"%%Pages: 1\n",
962952
end="", file=fh)
963-
if title:
964-
print("%%Title: " + title, file=fh)
965-
# get source date from SOURCE_DATE_EPOCH, if set
966-
# See https://reproducible-builds.org/specs/source-date-epoch/
967-
source_date_epoch = os.getenv("SOURCE_DATE_EPOCH")
968-
if source_date_epoch:
969-
source_date = datetime.datetime.utcfromtimestamp(
970-
int(source_date_epoch)).strftime("%a %b %d %H:%M:%S %Y")
971-
else:
972-
source_date = time.ctime()
973-
print(f"%%Creator: {creator_str}\n"
974-
f"%%CreationDate: {source_date}\n"
953+
print(f"{dsc_comments}\n"
975954
f"%%Orientation: {orientation.name}\n"
976955
f"%%BoundingBox: {bbox[0]} {bbox[1]} {bbox[2]} {bbox[3]}\n"
977956
f"%%EndComments\n",
@@ -1079,28 +1058,18 @@ def print_figure_impl(fh):
10791058

10801059
@cbook._delete_parameter("3.2", "dryrun")
10811060
def _print_figure_tex(
1082-
self, outfile, format, dpi, facecolor, edgecolor,
1083-
orientation, papertype, *,
1084-
metadata=None, dryrun=False, bbox_inches_restore=None, **kwargs):
1061+
self, outfile, format, *,
1062+
dpi, dsc_comments, orientation, papertype,
1063+
dryrun=False, bbox_inches_restore=None, **kwargs):
10851064
"""
1086-
If text.usetex is True in rc, a temporary pair of tex/eps files
1065+
If :rc:`text.usetex` is True, a temporary pair of tex/eps files
10871066
are created to allow tex to manage the text layout via the PSFrags
10881067
package. These files are processed to yield the final ps or eps file.
10891068
1090-
metadata must be a dictionary. Currently, only the value for
1091-
the key 'Creator' is used.
1069+
The rest of the behavior is as for `._print_figure`.
10921070
"""
10931071
is_eps = format == 'eps'
1094-
if is_writable_file_like(outfile):
1095-
title = None
1096-
else:
1097-
try:
1098-
title = os.fspath(outfile)
1099-
except TypeError:
1100-
raise ValueError(
1101-
"outfile must be a path or a file-like object")
11021072

1103-
self.figure.dpi = 72 # ignore the dpi kwarg
11041073
width, height = self.figure.get_size_inches()
11051074
xo = 0
11061075
yo = 0
@@ -1112,12 +1081,6 @@ def _print_figure_tex(
11121081
ury = lly + h
11131082
bbox = (llx, lly, urx, ury)
11141083

1115-
# generate PostScript code for the figure and store it in a string
1116-
origfacecolor = self.figure.get_facecolor()
1117-
origedgecolor = self.figure.get_edgecolor()
1118-
self.figure.set_facecolor(facecolor)
1119-
self.figure.set_edgecolor(edgecolor)
1120-
11211084
if dryrun:
11221085
class NullWriter:
11231086
def write(self, *args, **kwargs):
@@ -1138,35 +1101,13 @@ def write(self, *args, **kwargs):
11381101
if dryrun: # return immediately if dryrun (tightbbox=True)
11391102
return
11401103

1141-
self.figure.set_facecolor(origfacecolor)
1142-
self.figure.set_edgecolor(origedgecolor)
1143-
1144-
# check for custom metadata
1145-
if metadata is not None and 'Creator' in metadata:
1146-
creator_str = metadata['Creator']
1147-
else:
1148-
creator_str = "matplotlib version " + __version__ + \
1149-
", http://matplotlib.org/"
1150-
11511104
# write to a temp file, we'll move it to outfile when done
1152-
11531105
with TemporaryDirectory() as tmpdir:
11541106
tmpfile = os.path.join(tmpdir, "tmp.ps")
1155-
# get source date from SOURCE_DATE_EPOCH, if set
1156-
# See https://reproducible-builds.org/specs/source-date-epoch/
1157-
source_date_epoch = os.getenv("SOURCE_DATE_EPOCH")
1158-
if source_date_epoch:
1159-
source_date = datetime.datetime.utcfromtimestamp(
1160-
int(source_date_epoch)).strftime("%a %b %d %H:%M:%S %Y")
1161-
else:
1162-
source_date = time.ctime()
11631107
pathlib.Path(tmpfile).write_text(
11641108
f"""\
11651109
%!PS-Adobe-3.0 EPSF-3.0
1166-
{f'''%%Title: {title}
1167-
''' if title else ""}\
1168-
%%Creator: {creator_str}
1169-
%%CreationDate: {source_date}
1110+
{dsc_comments}
11701111
%%BoundingBox: {bbox[0]} {bbox[1]} {bbox[2]} {bbox[3]}
11711112
%%EndComments
11721113
%%BeginProlog
@@ -1195,12 +1136,9 @@ def write(self, *args, **kwargs):
11951136
paper_width, paper_height = orientation.swap_if_landscape(
11961137
self.figure.get_size_inches())
11971138
else:
1198-
temp_papertype = _get_papertype(width, height)
11991139
if papertype == 'auto':
1200-
papertype = temp_papertype
1201-
paper_width, paper_height = papersize[temp_papertype]
1202-
else:
1203-
paper_width, paper_height = papersize[papertype]
1140+
papertype = _get_papertype(width, height)
1141+
paper_width, paper_height = papersize[papertype]
12041142

12051143
texmanager = ps_renderer.get_texmanager()
12061144
font_preamble = texmanager.get_font_preamble()

0 commit comments

Comments
 (0)