Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 8956fc6

Browse files
committed
Improve usability of dviread.Text by third parties.
dviread.Text specifies individual glyphs in parsed dvi files; this is used by the pdf and svg backends (via textpath, for svg) to parse the result of usetex-compiled strings and embed the right glyphs at the right places in the output file (as a reminder, agg currenly uses dvipng to rasterize the dvi file, and the ps backend relies on pstricks). Unfortunately, if third-party backends (e.g. mplcairo) want to do use the same strategy as pdf/svg, then they need to jump through a few hoops (e.g. understand PsfontsMap and find_tex_font) and use some private APIs (_parse_enc), as explained below. Try to improve the situation, by adding some methods on the Text class (which may later allow deprecating PsfontsMap and find_tex_font as public API). First, the actual font to be used is speficied via the `.font` attribute, which itself has a `.texname` which itself must be used as a key into `PsfontsMap(find_tex_font("pdftex.map"))` to get the actual font path (and some other info). Instead, just provide a `.font_path` property. pdftex.map can also require that the font be "slanted" or "extended" (that's some of the "other info), lift that as well to `.font_effects`. The `.font` attribute has a `.size`; also we can lift up to `.font_size`. Altogether, this will allow making `.font` private (later) -- except for the fact that Text is a namedtuple so deprecating fields is rather annoying. The trickiest part is actually specifying what glyph to select from the font. dvi just gives us an integer, whose interpretation depends again on pdftex.map. If pdftex.map specifies "no encoding" for the font, then the integer is the "native glyph index" of the font, and should be passed as-is to FreeType's FT_Load_Char (after selecting the native charmap). If pdftex.map does specify an encoding, then that's a file that needs to be separately loaded, parsed (with _parse_enc), and ultimately converts the index into a glyph name (which can be passed to FreeType's FT_Load_Glyph). Altogether, from the PoV of the end user, the "glyph specification" is thus either an int (a native charmap index) or a str (a glyph name); thus, provide `.glyph_name_or_index` which is that API. As an example of using that API, see the changes to textpath.py.
1 parent 3a994d2 commit 8956fc6

File tree

3 files changed

+94
-56
lines changed

3 files changed

+94
-56
lines changed

lib/matplotlib/dviread.py

Lines changed: 62 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -58,10 +58,71 @@
5858

5959
# The marks on a page consist of text and boxes. A page also has dimensions.
6060
Page = namedtuple('Page', 'text boxes height width descent')
61-
Text = namedtuple('Text', 'x y font glyph width')
6261
Box = namedtuple('Box', 'x y height width')
6362

6463

64+
# Also a namedtuple, for backcompat.
65+
class Text(namedtuple('Text', 'x y font glyph width')):
66+
"""
67+
A glyph in the dvi file.
68+
69+
The *x* and *y* attributes directly position the glyph. The *font*,
70+
*glyph*, and *width* attributes are kept public for back-compatibility,
71+
but users wanting to draw the glyph themselves are encouraged to instead
72+
load the font specified by `font_path` at `font_size`, warp it with the
73+
effects specified by `font_effects`, and load the glyph specified by
74+
`glyph_name_or_index`.
75+
"""
76+
77+
def _get_pdftexmap_entry(self):
78+
return PsfontsMap(find_tex_file("pdftex.map"))[self.font.texname]
79+
80+
@property
81+
def font_path(self):
82+
"""The `~pathlib.Path` to the font for this glyph."""
83+
psfont = self._get_pdftexmap_entry()
84+
if psfont.filename is None:
85+
raise ValueError("No usable font file found for {} ({}); "
86+
"the font may lack a Type-1 version"
87+
.format(psfont.psname.decode("ascii"),
88+
psfont.texname.decode("ascii")))
89+
return Path(psfont.filename)
90+
91+
@property
92+
def font_size(self):
93+
"""The font size."""
94+
return self.font.size
95+
96+
@property
97+
def font_effects(self):
98+
"""
99+
The "font effects" dict for this glyph.
100+
101+
This dict contains the values for this glyph of SlantFont and
102+
ExtendFont (if any), read off :file:`pdftex.map`.
103+
"""
104+
return self._get_pdftexmap_entry().effects
105+
106+
@property
107+
def glyph_name_or_index(self):
108+
"""
109+
Either the glyph name or the native charmap glyph index.
110+
111+
If :file:`pdftex.map` specifies an encoding for this glyph's font, that
112+
is a mapping of glyph indices to Adobe glyph names; use it to convert
113+
dvi indices to glyph names. Callers can then convert glyph names to
114+
glyph indices (with FT_Get_Name_Index/get_name_index), and load the
115+
glyph using FT_Load_Glyph/load_glyph.
116+
117+
If :file:`pdftex.map` specifies no encoding, the indices directly map
118+
to the font's "native" charmap; glyphs should directly loaded using
119+
FT_Load_Char/load_char after selecting the native charmap.
120+
"""
121+
entry = self._get_pdftexmap_entry()
122+
return (_parse_enc(entry.encoding)[self.glyph]
123+
if entry.encoding is not None else self.glyph)
124+
125+
65126
# Opcode argument parsing
66127
#
67128
# Each of the following functions takes a Dvi object and delta,

lib/matplotlib/tests/test_usetex.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -131,7 +131,7 @@ def test_missing_psfont(fmt, monkeypatch):
131131
monkeypatch.setattr(
132132
dviread.PsfontsMap, '__getitem__',
133133
lambda self, k: dviread.PsFont(
134-
texname='texfont', psname='Some Font',
134+
texname=b'texfont', psname=b'Some Font',
135135
effects=None, encoding=None, filename=None))
136136
mpl.rcParams['text.usetex'] = True
137137
fig, ax = plt.subplots()

lib/matplotlib/textpath.py

Lines changed: 31 additions & 54 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,4 @@
11
from collections import OrderedDict
2-
import functools
32
import logging
43
import urllib.parse
54

@@ -243,25 +242,30 @@ def get_glyphs_tex(self, prop, s, glyph_map=None,
243242

244243
# Gather font information and do some setup for combining
245244
# characters into strings.
246-
for x1, y1, dvifont, glyph, width in page.text:
247-
font, enc = self._get_ps_font_and_encoding(dvifont.texname)
248-
char_id = self._get_char_id(font, glyph)
249-
245+
for text in page.text:
246+
font = get_font(text.font_path)
247+
char_id = self._get_char_id(font, text.glyph)
250248
if char_id not in glyph_map:
249+
glyph_name_or_index = text.glyph_name_or_index
251250
font.clear()
252251
font.set_size(self.FONT_SCALE, self.DPI)
253-
# See comments in _get_ps_font_and_encoding.
254-
if enc is not None:
255-
index = font.get_name_index(enc[glyph])
252+
# See comments in Text.glyph_name_or_index.
253+
if isinstance(glyph_name_or_index, str):
254+
index = font.get_name_index(glyph_name_or_index)
256255
font.load_glyph(index, flags=LOAD_TARGET_LIGHT)
257-
else:
258-
font.load_char(glyph, flags=LOAD_TARGET_LIGHT)
256+
elif isinstance(glyph_name_or_index, int):
257+
self._select_native_charmap(font)
258+
font.load_char(
259+
glyph_name_or_index, flags=LOAD_TARGET_LIGHT)
260+
else: # Should not occur.
261+
raise TypeError(f"Glyph spec of unexpected type: "
262+
f"{glyph_name_or_index!r}")
259263
glyph_map_new[char_id] = font.get_path()
260264

261265
glyph_ids.append(char_id)
262-
xpositions.append(x1)
263-
ypositions.append(y1)
264-
sizes.append(dvifont.size / self.FONT_SCALE)
266+
xpositions.append(text.x)
267+
ypositions.append(text.y)
268+
sizes.append(text.font_size / self.FONT_SCALE)
265269

266270
myrects = []
267271

@@ -277,48 +281,21 @@ def get_glyphs_tex(self, prop, s, glyph_map=None,
277281
glyph_map_new, myrects)
278282

279283
@staticmethod
280-
@functools.lru_cache(50)
281-
def _get_ps_font_and_encoding(texname):
282-
tex_font_map = dviread.PsfontsMap(dviread._find_tex_file('pdftex.map'))
283-
psfont = tex_font_map[texname]
284-
if psfont.filename is None:
285-
raise ValueError(
286-
f"No usable font file found for {psfont.psname} ({texname}). "
287-
f"The font may lack a Type-1 version.")
288-
289-
font = get_font(psfont.filename)
290-
291-
if psfont.encoding:
292-
# If psfonts.map specifies an encoding, use it: it gives us a
293-
# mapping of glyph indices to Adobe glyph names; use it to convert
294-
# dvi indices to glyph names and use the FreeType-synthesized
295-
# Unicode charmap to convert glyph names to glyph indices (with
296-
# FT_Get_Name_Index/get_name_index), and load the glyph using
297-
# FT_Load_Glyph/load_glyph. (That charmap has a coverage at least
298-
# as good as, and possibly better than, the native charmaps.)
299-
enc = dviread._parse_enc(psfont.encoding)
300-
else:
301-
# If psfonts.map specifies no encoding, the indices directly
302-
# map to the font's "native" charmap; so don't use the
303-
# FreeType-synthesized charmap but the native ones (we can't
304-
# directly identify it but it's typically an Adobe charmap), and
305-
# directly load the dvi glyph indices using FT_Load_Char/load_char.
306-
for charmap_code in [
307-
1094992451, # ADOBE_CUSTOM.
308-
1094995778, # ADOBE_STANDARD.
309-
]:
310-
try:
311-
font.select_charmap(charmap_code)
312-
except (ValueError, RuntimeError):
313-
pass
314-
else:
315-
break
284+
def _select_native_charmap(font):
285+
# Select the native charmap. (we can't directly identify it but it's
286+
# typically an Adobe charmap).
287+
for charmap_code in [
288+
1094992451, # ADOBE_CUSTOM.
289+
1094995778, # ADOBE_STANDARD.
290+
]:
291+
try:
292+
font.select_charmap(charmap_code)
293+
except (ValueError, RuntimeError):
294+
pass
316295
else:
317-
_log.warning("No supported encoding in font (%s).",
318-
psfont.filename)
319-
enc = None
320-
321-
return font, enc
296+
break
297+
else:
298+
_log.warning("No supported encoding in font (%s).", font.fname)
322299

323300

324301
text_to_path = TextToPath()

0 commit comments

Comments
 (0)