diff --git a/lib/matplotlib/font_manager.py b/lib/matplotlib/font_manager.py index cfa5629d30ff..5eb726618faa 100644 --- a/lib/matplotlib/font_manager.py +++ b/lib/matplotlib/font_manager.py @@ -23,8 +23,10 @@ # - setWeights function needs improvement # - 'light' is an invalid weight value, remove it. +from base64 import b64encode import dataclasses from functools import lru_cache +from io import BytesIO import json import logging from numbers import Number @@ -380,6 +382,22 @@ def findSystemFonts(fontpaths=None, fontext='ttf'): return [fname for fname in fontfiles if os.path.exists(fname)] +def fontentry_helper_repr_png_(fontent): + from matplotlib.figure import Figure # Circular import. + fig = Figure() + font_path = Path(fontent.fname) if fontent.fname != '' else None + fig.text(0, 0, fontent.name, font=font_path) + with BytesIO() as buf: + fig.savefig(buf, bbox_inches='tight', transparent=True) + return buf.getvalue() + + +def fontentry_helper_repr_html_(fontent): + png_stream = fontentry_helper_repr_png_(fontent) + png_b64 = b64encode(png_stream).decode() + return f"" + + FontEntry = dataclasses.make_dataclass( 'FontEntry', [ ('fname', str, dataclasses.field(default='')), @@ -395,7 +413,11 @@ def findSystemFonts(fontpaths=None, fontext='ttf'): A class for storing Font properties. It is used when populating the font lookup dictionary. - """}) + """, + '_repr_html_': lambda self: fontentry_helper_repr_html_(self), + '_repr_png_': lambda self: fontentry_helper_repr_png_(self), + } +) def ttfFontProperty(font): diff --git a/lib/matplotlib/tests/test_font_manager.py b/lib/matplotlib/tests/test_font_manager.py index a07c68051c8a..fb1119e33489 100644 --- a/lib/matplotlib/tests/test_font_manager.py +++ b/lib/matplotlib/tests/test_font_manager.py @@ -2,6 +2,7 @@ import multiprocessing import os from pathlib import Path +from PIL import Image import shutil import subprocess import sys @@ -11,9 +12,10 @@ import pytest from matplotlib.font_manager import ( - findfont, findSystemFonts, FontProperties, fontManager, json_dump, - json_load, get_font, is_opentype_cff_font, MSUserFontDirectories, - _get_fontconfig_fonts, ft2font, ttfFontProperty, cbook) + findfont, findSystemFonts, FontEntry, FontProperties, fontManager, + json_dump, json_load, get_font, is_opentype_cff_font, + MSUserFontDirectories, _get_fontconfig_fonts, ft2font, + ttfFontProperty, cbook) from matplotlib import pyplot as plt, rc_context has_fclist = shutil.which('fc-list') is not None @@ -268,6 +270,24 @@ def test_fontcache_thread_safe(): f"{proc.returncode}.") +def test_fontentry_dataclass(): + fontent = FontEntry(name='font-name') + + png = fontent._repr_png_() + img = Image.open(BytesIO(png)) + assert img.width > 0 + assert img.height > 0 + + html = fontent._repr_html_() + assert html.startswith("