Skip to content

Commit 0d4bc8e

Browse files
committed
Move towards making texmanager stateless.
Previously, TexManager needed to call get_font_config at a specific place in the middle of processing to update some internal attributes before proceeding with TeX source generation. Instead, move towards making TexManager stateless (except for caching), i.e. the user facing API should be thought of as a bunch of independently callable functions `make_tex()`, `make_dvi()`, etc. (they will probably stay as methods on a "empty" TexManager object for a long time for backcompat, in fact).
1 parent 2fe38b5 commit 0d4bc8e

File tree

3 files changed

+78
-63
lines changed

3 files changed

+78
-63
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
``TexManager.get_font_config``
2+
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
3+
... is deprecated with no replacement. (It previously returned an internal
4+
hashed key for used for caching purposes.)

lib/matplotlib/tests/test_texmanager.py

+4-7
Original file line numberDiff line numberDiff line change
@@ -7,17 +7,14 @@
77

88

99
def test_fontconfig_preamble():
10-
"""Test that the preamble is included in _fontconfig."""
10+
"""Test that the preamble is included in the source."""
1111
plt.rcParams['text.usetex'] = True
1212

13-
tm1 = TexManager()
14-
font_config1 = tm1.get_font_config()
15-
13+
src1 = TexManager()._get_tex_source("", fontsize=12)
1614
plt.rcParams['text.latex.preamble'] = '\\usepackage{txfonts}'
17-
tm2 = TexManager()
18-
font_config2 = tm2.get_font_config()
15+
src2 = TexManager()._get_tex_source("", fontsize=12)
1916

20-
assert font_config1 != font_config2
17+
assert src1 != src2
2118

2219

2320
@pytest.mark.parametrize(

lib/matplotlib/texmanager.py

+70-56
Original file line numberDiff line numberDiff line change
@@ -61,37 +61,44 @@ class TexManager:
6161
"""
6262

6363
texcache = os.path.join(mpl.get_cachedir(), 'tex.cache')
64-
6564
_grey_arrayd = {}
66-
_font_family = 'serif'
65+
6766
_font_families = ('serif', 'sans-serif', 'cursive', 'monospace')
68-
_font_info = {
69-
'new century schoolbook': ('pnc', r'\renewcommand{\rmdefault}{pnc}'),
70-
'bookman': ('pbk', r'\renewcommand{\rmdefault}{pbk}'),
71-
'times': ('ptm', r'\usepackage{mathptmx}'),
72-
'palatino': ('ppl', r'\usepackage{mathpazo}'),
73-
'zapf chancery': ('pzc', r'\usepackage{chancery}'),
74-
'cursive': ('pzc', r'\usepackage{chancery}'),
75-
'charter': ('pch', r'\usepackage{charter}'),
76-
'serif': ('cmr', ''),
77-
'sans-serif': ('cmss', ''),
78-
'helvetica': ('phv', r'\usepackage{helvet}'),
79-
'avant garde': ('pag', r'\usepackage{avant}'),
80-
'courier': ('pcr', r'\usepackage{courier}'),
67+
_font_preambles = {
68+
'new century schoolbook': r'\renewcommand{\rmdefault}{pnc}',
69+
'bookman': r'\renewcommand{\rmdefault}{pbk}',
70+
'times': r'\usepackage{mathptmx}',
71+
'palatino': r'\usepackage{mathpazo}',
72+
'zapf chancery': r'\usepackage{chancery}',
73+
'cursive': r'\usepackage{chancery}',
74+
'charter': r'\usepackage{charter}',
75+
'serif': '',
76+
'sans-serif': '',
77+
'helvetica': r'\usepackage{helvet}',
78+
'avant garde': r'\usepackage{avant}',
79+
'courier': r'\usepackage{courier}',
8180
# Loading the type1ec package ensures that cm-super is installed, which
8281
# is necessary for Unicode computer modern. (It also allows the use of
8382
# computer modern at arbitrary sizes, but that's just a side effect.)
84-
'monospace': ('cmtt', r'\usepackage{type1ec}'),
85-
'computer modern roman': ('cmr', r'\usepackage{type1ec}'),
86-
'computer modern sans serif': ('cmss', r'\usepackage{type1ec}'),
87-
'computer modern typewriter': ('cmtt', r'\usepackage{type1ec}')}
83+
'monospace': r'\usepackage{type1ec}',
84+
'computer modern roman': r'\usepackage{type1ec}',
85+
'computer modern sans serif': r'\usepackage{type1ec}',
86+
'computer modern typewriter': r'\usepackage{type1ec}',
87+
}
8888
_font_types = {
89-
'new century schoolbook': 'serif', 'bookman': 'serif',
90-
'times': 'serif', 'palatino': 'serif', 'charter': 'serif',
91-
'computer modern roman': 'serif', 'zapf chancery': 'cursive',
92-
'helvetica': 'sans-serif', 'avant garde': 'sans-serif',
89+
'new century schoolbook': 'serif',
90+
'bookman': 'serif',
91+
'times': 'serif',
92+
'palatino': 'serif',
93+
'zapf chancery': 'cursive',
94+
'charter': 'serif',
95+
'helvetica': 'sans-serif',
96+
'avant garde': 'sans-serif',
97+
'courier': 'monospace',
98+
'computer modern roman': 'serif',
9399
'computer modern sans serif': 'sans-serif',
94-
'courier': 'monospace', 'computer modern typewriter': 'monospace'}
100+
'computer modern typewriter': 'monospace',
101+
}
95102

96103
grey_arrayd = _api.deprecate_privatize_attribute("3.5")
97104
font_family = _api.deprecate_privatize_attribute("3.5")
@@ -103,33 +110,46 @@ def __new__(cls):
103110
Path(cls.texcache).mkdir(parents=True, exist_ok=True)
104111
return object.__new__(cls)
105112

113+
@_api.deprecated("3.6")
106114
def get_font_config(self):
115+
preamble, font_cmd = self._get_font_preamble_and_command()
116+
# Add a hash of the latex preamble to fontconfig so that the
117+
# correct png is selected for strings rendered with same font and dpi
118+
# even if the latex preamble changes within the session
119+
preambles = preamble + font_cmd + self.get_custom_preamble()
120+
return hashlib.md5(preambles.encode('utf-8')).hexdigest()
121+
122+
def _get_font_family_and_reduced(self):
107123
ff = rcParams['font.family']
108124
ff_val = ff[0].lower() if len(ff) == 1 else None
109125
reduced_notation = False
110126
if len(ff) == 1 and ff_val in self._font_families:
111-
self._font_family = ff_val
112-
elif len(ff) == 1 and ff_val in self._font_info:
113-
reduced_notation = True
114-
self._font_family = self._font_types[ff_val]
127+
return ff_val, False
128+
elif len(ff) == 1 and ff_val in self._font_preambles:
129+
return self._font_types[ff_val], True
115130
else:
116131
_log.info('font.family must be one of (%s) when text.usetex is '
117132
'True. serif will be used by default.',
118133
', '.join(self._font_families))
119-
self._font_family = 'serif'
134+
return 'serif', False
135+
136+
def _get_font_preamble_and_command(self):
137+
requested_family, is_reduced_font = self._get_font_family_and_reduced()
120138

121-
fontconfig = [self._font_family]
122-
fonts = {}
139+
preambles = {}
123140
for font_family in self._font_families:
124-
if reduced_notation and self._font_family == font_family:
125-
fonts[font_family] = self._font_info[ff_val]
141+
if is_reduced_font and font_family == requested_family:
142+
preambles[font_family] = self._font_preambles[
143+
rcParams['font.family'][0].lower()]
126144
else:
127145
for font in rcParams['font.' + font_family]:
128-
if font.lower() in self._font_info:
129-
fonts[font_family] = self._font_info[font.lower()]
146+
if font.lower() in self._font_preambles:
147+
preambles[font_family] = \
148+
self._font_preambles[font.lower()]
130149
_log.debug(
131150
'family: %s, font: %s, info: %s',
132-
font_family, font, self._font_info[font.lower()])
151+
font_family, font,
152+
self._font_preambles[font.lower()])
133153
break
134154
else:
135155
_log.debug('%s font is not compatible with usetex.',
@@ -138,24 +158,20 @@ def get_font_config(self):
138158
_log.info('No LaTeX-compatible font found for the %s font'
139159
'family in rcParams. Using default.',
140160
font_family)
141-
fonts[font_family] = self._font_info[font_family]
142-
fontconfig.append(fonts[font_family][0])
143-
# Add a hash of the latex preamble to fontconfig so that the
144-
# correct png is selected for strings rendered with same font and dpi
145-
# even if the latex preamble changes within the session
146-
preamble_bytes = self.get_custom_preamble().encode('utf-8')
147-
fontconfig.append(hashlib.md5(preamble_bytes).hexdigest())
161+
preambles[font_family] = self._font_preambles[font_family]
148162

149163
# The following packages and commands need to be included in the latex
150164
# file's preamble:
151-
cmd = {fonts[family][1]
165+
cmd = {preambles[family]
152166
for family in ['serif', 'sans-serif', 'monospace']}
153-
if self._font_family == 'cursive':
154-
cmd.add(fonts['cursive'][1])
167+
if requested_family == 'cursive':
168+
cmd.add(preambles['cursive'])
155169
cmd.add(r'\usepackage{type1cm}')
156-
self._font_preamble = '\n'.join(sorted(cmd))
157-
158-
return ''.join(fontconfig)
170+
preamble = '\n'.join(sorted(cmd))
171+
fontcmd = (r'\sffamily' if requested_family == 'sans-serif' else
172+
r'\ttfamily' if requested_family == 'monospace' else
173+
r'\rmfamily')
174+
return preamble, fontcmd
159175

160176
def get_basefile(self, tex, fontsize, dpi=None):
161177
"""
@@ -169,26 +185,24 @@ def get_font_preamble(self):
169185
"""
170186
Return a string containing font configuration for the tex preamble.
171187
"""
172-
return self._font_preamble
188+
font_preamble, command = self._get_font_preamble_and_command()
189+
return font_preamble
173190

174191
def get_custom_preamble(self):
175192
"""Return a string containing user additions to the tex preamble."""
176193
return rcParams['text.latex.preamble']
177194

178195
def _get_tex_source(self, tex, fontsize):
179196
"""Return the complete TeX source for processing a TeX string."""
180-
self.get_font_config() # Updates self._font_preamble.
197+
font_preamble, fontcmd = self._get_font_preamble_and_command()
181198
baselineskip = 1.25 * fontsize
182-
fontcmd = (r'\sffamily' if self._font_family == 'sans-serif' else
183-
r'\ttfamily' if self._font_family == 'monospace' else
184-
r'\rmfamily')
185199
return "\n".join([
186200
r"\documentclass{article}",
187201
r"% Pass-through \mathdefault, which is used in non-usetex mode",
188202
r"% to use the default text font but was historically suppressed",
189203
r"% in usetex mode.",
190204
r"\newcommand{\mathdefault}[1]{#1}",
191-
self._font_preamble,
205+
font_preamble,
192206
r"\usepackage[utf8]{inputenc}",
193207
r"\DeclareUnicodeCharacter{2212}{\ensuremath{-}}",
194208
r"% geometry is loaded before the custom preamble as ",
@@ -301,7 +315,7 @@ def get_grey(self, tex, fontsize=None, dpi=None):
301315
fontsize = rcParams['font.size']
302316
if not dpi:
303317
dpi = rcParams['savefig.dpi']
304-
key = tex, self.get_font_config(), fontsize, dpi
318+
key = self._get_tex_source(tex, fontsize), dpi
305319
alpha = self._grey_arrayd.get(key)
306320
if alpha is None:
307321
pngfile = self.make_png(tex, fontsize, dpi)

0 commit comments

Comments
 (0)