""" A module for finding, managing, and using fonts across platforms.
This module provides a single :class:`FontManager` instance that can be shared across backends and platforms. The :func:`findfont` function returns the best TrueType (TTF) font file in the local or system font path that matches the specified :class:`FontProperties` instance. The :class:`FontManager` also handles Adobe Font Metrics (AFM) font files for use by the PostScript backend.
The design is based on the `W3C Cascading Style Sheet, Level 1 (CSS1) font specification <http://www.w3.org/TR/1998/REC-CSS2-19980512/>`_. Future versions may implement the Level 2 or 2.1 specifications.
Experimental support is included for using `fontconfig` on Unix variant platforms (Linux, OS X, Solaris). To enable it, set the constant ``USE_FONTCONFIG`` in this file to ``True``. Fontconfig has the advantage that it is the standard way to look up fonts on X11 platforms, so if a font is installed, it is much more likely to be found. """
# KNOWN ISSUES # # - documentation # - font variant is untested # - font stretch is incomplete # - font size is incomplete # - default font algorithm needs improvement and testing # - setWeights function needs improvement # - 'light' is an invalid weight value, remove it. # - update_fonts not implemented
except ImportError: from dummy_threading import Timer
parse_fontconfig_pattern, generate_fontconfig_pattern)
'xx-small' : 0.579, 'x-small' : 0.694, 'small' : 0.833, 'medium' : 1.0, 'large' : 1.200, 'x-large' : 1.440, 'xx-large' : 1.728, 'larger' : 1.2, 'smaller' : 0.833, None : 1.0}
'ultra-condensed' : 100, 'extra-condensed' : 200, 'condensed' : 300, 'semi-condensed' : 400, 'normal' : 500, 'semi-expanded' : 600, 'expanded' : 700, 'extra-expanded' : 800, 'ultra-expanded' : 900}
'ultralight' : 100, 'light' : 200, 'normal' : 400, 'regular' : 400, 'book' : 400, 'medium' : 500, 'roman' : 500, 'semibold' : 600, 'demibold' : 600, 'demi' : 600, 'bold' : 700, 'heavy' : 800, 'extra bold' : 800, 'black' : 900}
'serif', 'sans-serif', 'sans serif', 'cursive', 'fantasy', 'monospace', 'sans'}
# OS Font paths r'Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders'
r'SOFTWARE\Microsoft\Windows NT\CurrentVersion\Fonts', r'SOFTWARE\Microsoft\Windows\CurrentVersion\Fonts']
# an old standard installation point "/usr/X11R6/lib/X11/fonts/TTF/", "/usr/X11/lib/X11/fonts", # here is the new standard location for fonts "/usr/share/fonts/", # documented as a good place to install new fonts "/usr/local/share/fonts/", # common application, not really useful "/usr/lib/openoffice/share/fonts/truetype/", ]
"/Library/Fonts/", "/Network/Library/Fonts/", "/System/Library/Fonts/", # fonts installed via MacPorts "/opt/local/share/fonts", ]
""" Return a list of file extensions extensions that are synonyms for the given file extension *fileext*. """ 'otf': ('ttf', 'otf'), 'afm': ('afm',)}[fontext]
""" Return a list of all fonts matching any of the extensions, found recursively under the directory. """ # os.walk ignores access errors, unlike Path.glob. for dirpath, _, filenames in os.walk(directory) for filename in filenames if Path(filename).suffix.lower() in extensions]
r""" Return the user-specified font directory for Win32. This is looked up from the registry key::
\\HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders\Fonts
If the key is not found, $WINDIR/Fonts will be returned. """ import winreg try: with winreg.OpenKey(winreg.HKEY_CURRENT_USER, MSFolders) as user: return winreg.QueryValueEx(user, 'Fonts')[0] except OSError: return os.path.join(os.environ['WINDIR'], 'Fonts')
""" Search for fonts in the specified font directory, or use the system directories if none given. A list of TrueType font filenames are returned by default, or AFM fonts if *fontext* == 'afm'. """ import winreg
if directory is None: directory = win32FontDirectory()
fontext = ['.' + ext for ext in get_fontext_synonyms(fontext)]
items = set() for fontdir in MSFontDirectories: try: with winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, fontdir) as local: for j in range(winreg.QueryInfoKey(local)[1]): key, direc, tp = winreg.EnumValue(local, j) if not isinstance(direc, str): continue # Work around for https://bugs.python.org/issue25778, which # is fixed in Py>=3.6.1. direc = direc.split("\0", 1)[0] try: path = Path(directory, direc).resolve() except (FileNotFoundError, RuntimeError): # Don't fail with invalid entries (FileNotFoundError is # only necessary on Py3.5). continue if path.suffix.lower() in fontext: items.add(str(path)) except (OSError, MemoryError): continue return list(items)
"""Get list of font files on OS X.""" if directories is None: directories = OSXFontDirectories return [path for directory in directories for path in list_fonts(directory, get_fontext_synonyms(fontext))]
def _call_fc_list(): """Cache and list the font filenames known to `fc-list`. """ # Delay the warning by 5s. 'Matplotlib is building the font cache using fc-list. ' 'This may take a moment.')) except (OSError, subprocess.CalledProcessError): return [] finally:
"""List the font filenames known to `fc-list` having the given extension. """ if Path(fname).suffix.lower() in fontext]
""" Search for fonts in the specified font paths. If no paths are given, will use a standard set of system paths, as well as the list of fonts tracked by fontconfig if fontconfig is installed and available. A list of TrueType fonts are returned by default with AFM fonts as an option. """
fontpaths = [win32FontDirectory()] # now get all installed fonts directly... fontfiles.update(win32InstalledFonts(fontext=fontext)) else: # check for OS X & load its fonts if present fontfiles.update(OSXInstalledFonts(fontext=fontext))
fontpaths = [fontpaths]
""" A class for storing Font properties. It is used when populating the font lookup dictionary. """ fname ='', name ='', style ='normal', variant='normal', weight ='normal', stretch='normal', size ='medium', ):
def __repr__(self): return "<Font '%s' (%s) %s %s %s %s>" % ( self.name, os.path.basename(self.fname), self.style, self.variant, self.weight, self.stretch)
""" Extract information from a TrueType font file.
Parameters ---------- font : `.FT2Font` The TrueType font file from which information will be extracted.
Returns ------- `FontEntry` The extracted font properties.
"""
# Styles are: italic, oblique, and normal (default)
# These tables are actually mac_roman-encoded, but mac_roman support may be # missing in some alternative Python implementations and we are only going # to look for ASCII substrings, where any ASCII-compatible encoding works. else:
# Variants are: small-caps and normal (default)
# !!!! Untested variant = 'small-caps' else:
weight = 700 else:
# Stretch can be absolute and relative # Absolute stretches are: ultra-condensed, extra-condensed, condensed, # semi-condensed, normal, semi-expanded, expanded, extra-expanded, # and ultra-expanded. # Relative stretches are: wider, narrower # Child value is: inherit
sfnt4.find('cond') >= 0): stretch = 'condensed' stretch = 'semi-condensed' stretch = 'expanded' else:
# Sizes can be absolute and relative. # Absolute sizes are: xx-small, x-small, small, medium, large, x-large, # and xx-large. # Relative sizes are: larger, smaller # Length value is an absolute font size, e.g., 12pt # Percentage values are in 'em's. Most robust specification.
raise NotImplementedError("Non-scalable fonts are not supported")
""" Extract information from an AFM font file.
Parameters ---------- font : `.AFM` The AFM font file from which information will be extracted.
Returns ------- `FontEntry` The extracted font properties.
"""
# Styles are: italic, oblique, and normal (default)
style = 'oblique' else:
# Variants are: small-caps and normal (default)
# !!!! Untested variant = 'small-caps' else:
# Stretch can be absolute and relative # Absolute stretches are: ultra-condensed, extra-condensed, condensed, # semi-condensed, normal, semi-expanded, expanded, extra-expanded, # and ultra-expanded. # Relative stretches are: wider, narrower # Child value is: inherit stretch = 'semi-condensed' stretch = 'expanded' else:
# Sizes can be absolute and relative. # Absolute sizes are: xx-small, x-small, small, medium, large, x-large, # and xx-large. # Relative sizes are: larger, smaller # Length value is an absolute font size, e.g., 12pt # Percentage values are in 'em's. Most robust specification.
# All AFM fonts are apparently scalable.
""" A function to create a font lookup list. The default is to create a list of TrueType fonts. An AFM font list can optionally be created. """
# Add fonts from list of known font files. else: except EnvironmentError: _log.info("Could not open font file %s", fpath) continue except RuntimeError: _log.info("Could not parse font file %s", fpath) continue except KeyError: continue else: except RuntimeError: _log.info("Could not open font file %s", fpath) continue except UnicodeError: _log.info("Cannot handle unicode filenames") continue except OSError: _log.info("IO error - cannot open font file %s", fpath) continue except (KeyError, RuntimeError, ValueError, NotImplementedError): continue
""" A class for storing and manipulating font properties.
The font properties are those described in the `W3C Cascading Style Sheet, Level 1 <http://www.w3.org/TR/1998/REC-CSS2-19980512/>`_ font specification. The six properties are:
- family: A list of font names in decreasing order of priority. The items may include a generic font family name, either 'serif', 'sans-serif', 'cursive', 'fantasy', or 'monospace'. In that case, the actual font to be used will be looked up from the associated rcParam.
- style: Either 'normal', 'italic' or 'oblique'.
- variant: Either 'normal' or 'small-caps'.
- stretch: A numeric value in the range 0-1000 or one of 'ultra-condensed', 'extra-condensed', 'condensed', 'semi-condensed', 'normal', 'semi-expanded', 'expanded', 'extra-expanded' or 'ultra-expanded'
- weight: A numeric value in the range 0-1000 or one of 'ultralight', 'light', 'normal', 'regular', 'book', 'medium', 'roman', 'semibold', 'demibold', 'demi', 'bold', 'heavy', 'extra bold', 'black'
- size: Either an relative value of 'xx-small', 'x-small', 'small', 'medium', 'large', 'x-large', 'xx-large' or an absolute font size, e.g., 12
The default font property for TrueType fonts (as specified in the default rcParams) is::
sans-serif, normal, normal, normal, normal, scalable.
Alternatively, a font may be specified using an absolute path to a .ttf file, by using the *fname* kwarg.
The preferred usage of font sizes is to use the relative values, e.g., 'large', instead of absolute font sizes, e.g., 12. This approach allows all text sizes to be made larger or smaller based on the font manager's default font size.
This class will also accept a `fontconfig <https://www.freedesktop.org/wiki/Software/fontconfig/>`_ pattern, if it is the only argument provided. See the documentation on `fontconfig patterns <https://www.freedesktop.org/software/fontconfig/fontconfig-user.html>`_. This support does not require fontconfig to be installed. We are merely borrowing its pattern syntax for use here.
Note that Matplotlib's internal font manager and fontconfig use a different algorithm to lookup fonts, so the results of the same pattern may be different in Matplotlib than in other applications that use fontconfig. """
family = None, style = None, variant= None, weight = None, stretch= None, size = None, fname = None, # if set, it's a hardcoded filename to use _init = None # used only by copy() ):
# This is used only by copy()
# Treat family as a fontconfig pattern if it is the only # parameter provided. variant is None and weight is None and stretch is None and size is None and fname is None):
self.get_slant(), self.get_variant(), self.get_weight(), self.get_stretch(), self.get_size_in_points(), self.get_file())
def __str__(self): return self.get_fontconfig_pattern()
""" Return a list of font names that comprise the font family. """
""" Return the name of the font that best matches the font properties. """ return get_font(findfont(self)).family_name
""" Return the font style. Values are: 'normal', 'italic' or 'oblique'. """
""" Return the font variant. Values are: 'normal' or 'small-caps'. """
""" Set the font weight. Options are: A numeric value in the range 0-1000 or one of 'light', 'normal', 'regular', 'book', 'medium', 'roman', 'semibold', 'demibold', 'demi', 'bold', 'heavy', 'extra bold', 'black' """
""" Return the font stretch or width. Options are: 'ultra-condensed', 'extra-condensed', 'condensed', 'semi-condensed', 'normal', 'semi-expanded', 'expanded', 'extra-expanded', 'ultra-expanded'. """
""" Return the font size. """
""" Return the filename of the associated font. """
""" Get a fontconfig pattern suitable for looking up the font as specified with fontconfig's ``fc-match`` utility.
See the documentation on `fontconfig patterns <https://www.freedesktop.org/software/fontconfig/fontconfig-user.html>`_.
This support does not require fontconfig to be installed or support for it to be enabled. We are merely borrowing its pattern syntax for use here. """ return generate_fontconfig_pattern(self)
""" Change the font family. May be either an alias (generic name is CSS parlance), such as: 'serif', 'sans-serif', 'cursive', 'fantasy', or 'monospace', a real font name or a list of real font names. Real font names are not supported when `text.usetex` is `True`. """
""" Set the font style. Values are: 'normal', 'italic' or 'oblique'. """ raise ValueError("style must be normal, italic or oblique")
""" Set the font variant. Values are: 'normal' or 'small-caps'. """ raise ValueError("variant must be normal or small-caps")
""" Set the font weight. May be either a numeric value in the range 0-1000 or one of 'ultralight', 'light', 'normal', 'regular', 'book', 'medium', 'roman', 'semibold', 'demibold', 'demi', 'bold', 'heavy', 'extra bold', 'black' """ if weight < 0 or weight > 1000: raise ValueError() raise ValueError("weight is invalid")
""" Set the font stretch or width. Options are: 'ultra-condensed', 'extra-condensed', 'condensed', 'semi-condensed', 'normal', 'semi-expanded', 'expanded', 'extra-expanded' or 'ultra-expanded', or a numeric value in the range 0-1000. """ if stretch < 0 or stretch > 1000: raise ValueError() raise ValueError("stretch is invalid")
""" Set the font size. Either an relative value of 'xx-small', 'x-small', 'small', 'medium', 'large', 'x-large', 'xx-large' or an absolute font size, e.g., 12. """ except KeyError: raise ValueError( "Size is invalid. Valid font size are " + ", ".join(map(str, font_scalings))) else: _log.info('Fontsize %1.2f < 1.0 pt not allowed by FreeType. ' 'Setting fontsize = 1 pt', size) size = 1.0
""" Set the filename of the fontfile to use. In this case, all other properties will be ignored. """
""" Set the properties by parsing a fontconfig *pattern*.
See the documentation on `fontconfig patterns <https://www.freedesktop.org/software/fontconfig/fontconfig-user.html>`_.
This support does not require fontconfig to be installed or support for it to be enabled. We are merely borrowing its pattern syntax for use here. """ else: getattr(self, "set_" + key)(val)
"""Return a deep copy of self"""
# Cache paths of fonts shipped with mpl relative to the mpl # data path, which helps in the presence of venvs. Path(d["fname"]).relative_to(mpl.get_data_path())) else: return super().default(o)
cls = o.pop('__class__', None) if cls is None: return o elif cls == 'FontManager': r = FontManager.__new__(FontManager) r.__dict__.update(o) return r elif cls == 'FontEntry': r = FontEntry.__new__(FontEntry) r.__dict__.update(o) if not os.path.isabs(r.fname): r.fname = os.path.join(mpl.get_data_path(), r.fname) return r else: raise ValueError("don't know how to deserialize __class__=%s" % cls)
""" Dumps a data structure as JSON in the named file.
Handles FontManager and its fields. File paths that are children of the Matplotlib data path (typically, fonts shipped with Matplotlib) are stored relative to that data path (to remain valid across virtualenvs). """ except OSError as e: warnings.warn('Could not save font_manager cache {}'.format(e))
""" Loads a data structure as JSON from the named file.
Handles FontManager and its fields. Relative file paths are interpreted as being relative to the Matplotlib data path, and transformed into absolute paths. """ return json.load(fh, object_hook=_json_decode)
""" A class to store temporary caches that are (a) not saved to disk and (b) invalidated whenever certain font-related rcParams---namely the family lookup lists---are changed or the font cache is reloaded. This avoids the expensive linear search through all fonts every time a font is looked up. """ # A list of rcparam names that, when changed, invalidated this # cache. 'font.serif', 'font.sans-serif', 'font.cursive', 'font.fantasy', 'font.monospace')
self._lookup_cache = {} self._last_rcParams = self.make_rcparams_key()
return [id(fontManager)] + [ rcParams[param] for param in self.invalidating_rcparams]
key = self.make_rcparams_key() if key != self._last_rcParams: self._lookup_cache = {} self._last_rcParams = key return self._lookup_cache.get(prop)
key = self.make_rcparams_key() if key != self._last_rcParams: self._lookup_cache = {} self._last_rcParams = key self._lookup_cache[prop] = value
""" On import, the :class:`FontManager` singleton instance creates a list of TrueType fonts based on the font properties: name, style, variant, weight, stretch, and size. The :meth:`findfont` method does a nearest neighbor search to find the font that most closely matches the specification. If no good enough match is found, a default font is returned. """ # Increment this version number whenever the font cache data # format or behavior has changed and requires a existing font # cache files to be rebuilt.
os.path.join(rcParams['datapath'], 'fonts', 'afm'), os.path.join(rcParams['datapath'], 'fonts', 'pdfcorefonts')]
# Create list of font paths ttfpath = os.environ[pathname] if ttfpath.find(';') >= 0: #win32 style paths.extend(ttfpath.split(';')) elif ttfpath.find(':') >= 0: # unix style paths.extend(ttfpath.split(':')) else: paths.append(ttfpath) # Load TrueType fonts and create font dictionary.
'ttf': 'DejaVu Sans', 'afm': 'Helvetica'}
(fname for fname in ttffiles if fname.lower().endswith("dejavusans.ttf")), ttffiles[0])
+ findSystemFonts(fontext='afm'))
def ttffiles(self): return [font.fname for font in self.ttflist]
def afmfiles(self): return [font.fname for font in self.afmlist]
""" Return the default font weight. """ return self.__default_weight
def get_default_size(): """ Return the default font size. """
""" Set the default font weight. The initial value is 'normal'. """ self.__default_weight = weight
""" Update the font dictionary with new font files. Currently not implemented. """ # !!!! Needs implementing raise NotImplementedError
# Each of the scoring functions below should return a value between # 0.0 (perfect match) and 1.0 (terrible match) """ Returns a match score between the list of font families in *families* and the font family name *family2*.
An exact match at the head of the list returns 0.0.
A match further down the list will return between 0 and 1.
No match will return 1.0. """ families = [families] return 1.0 family1 = 'sans-serif' # The score should be weighted by where in the # list the font was found.
""" Returns a match score between *style1* and *style2*.
An exact match returns 0.0.
A match between 'italic' and 'oblique' returns 0.1.
No match returns 1.0. """ style2 in ('italic', 'oblique'):
""" Returns a match score between *variant1* and *variant2*.
An exact match returns 0.0, otherwise 1.0. """ else: return 1.0
""" Returns a match score between *stretch1* and *stretch2*.
The result is the absolute value of the difference between the CSS numeric values of *stretch1* and *stretch2*, normalized between 0.0 and 1.0. """
""" Returns a match score between *weight1* and *weight2*.
The result is 0.0 if both weight1 and weight 2 are given as strings and have the same value.
Otherwise, the result is the absolute value of the difference between the CSS numeric values of *weight1* and *weight2*, normalized between 0.05 and 1.0. """
# exact match of the weight names, e.g. weight1 == weight2 == "regular" isinstance(weight2, str) and weight1 == weight2):
""" Returns a match score between *size1* and *size2*.
If *size2* (the size specified in the font file) is 'scalable', this function always returns 0.0, since any font size can be generated.
Otherwise, the result is the absolute distance between *size1* and *size2*, normalized so that the usual range of font sizes (6pt - 72pt) will lie between 0.0 and 1.0. """ # Size value should have already been try: sizeval1 = float(size1) except ValueError: sizeval1 = self.default_size * font_scalings[size1] try: sizeval2 = float(size2) except ValueError: return 1.0 return abs(sizeval1 - sizeval2) / 72.0
fallback_to_default=True, rebuild_if_missing=True): """ Search the font list for the font that most closely matches the :class:`FontProperties` *prop*.
:meth:`findfont` performs a nearest neighbor search. Each font is given a similarity score to the target font properties. The first font with the highest score is returned. If no matches below a certain threshold are found, the default font (usually DejaVu Sans) is returned.
`directory`, is specified, will only return fonts from the given directory (or subdirectory of that directory).
The result is cached, so subsequent lookups don't have to perform the O(n) nearest neighbor search.
If `fallback_to_default` is True, will fallback to the default font family (usually "DejaVu Sans" or "Helvetica") if the first lookup hard-fails.
See the `W3C Cascading Style Sheet, Level 1 <http://www.w3.org/TR/1998/REC-CSS2-19980512/>`_ documentation for a description of the font finding algorithm. """ # Pass the relevant rcParams (and the font manager, as `self`) to # _findfont_cached so to prevent using a stale cache entry after an # rcParam was changed. "font.serif", "font.sans-serif", "font.cursive", "font.fantasy", "font.monospace"]) prop, fontext, directory, fallback_to_default, rebuild_if_missing, rc_params)
def _findfont_cached(self, prop, fontext, directory, fallback_to_default, rebuild_if_missing, rc_params):
_log.debug('findfont returning %s', fname) return fname
fontlist = self.afmlist else:
Path(directory) not in Path(font.fname).parents): continue # Matching family should have highest priority, so it is multiplied # by 10.0 self.score_family(prop.get_family(), font.name) * 10.0 + \ self.score_style(prop.get_style(), font.style) + \ self.score_variant(prop.get_variant(), font.variant) + \ self.score_weight(prop.get_weight(), font.weight) + \ self.score_stretch(prop.get_stretch(), font.stretch) + \ self.score_size(prop.get_size(), font.size)
if fallback_to_default: warnings.warn( 'findfont: Font family %s not found. Falling back to %s.' % (prop.get_family(), self.defaultFamily[fontext])) default_prop = prop.copy() default_prop.set_family(self.defaultFamily[fontext]) return self.findfont(default_prop, fontext, directory, False) else: # This is a hard fail -- we can't find anything reasonable, # so just return the DejuVuSans.ttf warnings.warn('findfont: Could not match %s. Returning %s.' % (prop, self.defaultFont[fontext]), UserWarning) result = self.defaultFont[fontext] else: prop, best_font.name, best_font.fname, best_score)
if rebuild_if_missing: _log.info( 'findfont: Found a missing font file. Rebuilding cache.') _rebuild() return fontManager.findfont( prop, fontext, directory, True, False) else: raise ValueError("No valid font could be found")
def is_opentype_cff_font(filename): """ Returns True if the given font is a Postscript Compact Font Format Font embedded in an OpenType wrapper. Used by the PostScript and PDF backends that can not subset these fonts. """ if os.path.splitext(filename)[1].lower() == '.otf': with open(filename, 'rb') as fd: return fd.read(4) == b"OTTO" else: return False
# The experimental fontconfig-based backend.
def fc_match(pattern, fontext): fontexts = get_fontext_synonyms(fontext) ext = "." + fontext try: pipe = subprocess.Popen( ['fc-match', '-s', '--format=%{file}\\n', pattern], stdout=subprocess.PIPE, stderr=subprocess.PIPE) output = pipe.communicate()[0] except OSError: return None
# The bulk of the output from fc-list is ascii, so we keep the # result in bytes and parse it as bytes, until we extract the # filename, which is in sys.filesystemencoding(). if pipe.returncode == 0: for fname in map(os.fsdecode, output.split(b'\n')): if os.path.splitext(fname)[1][1:] in fontexts: return fname return None
_fc_match_cache = {}
def findfont(prop, fontext='ttf'): if not isinstance(prop, str): prop = prop.get_fontconfig_pattern() cached = _fc_match_cache.get(prop) if cached is not None: return cached
result = fc_match(prop, fontext) if result is None: result = fc_match(':', fontext)
_fc_match_cache[prop] = result return result
else:
cachedir, 'fontlist-v{}.json'.format(FontManager.__version__))
global fontManager
if (not hasattr(fontManager, '_version') or fontManager._version != FontManager.__version__): _rebuild() else: fontManager.default_size = None _log.debug("Using fontManager instance from %s", _fmcache) raise else: _rebuild()
global fontManager |