Skip to content

Commit 0e2c60e

Browse files
committed
Pathlibify font_manager (only internally, doesn't change the API).
1 parent fb4b612 commit 0e2c60e

File tree

2 files changed

+21
-56
lines changed

2 files changed

+21
-56
lines changed

lib/matplotlib/font_manager.py

+19-45
Original file line numberDiff line numberDiff line change
@@ -34,13 +34,13 @@
3434
from collections import Iterable
3535
from functools import lru_cache
3636
import json
37+
import logging
3738
import os
3839
from pathlib import Path
3940
import subprocess
4041
import sys
4142
from threading import Timer
4243
import warnings
43-
import logging
4444

4545
from matplotlib import afm, cbook, ft2font, rcParams, get_cachedir
4646
from matplotlib.fontconfig_pattern import (
@@ -130,13 +130,8 @@
130130
]
131131

132132
if not USE_FONTCONFIG and sys.platform != 'win32':
133-
home = os.environ.get('HOME')
134-
if home is not None:
135-
# user fonts on OSX
136-
path = os.path.join(home, 'Library', 'Fonts')
137-
OSXFontDirectories.append(path)
138-
path = os.path.join(home, '.fonts')
139-
X11FontDirectories.append(path)
133+
OSXFontDirectories.append(str(Path.home() / "Library/Fonts"))
134+
X11FontDirectories.append(str(Path.home() / ".fonts"))
140135

141136

142137
def get_fontext_synonyms(fontext):
@@ -161,26 +156,20 @@ def list_fonts(directory, extensions):
161156

162157

163158
def win32FontDirectory():
164-
"""
159+
r"""
165160
Return the user-specified font directory for Win32. This is
166161
looked up from the registry key::
167162
168-
\\\\HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\Shell Folders\\Fonts
163+
\\HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders\Fonts
169164
170165
If the key is not found, $WINDIR/Fonts will be returned.
171166
"""
172167
import winreg
173168
try:
174-
user = winreg.OpenKey(winreg.HKEY_CURRENT_USER, MSFolders)
175-
try:
169+
with winreg.OpenKey(winreg.HKEY_CURRENT_USER, MSFolders) as user:
176170
return winreg.QueryValueEx(user, 'Fonts')[0]
177-
except OSError:
178-
pass # Fall through to default
179-
finally:
180-
winreg.CloseKey(user)
181171
except OSError:
182-
pass # Fall through to default
183-
return os.path.join(os.environ['WINDIR'], 'Fonts')
172+
return os.path.join(os.environ['WINDIR'], 'Fonts')
184173

185174

186175
def win32InstalledFonts(directory=None, fontext='ttf'):
@@ -198,33 +187,23 @@ def win32InstalledFonts(directory=None, fontext='ttf'):
198187

199188
fontext = get_fontext_synonyms(fontext)
200189

201-
key, items = None, set()
190+
items = set()
202191
for fontdir in MSFontDirectories:
203192
try:
204-
local = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, fontdir)
205-
except OSError:
206-
continue
207-
if not local:
208-
return list_fonts(directory, fontext)
209-
try:
210-
for j in range(winreg.QueryInfoKey(local)[1]):
211-
try:
193+
with winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, fontdir) as local:
194+
for j in range(winreg.QueryInfoKey(local)[1]):
212195
key, direc, tp = winreg.EnumValue(local, j)
213196
if not isinstance(direc, str):
214197
continue
215198
# Work around for https://bugs.python.org/issue25778, which
216199
# is fixed in Py>=3.6.1.
217200
direc = direc.split("\0", 1)[0]
218-
if not os.path.dirname(direc):
219-
direc = os.path.join(directory, direc)
220-
direc = os.path.abspath(direc).lower()
221-
if os.path.splitext(direc)[1][1:] in fontext:
222-
items.add(direc)
223-
except (EnvironmentError, MemoryError, WindowsError):
224-
continue
225-
return list(items)
226-
finally:
227-
winreg.CloseKey(local)
201+
path = Path(directory, direc).resolve()
202+
if path.suffix.lower() in fontext:
203+
items.add(str(path))
204+
return list(items)
205+
except (OSError, MemoryError):
206+
continue
228207
return None
229208

230209

@@ -261,7 +240,7 @@ def get_fontconfig_fonts(fontext='ttf'):
261240
"""
262241
fontext = get_fontext_synonyms(fontext)
263242
return [fname for fname in _call_fc_list()
264-
if os.path.splitext(fname)[1][1:] in fontext]
243+
if Path(fname).suffix[1:] in fontext]
265244

266245

267246
def findSystemFonts(fontpaths=None, fontext='ttf'):
@@ -282,8 +261,7 @@ def findSystemFonts(fontpaths=None, fontext='ttf'):
282261
fontpaths = [fontdir]
283262
# now get all installed fonts directly...
284263
for f in win32InstalledFonts(fontdir):
285-
base, ext = os.path.splitext(f)
286-
if len(ext)>1 and ext[1:].lower() in fontexts:
264+
if Path(f).suffix in fontexts:
287265
fontfiles.add(f)
288266
else:
289267
fontpaths = X11FontDirectories
@@ -1225,16 +1203,12 @@ def _findfont_cached(self, prop, fontext, directory, fallback_to_default,
12251203
else:
12261204
fontlist = self.ttflist
12271205

1228-
if directory is not None:
1229-
directory = os.path.normcase(directory)
1230-
12311206
best_score = 1e64
12321207
best_font = None
12331208

12341209
for font in fontlist:
12351210
if (directory is not None and
1236-
os.path.commonprefix([os.path.normcase(font.fname),
1237-
directory]) != directory):
1211+
Path(directory) not in Path(font.fname).parents):
12381212
continue
12391213
# Matching family should have highest priority, so it is multiplied
12401214
# by 10.0

lib/matplotlib/tests/test_font_manager.py

+2-11
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,5 @@
1-
from __future__ import absolute_import, division, print_function
2-
3-
import six
4-
51
import os
2+
import shutil
63
import tempfile
74
import warnings
85

@@ -14,13 +11,7 @@
1411
get_fontconfig_fonts, is_opentype_cff_font, fontManager as fm)
1512
from matplotlib import rc_context
1613

17-
if six.PY2:
18-
from distutils.spawn import find_executable
19-
has_fclist = find_executable('fc-list') is not None
20-
else:
21-
# py >= 3.3
22-
from shutil import which
23-
has_fclist = which('fc-list') is not None
14+
has_fclist = shutil.which('fc-list') is not None
2415

2516

2617
def test_font_priority():

0 commit comments

Comments
 (0)