44
55from __future__ import annotations
66
7+ from contextlib import contextmanager
78from io import BytesIO
89import functools
910import logging
1819
1920
2021if typing .TYPE_CHECKING :
22+ from collections .abc import Generator
23+ from contextlib import AbstractContextManager
24+
2125 from .font_manager import FontPath
2226 from .ft2font import CharacterCodeType , FT2Font , GlyphIndexType
2327 from fontTools .ttLib import TTFont
@@ -35,7 +39,30 @@ def _cached_get_afm_from_fname(fname):
3539 return AFM (fh )
3640
3741
38- def get_glyphs_subset (fontfile : FontPath , glyphs : set [GlyphIndexType ]) -> TTFont :
42+ class SubsetResults (typing .NamedTuple ):
43+ """
44+ The results of a subsetting operation on a font.
45+
46+ Attributes
47+ ----------
48+ font : TTFont
49+ An open font object representing the subset.
50+ glyph_index_map : dict
51+ Mapping of requested glyph indices to actual subset glyph indices.
52+ """
53+
54+ font : TTFont
55+ glyph_index_map : dict [GlyphIndexType , GlyphIndexType ]
56+
57+ @contextmanager
58+ def _as_cm (self ) -> Generator [SubsetResults , None , None ]:
59+ with self .font :
60+ yield self
61+
62+
63+ def get_glyphs_subset (
64+ fontfile : FontPath , glyphs : set [GlyphIndexType ]
65+ ) -> AbstractContextManager [SubsetResults ]:
3966 """
4067 Subset a TTF font.
4168
@@ -50,12 +77,10 @@ def get_glyphs_subset(fontfile: FontPath, glyphs: set[GlyphIndexType]) -> TTFont
5077
5178 Returns
5279 -------
53- fontTools.ttLib.ttFont.TTFont
54- An open font object representing the subset, which needs to
55- be closed by the caller.
80+ SubsetResults
81+ The font and new glyph index mapping.
5682 """
57- options = subset .Options (glyph_names = True , recommended_glyphs = True ,
58- retain_gids = True )
83+ options = subset .Options (glyph_names = True , recommended_glyphs = True )
5984
6085 # Prevent subsetting extra tables.
6186 options .drop_tables += [
@@ -87,7 +112,7 @@ def get_glyphs_subset(fontfile: FontPath, glyphs: set[GlyphIndexType]) -> TTFont
87112 subsetter = subset .Subsetter (options = options )
88113 subsetter .populate (gids = glyphs )
89114 subsetter .subset (font )
90- return font
115+ return SubsetResults ( font , subsetter . glyph_index_map ). _as_cm ()
91116
92117
93118def font_as_file (font ):
0 commit comments