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

Skip to content

Commit a5b164c

Browse files
committed
Pathlibify font_manager (only internally, doesn't change the API).
1 parent 197bb59 commit a5b164c

File tree

3 files changed

+30
-64
lines changed

3 files changed

+30
-64
lines changed

lib/matplotlib/cbook/__init__.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -676,6 +676,7 @@ def dedent(s):
676676
return result
677677

678678

679+
@deprecated("3.0")
679680
def listFiles(root, patterns='*', recurse=1, return_folders=0):
680681
"""
681682
Recursively list files

lib/matplotlib/font_manager.py

Lines changed: 27 additions & 53 deletions
Original file line numberDiff line numberDiff line change
@@ -34,12 +34,13 @@
3434
from collections import Iterable
3535
from functools import lru_cache
3636
import json
37+
import logging
3738
import os
39+
from pathlib import Path
3840
import subprocess
3941
import sys
4042
from threading import Timer
4143
import warnings
42-
import logging
4344

4445
from matplotlib import afm, cbook, ft2font, rcParams, get_cachedir
4546
from matplotlib.fontconfig_pattern import (
@@ -129,13 +130,8 @@
129130
]
130131

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

140136

141137
def get_fontext_synonyms(fontext):
@@ -151,34 +147,28 @@ def get_fontext_synonyms(fontext):
151147
def list_fonts(directory, extensions):
152148
"""
153149
Return a list of all fonts matching any of the extensions,
154-
possibly upper-cased, found recursively under the directory.
150+
found recursively under the directory.
155151
"""
156-
pattern = ';'.join(['*.%s;*.%s' % (ext, ext.upper())
157-
for ext in extensions])
158-
return cbook.listFiles(directory, pattern)
152+
return [str(path)
153+
for path in Path().rglob("*")
154+
if path.is_file() and path.suffix[1:] in extensions]
159155

160156

161157
def win32FontDirectory():
162-
"""
158+
r"""
163159
Return the user-specified font directory for Win32. This is
164160
looked up from the registry key::
165161
166-
\\\\HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\Shell Folders\\Fonts
162+
\\HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders\Fonts
167163
168164
If the key is not found, $WINDIR/Fonts will be returned.
169165
"""
170166
import winreg
171167
try:
172-
user = winreg.OpenKey(winreg.HKEY_CURRENT_USER, MSFolders)
173-
try:
168+
with winreg.OpenKey(winreg.HKEY_CURRENT_USER, MSFolders) as user:
174169
return winreg.QueryValueEx(user, 'Fonts')[0]
175-
except OSError:
176-
pass # Fall through to default
177-
finally:
178-
winreg.CloseKey(user)
179170
except OSError:
180-
pass # Fall through to default
181-
return os.path.join(os.environ['WINDIR'], 'Fonts')
171+
return os.path.join(os.environ['WINDIR'], 'Fonts')
182172

183173

184174
def win32InstalledFonts(directory=None, fontext='ttf'):
@@ -196,37 +186,23 @@ def win32InstalledFonts(directory=None, fontext='ttf'):
196186

197187
fontext = get_fontext_synonyms(fontext)
198188

199-
key, items = None, set()
189+
items = set()
200190
for fontdir in MSFontDirectories:
201191
try:
202-
local = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, fontdir)
203-
except OSError:
204-
continue
205-
if not local:
206-
return list_fonts(directory, fontext)
207-
try:
208-
for j in range(winreg.QueryInfoKey(local)[1]):
209-
try:
192+
with winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, fontdir) as local:
193+
for j in range(winreg.QueryInfoKey(local)[1]):
210194
key, direc, tp = winreg.EnumValue(local, j)
211195
if not isinstance(direc, str):
212196
continue
213197
# Work around for https://bugs.python.org/issue25778, which
214198
# is fixed in Py>=3.6.1.
215199
direc = direc.split("\0", 1)[0]
216-
if not os.path.dirname(direc):
217-
direc = os.path.join(directory, direc)
218-
direc = os.path.abspath(direc).lower()
219-
if os.path.splitext(direc)[1][1:] in fontext:
220-
items.add(direc)
221-
except EnvironmentError:
222-
continue
223-
except WindowsError:
224-
continue
225-
except MemoryError:
226-
continue
227-
return list(items)
228-
finally:
229-
winreg.CloseKey(local)
200+
path = Path(directory, direc).resolve()
201+
if path.suffix.lower() in fontext:
202+
items.add(str(path))
203+
return list(items)
204+
except (OSError, MemoryError):
205+
continue
230206
return None
231207

232208

@@ -242,6 +218,9 @@ def OSXInstalledFonts(directories=None, fontext='ttf'):
242218
files = []
243219
for path in directories:
244220
if fontext is None:
221+
cbook.warn_deprecated(
222+
"3.0", "Support for listing all files regardless of extension "
223+
"is deprecated.")
245224
files.extend(cbook.listFiles(path, '*'))
246225
else:
247226
files.extend(list_fonts(path, fontext))
@@ -271,7 +250,7 @@ def get_fontconfig_fonts(fontext='ttf'):
271250
"""
272251
fontext = get_fontext_synonyms(fontext)
273252
return [fname for fname in _call_fc_list()
274-
if os.path.splitext(fname)[1][1:] in fontext]
253+
if Path(fname).suffix[1:] in fontext]
275254

276255

277256
def findSystemFonts(fontpaths=None, fontext='ttf'):
@@ -292,8 +271,7 @@ def findSystemFonts(fontpaths=None, fontext='ttf'):
292271
fontpaths = [fontdir]
293272
# now get all installed fonts directly...
294273
for f in win32InstalledFonts(fontdir):
295-
base, ext = os.path.splitext(f)
296-
if len(ext)>1 and ext[1:].lower() in fontexts:
274+
if Path(f).suffix in fontexts:
297275
fontfiles.add(f)
298276
else:
299277
fontpaths = X11FontDirectories
@@ -1238,16 +1216,12 @@ def _findfont_cached(self, prop, fontext, directory, fallback_to_default,
12381216
else:
12391217
fontlist = self.ttflist
12401218

1241-
if directory is not None:
1242-
directory = os.path.normcase(directory)
1243-
12441219
best_score = 1e64
12451220
best_font = None
12461221

12471222
for font in fontlist:
12481223
if (directory is not None and
1249-
os.path.commonprefix([os.path.normcase(font.fname),
1250-
directory]) != directory):
1224+
Path(directory) not in Path(font.fname).parents):
12511225
continue
12521226
# Matching family should have highest priority, so it is multiplied
12531227
# by 10.0

lib/matplotlib/tests/test_font_manager.py

Lines changed: 2 additions & 11 deletions
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)