Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

Commit 03052fa

Browse filesBrowse files
committed
Py3fy font_manager.
1 parent b5391ce commit 03052fa
Copy full SHA for 03052fa

File tree

Expand file treeCollapse file tree

2 files changed

+55
-83
lines changed
Filter options
Expand file treeCollapse file tree

2 files changed

+55
-83
lines changed
+5Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
Removal of deprecated functions
2+
```````````````````````````````
3+
The following previously deprecated functions have been removed:
4+
- ``matplotlib.font_manager.ttfdict_to_fnames``
5+
- ``matplotlib.font_manager.weight_as_number``

‎lib/matplotlib/font_manager.py

Copy file name to clipboardExpand all lines: lib/matplotlib/font_manager.py
+50-83Lines changed: 50 additions & 83 deletions
Original file line numberDiff line numberDiff line change
@@ -20,28 +20,16 @@
2020
found.
2121
"""
2222

23-
import six
24-
25-
"""
26-
KNOWN ISSUES
27-
28-
- documentation
29-
- font variant is untested
30-
- font stretch is incomplete
31-
- font size is incomplete
32-
- default font algorithm needs improvement and testing
33-
- setWeights function needs improvement
34-
- 'light' is an invalid weight value, remove it.
35-
- update_fonts not implemented
36-
37-
Authors : John Hunter <jdhunter@ace.bsd.uchicago.edu>
38-
Paul Barrett <Barrett@STScI.Edu>
39-
Michael Droettboom <mdroe@STScI.edu>
40-
Copyright : John Hunter (2004,2005), Paul Barrett (2004,2005)
41-
License : matplotlib license (PSF compatible)
42-
The font directory code is from ttfquery,
43-
see license/LICENSE_TTFQUERY.
44-
"""
23+
# KNOWN ISSUES
24+
#
25+
# - documentation
26+
# - font variant is untested
27+
# - font stretch is incomplete
28+
# - font size is incomplete
29+
# - default font algorithm needs improvement and testing
30+
# - setWeights function needs improvement
31+
# - 'light' is an invalid weight value, remove it.
32+
# - update_fonts not implemented
4533

4634
from collections import Iterable
4735
from functools import lru_cache
@@ -179,22 +167,17 @@ def win32FontDirectory():
179167
180168
If the key is not found, $WINDIR/Fonts will be returned.
181169
"""
170+
import winreg
182171
try:
183-
from six.moves import winreg
184-
except ImportError:
185-
pass # Fall through to default
186-
else:
172+
user = winreg.OpenKey(winreg.HKEY_CURRENT_USER, MSFolders)
187173
try:
188-
user = winreg.OpenKey(winreg.HKEY_CURRENT_USER, MSFolders)
189-
try:
190-
try:
191-
return winreg.QueryValueEx(user, 'Fonts')[0]
192-
except OSError:
193-
pass # Fall through to default
194-
finally:
195-
winreg.CloseKey(user)
174+
return winreg.QueryValueEx(user, 'Fonts')[0]
196175
except OSError:
197176
pass # Fall through to default
177+
finally:
178+
winreg.CloseKey(user)
179+
except OSError:
180+
pass # Fall through to default
198181
return os.path.join(os.environ['WINDIR'], 'Fonts')
199182

200183

@@ -206,7 +189,8 @@ def win32InstalledFonts(directory=None, fontext='ttf'):
206189
'afm'.
207190
"""
208191

209-
from six.moves import winreg
192+
import winreg
193+
210194
if directory is None:
211195
directory = win32FontDirectory()
212196

@@ -224,7 +208,7 @@ def win32InstalledFonts(directory=None, fontext='ttf'):
224208
for j in range(winreg.QueryInfoKey(local)[1]):
225209
try:
226210
key, direc, tp = winreg.EnumValue(local, j)
227-
if not isinstance(direc, six.string_types):
211+
if not isinstance(direc, str):
228212
continue
229213
# Work around for https://bugs.python.org/issue25778, which
230214
# is fixed in Py>=3.6.1.
@@ -274,19 +258,12 @@ def _call_fc_list():
274258
'This may take a moment.'))
275259
timer.start()
276260
try:
277-
out = subprocess.check_output([str('fc-list'), '--format=%{file}\\n'])
261+
out = subprocess.check_output(['fc-list', '--format=%{file}\\n'])
278262
except (OSError, subprocess.CalledProcessError):
279263
return []
280264
finally:
281265
timer.cancel()
282-
fnames = []
283-
for fname in out.split(b'\n'):
284-
try:
285-
fname = six.text_type(fname, sys.getfilesystemencoding())
286-
except UnicodeDecodeError:
287-
continue
288-
fnames.append(fname)
289-
return fnames
266+
return [os.fsdecode(fname) for fname in out.split(b'\n')]
290267

291268

292269
def get_fontconfig_fonts(fontext='ttf'):
@@ -328,7 +305,7 @@ def findSystemFonts(fontpaths=None, fontext='ttf'):
328305
for f in get_fontconfig_fonts(fontext):
329306
fontfiles.add(f)
330307

331-
elif isinstance(fontpaths, six.string_types):
308+
elif isinstance(fontpaths, str):
332309
fontpaths = [fontpaths]
333310

334311
for path in fontpaths:
@@ -478,9 +455,9 @@ def afmFontProperty(fontpath, font):
478455

479456
# Styles are: italic, oblique, and normal (default)
480457

481-
if font.get_angle() != 0 or name.lower().find('italic') >= 0:
458+
if font.get_angle() != 0 or 'italic' in name.lower():
482459
style = 'italic'
483-
elif name.lower().find('oblique') >= 0:
460+
elif 'oblique' in name.lower():
484461
style = 'oblique'
485462
else:
486463
style = 'normal'
@@ -501,12 +478,11 @@ def afmFontProperty(fontpath, font):
501478
# and ultra-expanded.
502479
# Relative stretches are: wider, narrower
503480
# Child value is: inherit
504-
if fontname.find('narrow') >= 0 or fontname.find('condensed') >= 0 or \
505-
fontname.find('cond') >= 0:
506-
stretch = 'condensed'
507-
elif fontname.find('demi cond') >= 0:
481+
if 'demi cond' in fontname:
508482
stretch = 'semi-condensed'
509-
elif fontname.find('wide') >= 0 or fontname.find('expanded') >= 0:
483+
elif 'narrow' in fontname or 'cond' in fontname:
484+
stretch = 'condensed'
485+
elif 'wide' in fontname or 'expanded' in fontname:
510486
stretch = 'expanded'
511487
else:
512488
stretch = 'normal'
@@ -568,7 +544,7 @@ def createFontList(fontfiles, fontext='ttf'):
568544
except UnicodeError:
569545
_log.info("Cannot handle unicode filenames")
570546
continue
571-
except IOError:
547+
except OSError:
572548
_log.info("IO error - cannot open font file %s", fpath)
573549
continue
574550
try:
@@ -646,7 +622,7 @@ def __init__(self,
646622
weight = None,
647623
stretch= None,
648624
size = None,
649-
fname = None, # if this is set, it's a hardcoded filename to use
625+
fname = None, # if set, it's a hardcoded filename to use
650626
_init = None # used only by copy()
651627
):
652628
self._family = _normalize_font_family(rcParams['font.family'])
@@ -662,7 +638,7 @@ def __init__(self,
662638
self.__dict__.update(_init.__dict__)
663639
return
664640

665-
if isinstance(family, six.string_types):
641+
if isinstance(family, str):
666642
# Treat family as a fontconfig pattern if it is the only
667643
# parameter provided.
668644
if (style is None and
@@ -712,23 +688,20 @@ def get_family(self):
712688

713689
def get_name(self):
714690
"""
715-
Return the name of the font that best matches the font
716-
properties.
691+
Return the name of the font that best matches the font properties.
717692
"""
718693
return get_font(findfont(self)).family_name
719694

720695
def get_style(self):
721696
"""
722-
Return the font style. Values are: 'normal', 'italic' or
723-
'oblique'.
697+
Return the font style. Values are: 'normal', 'italic' or 'oblique'.
724698
"""
725699
return self._slant
726700
get_slant = get_style
727701

728702
def get_variant(self):
729703
"""
730-
Return the font variant. Values are: 'normal' or
731-
'small-caps'.
704+
Return the font variant. Values are: 'normal' or 'small-caps'.
732705
"""
733706
return self._variant
734707

@@ -793,8 +766,7 @@ def set_family(self, family):
793766

794767
def set_style(self, style):
795768
"""
796-
Set the font style. Values are: 'normal', 'italic' or
797-
'oblique'.
769+
Set the font style. Values are: 'normal', 'italic' or 'oblique'.
798770
"""
799771
if style is None:
800772
style = rcParams['font.style']
@@ -892,7 +864,7 @@ def set_fontconfig_pattern(self, pattern):
892864
support for it to be enabled. We are merely borrowing its
893865
pattern syntax for use here.
894866
"""
895-
for key, val in six.iteritems(self._parse_fontconfig_pattern(pattern)):
867+
for key, val in self._parse_fontconfig_pattern(pattern).items():
896868
if type(val) == list:
897869
getattr(self, "set_" + key)(val[0])
898870
else:
@@ -936,9 +908,10 @@ def json_dump(data, filename):
936908
with open(filename, 'w') as fh:
937909
try:
938910
json.dump(data, fh, cls=JSONEncoder, indent=2)
939-
except IOError as e:
911+
except OSError as e:
940912
warnings.warn('Could not save font_manager cache ', e)
941913

914+
942915
def json_load(filename):
943916
"""Loads a data structure as JSON from the named file.
944917
Handles FontManager and its fields."""
@@ -948,10 +921,8 @@ def json_load(filename):
948921

949922

950923
def _normalize_font_family(family):
951-
if isinstance(family, six.string_types):
952-
family = [six.text_type(family)]
953-
elif isinstance(family, Iterable):
954-
family = [six.text_type(f) for f in family]
924+
if isinstance(family, str):
925+
family = [family]
955926
return family
956927

957928

@@ -1170,14 +1141,14 @@ def score_weight(self, weight1, weight2):
11701141
The result is 0.0 if both weight1 and weight 2 are given as strings
11711142
and have the same value.
11721143
1173-
Otherwise, the result is the absolute value of the difference between the
1174-
CSS numeric values of *weight1* and *weight2*, normalized
1175-
between 0.05 and 1.0.
1144+
Otherwise, the result is the absolute value of the difference between
1145+
the CSS numeric values of *weight1* and *weight2*, normalized between
1146+
0.05 and 1.0.
11761147
"""
11771148

1178-
# exact match of the weight names (e.g. weight1 == weight2 == "regular")
1179-
if (isinstance(weight1, six.string_types) and
1180-
isinstance(weight2, six.string_types) and
1149+
# exact match of the weight names, e.g. weight1 == weight2 == "regular"
1150+
if (isinstance(weight1, str) and
1151+
isinstance(weight2, str) and
11811152
weight1 == weight2):
11821153
return 0.0
11831154
try:
@@ -1364,26 +1335,22 @@ def fc_match(pattern, fontext):
13641335
stdout=subprocess.PIPE,
13651336
stderr=subprocess.PIPE)
13661337
output = pipe.communicate()[0]
1367-
except (OSError, IOError):
1338+
except OSError:
13681339
return None
13691340

13701341
# The bulk of the output from fc-list is ascii, so we keep the
13711342
# result in bytes and parse it as bytes, until we extract the
13721343
# filename, which is in sys.filesystemencoding().
13731344
if pipe.returncode == 0:
1374-
for fname in output.split(b'\n'):
1375-
try:
1376-
fname = six.text_type(fname, sys.getfilesystemencoding())
1377-
except UnicodeDecodeError:
1378-
continue
1345+
for fname in map(os.fsdecode, output.split(b'\n')):
13791346
if os.path.splitext(fname)[1][1:] in fontexts:
13801347
return fname
13811348
return None
13821349

13831350
_fc_match_cache = {}
13841351

13851352
def findfont(prop, fontext='ttf'):
1386-
if not isinstance(prop, six.string_types):
1353+
if not isinstance(prop, str):
13871354
prop = prop.get_fontconfig_pattern()
13881355
cached = _fc_match_cache.get(prop)
13891356
if cached is not None:

0 commit comments

Comments
0 (0)
Morty Proxy This is a proxified and sanitized view of the page, visit original site.