font_manager.py 44 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351
  1. """
  2. A module for finding, managing, and using fonts across platforms.
  3. This module provides a single `FontManager` instance that can
  4. be shared across backends and platforms. The `findfont`
  5. function returns the best TrueType (TTF) font file in the local or
  6. system font path that matches the specified `FontProperties`
  7. instance. The `FontManager` also handles Adobe Font Metrics
  8. (AFM) font files for use by the PostScript backend.
  9. The design is based on the `W3C Cascading Style Sheet, Level 1 (CSS1)
  10. font specification <http://www.w3.org/TR/1998/REC-CSS2-19980512/>`_.
  11. Future versions may implement the Level 2 or 2.1 specifications.
  12. """
  13. # KNOWN ISSUES
  14. #
  15. # - documentation
  16. # - font variant is untested
  17. # - font stretch is incomplete
  18. # - font size is incomplete
  19. # - default font algorithm needs improvement and testing
  20. # - setWeights function needs improvement
  21. # - 'light' is an invalid weight value, remove it.
  22. from functools import lru_cache
  23. import json
  24. import logging
  25. from numbers import Number
  26. import os
  27. from pathlib import Path
  28. import subprocess
  29. import sys
  30. try:
  31. from threading import Timer
  32. except ImportError:
  33. from dummy_threading import Timer
  34. import matplotlib as mpl
  35. from matplotlib import afm, cbook, ft2font, rcParams
  36. from matplotlib.fontconfig_pattern import (
  37. parse_fontconfig_pattern, generate_fontconfig_pattern)
  38. _log = logging.getLogger(__name__)
  39. font_scalings = {
  40. 'xx-small': 0.579,
  41. 'x-small': 0.694,
  42. 'small': 0.833,
  43. 'medium': 1.0,
  44. 'large': 1.200,
  45. 'x-large': 1.440,
  46. 'xx-large': 1.728,
  47. 'larger': 1.2,
  48. 'smaller': 0.833,
  49. None: 1.0,
  50. }
  51. stretch_dict = {
  52. 'ultra-condensed': 100,
  53. 'extra-condensed': 200,
  54. 'condensed': 300,
  55. 'semi-condensed': 400,
  56. 'normal': 500,
  57. 'semi-expanded': 600,
  58. 'semi-extended': 600,
  59. 'expanded': 700,
  60. 'extended': 700,
  61. 'extra-expanded': 800,
  62. 'extra-extended': 800,
  63. 'ultra-expanded': 900,
  64. 'ultra-extended': 900,
  65. }
  66. weight_dict = {
  67. 'ultralight': 100,
  68. 'light': 200,
  69. 'normal': 400,
  70. 'regular': 400,
  71. 'book': 400,
  72. 'medium': 500,
  73. 'roman': 500,
  74. 'semibold': 600,
  75. 'demibold': 600,
  76. 'demi': 600,
  77. 'bold': 700,
  78. 'heavy': 800,
  79. 'extra bold': 800,
  80. 'black': 900,
  81. }
  82. font_family_aliases = {
  83. 'serif',
  84. 'sans-serif',
  85. 'sans serif',
  86. 'cursive',
  87. 'fantasy',
  88. 'monospace',
  89. 'sans',
  90. }
  91. # OS Font paths
  92. MSFolders = \
  93. r'Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders'
  94. MSFontDirectories = [
  95. r'SOFTWARE\Microsoft\Windows NT\CurrentVersion\Fonts',
  96. r'SOFTWARE\Microsoft\Windows\CurrentVersion\Fonts']
  97. MSUserFontDirectories = [
  98. str(Path.home() / 'AppData/Local/Microsoft/Windows/Fonts'),
  99. str(Path.home() / 'AppData/Roaming/Microsoft/Windows/Fonts'),
  100. ]
  101. X11FontDirectories = [
  102. # an old standard installation point
  103. "/usr/X11R6/lib/X11/fonts/TTF/",
  104. "/usr/X11/lib/X11/fonts",
  105. # here is the new standard location for fonts
  106. "/usr/share/fonts/",
  107. # documented as a good place to install new fonts
  108. "/usr/local/share/fonts/",
  109. # common application, not really useful
  110. "/usr/lib/openoffice/share/fonts/truetype/",
  111. # user fonts
  112. str(Path(os.environ.get('XDG_DATA_HOME',
  113. Path.home() / ".local/share")) / "fonts"),
  114. str(Path.home() / ".fonts"),
  115. ]
  116. OSXFontDirectories = [
  117. "/Library/Fonts/",
  118. "/Network/Library/Fonts/",
  119. "/System/Library/Fonts/",
  120. # fonts installed via MacPorts
  121. "/opt/local/share/fonts",
  122. # user fonts
  123. str(Path.home() / "Library/Fonts"),
  124. ]
  125. def get_fontext_synonyms(fontext):
  126. """
  127. Return a list of file extensions extensions that are synonyms for
  128. the given file extension *fileext*.
  129. """
  130. return {
  131. 'afm': ['afm'],
  132. 'otf': ['otf', 'ttc', 'ttf'],
  133. 'ttc': ['otf', 'ttc', 'ttf'],
  134. 'ttf': ['otf', 'ttc', 'ttf'],
  135. }[fontext]
  136. def list_fonts(directory, extensions):
  137. """
  138. Return a list of all fonts matching any of the extensions, found
  139. recursively under the directory.
  140. """
  141. extensions = ["." + ext for ext in extensions]
  142. return [os.path.join(dirpath, filename)
  143. # os.walk ignores access errors, unlike Path.glob.
  144. for dirpath, _, filenames in os.walk(directory)
  145. for filename in filenames
  146. if Path(filename).suffix.lower() in extensions]
  147. def win32FontDirectory():
  148. r"""
  149. Return the user-specified font directory for Win32. This is
  150. looked up from the registry key ::
  151. \\HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders\Fonts
  152. If the key is not found, ``%WINDIR%\Fonts`` will be returned.
  153. """
  154. import winreg
  155. try:
  156. with winreg.OpenKey(winreg.HKEY_CURRENT_USER, MSFolders) as user:
  157. return winreg.QueryValueEx(user, 'Fonts')[0]
  158. except OSError:
  159. return os.path.join(os.environ['WINDIR'], 'Fonts')
  160. def _win32RegistryFonts(reg_domain, base_dir):
  161. r"""
  162. Searches for fonts in the Windows registry.
  163. Parameters
  164. ----------
  165. reg_domain : int
  166. The top level registry domain (e.g. HKEY_LOCAL_MACHINE).
  167. base_dir : str
  168. The path to the folder where the font files are usually located (e.g.
  169. C:\Windows\Fonts). If only the filename of the font is stored in the
  170. registry, the absolute path is built relative to this base directory.
  171. Returns
  172. -------
  173. `set`
  174. `pathlib.Path` objects with the absolute path to the font files found.
  175. """
  176. import winreg
  177. items = set()
  178. for reg_path in MSFontDirectories:
  179. try:
  180. with winreg.OpenKey(reg_domain, reg_path) as local:
  181. for j in range(winreg.QueryInfoKey(local)[1]):
  182. # value may contain the filename of the font or its
  183. # absolute path.
  184. key, value, tp = winreg.EnumValue(local, j)
  185. if not isinstance(value, str):
  186. continue
  187. # Work around for https://bugs.python.org/issue25778, which
  188. # is fixed in Py>=3.6.1.
  189. value = value.split("\0", 1)[0]
  190. try:
  191. # If value contains already an absolute path, then it
  192. # is not changed further.
  193. path = Path(base_dir, value).resolve()
  194. except RuntimeError:
  195. # Don't fail with invalid entries.
  196. continue
  197. items.add(path)
  198. except (OSError, MemoryError):
  199. continue
  200. return items
  201. def win32InstalledFonts(directory=None, fontext='ttf'):
  202. """
  203. Search for fonts in the specified font directory, or use the
  204. system directories if none given. Additionally, it is searched for user
  205. fonts installed. A list of TrueType font filenames are returned by default,
  206. or AFM fonts if *fontext* == 'afm'.
  207. """
  208. import winreg
  209. if directory is None:
  210. directory = win32FontDirectory()
  211. fontext = ['.' + ext for ext in get_fontext_synonyms(fontext)]
  212. items = set()
  213. # System fonts
  214. items.update(_win32RegistryFonts(winreg.HKEY_LOCAL_MACHINE, directory))
  215. # User fonts
  216. for userdir in MSUserFontDirectories:
  217. items.update(_win32RegistryFonts(winreg.HKEY_CURRENT_USER, userdir))
  218. # Keep only paths with matching file extension.
  219. return [str(path) for path in items if path.suffix.lower() in fontext]
  220. @cbook.deprecated("3.1")
  221. def OSXInstalledFonts(directories=None, fontext='ttf'):
  222. """Get list of font files on OS X."""
  223. if directories is None:
  224. directories = OSXFontDirectories
  225. return [path
  226. for directory in directories
  227. for path in list_fonts(directory, get_fontext_synonyms(fontext))]
  228. @lru_cache()
  229. def _call_fc_list():
  230. """Cache and list the font filenames known to `fc-list`.
  231. """
  232. # Delay the warning by 5s.
  233. timer = Timer(5, lambda: _log.warning(
  234. 'Matplotlib is building the font cache using fc-list. '
  235. 'This may take a moment.'))
  236. timer.start()
  237. try:
  238. if b'--format' not in subprocess.check_output(['fc-list', '--help']):
  239. _log.warning( # fontconfig 2.7 implemented --format.
  240. 'Matplotlib needs fontconfig>=2.7 to query system fonts.')
  241. return []
  242. out = subprocess.check_output(['fc-list', '--format=%{file}\\n'])
  243. except (OSError, subprocess.CalledProcessError):
  244. return []
  245. finally:
  246. timer.cancel()
  247. return [os.fsdecode(fname) for fname in out.split(b'\n')]
  248. def get_fontconfig_fonts(fontext='ttf'):
  249. """List the font filenames known to `fc-list` having the given extension.
  250. """
  251. fontext = ['.' + ext for ext in get_fontext_synonyms(fontext)]
  252. return [fname for fname in _call_fc_list()
  253. if Path(fname).suffix.lower() in fontext]
  254. def findSystemFonts(fontpaths=None, fontext='ttf'):
  255. """
  256. Search for fonts in the specified font paths. If no paths are
  257. given, will use a standard set of system paths, as well as the
  258. list of fonts tracked by fontconfig if fontconfig is installed and
  259. available. A list of TrueType fonts are returned by default with
  260. AFM fonts as an option.
  261. """
  262. fontfiles = set()
  263. fontexts = get_fontext_synonyms(fontext)
  264. if fontpaths is None:
  265. if sys.platform == 'win32':
  266. fontpaths = MSUserFontDirectories + [win32FontDirectory()]
  267. # now get all installed fonts directly...
  268. fontfiles.update(win32InstalledFonts(fontext=fontext))
  269. else:
  270. fontpaths = X11FontDirectories
  271. if sys.platform == 'darwin':
  272. fontpaths = [*X11FontDirectories, *OSXFontDirectories]
  273. fontfiles.update(get_fontconfig_fonts(fontext))
  274. elif isinstance(fontpaths, str):
  275. fontpaths = [fontpaths]
  276. for path in fontpaths:
  277. fontfiles.update(map(os.path.abspath, list_fonts(path, fontexts)))
  278. return [fname for fname in fontfiles if os.path.exists(fname)]
  279. class FontEntry:
  280. """
  281. A class for storing Font properties. It is used when populating
  282. the font lookup dictionary.
  283. """
  284. def __init__(self,
  285. fname ='',
  286. name ='',
  287. style ='normal',
  288. variant='normal',
  289. weight ='normal',
  290. stretch='normal',
  291. size ='medium',
  292. ):
  293. self.fname = fname
  294. self.name = name
  295. self.style = style
  296. self.variant = variant
  297. self.weight = weight
  298. self.stretch = stretch
  299. try:
  300. self.size = str(float(size))
  301. except ValueError:
  302. self.size = size
  303. def __repr__(self):
  304. return "<Font '%s' (%s) %s %s %s %s>" % (
  305. self.name, os.path.basename(self.fname), self.style, self.variant,
  306. self.weight, self.stretch)
  307. def ttfFontProperty(font):
  308. """
  309. Extract information from a TrueType font file.
  310. Parameters
  311. ----------
  312. font : `.FT2Font`
  313. The TrueType font file from which information will be extracted.
  314. Returns
  315. -------
  316. `FontEntry`
  317. The extracted font properties.
  318. """
  319. name = font.family_name
  320. # Styles are: italic, oblique, and normal (default)
  321. sfnt = font.get_sfnt()
  322. # These tables are actually mac_roman-encoded, but mac_roman support may be
  323. # missing in some alternative Python implementations and we are only going
  324. # to look for ASCII substrings, where any ASCII-compatible encoding works
  325. # - or big-endian UTF-16, since important Microsoft fonts use that.
  326. sfnt2 = (sfnt.get((1, 0, 0, 2), b'').decode('latin-1').lower() or
  327. sfnt.get((3, 1, 0x0409, 2), b'').decode('utf_16_be').lower())
  328. sfnt4 = (sfnt.get((1, 0, 0, 4), b'').decode('latin-1').lower() or
  329. sfnt.get((3, 1, 0x0409, 4), b'').decode('utf_16_be').lower())
  330. if sfnt4.find('oblique') >= 0:
  331. style = 'oblique'
  332. elif sfnt4.find('italic') >= 0:
  333. style = 'italic'
  334. elif sfnt2.find('regular') >= 0:
  335. style = 'normal'
  336. elif font.style_flags & ft2font.ITALIC:
  337. style = 'italic'
  338. else:
  339. style = 'normal'
  340. # Variants are: small-caps and normal (default)
  341. # !!!! Untested
  342. if name.lower() in ['capitals', 'small-caps']:
  343. variant = 'small-caps'
  344. else:
  345. variant = 'normal'
  346. if font.style_flags & ft2font.BOLD:
  347. weight = 700
  348. else:
  349. weight = next((w for w in weight_dict if w in sfnt4), 400)
  350. # Stretch can be absolute and relative
  351. # Absolute stretches are: ultra-condensed, extra-condensed, condensed,
  352. # semi-condensed, normal, semi-expanded, expanded, extra-expanded,
  353. # and ultra-expanded.
  354. # Relative stretches are: wider, narrower
  355. # Child value is: inherit
  356. if any(word in sfnt4 for word in ['narrow', 'condensed', 'cond']):
  357. stretch = 'condensed'
  358. elif 'demi cond' in sfnt4:
  359. stretch = 'semi-condensed'
  360. elif any(word in sfnt4 for word in ['wide', 'expanded', 'extended']):
  361. stretch = 'expanded'
  362. else:
  363. stretch = 'normal'
  364. # Sizes can be absolute and relative.
  365. # Absolute sizes are: xx-small, x-small, small, medium, large, x-large,
  366. # and xx-large.
  367. # Relative sizes are: larger, smaller
  368. # Length value is an absolute font size, e.g., 12pt
  369. # Percentage values are in 'em's. Most robust specification.
  370. if not font.scalable:
  371. raise NotImplementedError("Non-scalable fonts are not supported")
  372. size = 'scalable'
  373. return FontEntry(font.fname, name, style, variant, weight, stretch, size)
  374. def afmFontProperty(fontpath, font):
  375. """
  376. Extract information from an AFM font file.
  377. Parameters
  378. ----------
  379. font : `.AFM`
  380. The AFM font file from which information will be extracted.
  381. Returns
  382. -------
  383. `FontEntry`
  384. The extracted font properties.
  385. """
  386. name = font.get_familyname()
  387. fontname = font.get_fontname().lower()
  388. # Styles are: italic, oblique, and normal (default)
  389. if font.get_angle() != 0 or 'italic' in name.lower():
  390. style = 'italic'
  391. elif 'oblique' in name.lower():
  392. style = 'oblique'
  393. else:
  394. style = 'normal'
  395. # Variants are: small-caps and normal (default)
  396. # !!!! Untested
  397. if name.lower() in ['capitals', 'small-caps']:
  398. variant = 'small-caps'
  399. else:
  400. variant = 'normal'
  401. weight = font.get_weight().lower()
  402. if weight not in weight_dict:
  403. weight = 'normal'
  404. # Stretch can be absolute and relative
  405. # Absolute stretches are: ultra-condensed, extra-condensed, condensed,
  406. # semi-condensed, normal, semi-expanded, expanded, extra-expanded,
  407. # and ultra-expanded.
  408. # Relative stretches are: wider, narrower
  409. # Child value is: inherit
  410. if 'demi cond' in fontname:
  411. stretch = 'semi-condensed'
  412. elif any(word in fontname for word in ['narrow', 'cond']):
  413. stretch = 'condensed'
  414. elif any(word in fontname for word in ['wide', 'expanded', 'extended']):
  415. stretch = 'expanded'
  416. else:
  417. stretch = 'normal'
  418. # Sizes can be absolute and relative.
  419. # Absolute sizes are: xx-small, x-small, small, medium, large, x-large,
  420. # and xx-large.
  421. # Relative sizes are: larger, smaller
  422. # Length value is an absolute font size, e.g., 12pt
  423. # Percentage values are in 'em's. Most robust specification.
  424. # All AFM fonts are apparently scalable.
  425. size = 'scalable'
  426. return FontEntry(fontpath, name, style, variant, weight, stretch, size)
  427. @cbook.deprecated("3.2", alternative="FontManager.addfont")
  428. def createFontList(fontfiles, fontext='ttf'):
  429. """
  430. A function to create a font lookup list. The default is to create
  431. a list of TrueType fonts. An AFM font list can optionally be
  432. created.
  433. """
  434. fontlist = []
  435. # Add fonts from list of known font files.
  436. seen = set()
  437. for fpath in fontfiles:
  438. _log.debug('createFontDict: %s', fpath)
  439. fname = os.path.split(fpath)[1]
  440. if fname in seen:
  441. continue
  442. if fontext == 'afm':
  443. try:
  444. with open(fpath, 'rb') as fh:
  445. font = afm.AFM(fh)
  446. except EnvironmentError:
  447. _log.info("Could not open font file %s", fpath)
  448. continue
  449. except RuntimeError:
  450. _log.info("Could not parse font file %s", fpath)
  451. continue
  452. try:
  453. prop = afmFontProperty(fpath, font)
  454. except KeyError as exc:
  455. _log.info("Could not extract properties for %s: %s",
  456. fpath, exc)
  457. continue
  458. else:
  459. try:
  460. font = ft2font.FT2Font(fpath)
  461. except (OSError, RuntimeError) as exc:
  462. _log.info("Could not open font file %s: %s", fpath, exc)
  463. continue
  464. except UnicodeError:
  465. _log.info("Cannot handle unicode filenames")
  466. continue
  467. try:
  468. prop = ttfFontProperty(font)
  469. except (KeyError, RuntimeError, ValueError,
  470. NotImplementedError) as exc:
  471. _log.info("Could not extract properties for %s: %s",
  472. fpath, exc)
  473. continue
  474. fontlist.append(prop)
  475. seen.add(fname)
  476. return fontlist
  477. class FontProperties:
  478. """
  479. A class for storing and manipulating font properties.
  480. The font properties are those described in the `W3C Cascading
  481. Style Sheet, Level 1
  482. <http://www.w3.org/TR/1998/REC-CSS2-19980512/>`_ font
  483. specification. The six properties are:
  484. - family: A list of font names in decreasing order of priority.
  485. The items may include a generic font family name, either
  486. 'serif', 'sans-serif', 'cursive', 'fantasy', or 'monospace'.
  487. In that case, the actual font to be used will be looked up
  488. from the associated rcParam.
  489. - style: Either 'normal', 'italic' or 'oblique'.
  490. - variant: Either 'normal' or 'small-caps'.
  491. - stretch: A numeric value in the range 0-1000 or one of
  492. 'ultra-condensed', 'extra-condensed', 'condensed',
  493. 'semi-condensed', 'normal', 'semi-expanded', 'expanded',
  494. 'extra-expanded' or 'ultra-expanded'.
  495. - weight: A numeric value in the range 0-1000 or one of
  496. 'ultralight', 'light', 'normal', 'regular', 'book', 'medium',
  497. 'roman', 'semibold', 'demibold', 'demi', 'bold', 'heavy',
  498. 'extra bold', 'black'.
  499. - size: Either an relative value of 'xx-small', 'x-small',
  500. 'small', 'medium', 'large', 'x-large', 'xx-large' or an
  501. absolute font size, e.g., 12.
  502. The default font property for TrueType fonts (as specified in the
  503. default rcParams) is ::
  504. sans-serif, normal, normal, normal, normal, scalable.
  505. Alternatively, a font may be specified using an absolute path to a
  506. .ttf file, by using the *fname* kwarg.
  507. The preferred usage of font sizes is to use the relative values,
  508. e.g., 'large', instead of absolute font sizes, e.g., 12. This
  509. approach allows all text sizes to be made larger or smaller based
  510. on the font manager's default font size.
  511. This class will also accept a fontconfig_ pattern_, if it is the only
  512. argument provided. This support does not depend on fontconfig; we are
  513. merely borrowing its pattern syntax for use here.
  514. .. _fontconfig: https://www.freedesktop.org/wiki/Software/fontconfig/
  515. .. _pattern:
  516. https://www.freedesktop.org/software/fontconfig/fontconfig-user.html
  517. Note that Matplotlib's internal font manager and fontconfig use a
  518. different algorithm to lookup fonts, so the results of the same pattern
  519. may be different in Matplotlib than in other applications that use
  520. fontconfig.
  521. """
  522. def __init__(self,
  523. family = None,
  524. style = None,
  525. variant= None,
  526. weight = None,
  527. stretch= None,
  528. size = None,
  529. fname = None, # if set, it's a hardcoded filename to use
  530. ):
  531. self._family = _normalize_font_family(rcParams['font.family'])
  532. self._slant = rcParams['font.style']
  533. self._variant = rcParams['font.variant']
  534. self._weight = rcParams['font.weight']
  535. self._stretch = rcParams['font.stretch']
  536. self._size = rcParams['font.size']
  537. self._file = None
  538. if isinstance(family, str):
  539. # Treat family as a fontconfig pattern if it is the only
  540. # parameter provided.
  541. if (style is None and
  542. variant is None and
  543. weight is None and
  544. stretch is None and
  545. size is None and
  546. fname is None):
  547. self.set_fontconfig_pattern(family)
  548. return
  549. self.set_family(family)
  550. self.set_style(style)
  551. self.set_variant(variant)
  552. self.set_weight(weight)
  553. self.set_stretch(stretch)
  554. self.set_file(fname)
  555. self.set_size(size)
  556. def _parse_fontconfig_pattern(self, pattern):
  557. return parse_fontconfig_pattern(pattern)
  558. def __hash__(self):
  559. l = (tuple(self.get_family()),
  560. self.get_slant(),
  561. self.get_variant(),
  562. self.get_weight(),
  563. self.get_stretch(),
  564. self.get_size_in_points(),
  565. self.get_file())
  566. return hash(l)
  567. def __eq__(self, other):
  568. return hash(self) == hash(other)
  569. def __str__(self):
  570. return self.get_fontconfig_pattern()
  571. def get_family(self):
  572. """
  573. Return a list of font names that comprise the font family.
  574. """
  575. return self._family
  576. def get_name(self):
  577. """
  578. Return the name of the font that best matches the font properties.
  579. """
  580. return get_font(findfont(self)).family_name
  581. def get_style(self):
  582. """
  583. Return the font style. Values are: 'normal', 'italic' or 'oblique'.
  584. """
  585. return self._slant
  586. get_slant = get_style
  587. def get_variant(self):
  588. """
  589. Return the font variant. Values are: 'normal' or 'small-caps'.
  590. """
  591. return self._variant
  592. def get_weight(self):
  593. """
  594. Set the font weight. Options are: A numeric value in the
  595. range 0-1000 or one of 'light', 'normal', 'regular', 'book',
  596. 'medium', 'roman', 'semibold', 'demibold', 'demi', 'bold',
  597. 'heavy', 'extra bold', 'black'
  598. """
  599. return self._weight
  600. def get_stretch(self):
  601. """
  602. Return the font stretch or width. Options are: 'ultra-condensed',
  603. 'extra-condensed', 'condensed', 'semi-condensed', 'normal',
  604. 'semi-expanded', 'expanded', 'extra-expanded', 'ultra-expanded'.
  605. """
  606. return self._stretch
  607. def get_size(self):
  608. """
  609. Return the font size.
  610. """
  611. return self._size
  612. def get_size_in_points(self):
  613. return self._size
  614. def get_file(self):
  615. """
  616. Return the filename of the associated font.
  617. """
  618. return self._file
  619. def get_fontconfig_pattern(self):
  620. """
  621. Get a fontconfig_ pattern_ suitable for looking up the font as
  622. specified with fontconfig's ``fc-match`` utility.
  623. This support does not depend on fontconfig; we are merely borrowing its
  624. pattern syntax for use here.
  625. """
  626. return generate_fontconfig_pattern(self)
  627. def set_family(self, family):
  628. """
  629. Change the font family. May be either an alias (generic name
  630. is CSS parlance), such as: 'serif', 'sans-serif', 'cursive',
  631. 'fantasy', or 'monospace', a real font name or a list of real
  632. font names. Real font names are not supported when
  633. `text.usetex` is `True`.
  634. """
  635. if family is None:
  636. family = rcParams['font.family']
  637. self._family = _normalize_font_family(family)
  638. set_name = set_family
  639. def set_style(self, style):
  640. """
  641. Set the font style. Values are: 'normal', 'italic' or 'oblique'.
  642. """
  643. if style is None:
  644. style = rcParams['font.style']
  645. cbook._check_in_list(['normal', 'italic', 'oblique'], style=style)
  646. self._slant = style
  647. set_slant = set_style
  648. def set_variant(self, variant):
  649. """
  650. Set the font variant. Values are: 'normal' or 'small-caps'.
  651. """
  652. if variant is None:
  653. variant = rcParams['font.variant']
  654. cbook._check_in_list(['normal', 'small-caps'], variant=variant)
  655. self._variant = variant
  656. def set_weight(self, weight):
  657. """
  658. Set the font weight. May be either a numeric value in the
  659. range 0-1000 or one of 'ultralight', 'light', 'normal',
  660. 'regular', 'book', 'medium', 'roman', 'semibold', 'demibold',
  661. 'demi', 'bold', 'heavy', 'extra bold', 'black'
  662. """
  663. if weight is None:
  664. weight = rcParams['font.weight']
  665. try:
  666. weight = int(weight)
  667. if weight < 0 or weight > 1000:
  668. raise ValueError()
  669. except ValueError:
  670. if weight not in weight_dict:
  671. raise ValueError("weight is invalid")
  672. self._weight = weight
  673. def set_stretch(self, stretch):
  674. """
  675. Set the font stretch or width. Options are: 'ultra-condensed',
  676. 'extra-condensed', 'condensed', 'semi-condensed', 'normal',
  677. 'semi-expanded', 'expanded', 'extra-expanded' or
  678. 'ultra-expanded', or a numeric value in the range 0-1000.
  679. """
  680. if stretch is None:
  681. stretch = rcParams['font.stretch']
  682. try:
  683. stretch = int(stretch)
  684. if stretch < 0 or stretch > 1000:
  685. raise ValueError()
  686. except ValueError:
  687. if stretch not in stretch_dict:
  688. raise ValueError("stretch is invalid")
  689. self._stretch = stretch
  690. def set_size(self, size):
  691. """
  692. Set the font size. Either an relative value of 'xx-small',
  693. 'x-small', 'small', 'medium', 'large', 'x-large', 'xx-large'
  694. or an absolute font size, e.g., 12.
  695. """
  696. if size is None:
  697. size = rcParams['font.size']
  698. try:
  699. size = float(size)
  700. except ValueError:
  701. try:
  702. scale = font_scalings[size]
  703. except KeyError:
  704. raise ValueError(
  705. "Size is invalid. Valid font size are "
  706. + ", ".join(map(str, font_scalings)))
  707. else:
  708. size = scale * FontManager.get_default_size()
  709. if size < 1.0:
  710. _log.info('Fontsize %1.2f < 1.0 pt not allowed by FreeType. '
  711. 'Setting fontsize = 1 pt', size)
  712. size = 1.0
  713. self._size = size
  714. def set_file(self, file):
  715. """
  716. Set the filename of the fontfile to use. In this case, all
  717. other properties will be ignored.
  718. """
  719. self._file = os.fspath(file) if file is not None else None
  720. def set_fontconfig_pattern(self, pattern):
  721. """
  722. Set the properties by parsing a fontconfig_ *pattern*.
  723. This support does not depend on fontconfig; we are merely borrowing its
  724. pattern syntax for use here.
  725. """
  726. for key, val in self._parse_fontconfig_pattern(pattern).items():
  727. if type(val) == list:
  728. getattr(self, "set_" + key)(val[0])
  729. else:
  730. getattr(self, "set_" + key)(val)
  731. def copy(self):
  732. """Return a copy of self."""
  733. new = type(self)()
  734. vars(new).update(vars(self))
  735. return new
  736. class _JSONEncoder(json.JSONEncoder):
  737. def default(self, o):
  738. if isinstance(o, FontManager):
  739. return dict(o.__dict__, __class__='FontManager')
  740. elif isinstance(o, FontEntry):
  741. d = dict(o.__dict__, __class__='FontEntry')
  742. try:
  743. # Cache paths of fonts shipped with Matplotlib relative to the
  744. # Matplotlib data path, which helps in the presence of venvs.
  745. d["fname"] = str(
  746. Path(d["fname"]).relative_to(mpl.get_data_path()))
  747. except ValueError:
  748. pass
  749. return d
  750. else:
  751. return super().default(o)
  752. @cbook.deprecated("3.2", alternative="json_dump")
  753. class JSONEncoder(_JSONEncoder):
  754. pass
  755. def _json_decode(o):
  756. cls = o.pop('__class__', None)
  757. if cls is None:
  758. return o
  759. elif cls == 'FontManager':
  760. r = FontManager.__new__(FontManager)
  761. r.__dict__.update(o)
  762. return r
  763. elif cls == 'FontEntry':
  764. r = FontEntry.__new__(FontEntry)
  765. r.__dict__.update(o)
  766. if not os.path.isabs(r.fname):
  767. r.fname = os.path.join(mpl.get_data_path(), r.fname)
  768. return r
  769. else:
  770. raise ValueError("don't know how to deserialize __class__=%s" % cls)
  771. def json_dump(data, filename):
  772. """
  773. Dump `FontManager` *data* as JSON to the file named *filename*.
  774. Notes
  775. -----
  776. File paths that are children of the Matplotlib data path (typically, fonts
  777. shipped with Matplotlib) are stored relative to that data path (to remain
  778. valid across virtualenvs).
  779. See Also
  780. --------
  781. json_load
  782. """
  783. with open(filename, 'w') as fh:
  784. try:
  785. json.dump(data, fh, cls=_JSONEncoder, indent=2)
  786. except OSError as e:
  787. _log.warning('Could not save font_manager cache {}'.format(e))
  788. def json_load(filename):
  789. """
  790. Load a `FontManager` from the JSON file named *filename*.
  791. See Also
  792. --------
  793. json_dump
  794. """
  795. with open(filename, 'r') as fh:
  796. return json.load(fh, object_hook=_json_decode)
  797. def _normalize_font_family(family):
  798. if isinstance(family, str):
  799. family = [family]
  800. return family
  801. class FontManager:
  802. """
  803. On import, the :class:`FontManager` singleton instance creates a
  804. list of TrueType fonts based on the font properties: name, style,
  805. variant, weight, stretch, and size. The :meth:`findfont` method
  806. does a nearest neighbor search to find the font that most closely
  807. matches the specification. If no good enough match is found, a
  808. default font is returned.
  809. """
  810. # Increment this version number whenever the font cache data
  811. # format or behavior has changed and requires a existing font
  812. # cache files to be rebuilt.
  813. __version__ = 310
  814. def __init__(self, size=None, weight='normal'):
  815. self._version = self.__version__
  816. self.__default_weight = weight
  817. self.default_size = size
  818. paths = [cbook._get_data_path('fonts', subdir)
  819. for subdir in ['ttf', 'afm', 'pdfcorefonts']]
  820. # Create list of font paths
  821. for pathname in ['TTFPATH', 'AFMPATH']:
  822. if pathname in os.environ:
  823. ttfpath = os.environ[pathname]
  824. if ttfpath.find(';') >= 0: # win32 style
  825. paths.extend(ttfpath.split(';'))
  826. elif ttfpath.find(':') >= 0: # unix style
  827. paths.extend(ttfpath.split(':'))
  828. else:
  829. paths.append(ttfpath)
  830. _log.debug('font search path %s', str(paths))
  831. # Load TrueType fonts and create font dictionary.
  832. self.defaultFamily = {
  833. 'ttf': 'DejaVu Sans',
  834. 'afm': 'Helvetica'}
  835. self.afmlist = []
  836. self.ttflist = []
  837. for fontext in ["afm", "ttf"]:
  838. for path in [*findSystemFonts(paths, fontext=fontext),
  839. *findSystemFonts(fontext=fontext)]:
  840. try:
  841. self.addfont(path)
  842. except OSError as exc:
  843. _log.info("Failed to open font file %s: %s", path, exc)
  844. except Exception as exc:
  845. _log.info("Failed to extract font properties from %s: %s",
  846. path, exc)
  847. def addfont(self, path):
  848. """
  849. Cache the properties of the font at *path* to make it available to the
  850. `FontManager`. The type of font is inferred from the path suffix.
  851. Parameters
  852. ----------
  853. path : str or path-like
  854. """
  855. if Path(path).suffix.lower() == ".afm":
  856. with open(path, "rb") as fh:
  857. font = afm.AFM(fh)
  858. prop = afmFontProperty(path, font)
  859. self.afmlist.append(prop)
  860. else:
  861. font = ft2font.FT2Font(path)
  862. prop = ttfFontProperty(font)
  863. self.ttflist.append(prop)
  864. @property
  865. def defaultFont(self):
  866. # Lazily evaluated (findfont then caches the result) to avoid including
  867. # the venv path in the json serialization.
  868. return {ext: self.findfont(family, fontext=ext)
  869. for ext, family in self.defaultFamily.items()}
  870. def get_default_weight(self):
  871. """
  872. Return the default font weight.
  873. """
  874. return self.__default_weight
  875. @staticmethod
  876. def get_default_size():
  877. """
  878. Return the default font size.
  879. """
  880. return rcParams['font.size']
  881. def set_default_weight(self, weight):
  882. """
  883. Set the default font weight. The initial value is 'normal'.
  884. """
  885. self.__default_weight = weight
  886. # Each of the scoring functions below should return a value between
  887. # 0.0 (perfect match) and 1.0 (terrible match)
  888. def score_family(self, families, family2):
  889. """
  890. Returns a match score between the list of font families in
  891. *families* and the font family name *family2*.
  892. An exact match at the head of the list returns 0.0.
  893. A match further down the list will return between 0 and 1.
  894. No match will return 1.0.
  895. """
  896. if not isinstance(families, (list, tuple)):
  897. families = [families]
  898. elif len(families) == 0:
  899. return 1.0
  900. family2 = family2.lower()
  901. step = 1 / len(families)
  902. for i, family1 in enumerate(families):
  903. family1 = family1.lower()
  904. if family1 in font_family_aliases:
  905. if family1 in ('sans', 'sans serif'):
  906. family1 = 'sans-serif'
  907. options = rcParams['font.' + family1]
  908. options = [x.lower() for x in options]
  909. if family2 in options:
  910. idx = options.index(family2)
  911. return (i + (idx / len(options))) * step
  912. elif family1 == family2:
  913. # The score should be weighted by where in the
  914. # list the font was found.
  915. return i * step
  916. return 1.0
  917. def score_style(self, style1, style2):
  918. """
  919. Returns a match score between *style1* and *style2*.
  920. An exact match returns 0.0.
  921. A match between 'italic' and 'oblique' returns 0.1.
  922. No match returns 1.0.
  923. """
  924. if style1 == style2:
  925. return 0.0
  926. elif (style1 in ('italic', 'oblique')
  927. and style2 in ('italic', 'oblique')):
  928. return 0.1
  929. return 1.0
  930. def score_variant(self, variant1, variant2):
  931. """
  932. Returns a match score between *variant1* and *variant2*.
  933. An exact match returns 0.0, otherwise 1.0.
  934. """
  935. if variant1 == variant2:
  936. return 0.0
  937. else:
  938. return 1.0
  939. def score_stretch(self, stretch1, stretch2):
  940. """
  941. Returns a match score between *stretch1* and *stretch2*.
  942. The result is the absolute value of the difference between the
  943. CSS numeric values of *stretch1* and *stretch2*, normalized
  944. between 0.0 and 1.0.
  945. """
  946. try:
  947. stretchval1 = int(stretch1)
  948. except ValueError:
  949. stretchval1 = stretch_dict.get(stretch1, 500)
  950. try:
  951. stretchval2 = int(stretch2)
  952. except ValueError:
  953. stretchval2 = stretch_dict.get(stretch2, 500)
  954. return abs(stretchval1 - stretchval2) / 1000.0
  955. def score_weight(self, weight1, weight2):
  956. """
  957. Returns a match score between *weight1* and *weight2*.
  958. The result is 0.0 if both weight1 and weight 2 are given as strings
  959. and have the same value.
  960. Otherwise, the result is the absolute value of the difference between
  961. the CSS numeric values of *weight1* and *weight2*, normalized between
  962. 0.05 and 1.0.
  963. """
  964. # exact match of the weight names, e.g. weight1 == weight2 == "regular"
  965. if cbook._str_equal(weight1, weight2):
  966. return 0.0
  967. w1 = weight1 if isinstance(weight1, Number) else weight_dict[weight1]
  968. w2 = weight2 if isinstance(weight2, Number) else weight_dict[weight2]
  969. return 0.95 * (abs(w1 - w2) / 1000) + 0.05
  970. def score_size(self, size1, size2):
  971. """
  972. Returns a match score between *size1* and *size2*.
  973. If *size2* (the size specified in the font file) is 'scalable', this
  974. function always returns 0.0, since any font size can be generated.
  975. Otherwise, the result is the absolute distance between *size1* and
  976. *size2*, normalized so that the usual range of font sizes (6pt -
  977. 72pt) will lie between 0.0 and 1.0.
  978. """
  979. if size2 == 'scalable':
  980. return 0.0
  981. # Size value should have already been
  982. try:
  983. sizeval1 = float(size1)
  984. except ValueError:
  985. sizeval1 = self.default_size * font_scalings[size1]
  986. try:
  987. sizeval2 = float(size2)
  988. except ValueError:
  989. return 1.0
  990. return abs(sizeval1 - sizeval2) / 72
  991. def findfont(self, prop, fontext='ttf', directory=None,
  992. fallback_to_default=True, rebuild_if_missing=True):
  993. """
  994. Find a font that most closely matches the given font properties.
  995. Parameters
  996. ----------
  997. prop : str or `~matplotlib.font_manager.FontProperties`
  998. The font properties to search for. This can be either a
  999. `.FontProperties` object or a string defining a
  1000. `fontconfig patterns`_.
  1001. fontext : {'ttf', 'afm'}, optional, default: 'ttf'
  1002. The extension of the font file:
  1003. - 'ttf': TrueType and OpenType fonts (.ttf, .ttc, .otf)
  1004. - 'afm': Adobe Font Metrics (.afm)
  1005. directory : str, optional
  1006. If given, only search this directory and its subdirectories.
  1007. fallback_to_default : bool
  1008. If True, will fallback to the default font family (usually
  1009. "DejaVu Sans" or "Helvetica") if the first lookup hard-fails.
  1010. rebuild_if_missing : bool
  1011. Whether to rebuild the font cache and search again if no match
  1012. is found.
  1013. Returns
  1014. -------
  1015. fontfile : str
  1016. The filename of the best matching font.
  1017. Notes
  1018. -----
  1019. This performs a nearest neighbor search. Each font is given a
  1020. similarity score to the target font properties. The first font with
  1021. the highest score is returned. If no matches below a certain
  1022. threshold are found, the default font (usually DejaVu Sans) is
  1023. returned.
  1024. The result is cached, so subsequent lookups don't have to
  1025. perform the O(n) nearest neighbor search.
  1026. See the `W3C Cascading Style Sheet, Level 1
  1027. <http://www.w3.org/TR/1998/REC-CSS2-19980512/>`_ documentation
  1028. for a description of the font finding algorithm.
  1029. .. _fontconfig patterns:
  1030. https://www.freedesktop.org/software/fontconfig/fontconfig-user.html
  1031. """
  1032. # Pass the relevant rcParams (and the font manager, as `self`) to
  1033. # _findfont_cached so to prevent using a stale cache entry after an
  1034. # rcParam was changed.
  1035. rc_params = tuple(tuple(rcParams[key]) for key in [
  1036. "font.serif", "font.sans-serif", "font.cursive", "font.fantasy",
  1037. "font.monospace"])
  1038. return self._findfont_cached(
  1039. prop, fontext, directory, fallback_to_default, rebuild_if_missing,
  1040. rc_params)
  1041. @lru_cache()
  1042. def _findfont_cached(self, prop, fontext, directory, fallback_to_default,
  1043. rebuild_if_missing, rc_params):
  1044. if not isinstance(prop, FontProperties):
  1045. prop = FontProperties(prop)
  1046. fname = prop.get_file()
  1047. if fname is not None:
  1048. return fname
  1049. if fontext == 'afm':
  1050. fontlist = self.afmlist
  1051. else:
  1052. fontlist = self.ttflist
  1053. best_score = 1e64
  1054. best_font = None
  1055. _log.debug('findfont: Matching %s.', prop)
  1056. for font in fontlist:
  1057. if (directory is not None and
  1058. Path(directory) not in Path(font.fname).parents):
  1059. continue
  1060. # Matching family should have top priority, so multiply it by 10.
  1061. score = (self.score_family(prop.get_family(), font.name) * 10
  1062. + self.score_style(prop.get_style(), font.style)
  1063. + self.score_variant(prop.get_variant(), font.variant)
  1064. + self.score_weight(prop.get_weight(), font.weight)
  1065. + self.score_stretch(prop.get_stretch(), font.stretch)
  1066. + self.score_size(prop.get_size(), font.size))
  1067. _log.debug('findfont: score(%s) = %s', font, score)
  1068. if score < best_score:
  1069. best_score = score
  1070. best_font = font
  1071. if score == 0:
  1072. break
  1073. if best_font is None or best_score >= 10.0:
  1074. if fallback_to_default:
  1075. _log.warning(
  1076. 'findfont: Font family %s not found. Falling back to %s.',
  1077. prop.get_family(), self.defaultFamily[fontext])
  1078. default_prop = prop.copy()
  1079. default_prop.set_family(self.defaultFamily[fontext])
  1080. return self.findfont(default_prop, fontext, directory, False)
  1081. else:
  1082. # This is a hard fail -- we can't find anything reasonable,
  1083. # so just return the DejaVuSans.ttf
  1084. _log.warning('findfont: Could not match %s. Returning %s.',
  1085. prop, self.defaultFont[fontext])
  1086. result = self.defaultFont[fontext]
  1087. else:
  1088. _log.debug('findfont: Matching %s to %s (%r) with score of %f.',
  1089. prop, best_font.name, best_font.fname, best_score)
  1090. result = best_font.fname
  1091. if not os.path.isfile(result):
  1092. if rebuild_if_missing:
  1093. _log.info(
  1094. 'findfont: Found a missing font file. Rebuilding cache.')
  1095. _rebuild()
  1096. return fontManager.findfont(
  1097. prop, fontext, directory, True, False)
  1098. else:
  1099. raise ValueError("No valid font could be found")
  1100. return result
  1101. @lru_cache()
  1102. def is_opentype_cff_font(filename):
  1103. """
  1104. Return whether the given font is a Postscript Compact Font Format Font
  1105. embedded in an OpenType wrapper. Used by the PostScript and PDF backends
  1106. that can not subset these fonts.
  1107. """
  1108. if os.path.splitext(filename)[1].lower() == '.otf':
  1109. with open(filename, 'rb') as fd:
  1110. return fd.read(4) == b"OTTO"
  1111. else:
  1112. return False
  1113. _fmcache = os.path.join(
  1114. mpl.get_cachedir(), 'fontlist-v{}.json'.format(FontManager.__version__))
  1115. fontManager = None
  1116. _get_font = lru_cache(64)(ft2font.FT2Font)
  1117. # FT2Font objects cannot be used across fork()s because they reference the same
  1118. # FT_Library object. While invalidating *all* existing FT2Fonts after a fork
  1119. # would be too complicated to be worth it, the main way FT2Fonts get reused is
  1120. # via the cache of _get_font, which we can empty upon forking (in Py3.7+).
  1121. if hasattr(os, "register_at_fork"):
  1122. os.register_at_fork(after_in_child=_get_font.cache_clear)
  1123. def get_font(filename, hinting_factor=None):
  1124. if hinting_factor is None:
  1125. hinting_factor = rcParams['text.hinting_factor']
  1126. return _get_font(os.fspath(filename), hinting_factor,
  1127. _kerning_factor=rcParams['text.kerning_factor'])
  1128. def _rebuild():
  1129. global fontManager
  1130. fontManager = FontManager()
  1131. with cbook._lock_path(_fmcache):
  1132. json_dump(fontManager, _fmcache)
  1133. _log.info("generated new fontManager")
  1134. try:
  1135. fontManager = json_load(_fmcache)
  1136. except Exception:
  1137. _rebuild()
  1138. else:
  1139. if getattr(fontManager, '_version', object()) != FontManager.__version__:
  1140. _rebuild()
  1141. else:
  1142. _log.debug("Using fontManager instance from %s", _fmcache)
  1143. findfont = fontManager.findfont