Skip to content

Add support for loading all fonts from collections #30334

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 6 commits into
base: text-overhaul
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 6 additions & 5 deletions lib/matplotlib/backends/_backend_pdf_ps.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ def get_glyphs_subset(fontfile, characters):

Parameters
----------
fontfile : str
fontfile : FontPath
Path to the font file
characters : str
Continuous set of characters to include in subset
Expand Down Expand Up @@ -66,8 +66,7 @@ def get_glyphs_subset(fontfile, characters):
'xref', # The cross-reference table (some Apple font tooling information).
]
# if fontfile is a ttc, specify font number
if fontfile.endswith(".ttc"):
options.font_number = 0
options.font_number = fontfile.face_index

font = subset.load_font(fontfile, options)
subsetter = subset.Subsetter(options=options)
Expand Down Expand Up @@ -110,11 +109,13 @@ def track(self, font, s):
"""Record that string *s* is being typeset using font *font*."""
char_to_font = font._get_fontmap(s)
for _c, _f in char_to_font.items():
self.used.setdefault(_f.fname, set()).add(ord(_c))
font_path = font_manager.FontPath(_f.fname, _f.face_index)
self.used.setdefault(font_path, set()).add(ord(_c))

def track_glyph(self, font, glyph):
"""Record that codepoint *glyph* is being typeset using font *font*."""
self.used.setdefault(font.fname, set()).add(glyph)
font_path = font_manager.FontPath(font.fname, font.face_index)
self.used.setdefault(font_path, set()).add(glyph)


class RendererPDFPSBase(RendererBase):
Expand Down
33 changes: 19 additions & 14 deletions lib/matplotlib/backends/backend_pdf.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@
RendererBase)
from matplotlib.backends.backend_mixed import MixedModeRenderer
from matplotlib.figure import Figure
from matplotlib.font_manager import get_font, fontManager as _fontManager
from matplotlib.font_manager import FontPath, get_font, fontManager as _fontManager
from matplotlib._afm import AFM
from matplotlib.ft2font import FT2Font, FaceFlags, Kerning, LoadFlags, StyleFlags
from matplotlib.transforms import Affine2D, BboxBase
Expand Down Expand Up @@ -910,8 +910,10 @@ def fontName(self, fontprop):
as the filename of the font.
"""

if isinstance(fontprop, str):
if isinstance(fontprop, FontPath):
filenames = [fontprop]
elif isinstance(fontprop, str):
filenames = [FontPath(fontprop, 0)]
elif mpl.rcParams['pdf.use14corefonts']:
filenames = _fontManager._find_fonts_by_props(
fontprop, fontext='afm', directory=RendererPdf._afm_font_dir
Expand Down Expand Up @@ -950,9 +952,8 @@ def writeFonts(self):
for pdfname, dvifont in sorted(self._dviFontInfo.items()):
_log.debug('Embedding Type-1 font %s from dvi.', dvifont.texname)
fonts[pdfname] = self._embedTeXFont(dvifont)
for filename in sorted(self._fontNames):
Fx = self._fontNames[filename]
_log.debug('Embedding font %s.', filename)
for filename, Fx in sorted(self._fontNames.items()):
_log.debug('Embedding font %r.', filename)
if filename.endswith('.afm'):
# from pdf.use14corefonts
_log.debug('Writing AFM font.')
Expand Down Expand Up @@ -1004,7 +1005,8 @@ def _embedTeXFont(self, dvifont):

# Reduce the font to only the glyphs used in the document, get the encoding
# for that subset, and compute various properties based on the encoding.
chars = frozenset(self._character_tracker.used[dvifont.fname])
font_path = FontPath(dvifont.fname, dvifont.face_index)
chars = frozenset(self._character_tracker.used[font_path])
t1font = t1font.subset(chars, self._get_subset_prefix(chars))
fontdict['BaseFont'] = Name(t1font.prop['FontName'])
# createType1Descriptor writes the font data as a side effect
Expand Down Expand Up @@ -1113,6 +1115,7 @@ def _get_xobject_glyph_name(self, filename, glyph_name):
return "-".join([
Fx.name.decode(),
os.path.splitext(os.path.basename(filename))[0],
str(filename.face_index),
glyph_name])

_identityToUnicodeCMap = b"""/CIDInit /ProcSet findresource begin
Expand Down Expand Up @@ -1270,11 +1273,11 @@ def embedTTFType42(font, characters, descriptor):
toUnicodeMapObject = self.reserveObject('ToUnicode map')

subset_str = "".join(chr(c) for c in characters)
_log.debug("SUBSET %s characters: %s", filename, subset_str)
_log.debug("SUBSET %r characters: %s", filename, subset_str)
with _backend_pdf_ps.get_glyphs_subset(filename, subset_str) as subset:
fontdata = _backend_pdf_ps.font_as_file(subset)
_log.debug(
"SUBSET %s %d -> %d", filename,
"SUBSET %r %d -> %d", filename,
os.stat(filename).st_size, fontdata.getbuffer().nbytes
)

Expand Down Expand Up @@ -2218,18 +2221,18 @@ def draw_mathtext(self, gc, x, y, s, prop, angle):
self.file.output(Op.begin_text)
for font, fontsize, num, ox, oy in glyphs:
self.file._character_tracker.track_glyph(font, num)
fontname = font.fname
font_path = FontPath(font.fname, font.face_index)
if not _font_supports_glyph(fonttype, num):
# Unsupported chars (i.e. multibyte in Type 3 or beyond BMP in
# Type 42) must be emitted separately (below).
unsupported_chars.append((font, fontsize, ox, oy, num))
else:
self._setup_textpos(ox, oy, 0, oldx, oldy)
oldx, oldy = ox, oy
if (fontname, fontsize) != prev_font:
self.file.output(self.file.fontName(fontname), fontsize,
if (font_path, fontsize) != prev_font:
self.file.output(self.file.fontName(font_path), fontsize,
Op.selectfont)
prev_font = fontname, fontsize
prev_font = font_path, fontsize
self.file.output(self.encode_string(chr(num), fonttype),
Op.show)
self.file.output(Op.end_text)
Expand Down Expand Up @@ -2413,7 +2416,8 @@ def draw_text(self, gc, x, y, s, prop, angle, ismath=False, mtext=None):
self.file.output(Op.begin_text)
prev_start_x = 0
for ft_object, start_x, kerns_or_chars in singlebyte_chunks:
ft_name = self.file.fontName(ft_object.fname)
font_path = FontPath(ft_object.fname, ft_object.face_index)
ft_name = self.file.fontName(font_path)
self.file.output(ft_name, fontsize, Op.selectfont)
self._setup_textpos(start_x, 0, 0, prev_start_x, 0, 0)
self.file.output(
Expand All @@ -2435,7 +2439,8 @@ def draw_text(self, gc, x, y, s, prop, angle, ismath=False, mtext=None):
def _draw_xobject_glyph(self, font, fontsize, glyph_idx, x, y):
"""Draw a multibyte character from a Type 3 font as an XObject."""
glyph_name = font.get_glyph_name(glyph_idx)
name = self.file._get_xobject_glyph_name(font.fname, glyph_name)
name = self.file._get_xobject_glyph_name(FontPath(font.fname, font.face_index),
glyph_name)
self.file.output(
Op.gsave,
0.001 * fontsize, 0, 0, 0.001 * fontsize, x, y, Op.concat_matrix,
Expand Down
25 changes: 13 additions & 12 deletions lib/matplotlib/backends/backend_pgf.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,9 +38,17 @@

def _get_preamble():
"""Prepare a LaTeX preamble based on the rcParams configuration."""
font_size_pt = FontProperties(
size=mpl.rcParams["font.size"]
).get_size_in_points()
def _to_fontspec():
for command, family in [("setmainfont", "serif"),
("setsansfont", "sans\\-serif"),
("setmonofont", "monospace")]:
font_path = fm.findfont(family)
path = pathlib.Path(font_path)
yield r" \%s{%s}[Path=\detokenize{%s/}%s]" % (
command, path.name, path.parent.as_posix(),
f',FontIndex={font_path.face_index:d}' if path.suffix == '.ttc' else '')

font_size_pt = FontProperties(size=mpl.rcParams["font.size"]).get_size_in_points()
return "\n".join([
# Remove Matplotlib's custom command \mathdefault. (Not using
# \mathnormal instead since this looks odd with Computer Modern.)
Expand All @@ -63,15 +71,8 @@ def _get_preamble():
*([
r"\ifdefined\pdftexversion\else % non-pdftex case.",
r" \usepackage{fontspec}",
] + [
r" \%s{%s}[Path=\detokenize{%s/}]"
% (command, path.name, path.parent.as_posix())
for command, path in zip(
["setmainfont", "setsansfont", "setmonofont"],
[pathlib.Path(fm.findfont(family))
for family in ["serif", "sans\\-serif", "monospace"]]
)
] + [r"\fi"] if mpl.rcParams["pgf.rcfonts"] else []),
*_to_fontspec(),
r"\fi"] if mpl.rcParams["pgf.rcfonts"] else []),
# Documented as "must come last".
mpl.texmanager._usepackage_if_not_loaded("underscore", option="strings"),
])
Expand Down
14 changes: 5 additions & 9 deletions lib/matplotlib/backends/backend_ps.py
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,7 @@ def _font_to_ps_type3(font_path, chars):

Parameters
----------
font_path : path-like
font_path : FontPath
Path to the font to be subsetted.
chars : str
The characters to include in the subsetted font.
Expand Down Expand Up @@ -175,22 +175,18 @@ def _font_to_ps_type42(font_path, chars, fh):

Parameters
----------
font_path : path-like
font_path : FontPath
Path to the font to be subsetted.
chars : str
The characters to include in the subsetted font.
fh : file-like
Where to write the font.
"""
subset_str = ''.join(chr(c) for c in chars)
_log.debug("SUBSET %s characters: %s", font_path, subset_str)
_log.debug("SUBSET %r characters: %s", font_path, subset_str)
try:
kw = {}
# fix this once we support loading more fonts from a collection
# https://github.com/matplotlib/matplotlib/issues/3135#issuecomment-571085541
if font_path.endswith('.ttc'):
kw['fontNumber'] = 0
with (fontTools.ttLib.TTFont(font_path, **kw) as font,
with (fontTools.ttLib.TTFont(font_path.path,
fontNumber=font_path.face_index) as font,
_backend_pdf_ps.get_glyphs_subset(font_path, subset_str) as subset):
fontdata = _backend_pdf_ps.font_as_file(subset).getvalue()
_log.debug(
Expand Down
4 changes: 4 additions & 0 deletions lib/matplotlib/dviread.py
Original file line number Diff line number Diff line change
Expand Up @@ -610,6 +610,10 @@ def fname(self):
"""A fake filename"""
return self.texname.decode('latin-1')

@property
def face_index(self): # For compatibility with FT2Font.
return 0

def _get_fontmap(self, string):
"""Get the mapping from characters to the font that includes them.

Expand Down
2 changes: 2 additions & 0 deletions lib/matplotlib/dviread.pyi
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,8 @@ class DviFont:
def widths(self) -> list[int]: ...
@property
def fname(self) -> str: ...
@property
def face_index(self) -> int: ...

class Vf(Dvi):
def __init__(self, filename: str | os.PathLike) -> None: ...
Expand Down
Loading
Loading
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy