8000 Various cleanups to pgf backend. by anntzer · Pull Request #20466 · matplotlib/matplotlib · GitHub
[go: up one dir, main page]

Skip to content

Various cleanups to pgf backend. #20466

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jun 22, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions doc/api/next_api_changes/deprecations/20466-AL.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
``backend_pgf.LatexManager.str_cache``
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
... is deprecated.
76 changes: 32 additions & 44 deletions lib/matplotlib/backends/backend_pgf.py
Original file line number Diff line number Diff line change
Expand Up @@ -122,8 +122,11 @@ def writeln(fh, line):
fh.write("%\n")


def _font_properties_str(prop):
# translate font properties to latex commands, return as string
def _escape_and_apply_props(s, prop):
"""
Generate a TeX string that renders string *s* with font properties *prop*,
also applying any required escapes to *s*.
"""
commands = []

families = {"serif": r"\rmfamily", "sans": r"\sffamily",
Expand All @@ -149,7 +152,7 @@ def _font_properties_str(prop):
commands.append(r"\bfseries")

commands.append(r"\selectfont")
return "".join(commands)
return "".join(commands) + " " + common_texification(s)


def _metadata_to_str(key, value):
Expand Down Expand Up @@ -296,7 +299,10 @@ def __init__(self):
"or error in preamble.", stdout)

self.latex = None # Will be set up on first use.
self.str_cache = {} # cache for strings already processed
# Per-instance cache.
self._get_box_metrics = functools.lru_cache()(self._get_box_metrics)

str_cache = _api.deprecated("3.5")(property(lambda self: {}))

def _setup_latex_process(self):
# Open LaTeX process for real work; register it for deletion. On
Expand All @@ -322,46 +328,34 @@ def finalize_latex(latex):

def get_width_height_descent(self, text, prop):
"""
Get the width, total height and descent for a text typeset by the
current LaTeX environment.
Get the width, total height, and descent (in TeX points) for a text
typeset by the current LaTeX environment.
"""
return self._get_box_metrics(_escape_and_apply_props(text, prop))

# apply font properties and define textbox
prop_cmds = _font_properties_str(prop)
textbox = "\\sbox0{%s %s}" % (prop_cmds, text)

# check cache
if textbox in self.str_cache:
return self.str_cache[textbox]

# send textbox to LaTeX and wait for prompt
self._stdin_writeln(textbox)
try:
self._expect_prompt()
except LatexError as e:
raise ValueError("Error processing '{}'\nLaTeX Output:\n{}"
.format(text, e.latex_output)) from e

# typeout width, height and text offset of the last textbox
self._stdin_writeln(r"\typeout{\the\wd0,\the\ht0,\the\dp0}")
# read answer from latex and advance to the next prompt
def _get_box_metrics(self, tex):
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should probably get a note that __init__ wraps this with a per-instance-cache.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

done

"""
Get the width, total height and descent (in TeX points) for a TeX
command's output in the current LaTeX environment.
"""
# This method gets wrapped in __init__ for per-instance caching.
self._stdin_writeln( # Send textbox to TeX & request metrics typeout.
r"\sbox0{%s}\typeout{\the\wd0,\the\ht0,\the\dp0}" % tex)
try:
answer = self._expect_prompt()
except LatexError as e:
raise ValueError("Error processing '{}'\nLaTeX Output:\n{}"
.format(text, e.latex_output)) from e

# parse metrics from the answer string
except LatexError as err:
raise ValueError("Error measuring {!r}\nLaTeX Output:\n{}"
.format(tex, err.latex_output)) from err
try:
width, height, offset = answer.splitlines()[0].split(",")
# Parse metrics from the answer string. Last line is prompt, and
# next-to-last-line is blank line from \typeout.
width, height, offset = answer.splitlines()[-3].split(",")
except Exception as err:
raise ValueError("Error processing '{}'\nLaTeX Output:\n{}"
.format(text, answer)) from err
raise ValueError("Error measuring {!r}\nLaTeX Output:\n{}"
.format(tex, answer)) from err
w, h, o = float(width[:-2]), float(height[:-2]), float(offset[:-2])

# the height returned from LaTeX goes from base to top.
# the height matplotlib expects goes from bottom to top.
self.str_cache[textbox] = (w, h + o, o)
# The height returned from LaTeX goes from base to top;
# the height Matplotlib expects goes from bottom to top.
return w, h + o, o


Expand Down Expand Up @@ -671,9 +665,7 @@ def draw_text(self, gc, x, y, s, prop, angle, ismath=False, mtext=None):
# docstring inherited

# prepare string for tex
s = common_texification(s)
prop_cmds = _font_properties_str(prop)
s = r"%s %s" % (prop_cmds, s)
s = _escape_and_apply_props(s, prop)

writeln(self.fh, r"\begin{pgfscope}")

Expand Down Expand Up @@ -718,10 +710,6 @@ def draw_text(self, gc, x, y, s, prop, angle, ismath=False, mtext=None):

def get_text_width_height_descent(self, s, prop, ismath):
# docstring inherited

# check if the math is supposed to be displaystyled
s = common_texification(s)

# get text metrics in units of latex pt, convert to display units
w, h, d = (LatexManager._get_cached_or_new()
.get_width_height_descent(s, prop))
Expand Down
0