font_manager.py 56 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645
  1. """
  2. A module for finding, managing, and using fonts across platforms.
  3. This module provides a single `FontManager` instance, ``fontManager``, 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 `FontManager.addfont` function adds a custom font from a file without
  10. installing it into your operating system.
  11. The design is based on the `W3C Cascading Style Sheet, Level 1 (CSS1)
  12. font specification <http://www.w3.org/TR/1998/REC-CSS2-19980512/>`_.
  13. Future versions may implement the Level 2 or 2.1 specifications.
  14. """
  15. # KNOWN ISSUES
  16. #
  17. # - documentation
  18. # - font variant is untested
  19. # - font stretch is incomplete
  20. # - font size is incomplete
  21. # - default font algorithm needs improvement and testing
  22. # - setWeights function needs improvement
  23. # - 'light' is an invalid weight value, remove it.
  24. from __future__ import annotations
  25. from base64 import b64encode
  26. import copy
  27. import dataclasses
  28. from functools import lru_cache
  29. import functools
  30. from io import BytesIO
  31. import json
  32. import logging
  33. from numbers import Number
  34. import os
  35. from pathlib import Path
  36. import plistlib
  37. import re
  38. import subprocess
  39. import sys
  40. import threading
  41. import matplotlib as mpl
  42. from matplotlib import _api, _afm, cbook, ft2font
  43. from matplotlib._fontconfig_pattern import (
  44. parse_fontconfig_pattern, generate_fontconfig_pattern)
  45. from matplotlib.rcsetup import _validators
  46. _log = logging.getLogger(__name__)
  47. font_scalings = {
  48. 'xx-small': 0.579,
  49. 'x-small': 0.694,
  50. 'small': 0.833,
  51. 'medium': 1.0,
  52. 'large': 1.200,
  53. 'x-large': 1.440,
  54. 'xx-large': 1.728,
  55. 'larger': 1.2,
  56. 'smaller': 0.833,
  57. None: 1.0,
  58. }
  59. stretch_dict = {
  60. 'ultra-condensed': 100,
  61. 'extra-condensed': 200,
  62. 'condensed': 300,
  63. 'semi-condensed': 400,
  64. 'normal': 500,
  65. 'semi-expanded': 600,
  66. 'semi-extended': 600,
  67. 'expanded': 700,
  68. 'extended': 700,
  69. 'extra-expanded': 800,
  70. 'extra-extended': 800,
  71. 'ultra-expanded': 900,
  72. 'ultra-extended': 900,
  73. }
  74. weight_dict = {
  75. 'ultralight': 100,
  76. 'light': 200,
  77. 'normal': 400,
  78. 'regular': 400,
  79. 'book': 400,
  80. 'medium': 500,
  81. 'roman': 500,
  82. 'semibold': 600,
  83. 'demibold': 600,
  84. 'demi': 600,
  85. 'bold': 700,
  86. 'heavy': 800,
  87. 'extra bold': 800,
  88. 'black': 900,
  89. }
  90. _weight_regexes = [
  91. # From fontconfig's FcFreeTypeQueryFaceInternal; not the same as
  92. # weight_dict!
  93. ("thin", 100),
  94. ("extralight", 200),
  95. ("ultralight", 200),
  96. ("demilight", 350),
  97. ("semilight", 350),
  98. ("light", 300), # Needs to come *after* demi/semilight!
  99. ("book", 380),
  100. ("regular", 400),
  101. ("normal", 400),
  102. ("medium", 500),
  103. ("demibold", 600),
  104. ("demi", 600),
  105. ("semibold", 600),
  106. ("extrabold", 800),
  107. ("superbold", 800),
  108. ("ultrabold", 800),
  109. ("bold", 700), # Needs to come *after* extra/super/ultrabold!
  110. ("ultrablack", 1000),
  111. ("superblack", 1000),
  112. ("extrablack", 1000),
  113. (r"\bultra", 1000),
  114. ("black", 900), # Needs to come *after* ultra/super/extrablack!
  115. ("heavy", 900),
  116. ]
  117. font_family_aliases = {
  118. 'serif',
  119. 'sans-serif',
  120. 'sans serif',
  121. 'cursive',
  122. 'fantasy',
  123. 'monospace',
  124. 'sans',
  125. }
  126. # OS Font paths
  127. try:
  128. _HOME = Path.home()
  129. except Exception: # Exceptions thrown by home() are not specified...
  130. _HOME = Path(os.devnull) # Just an arbitrary path with no children.
  131. MSFolders = \
  132. r'Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders'
  133. MSFontDirectories = [
  134. r'SOFTWARE\Microsoft\Windows NT\CurrentVersion\Fonts',
  135. r'SOFTWARE\Microsoft\Windows\CurrentVersion\Fonts']
  136. MSUserFontDirectories = [
  137. str(_HOME / 'AppData/Local/Microsoft/Windows/Fonts'),
  138. str(_HOME / 'AppData/Roaming/Microsoft/Windows/Fonts'),
  139. ]
  140. X11FontDirectories = [
  141. # an old standard installation point
  142. "/usr/X11R6/lib/X11/fonts/TTF/",
  143. "/usr/X11/lib/X11/fonts",
  144. # here is the new standard location for fonts
  145. "/usr/share/fonts/",
  146. # documented as a good place to install new fonts
  147. "/usr/local/share/fonts/",
  148. # common application, not really useful
  149. "/usr/lib/openoffice/share/fonts/truetype/",
  150. # user fonts
  151. str((Path(os.environ.get('XDG_DATA_HOME') or _HOME / ".local/share"))
  152. / "fonts"),
  153. str(_HOME / ".fonts"),
  154. ]
  155. OSXFontDirectories = [
  156. "/Library/Fonts/",
  157. "/Network/Library/Fonts/",
  158. "/System/Library/Fonts/",
  159. # fonts installed via MacPorts
  160. "/opt/local/share/fonts",
  161. # user fonts
  162. str(_HOME / "Library/Fonts"),
  163. ]
  164. def get_fontext_synonyms(fontext):
  165. """
  166. Return a list of file extensions that are synonyms for
  167. the given file extension *fileext*.
  168. """
  169. return {
  170. 'afm': ['afm'],
  171. 'otf': ['otf', 'ttc', 'ttf'],
  172. 'ttc': ['otf', 'ttc', 'ttf'],
  173. 'ttf': ['otf', 'ttc', 'ttf'],
  174. }[fontext]
  175. def list_fonts(directory, extensions):
  176. """
  177. Return a list of all fonts matching any of the extensions, found
  178. recursively under the directory.
  179. """
  180. extensions = ["." + ext for ext in extensions]
  181. return [os.path.join(dirpath, filename)
  182. # os.walk ignores access errors, unlike Path.glob.
  183. for dirpath, _, filenames in os.walk(directory)
  184. for filename in filenames
  185. if Path(filename).suffix.lower() in extensions]
  186. def win32FontDirectory():
  187. r"""
  188. Return the user-specified font directory for Win32. This is
  189. looked up from the registry key ::
  190. \\HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders\Fonts
  191. If the key is not found, ``%WINDIR%\Fonts`` will be returned.
  192. """ # noqa: E501
  193. import winreg
  194. try:
  195. with winreg.OpenKey(winreg.HKEY_CURRENT_USER, MSFolders) as user:
  196. return winreg.QueryValueEx(user, 'Fonts')[0]
  197. except OSError:
  198. return os.path.join(os.environ['WINDIR'], 'Fonts')
  199. def _get_win32_installed_fonts():
  200. """List the font paths known to the Windows registry."""
  201. import winreg
  202. items = set()
  203. # Search and resolve fonts listed in the registry.
  204. for domain, base_dirs in [
  205. (winreg.HKEY_LOCAL_MACHINE, [win32FontDirectory()]), # System.
  206. (winreg.HKEY_CURRENT_USER, MSUserFontDirectories), # User.
  207. ]:
  208. for base_dir in base_dirs:
  209. for reg_path in MSFontDirectories:
  210. try:
  211. with winreg.OpenKey(domain, reg_path) as local:
  212. for j in range(winreg.QueryInfoKey(local)[1]):
  213. # value may contain the filename of the font or its
  214. # absolute path.
  215. key, value, tp = winreg.EnumValue(local, j)
  216. if not isinstance(value, str):
  217. continue
  218. try:
  219. # If value contains already an absolute path,
  220. # then it is not changed further.
  221. path = Path(base_dir, value).resolve()
  222. except RuntimeError:
  223. # Don't fail with invalid entries.
  224. continue
  225. items.add(path)
  226. except (OSError, MemoryError):
  227. continue
  228. return items
  229. @lru_cache
  230. def _get_fontconfig_fonts():
  231. """Cache and list the font paths known to ``fc-list``."""
  232. try:
  233. if b'--format' not in subprocess.check_output(['fc-list', '--help']):
  234. _log.warning( # fontconfig 2.7 implemented --format.
  235. 'Matplotlib needs fontconfig>=2.7 to query system fonts.')
  236. return []
  237. out = subprocess.check_output(['fc-list', '--format=%{file}\\n'])
  238. except (OSError, subprocess.CalledProcessError):
  239. return []
  240. return [Path(os.fsdecode(fname)) for fname in out.split(b'\n')]
  241. @lru_cache
  242. def _get_macos_fonts():
  243. """Cache and list the font paths known to ``system_profiler SPFontsDataType``."""
  244. try:
  245. d, = plistlib.loads(
  246. subprocess.check_output(["system_profiler", "-xml", "SPFontsDataType"]))
  247. except (OSError, subprocess.CalledProcessError, plistlib.InvalidFileException):
  248. return []
  249. return [Path(entry["path"]) for entry in d["_items"]]
  250. def findSystemFonts(fontpaths=None, fontext='ttf'):
  251. """
  252. Search for fonts in the specified font paths. If no paths are
  253. given, will use a standard set of system paths, as well as the
  254. list of fonts tracked by fontconfig if fontconfig is installed and
  255. available. A list of TrueType fonts are returned by default with
  256. AFM fonts as an option.
  257. """
  258. fontfiles = set()
  259. fontexts = get_fontext_synonyms(fontext)
  260. if fontpaths is None:
  261. if sys.platform == 'win32':
  262. installed_fonts = _get_win32_installed_fonts()
  263. fontpaths = []
  264. else:
  265. installed_fonts = _get_fontconfig_fonts()
  266. if sys.platform == 'darwin':
  267. installed_fonts += _get_macos_fonts()
  268. fontpaths = [*X11FontDirectories, *OSXFontDirectories]
  269. else:
  270. fontpaths = X11FontDirectories
  271. fontfiles.update(str(path) for path in installed_fonts
  272. if path.suffix.lower()[1:] in fontexts)
  273. elif isinstance(fontpaths, str):
  274. fontpaths = [fontpaths]
  275. for path in fontpaths:
  276. fontfiles.update(map(os.path.abspath, list_fonts(path, fontexts)))
  277. return [fname for fname in fontfiles if os.path.exists(fname)]
  278. @dataclasses.dataclass(frozen=True)
  279. class FontEntry:
  280. """
  281. A class for storing Font properties.
  282. It is used when populating the font lookup dictionary.
  283. """
  284. fname: str = ''
  285. name: str = ''
  286. style: str = 'normal'
  287. variant: str = 'normal'
  288. weight: str | int = 'normal'
  289. stretch: str = 'normal'
  290. size: str = 'medium'
  291. def _repr_html_(self) -> str:
  292. png_stream = self._repr_png_()
  293. png_b64 = b64encode(png_stream).decode()
  294. return f"<img src=\"data:image/png;base64, {png_b64}\" />"
  295. def _repr_png_(self) -> bytes:
  296. from matplotlib.figure import Figure # Circular import.
  297. fig = Figure()
  298. font_path = Path(self.fname) if self.fname != '' else None
  299. fig.text(0, 0, self.name, font=font_path)
  300. with BytesIO() as buf:
  301. fig.savefig(buf, bbox_inches='tight', transparent=True)
  302. return buf.getvalue()
  303. def ttfFontProperty(font):
  304. """
  305. Extract information from a TrueType font file.
  306. Parameters
  307. ----------
  308. font : `.FT2Font`
  309. The TrueType font file from which information will be extracted.
  310. Returns
  311. -------
  312. `FontEntry`
  313. The extracted font properties.
  314. """
  315. name = font.family_name
  316. # Styles are: italic, oblique, and normal (default)
  317. sfnt = font.get_sfnt()
  318. mac_key = (1, # platform: macintosh
  319. 0, # id: roman
  320. 0) # langid: english
  321. ms_key = (3, # platform: microsoft
  322. 1, # id: unicode_cs
  323. 0x0409) # langid: english_united_states
  324. # These tables are actually mac_roman-encoded, but mac_roman support may be
  325. # missing in some alternative Python implementations and we are only going
  326. # to look for ASCII substrings, where any ASCII-compatible encoding works
  327. # - or big-endian UTF-16, since important Microsoft fonts use that.
  328. sfnt2 = (sfnt.get((*mac_key, 2), b'').decode('latin-1').lower() or
  329. sfnt.get((*ms_key, 2), b'').decode('utf_16_be').lower())
  330. sfnt4 = (sfnt.get((*mac_key, 4), b'').decode('latin-1').lower() or
  331. sfnt.get((*ms_key, 4), b'').decode('utf_16_be').lower())
  332. if sfnt4.find('oblique') >= 0:
  333. style = 'oblique'
  334. elif sfnt4.find('italic') >= 0:
  335. style = 'italic'
  336. elif sfnt2.find('regular') >= 0:
  337. style = 'normal'
  338. elif ft2font.StyleFlags.ITALIC in font.style_flags:
  339. style = 'italic'
  340. else:
  341. style = 'normal'
  342. # Variants are: small-caps and normal (default)
  343. # !!!! Untested
  344. if name.lower() in ['capitals', 'small-caps']:
  345. variant = 'small-caps'
  346. else:
  347. variant = 'normal'
  348. # The weight-guessing algorithm is directly translated from fontconfig
  349. # 2.13.1's FcFreeTypeQueryFaceInternal (fcfreetype.c).
  350. wws_subfamily = 22
  351. typographic_subfamily = 16
  352. font_subfamily = 2
  353. styles = [
  354. sfnt.get((*mac_key, wws_subfamily), b'').decode('latin-1'),
  355. sfnt.get((*mac_key, typographic_subfamily), b'').decode('latin-1'),
  356. sfnt.get((*mac_key, font_subfamily), b'').decode('latin-1'),
  357. sfnt.get((*ms_key, wws_subfamily), b'').decode('utf-16-be'),
  358. sfnt.get((*ms_key, typographic_subfamily), b'').decode('utf-16-be'),
  359. sfnt.get((*ms_key, font_subfamily), b'').decode('utf-16-be'),
  360. ]
  361. styles = [*filter(None, styles)] or [font.style_name]
  362. def get_weight(): # From fontconfig's FcFreeTypeQueryFaceInternal.
  363. # OS/2 table weight.
  364. os2 = font.get_sfnt_table("OS/2")
  365. if os2 and os2["version"] != 0xffff:
  366. return os2["usWeightClass"]
  367. # PostScript font info weight.
  368. try:
  369. ps_font_info_weight = (
  370. font.get_ps_font_info()["weight"].replace(" ", "") or "")
  371. except ValueError:
  372. pass
  373. else:
  374. for regex, weight in _weight_regexes:
  375. if re.fullmatch(regex, ps_font_info_weight, re.I):
  376. return weight
  377. # Style name weight.
  378. for style in styles:
  379. style = style.replace(" ", "")
  380. for regex, weight in _weight_regexes:
  381. if re.search(regex, style, re.I):
  382. return weight
  383. if ft2font.StyleFlags.BOLD in font.style_flags:
  384. return 700 # "bold"
  385. return 500 # "medium", not "regular"!
  386. weight = int(get_weight())
  387. # Stretch can be absolute and relative
  388. # Absolute stretches are: ultra-condensed, extra-condensed, condensed,
  389. # semi-condensed, normal, semi-expanded, expanded, extra-expanded,
  390. # and ultra-expanded.
  391. # Relative stretches are: wider, narrower
  392. # Child value is: inherit
  393. if any(word in sfnt4 for word in ['narrow', 'condensed', 'cond']):
  394. stretch = 'condensed'
  395. elif 'demi cond' in sfnt4:
  396. stretch = 'semi-condensed'
  397. elif any(word in sfnt4 for word in ['wide', 'expanded', 'extended']):
  398. stretch = 'expanded'
  399. else:
  400. stretch = 'normal'
  401. # Sizes can be absolute and relative.
  402. # Absolute sizes are: xx-small, x-small, small, medium, large, x-large,
  403. # and xx-large.
  404. # Relative sizes are: larger, smaller
  405. # Length value is an absolute font size, e.g., 12pt
  406. # Percentage values are in 'em's. Most robust specification.
  407. if not font.scalable:
  408. raise NotImplementedError("Non-scalable fonts are not supported")
  409. size = 'scalable'
  410. return FontEntry(font.fname, name, style, variant, weight, stretch, size)
  411. def afmFontProperty(fontpath, font):
  412. """
  413. Extract information from an AFM font file.
  414. Parameters
  415. ----------
  416. fontpath : str
  417. The filename corresponding to *font*.
  418. font : AFM
  419. The AFM font file from which information will be extracted.
  420. Returns
  421. -------
  422. `FontEntry`
  423. The extracted font properties.
  424. """
  425. name = font.get_familyname()
  426. fontname = font.get_fontname().lower()
  427. # Styles are: italic, oblique, and normal (default)
  428. if font.get_angle() != 0 or 'italic' in name.lower():
  429. style = 'italic'
  430. elif 'oblique' in name.lower():
  431. style = 'oblique'
  432. else:
  433. style = 'normal'
  434. # Variants are: small-caps and normal (default)
  435. # !!!! Untested
  436. if name.lower() in ['capitals', 'small-caps']:
  437. variant = 'small-caps'
  438. else:
  439. variant = 'normal'
  440. weight = font.get_weight().lower()
  441. if weight not in weight_dict:
  442. weight = 'normal'
  443. # Stretch can be absolute and relative
  444. # Absolute stretches are: ultra-condensed, extra-condensed, condensed,
  445. # semi-condensed, normal, semi-expanded, expanded, extra-expanded,
  446. # and ultra-expanded.
  447. # Relative stretches are: wider, narrower
  448. # Child value is: inherit
  449. if 'demi cond' in fontname:
  450. stretch = 'semi-condensed'
  451. elif any(word in fontname for word in ['narrow', 'cond']):
  452. stretch = 'condensed'
  453. elif any(word in fontname for word in ['wide', 'expanded', 'extended']):
  454. stretch = 'expanded'
  455. else:
  456. stretch = 'normal'
  457. # Sizes can be absolute and relative.
  458. # Absolute sizes are: xx-small, x-small, small, medium, large, x-large,
  459. # and xx-large.
  460. # Relative sizes are: larger, smaller
  461. # Length value is an absolute font size, e.g., 12pt
  462. # Percentage values are in 'em's. Most robust specification.
  463. # All AFM fonts are apparently scalable.
  464. size = 'scalable'
  465. return FontEntry(fontpath, name, style, variant, weight, stretch, size)
  466. def _cleanup_fontproperties_init(init_method):
  467. """
  468. A decorator to limit the call signature to single a positional argument
  469. or alternatively only keyword arguments.
  470. We still accept but deprecate all other call signatures.
  471. When the deprecation expires we can switch the signature to::
  472. __init__(self, pattern=None, /, *, family=None, style=None, ...)
  473. plus a runtime check that pattern is not used alongside with the
  474. keyword arguments. This results eventually in the two possible
  475. call signatures::
  476. FontProperties(pattern)
  477. FontProperties(family=..., size=..., ...)
  478. """
  479. @functools.wraps(init_method)
  480. def wrapper(self, *args, **kwargs):
  481. # multiple args with at least some positional ones
  482. if len(args) > 1 or len(args) == 1 and kwargs:
  483. # Note: Both cases were previously handled as individual properties.
  484. # Therefore, we do not mention the case of font properties here.
  485. _api.warn_deprecated(
  486. "3.10",
  487. message="Passing individual properties to FontProperties() "
  488. "positionally was deprecated in Matplotlib %(since)s and "
  489. "will be removed in %(removal)s. Please pass all properties "
  490. "via keyword arguments."
  491. )
  492. # single non-string arg -> clearly a family not a pattern
  493. if len(args) == 1 and not kwargs and not cbook.is_scalar_or_string(args[0]):
  494. # Case font-family list passed as single argument
  495. _api.warn_deprecated(
  496. "3.10",
  497. message="Passing family as positional argument to FontProperties() "
  498. "was deprecated in Matplotlib %(since)s and will be removed "
  499. "in %(removal)s. Please pass family names as keyword"
  500. "argument."
  501. )
  502. # Note on single string arg:
  503. # This has been interpreted as pattern so far. We are already raising if a
  504. # non-pattern compatible family string was given. Therefore, we do not need
  505. # to warn for this case.
  506. return init_method(self, *args, **kwargs)
  507. return wrapper
  508. class FontProperties:
  509. """
  510. A class for storing and manipulating font properties.
  511. The font properties are the six properties described in the
  512. `W3C Cascading Style Sheet, Level 1
  513. <http://www.w3.org/TR/1998/REC-CSS2-19980512/>`_ font
  514. specification and *math_fontfamily* for math fonts:
  515. - family: A list of font names in decreasing order of priority.
  516. The items may include a generic font family name, either 'sans-serif',
  517. 'serif', 'cursive', 'fantasy', or 'monospace'. In that case, the actual
  518. font to be used will be looked up from the associated rcParam during the
  519. search process in `.findfont`. Default: :rc:`font.family`
  520. - style: Either 'normal', 'italic' or 'oblique'.
  521. Default: :rc:`font.style`
  522. - variant: Either 'normal' or 'small-caps'.
  523. Default: :rc:`font.variant`
  524. - stretch: A numeric value in the range 0-1000 or one of
  525. 'ultra-condensed', 'extra-condensed', 'condensed',
  526. 'semi-condensed', 'normal', 'semi-expanded', 'expanded',
  527. 'extra-expanded' or 'ultra-expanded'. Default: :rc:`font.stretch`
  528. - weight: A numeric value in the range 0-1000 or one of
  529. 'ultralight', 'light', 'normal', 'regular', 'book', 'medium',
  530. 'roman', 'semibold', 'demibold', 'demi', 'bold', 'heavy',
  531. 'extra bold', 'black'. Default: :rc:`font.weight`
  532. - size: Either a relative value of 'xx-small', 'x-small',
  533. 'small', 'medium', 'large', 'x-large', 'xx-large' or an
  534. absolute font size, e.g., 10. Default: :rc:`font.size`
  535. - math_fontfamily: The family of fonts used to render math text.
  536. Supported values are: 'dejavusans', 'dejavuserif', 'cm',
  537. 'stix', 'stixsans' and 'custom'. Default: :rc:`mathtext.fontset`
  538. Alternatively, a font may be specified using the absolute path to a font
  539. file, by using the *fname* kwarg. However, in this case, it is typically
  540. simpler to just pass the path (as a `pathlib.Path`, not a `str`) to the
  541. *font* kwarg of the `.Text` object.
  542. The preferred usage of font sizes is to use the relative values,
  543. e.g., 'large', instead of absolute font sizes, e.g., 12. This
  544. approach allows all text sizes to be made larger or smaller based
  545. on the font manager's default font size.
  546. This class accepts a single positional string as fontconfig_ pattern_,
  547. or alternatively individual properties as keyword arguments::
  548. FontProperties(pattern)
  549. FontProperties(*, family=None, style=None, variant=None, ...)
  550. This support does not depend on fontconfig; we are merely borrowing its
  551. pattern syntax for use here.
  552. .. _fontconfig: https://www.freedesktop.org/wiki/Software/fontconfig/
  553. .. _pattern:
  554. https://www.freedesktop.org/software/fontconfig/fontconfig-user.html
  555. Note that Matplotlib's internal font manager and fontconfig use a
  556. different algorithm to lookup fonts, so the results of the same pattern
  557. may be different in Matplotlib than in other applications that use
  558. fontconfig.
  559. """
  560. @_cleanup_fontproperties_init
  561. def __init__(self, family=None, style=None, variant=None, weight=None,
  562. stretch=None, size=None,
  563. fname=None, # if set, it's a hardcoded filename to use
  564. math_fontfamily=None):
  565. self.set_family(family)
  566. self.set_style(style)
  567. self.set_variant(variant)
  568. self.set_weight(weight)
  569. self.set_stretch(stretch)
  570. self.set_file(fname)
  571. self.set_size(size)
  572. self.set_math_fontfamily(math_fontfamily)
  573. # Treat family as a fontconfig pattern if it is the only parameter
  574. # provided. Even in that case, call the other setters first to set
  575. # attributes not specified by the pattern to the rcParams defaults.
  576. if (isinstance(family, str)
  577. and style is None and variant is None and weight is None
  578. and stretch is None and size is None and fname is None):
  579. self.set_fontconfig_pattern(family)
  580. @classmethod
  581. def _from_any(cls, arg):
  582. """
  583. Generic constructor which can build a `.FontProperties` from any of the
  584. following:
  585. - a `.FontProperties`: it is passed through as is;
  586. - `None`: a `.FontProperties` using rc values is used;
  587. - an `os.PathLike`: it is used as path to the font file;
  588. - a `str`: it is parsed as a fontconfig pattern;
  589. - a `dict`: it is passed as ``**kwargs`` to `.FontProperties`.
  590. """
  591. if arg is None:
  592. return cls()
  593. elif isinstance(arg, cls):
  594. return arg
  595. elif isinstance(arg, os.PathLike):
  596. return cls(fname=arg)
  597. elif isinstance(arg, str):
  598. return cls(arg)
  599. else:
  600. return cls(**arg)
  601. def __hash__(self):
  602. l = (tuple(self.get_family()),
  603. self.get_slant(),
  604. self.get_variant(),
  605. self.get_weight(),
  606. self.get_stretch(),
  607. self.get_size(),
  608. self.get_file(),
  609. self.get_math_fontfamily())
  610. return hash(l)
  611. def __eq__(self, other):
  612. return hash(self) == hash(other)
  613. def __str__(self):
  614. return self.get_fontconfig_pattern()
  615. def get_family(self):
  616. """
  617. Return a list of individual font family names or generic family names.
  618. The font families or generic font families (which will be resolved
  619. from their respective rcParams when searching for a matching font) in
  620. the order of preference.
  621. """
  622. return self._family
  623. def get_name(self):
  624. """
  625. Return the name of the font that best matches the font properties.
  626. """
  627. return get_font(findfont(self)).family_name
  628. def get_style(self):
  629. """
  630. Return the font style. Values are: 'normal', 'italic' or 'oblique'.
  631. """
  632. return self._slant
  633. def get_variant(self):
  634. """
  635. Return the font variant. Values are: 'normal' or 'small-caps'.
  636. """
  637. return self._variant
  638. def get_weight(self):
  639. """
  640. Set the font weight. Options are: A numeric value in the
  641. range 0-1000 or one of 'light', 'normal', 'regular', 'book',
  642. 'medium', 'roman', 'semibold', 'demibold', 'demi', 'bold',
  643. 'heavy', 'extra bold', 'black'
  644. """
  645. return self._weight
  646. def get_stretch(self):
  647. """
  648. Return the font stretch or width. Options are: 'ultra-condensed',
  649. 'extra-condensed', 'condensed', 'semi-condensed', 'normal',
  650. 'semi-expanded', 'expanded', 'extra-expanded', 'ultra-expanded'.
  651. """
  652. return self._stretch
  653. def get_size(self):
  654. """
  655. Return the font size.
  656. """
  657. return self._size
  658. def get_file(self):
  659. """
  660. Return the filename of the associated font.
  661. """
  662. return self._file
  663. def get_fontconfig_pattern(self):
  664. """
  665. Get a fontconfig_ pattern_ suitable for looking up the font as
  666. specified with fontconfig's ``fc-match`` utility.
  667. This support does not depend on fontconfig; we are merely borrowing its
  668. pattern syntax for use here.
  669. """
  670. return generate_fontconfig_pattern(self)
  671. def set_family(self, family):
  672. """
  673. Change the font family. Can be either an alias (generic name
  674. is CSS parlance), such as: 'serif', 'sans-serif', 'cursive',
  675. 'fantasy', or 'monospace', a real font name or a list of real
  676. font names. Real font names are not supported when
  677. :rc:`text.usetex` is `True`. Default: :rc:`font.family`
  678. """
  679. if family is None:
  680. family = mpl.rcParams['font.family']
  681. if isinstance(family, str):
  682. family = [family]
  683. self._family = family
  684. def set_style(self, style):
  685. """
  686. Set the font style.
  687. Parameters
  688. ----------
  689. style : {'normal', 'italic', 'oblique'}, default: :rc:`font.style`
  690. """
  691. if style is None:
  692. style = mpl.rcParams['font.style']
  693. _api.check_in_list(['normal', 'italic', 'oblique'], style=style)
  694. self._slant = style
  695. def set_variant(self, variant):
  696. """
  697. Set the font variant.
  698. Parameters
  699. ----------
  700. variant : {'normal', 'small-caps'}, default: :rc:`font.variant`
  701. """
  702. if variant is None:
  703. variant = mpl.rcParams['font.variant']
  704. _api.check_in_list(['normal', 'small-caps'], variant=variant)
  705. self._variant = variant
  706. def set_weight(self, weight):
  707. """
  708. Set the font weight.
  709. Parameters
  710. ----------
  711. weight : int or {'ultralight', 'light', 'normal', 'regular', 'book', \
  712. 'medium', 'roman', 'semibold', 'demibold', 'demi', 'bold', 'heavy', \
  713. 'extra bold', 'black'}, default: :rc:`font.weight`
  714. If int, must be in the range 0-1000.
  715. """
  716. if weight is None:
  717. weight = mpl.rcParams['font.weight']
  718. if weight in weight_dict:
  719. self._weight = weight
  720. return
  721. try:
  722. weight = int(weight)
  723. except ValueError:
  724. pass
  725. else:
  726. if 0 <= weight <= 1000:
  727. self._weight = weight
  728. return
  729. raise ValueError(f"{weight=} is invalid")
  730. def set_stretch(self, stretch):
  731. """
  732. Set the font stretch or width.
  733. Parameters
  734. ----------
  735. stretch : int or {'ultra-condensed', 'extra-condensed', 'condensed', \
  736. 'semi-condensed', 'normal', 'semi-expanded', 'expanded', 'extra-expanded', \
  737. 'ultra-expanded'}, default: :rc:`font.stretch`
  738. If int, must be in the range 0-1000.
  739. """
  740. if stretch is None:
  741. stretch = mpl.rcParams['font.stretch']
  742. if stretch in stretch_dict:
  743. self._stretch = stretch
  744. return
  745. try:
  746. stretch = int(stretch)
  747. except ValueError:
  748. pass
  749. else:
  750. if 0 <= stretch <= 1000:
  751. self._stretch = stretch
  752. return
  753. raise ValueError(f"{stretch=} is invalid")
  754. def set_size(self, size):
  755. """
  756. Set the font size.
  757. Parameters
  758. ----------
  759. size : float or {'xx-small', 'x-small', 'small', 'medium', \
  760. 'large', 'x-large', 'xx-large'}, default: :rc:`font.size`
  761. If a float, the font size in points. The string values denote
  762. sizes relative to the default font size.
  763. """
  764. if size is None:
  765. size = mpl.rcParams['font.size']
  766. try:
  767. size = float(size)
  768. except ValueError:
  769. try:
  770. scale = font_scalings[size]
  771. except KeyError as err:
  772. raise ValueError(
  773. "Size is invalid. Valid font size are "
  774. + ", ".join(map(str, font_scalings))) from err
  775. else:
  776. size = scale * FontManager.get_default_size()
  777. if size < 1.0:
  778. _log.info('Fontsize %1.2f < 1.0 pt not allowed by FreeType. '
  779. 'Setting fontsize = 1 pt', size)
  780. size = 1.0
  781. self._size = size
  782. def set_file(self, file):
  783. """
  784. Set the filename of the fontfile to use. In this case, all
  785. other properties will be ignored.
  786. """
  787. self._file = os.fspath(file) if file is not None else None
  788. def set_fontconfig_pattern(self, pattern):
  789. """
  790. Set the properties by parsing a fontconfig_ *pattern*.
  791. This support does not depend on fontconfig; we are merely borrowing its
  792. pattern syntax for use here.
  793. """
  794. for key, val in parse_fontconfig_pattern(pattern).items():
  795. if type(val) is list:
  796. getattr(self, "set_" + key)(val[0])
  797. else:
  798. getattr(self, "set_" + key)(val)
  799. def get_math_fontfamily(self):
  800. """
  801. Return the name of the font family used for math text.
  802. The default font is :rc:`mathtext.fontset`.
  803. """
  804. return self._math_fontfamily
  805. def set_math_fontfamily(self, fontfamily):
  806. """
  807. Set the font family for text in math mode.
  808. If not set explicitly, :rc:`mathtext.fontset` will be used.
  809. Parameters
  810. ----------
  811. fontfamily : str
  812. The name of the font family.
  813. Available font families are defined in the
  814. :ref:`default matplotlibrc file <customizing-with-matplotlibrc-files>`.
  815. See Also
  816. --------
  817. .text.Text.get_math_fontfamily
  818. """
  819. if fontfamily is None:
  820. fontfamily = mpl.rcParams['mathtext.fontset']
  821. else:
  822. valid_fonts = _validators['mathtext.fontset'].valid.values()
  823. # _check_in_list() Validates the parameter math_fontfamily as
  824. # if it were passed to rcParams['mathtext.fontset']
  825. _api.check_in_list(valid_fonts, math_fontfamily=fontfamily)
  826. self._math_fontfamily = fontfamily
  827. def copy(self):
  828. """Return a copy of self."""
  829. return copy.copy(self)
  830. # Aliases
  831. set_name = set_family
  832. get_slant = get_style
  833. set_slant = set_style
  834. get_size_in_points = get_size
  835. class _JSONEncoder(json.JSONEncoder):
  836. def default(self, o):
  837. if isinstance(o, FontManager):
  838. return dict(o.__dict__, __class__='FontManager')
  839. elif isinstance(o, FontEntry):
  840. d = dict(o.__dict__, __class__='FontEntry')
  841. try:
  842. # Cache paths of fonts shipped with Matplotlib relative to the
  843. # Matplotlib data path, which helps in the presence of venvs.
  844. d["fname"] = str(Path(d["fname"]).relative_to(mpl.get_data_path()))
  845. except ValueError:
  846. pass
  847. return d
  848. else:
  849. return super().default(o)
  850. def _json_decode(o):
  851. cls = o.pop('__class__', None)
  852. if cls is None:
  853. return o
  854. elif cls == 'FontManager':
  855. r = FontManager.__new__(FontManager)
  856. r.__dict__.update(o)
  857. return r
  858. elif cls == 'FontEntry':
  859. if not os.path.isabs(o['fname']):
  860. o['fname'] = os.path.join(mpl.get_data_path(), o['fname'])
  861. r = FontEntry(**o)
  862. return r
  863. else:
  864. raise ValueError("Don't know how to deserialize __class__=%s" % cls)
  865. def json_dump(data, filename):
  866. """
  867. Dump `FontManager` *data* as JSON to the file named *filename*.
  868. See Also
  869. --------
  870. json_load
  871. Notes
  872. -----
  873. File paths that are children of the Matplotlib data path (typically, fonts
  874. shipped with Matplotlib) are stored relative to that data path (to remain
  875. valid across virtualenvs).
  876. This function temporarily locks the output file to prevent multiple
  877. processes from overwriting one another's output.
  878. """
  879. try:
  880. with cbook._lock_path(filename), open(filename, 'w') as fh:
  881. json.dump(data, fh, cls=_JSONEncoder, indent=2)
  882. except OSError as e:
  883. _log.warning('Could not save font_manager cache %s', e)
  884. def json_load(filename):
  885. """
  886. Load a `FontManager` from the JSON file named *filename*.
  887. See Also
  888. --------
  889. json_dump
  890. """
  891. with open(filename) as fh:
  892. return json.load(fh, object_hook=_json_decode)
  893. class FontManager:
  894. """
  895. On import, the `FontManager` singleton instance creates a list of ttf and
  896. afm fonts and caches their `FontProperties`. The `FontManager.findfont`
  897. method does a nearest neighbor search to find the font that most closely
  898. matches the specification. If no good enough match is found, the default
  899. font is returned.
  900. Fonts added with the `FontManager.addfont` method will not persist in the
  901. cache; therefore, `addfont` will need to be called every time Matplotlib is
  902. imported. This method should only be used if and when a font cannot be
  903. installed on your operating system by other means.
  904. Notes
  905. -----
  906. The `FontManager.addfont` method must be called on the global `FontManager`
  907. instance.
  908. Example usage::
  909. import matplotlib.pyplot as plt
  910. from matplotlib import font_manager
  911. font_dirs = ["/resources/fonts"] # The path to the custom font file.
  912. font_files = font_manager.findSystemFonts(fontpaths=font_dirs)
  913. for font_file in font_files:
  914. font_manager.fontManager.addfont(font_file)
  915. """
  916. # Increment this version number whenever the font cache data
  917. # format or behavior has changed and requires an existing font
  918. # cache files to be rebuilt.
  919. __version__ = 390
  920. def __init__(self, size=None, weight='normal'):
  921. self._version = self.__version__
  922. self.__default_weight = weight
  923. self.default_size = size
  924. # Create list of font paths.
  925. paths = [cbook._get_data_path('fonts', subdir)
  926. for subdir in ['ttf', 'afm', 'pdfcorefonts']]
  927. _log.debug('font search path %s', paths)
  928. self.defaultFamily = {
  929. 'ttf': 'DejaVu Sans',
  930. 'afm': 'Helvetica'}
  931. self.afmlist = []
  932. self.ttflist = []
  933. # Delay the warning by 5s.
  934. timer = threading.Timer(5, lambda: _log.warning(
  935. 'Matplotlib is building the font cache; this may take a moment.'))
  936. timer.start()
  937. try:
  938. for fontext in ["afm", "ttf"]:
  939. for path in [*findSystemFonts(paths, fontext=fontext),
  940. *findSystemFonts(fontext=fontext)]:
  941. try:
  942. self.addfont(path)
  943. except OSError as exc:
  944. _log.info("Failed to open font file %s: %s", path, exc)
  945. except Exception as exc:
  946. _log.info("Failed to extract font properties from %s: "
  947. "%s", path, exc)
  948. finally:
  949. timer.cancel()
  950. def addfont(self, path):
  951. """
  952. Cache the properties of the font at *path* to make it available to the
  953. `FontManager`. The type of font is inferred from the path suffix.
  954. Parameters
  955. ----------
  956. path : str or path-like
  957. Notes
  958. -----
  959. This method is useful for adding a custom font without installing it in
  960. your operating system. See the `FontManager` singleton instance for
  961. usage and caveats about this function.
  962. """
  963. # Convert to string in case of a path as
  964. # afmFontProperty and FT2Font expect this
  965. path = os.fsdecode(path)
  966. if Path(path).suffix.lower() == ".afm":
  967. with open(path, "rb") as fh:
  968. font = _afm.AFM(fh)
  969. prop = afmFontProperty(path, font)
  970. self.afmlist.append(prop)
  971. else:
  972. font = ft2font.FT2Font(path)
  973. prop = ttfFontProperty(font)
  974. self.ttflist.append(prop)
  975. self._findfont_cached.cache_clear()
  976. @property
  977. def defaultFont(self):
  978. # Lazily evaluated (findfont then caches the result) to avoid including
  979. # the venv path in the json serialization.
  980. return {ext: self.findfont(family, fontext=ext)
  981. for ext, family in self.defaultFamily.items()}
  982. def get_default_weight(self):
  983. """
  984. Return the default font weight.
  985. """
  986. return self.__default_weight
  987. @staticmethod
  988. def get_default_size():
  989. """
  990. Return the default font size.
  991. """
  992. return mpl.rcParams['font.size']
  993. def set_default_weight(self, weight):
  994. """
  995. Set the default font weight. The initial value is 'normal'.
  996. """
  997. self.__default_weight = weight
  998. @staticmethod
  999. def _expand_aliases(family):
  1000. if family in ('sans', 'sans serif'):
  1001. family = 'sans-serif'
  1002. return mpl.rcParams['font.' + family]
  1003. # Each of the scoring functions below should return a value between
  1004. # 0.0 (perfect match) and 1.0 (terrible match)
  1005. def score_family(self, families, family2):
  1006. """
  1007. Return a match score between the list of font families in
  1008. *families* and the font family name *family2*.
  1009. An exact match at the head of the list returns 0.0.
  1010. A match further down the list will return between 0 and 1.
  1011. No match will return 1.0.
  1012. """
  1013. if not isinstance(families, (list, tuple)):
  1014. families = [families]
  1015. elif len(families) == 0:
  1016. return 1.0
  1017. family2 = family2.lower()
  1018. step = 1 / len(families)
  1019. for i, family1 in enumerate(families):
  1020. family1 = family1.lower()
  1021. if family1 in font_family_aliases:
  1022. options = [*map(str.lower, self._expand_aliases(family1))]
  1023. if family2 in options:
  1024. idx = options.index(family2)
  1025. return (i + (idx / len(options))) * step
  1026. elif family1 == family2:
  1027. # The score should be weighted by where in the
  1028. # list the font was found.
  1029. return i * step
  1030. return 1.0
  1031. def score_style(self, style1, style2):
  1032. """
  1033. Return a match score between *style1* and *style2*.
  1034. An exact match returns 0.0.
  1035. A match between 'italic' and 'oblique' returns 0.1.
  1036. No match returns 1.0.
  1037. """
  1038. if style1 == style2:
  1039. return 0.0
  1040. elif (style1 in ('italic', 'oblique')
  1041. and style2 in ('italic', 'oblique')):
  1042. return 0.1
  1043. return 1.0
  1044. def score_variant(self, variant1, variant2):
  1045. """
  1046. Return a match score between *variant1* and *variant2*.
  1047. An exact match returns 0.0, otherwise 1.0.
  1048. """
  1049. if variant1 == variant2:
  1050. return 0.0
  1051. else:
  1052. return 1.0
  1053. def score_stretch(self, stretch1, stretch2):
  1054. """
  1055. Return a match score between *stretch1* and *stretch2*.
  1056. The result is the absolute value of the difference between the
  1057. CSS numeric values of *stretch1* and *stretch2*, normalized
  1058. between 0.0 and 1.0.
  1059. """
  1060. try:
  1061. stretchval1 = int(stretch1)
  1062. except ValueError:
  1063. stretchval1 = stretch_dict.get(stretch1, 500)
  1064. try:
  1065. stretchval2 = int(stretch2)
  1066. except ValueError:
  1067. stretchval2 = stretch_dict.get(stretch2, 500)
  1068. return abs(stretchval1 - stretchval2) / 1000.0
  1069. def score_weight(self, weight1, weight2):
  1070. """
  1071. Return a match score between *weight1* and *weight2*.
  1072. The result is 0.0 if both weight1 and weight 2 are given as strings
  1073. and have the same value.
  1074. Otherwise, the result is the absolute value of the difference between
  1075. the CSS numeric values of *weight1* and *weight2*, normalized between
  1076. 0.05 and 1.0.
  1077. """
  1078. # exact match of the weight names, e.g. weight1 == weight2 == "regular"
  1079. if cbook._str_equal(weight1, weight2):
  1080. return 0.0
  1081. w1 = weight1 if isinstance(weight1, Number) else weight_dict[weight1]
  1082. w2 = weight2 if isinstance(weight2, Number) else weight_dict[weight2]
  1083. return 0.95 * (abs(w1 - w2) / 1000) + 0.05
  1084. def score_size(self, size1, size2):
  1085. """
  1086. Return a match score between *size1* and *size2*.
  1087. If *size2* (the size specified in the font file) is 'scalable', this
  1088. function always returns 0.0, since any font size can be generated.
  1089. Otherwise, the result is the absolute distance between *size1* and
  1090. *size2*, normalized so that the usual range of font sizes (6pt -
  1091. 72pt) will lie between 0.0 and 1.0.
  1092. """
  1093. if size2 == 'scalable':
  1094. return 0.0
  1095. # Size value should have already been
  1096. try:
  1097. sizeval1 = float(size1)
  1098. except ValueError:
  1099. sizeval1 = self.default_size * font_scalings[size1]
  1100. try:
  1101. sizeval2 = float(size2)
  1102. except ValueError:
  1103. return 1.0
  1104. return abs(sizeval1 - sizeval2) / 72
  1105. def findfont(self, prop, fontext='ttf', directory=None,
  1106. fallback_to_default=True, rebuild_if_missing=True):
  1107. """
  1108. Find the path to the font file most closely matching the given font properties.
  1109. Parameters
  1110. ----------
  1111. prop : str or `~matplotlib.font_manager.FontProperties`
  1112. The font properties to search for. This can be either a
  1113. `.FontProperties` object or a string defining a
  1114. `fontconfig patterns`_.
  1115. fontext : {'ttf', 'afm'}, default: 'ttf'
  1116. The extension of the font file:
  1117. - 'ttf': TrueType and OpenType fonts (.ttf, .ttc, .otf)
  1118. - 'afm': Adobe Font Metrics (.afm)
  1119. directory : str, optional
  1120. If given, only search this directory and its subdirectories.
  1121. fallback_to_default : bool
  1122. If True, will fall back to the default font family (usually
  1123. "DejaVu Sans" or "Helvetica") if the first lookup hard-fails.
  1124. rebuild_if_missing : bool
  1125. Whether to rebuild the font cache and search again if the first
  1126. match appears to point to a nonexisting font (i.e., the font cache
  1127. contains outdated entries).
  1128. Returns
  1129. -------
  1130. str
  1131. The filename of the best matching font.
  1132. Notes
  1133. -----
  1134. This performs a nearest neighbor search. Each font is given a
  1135. similarity score to the target font properties. The first font with
  1136. the highest score is returned. If no matches below a certain
  1137. threshold are found, the default font (usually DejaVu Sans) is
  1138. returned.
  1139. The result is cached, so subsequent lookups don't have to
  1140. perform the O(n) nearest neighbor search.
  1141. See the `W3C Cascading Style Sheet, Level 1
  1142. <http://www.w3.org/TR/1998/REC-CSS2-19980512/>`_ documentation
  1143. for a description of the font finding algorithm.
  1144. .. _fontconfig patterns:
  1145. https://www.freedesktop.org/software/fontconfig/fontconfig-user.html
  1146. """
  1147. # Pass the relevant rcParams (and the font manager, as `self`) to
  1148. # _findfont_cached so to prevent using a stale cache entry after an
  1149. # rcParam was changed.
  1150. rc_params = tuple(tuple(mpl.rcParams[key]) for key in [
  1151. "font.serif", "font.sans-serif", "font.cursive", "font.fantasy",
  1152. "font.monospace"])
  1153. ret = self._findfont_cached(
  1154. prop, fontext, directory, fallback_to_default, rebuild_if_missing,
  1155. rc_params)
  1156. if isinstance(ret, cbook._ExceptionInfo):
  1157. raise ret.to_exception()
  1158. return ret
  1159. def get_font_names(self):
  1160. """Return the list of available fonts."""
  1161. return list({font.name for font in self.ttflist})
  1162. def _find_fonts_by_props(self, prop, fontext='ttf', directory=None,
  1163. fallback_to_default=True, rebuild_if_missing=True):
  1164. """
  1165. Find the paths to the font files most closely matching the given properties.
  1166. Parameters
  1167. ----------
  1168. prop : str or `~matplotlib.font_manager.FontProperties`
  1169. The font properties to search for. This can be either a
  1170. `.FontProperties` object or a string defining a
  1171. `fontconfig patterns`_.
  1172. fontext : {'ttf', 'afm'}, default: 'ttf'
  1173. The extension of the font file:
  1174. - 'ttf': TrueType and OpenType fonts (.ttf, .ttc, .otf)
  1175. - 'afm': Adobe Font Metrics (.afm)
  1176. directory : str, optional
  1177. If given, only search this directory and its subdirectories.
  1178. fallback_to_default : bool
  1179. If True, will fall back to the default font family (usually
  1180. "DejaVu Sans" or "Helvetica") if none of the families were found.
  1181. rebuild_if_missing : bool
  1182. Whether to rebuild the font cache and search again if the first
  1183. match appears to point to a nonexisting font (i.e., the font cache
  1184. contains outdated entries).
  1185. Returns
  1186. -------
  1187. list[str]
  1188. The paths of the fonts found.
  1189. Notes
  1190. -----
  1191. This is an extension/wrapper of the original findfont API, which only
  1192. returns a single font for given font properties. Instead, this API
  1193. returns a list of filepaths of multiple fonts which closely match the
  1194. given font properties. Since this internally uses the original API,
  1195. there's no change to the logic of performing the nearest neighbor
  1196. search. See `findfont` for more details.
  1197. """
  1198. prop = FontProperties._from_any(prop)
  1199. fpaths = []
  1200. for family in prop.get_family():
  1201. cprop = prop.copy()
  1202. cprop.set_family(family) # set current prop's family
  1203. try:
  1204. fpaths.append(
  1205. self.findfont(
  1206. cprop, fontext, directory,
  1207. fallback_to_default=False, # don't fallback to default
  1208. rebuild_if_missing=rebuild_if_missing,
  1209. )
  1210. )
  1211. except ValueError:
  1212. if family in font_family_aliases:
  1213. _log.warning(
  1214. "findfont: Generic family %r not found because "
  1215. "none of the following families were found: %s",
  1216. family, ", ".join(self._expand_aliases(family))
  1217. )
  1218. else:
  1219. _log.warning("findfont: Font family %r not found.", family)
  1220. # only add default family if no other font was found and
  1221. # fallback_to_default is enabled
  1222. if not fpaths:
  1223. if fallback_to_default:
  1224. dfamily = self.defaultFamily[fontext]
  1225. cprop = prop.copy()
  1226. cprop.set_family(dfamily)
  1227. fpaths.append(
  1228. self.findfont(
  1229. cprop, fontext, directory,
  1230. fallback_to_default=True,
  1231. rebuild_if_missing=rebuild_if_missing,
  1232. )
  1233. )
  1234. else:
  1235. raise ValueError("Failed to find any font, and fallback "
  1236. "to the default font was disabled")
  1237. return fpaths
  1238. @lru_cache(1024)
  1239. def _findfont_cached(self, prop, fontext, directory, fallback_to_default,
  1240. rebuild_if_missing, rc_params):
  1241. prop = FontProperties._from_any(prop)
  1242. fname = prop.get_file()
  1243. if fname is not None:
  1244. return fname
  1245. if fontext == 'afm':
  1246. fontlist = self.afmlist
  1247. else:
  1248. fontlist = self.ttflist
  1249. best_score = 1e64
  1250. best_font = None
  1251. _log.debug('findfont: Matching %s.', prop)
  1252. for font in fontlist:
  1253. if (directory is not None and
  1254. Path(directory) not in Path(font.fname).parents):
  1255. continue
  1256. # Matching family should have top priority, so multiply it by 10.
  1257. score = (self.score_family(prop.get_family(), font.name) * 10
  1258. + self.score_style(prop.get_style(), font.style)
  1259. + self.score_variant(prop.get_variant(), font.variant)
  1260. + self.score_weight(prop.get_weight(), font.weight)
  1261. + self.score_stretch(prop.get_stretch(), font.stretch)
  1262. + self.score_size(prop.get_size(), font.size))
  1263. _log.debug('findfont: score(%s) = %s', font, score)
  1264. if score < best_score:
  1265. best_score = score
  1266. best_font = font
  1267. if score == 0:
  1268. break
  1269. if best_font is None or best_score >= 10.0:
  1270. if fallback_to_default:
  1271. _log.warning(
  1272. 'findfont: Font family %s not found. Falling back to %s.',
  1273. prop.get_family(), self.defaultFamily[fontext])
  1274. for family in map(str.lower, prop.get_family()):
  1275. if family in font_family_aliases:
  1276. _log.warning(
  1277. "findfont: Generic family %r not found because "
  1278. "none of the following families were found: %s",
  1279. family, ", ".join(self._expand_aliases(family)))
  1280. default_prop = prop.copy()
  1281. default_prop.set_family(self.defaultFamily[fontext])
  1282. return self.findfont(default_prop, fontext, directory,
  1283. fallback_to_default=False)
  1284. else:
  1285. # This return instead of raise is intentional, as we wish to
  1286. # cache that it was not found, which will not occur if it was
  1287. # actually raised.
  1288. return cbook._ExceptionInfo(
  1289. ValueError,
  1290. f"Failed to find font {prop}, and fallback to the default font was "
  1291. f"disabled"
  1292. )
  1293. else:
  1294. _log.debug('findfont: Matching %s to %s (%r) with score of %f.',
  1295. prop, best_font.name, best_font.fname, best_score)
  1296. result = best_font.fname
  1297. if not os.path.isfile(result):
  1298. if rebuild_if_missing:
  1299. _log.info(
  1300. 'findfont: Found a missing font file. Rebuilding cache.')
  1301. new_fm = _load_fontmanager(try_read_cache=False)
  1302. # Replace self by the new fontmanager, because users may have
  1303. # a reference to this specific instance.
  1304. # TODO: _load_fontmanager should really be (used by) a method
  1305. # modifying the instance in place.
  1306. vars(self).update(vars(new_fm))
  1307. return self.findfont(
  1308. prop, fontext, directory, rebuild_if_missing=False)
  1309. else:
  1310. # This return instead of raise is intentional, as we wish to
  1311. # cache that it was not found, which will not occur if it was
  1312. # actually raised.
  1313. return cbook._ExceptionInfo(ValueError, "No valid font could be found")
  1314. return _cached_realpath(result)
  1315. @lru_cache
  1316. def is_opentype_cff_font(filename):
  1317. """
  1318. Return whether the given font is a Postscript Compact Font Format Font
  1319. embedded in an OpenType wrapper. Used by the PostScript and PDF backends
  1320. that cannot subset these fonts.
  1321. """
  1322. if os.path.splitext(filename)[1].lower() == '.otf':
  1323. with open(filename, 'rb') as fd:
  1324. return fd.read(4) == b"OTTO"
  1325. else:
  1326. return False
  1327. @lru_cache(64)
  1328. def _get_font(font_filepaths, hinting_factor, *, _kerning_factor, thread_id):
  1329. first_fontpath, *rest = font_filepaths
  1330. return ft2font.FT2Font(
  1331. first_fontpath, hinting_factor,
  1332. _fallback_list=[
  1333. ft2font.FT2Font(
  1334. fpath, hinting_factor,
  1335. _kerning_factor=_kerning_factor
  1336. )
  1337. for fpath in rest
  1338. ],
  1339. _kerning_factor=_kerning_factor
  1340. )
  1341. # FT2Font objects cannot be used across fork()s because they reference the same
  1342. # FT_Library object. While invalidating *all* existing FT2Fonts after a fork
  1343. # would be too complicated to be worth it, the main way FT2Fonts get reused is
  1344. # via the cache of _get_font, which we can empty upon forking (not on Windows,
  1345. # which has no fork() or register_at_fork()).
  1346. if hasattr(os, "register_at_fork"):
  1347. os.register_at_fork(after_in_child=_get_font.cache_clear)
  1348. @lru_cache(64)
  1349. def _cached_realpath(path):
  1350. # Resolving the path avoids embedding the font twice in pdf/ps output if a
  1351. # single font is selected using two different relative paths.
  1352. return os.path.realpath(path)
  1353. def get_font(font_filepaths, hinting_factor=None):
  1354. """
  1355. Get an `.ft2font.FT2Font` object given a list of file paths.
  1356. Parameters
  1357. ----------
  1358. font_filepaths : Iterable[str, Path, bytes], str, Path, bytes
  1359. Relative or absolute paths to the font files to be used.
  1360. If a single string, bytes, or `pathlib.Path`, then it will be treated
  1361. as a list with that entry only.
  1362. If more than one filepath is passed, then the returned FT2Font object
  1363. will fall back through the fonts, in the order given, to find a needed
  1364. glyph.
  1365. Returns
  1366. -------
  1367. `.ft2font.FT2Font`
  1368. """
  1369. if isinstance(font_filepaths, (str, Path, bytes)):
  1370. paths = (_cached_realpath(font_filepaths),)
  1371. else:
  1372. paths = tuple(_cached_realpath(fname) for fname in font_filepaths)
  1373. if hinting_factor is None:
  1374. hinting_factor = mpl.rcParams['text.hinting_factor']
  1375. return _get_font(
  1376. # must be a tuple to be cached
  1377. paths,
  1378. hinting_factor,
  1379. _kerning_factor=mpl.rcParams['text.kerning_factor'],
  1380. # also key on the thread ID to prevent segfaults with multi-threading
  1381. thread_id=threading.get_ident()
  1382. )
  1383. def _load_fontmanager(*, try_read_cache=True):
  1384. fm_path = Path(
  1385. mpl.get_cachedir(), f"fontlist-v{FontManager.__version__}.json")
  1386. if try_read_cache:
  1387. try:
  1388. fm = json_load(fm_path)
  1389. except Exception:
  1390. pass
  1391. else:
  1392. if getattr(fm, "_version", object()) == FontManager.__version__:
  1393. _log.debug("Using fontManager instance from %s", fm_path)
  1394. return fm
  1395. fm = FontManager()
  1396. json_dump(fm, fm_path)
  1397. _log.info("generated new fontManager")
  1398. return fm
  1399. fontManager = _load_fontmanager()
  1400. findfont = fontManager.findfont
  1401. get_font_names = fontManager.get_font_names