font_manager.py 48 KB

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