font_manager.py 54 KB

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