Skip to content

Commit 6ec4b6d

Browse files
committed
Use libraqm for text in vector outputs
1 parent 6a792e2 commit 6ec4b6d

File tree

8 files changed

+176
-115
lines changed

8 files changed

+176
-115
lines changed

lib/matplotlib/_text_helpers.py

Lines changed: 10 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -4,29 +4,21 @@
44

55
from __future__ import annotations
66

7-
import dataclasses
7+
from collections.abc import Iterator
88

99
from . import _api
10-
from .ft2font import FT2Font, GlyphIndexType, Kerning, LoadFlags
10+
from .ft2font import FT2Font, CharacterCodeType, LayoutItem, LoadFlags
1111

1212

13-
@dataclasses.dataclass(frozen=True)
14-
class LayoutItem:
15-
ft_object: FT2Font
16-
char: str
17-
glyph_index: GlyphIndexType
18-
x: float
19-
prev_kern: float
20-
21-
22-
def warn_on_missing_glyph(codepoint, fontnames):
13+
def warn_on_missing_glyph(codepoint: CharacterCodeType, fontnames: str):
2314
_api.warn_external(
2415
f"Glyph {codepoint} "
2516
f"({chr(codepoint).encode('ascii', 'namereplace').decode('ascii')}) "
2617
f"missing from font(s) {fontnames}.")
2718

2819

29-
def layout(string, font, *, features=None, kern_mode=Kerning.DEFAULT, language=None):
20+
def layout(string: str, font: FT2Font, *, features=None,
21+
language=None) -> Iterator[LayoutItem]:
3022
"""
3123
Render *string* with *font*.
3224
@@ -41,8 +33,6 @@ def layout(string, font, *, features=None, kern_mode=Kerning.DEFAULT, language=N
4133
The font.
4234
features : tuple of str, optional
4335
The font features to apply to the text.
44-
kern_mode : Kerning
45-
A FreeType kerning mode.
4636
language : str, optional
4737
The language of the text in a format accepted by libraqm, namely `a BCP47
4838
language code <https://www.w3.org/International/articles/language-tags/>`_.
@@ -51,20 +41,8 @@ def layout(string, font, *, features=None, kern_mode=Kerning.DEFAULT, language=N
5141
------
5242
LayoutItem
5343
"""
54-
x = 0
55-
prev_glyph_idx = None
56-
char_to_font = font._get_fontmap(string) # TODO: Pass in features and language.
57-
base_font = font
58-
for char in string:
59-
# This has done the fallback logic
60-
font = char_to_font.get(char, base_font)
61-
glyph_idx = font.get_char_index(ord(char))
62-
kern = (
63-
base_font.get_kerning(prev_glyph_idx, glyph_idx, kern_mode) / 64
64-
if prev_glyph_idx is not None else 0.
65-
)
66-
x += kern
67-
glyph = font.load_glyph(glyph_idx, flags=LoadFlags.NO_HINTING)
68-
yield LayoutItem(font, char, glyph_idx, x, kern)
69-
x += glyph.linearHoriAdvance / 65536
70-
prev_glyph_idx = glyph_idx
44+
for raqm_item in font._layout(string, LoadFlags.NO_HINTING,
45+
features=features, language=language):
46+
raqm_item.ft_object.load_glyph(raqm_item.glyph_index,
47+
flags=LoadFlags.NO_HINTING)
48+
yield raqm_item

lib/matplotlib/backends/_backend_pdf_ps.py

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -108,10 +108,9 @@ def __init__(self):
108108

109109
def track(self, font, s):
110110
"""Record that string *s* is being typeset using font *font*."""
111-
char_to_font = font._get_fontmap(s)
112-
for _c, _f in char_to_font.items():
113-
glyph_index = _f.get_char_index(ord(_c))
114-
self.used.setdefault(_f.fname, set()).add(glyph_index)
111+
for raqm_item in font._layout(s, ft2font.LoadFlags.NO_HINTING):
112+
font_path = raqm_item.ft_object.fname
113+
self.used.setdefault(font_path, set()).add(raqm_item.glyph_index)
115114

116115
def track_glyph(self, font, glyph):
117116
"""Record that glyph index *glyph* is being typeset using font *font*."""

lib/matplotlib/backends/backend_pdf.py

Lines changed: 11 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -35,7 +35,7 @@
3535
from matplotlib.figure import Figure
3636
from matplotlib.font_manager import get_font, fontManager as _fontManager
3737
from matplotlib._afm import AFM
38-
from matplotlib.ft2font import FT2Font, FaceFlags, Kerning, LoadFlags, StyleFlags
38+
from matplotlib.ft2font import FT2Font, FaceFlags, LoadFlags, StyleFlags
3939
from matplotlib.transforms import Affine2D, BboxBase
4040
from matplotlib.path import Path
4141
from matplotlib.dates import UTC
@@ -2355,7 +2355,6 @@ def draw_text(self, gc, x, y, s, prop, angle, ismath=False, mtext=None):
23552355
fonttype = 1
23562356
else:
23572357
font = self._get_font_ttf(prop)
2358-
self.file._character_tracker.track(font, s)
23592358
fonttype = mpl.rcParams['pdf.fonttype']
23602359

23612360
if gc.get_url() is not None:
@@ -2367,6 +2366,8 @@ def draw_text(self, gc, x, y, s, prop, angle, ismath=False, mtext=None):
23672366
# If fonttype is neither 3 nor 42, emit the whole string at once
23682367
# without manual kerning.
23692368
if fonttype not in [3, 42]:
2369+
if not mpl.rcParams['pdf.use14corefonts']:
2370+
self.file._character_tracker.track(font, s)
23702371
self.file.output(Op.begin_text,
23712372
self.file.fontName(prop), fontsize, Op.selectfont)
23722373
self._setup_textpos(x, y, angle)
@@ -2394,9 +2395,11 @@ def draw_text(self, gc, x, y, s, prop, angle, ismath=False, mtext=None):
23942395
prev_was_multibyte = True
23952396
prev_font = font
23962397
for item in _text_helpers.layout(s, font, features=features,
2397-
kern_mode=Kerning.UNFITTED,
23982398
language=language):
2399-
if _font_supports_glyph(fonttype, ord(item.char)):
2399+
self.file._character_tracker.track_glyph(item.ft_object,
2400+
item.glyph_index)
2401+
if (len(item.char) == 1 and
2402+
_font_supports_glyph(fonttype, ord(item.char))):
24002403
if prev_was_multibyte or item.ft_object != prev_font:
24012404
singlebyte_chunks.append((item.ft_object, item.x, []))
24022405
prev_font = item.ft_object
@@ -2431,15 +2434,15 @@ def draw_text(self, gc, x, y, s, prop, angle, ismath=False, mtext=None):
24312434
prev_start_x = start_x
24322435
self.file.output(Op.end_text)
24332436
# Then emit all the multibyte characters, one at a time.
2434-
for ft_object, start_x, glyph_idx in multibyte_glyphs:
2437+
for ft_object, start_x, glyph_index in multibyte_glyphs:
24352438
self._draw_xobject_glyph(
2436-
ft_object, fontsize, glyph_idx, start_x, 0
2439+
ft_object, fontsize, glyph_index, start_x, 0
24372440
)
24382441
self.file.output(Op.grestore)
24392442

2440-
def _draw_xobject_glyph(self, font, fontsize, glyph_idx, x, y):
2443+
def _draw_xobject_glyph(self, font, fontsize, glyph_index, x, y):
24412444
"""Draw a multibyte character from a Type 3 font as an XObject."""
2442-
glyph_name = font.get_glyph_name(glyph_idx)
2445+
glyph_name = font.get_glyph_name(glyph_index)
24432446
name = self.file._get_xobject_glyph_name(font.fname, glyph_name)
24442447
self.file.output(
24452448
Op.gsave,

lib/matplotlib/backends/backend_ps.py

Lines changed: 7 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -769,7 +769,7 @@ def draw_text(self, gc, x, y, s, prop, angle, ismath=False, mtext=None):
769769
if ismath:
770770
return self.draw_mathtext(gc, x, y, s, prop, angle)
771771

772-
stream = [] # list of (ps_name, x, char_name)
772+
stream = [] # list of (ps_name, x, y, char_name)
773773

774774
if mpl.rcParams['ps.useafm']:
775775
font = self._get_font_afm(prop)
@@ -787,7 +787,7 @@ def draw_text(self, gc, x, y, s, prop, angle, ismath=False, mtext=None):
787787
kern = font.get_kern_dist_from_name(last_name, name)
788788
last_name = name
789789
thisx += kern * scale
790-
stream.append((ps_name, thisx, name))
790+
stream.append((ps_name, thisx, 0, name))
791791
thisx += width * scale
792792

793793
else:
@@ -797,20 +797,19 @@ def draw_text(self, gc, x, y, s, prop, angle, ismath=False, mtext=None):
797797
else:
798798
features = language = None
799799
font = self._get_font_ttf(prop)
800-
self._character_tracker.track(font, s)
801800
for item in _text_helpers.layout(s, font, features=features,
802801
language=language):
802+
self._character_tracker.track_glyph(item.ft_object, item.glyph_index)
803803
ps_name = (item.ft_object.postscript_name
804804
.encode("ascii", "replace").decode("ascii"))
805805
glyph_name = item.ft_object.get_glyph_name(item.glyph_index)
806-
stream.append((ps_name, item.x, glyph_name))
806+
stream.append((ps_name, item.x, item.y, glyph_name))
807807
self.set_color(*gc.get_rgb())
808808

809-
for ps_name, group in itertools. \
810-
groupby(stream, lambda entry: entry[0]):
809+
for ps_name, group in itertools.groupby(stream, lambda entry: entry[0]):
811810
self.set_font(ps_name, prop.get_size_in_points(), False)
812-
thetext = "\n".join(f"{x:g} 0 m /{name:s} glyphshow"
813-
for _, x, name in group)
811+
thetext = "\n".join(f"{x:g} {y:g} m /{name:s} glyphshow"
812+
for _, x, y, name in group)
814813
self._pswriter.write(f"""\
815814
gsave
816815
{self._get_clip_cmd(gc)}

lib/matplotlib/ft2font.pyi

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -202,7 +202,6 @@ class FT2Font(Buffer):
202202
) -> None: ...
203203
if sys.version_info[:2] >= (3, 12):
204204
def __buffer__(self, flags: int) -> memoryview: ...
205-
def _get_fontmap(self, string: str) -> dict[str, FT2Font]: ...
206205
def clear(self) -> None: ...
207206
def draw_glyph_to_bitmap(
208207
self, image: NDArray[np.uint8], x: int, y: int, glyph: Glyph, antialiased: bool = ...

lib/matplotlib/tests/test_ft2font.py

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -950,7 +950,7 @@ def test_fallback_last_resort(recwarn):
950950
"Glyph 128579 (\\N{UPSIDE-DOWN FACE}) missing from font(s)")
951951

952952

953-
def test__get_fontmap():
953+
def test__layout():
954954
fonts, test_str = _gen_multi_font_text()
955955
# Add some glyphs that don't exist in either font to check the Last Resort fallback.
956956
missing_glyphs = '\n几个汉字'
@@ -959,11 +959,11 @@ def test__get_fontmap():
959959
ft = fm.get_font(
960960
fm.fontManager._find_fonts_by_props(fm.FontProperties(family=fonts))
961961
)
962-
fontmap = ft._get_fontmap(test_str)
963-
for char, font in fontmap.items():
964-
if char in missing_glyphs:
965-
assert Path(font.fname).name == 'LastResortHE-Regular.ttf'
966-
elif ord(char) > 127:
967-
assert Path(font.fname).name == 'DejaVuSans.ttf'
968-
else:
969-
assert Path(font.fname).name == 'cmr10.ttf'
962+
for substr in test_str.split('\n'):
963+
for item in ft._layout(substr, ft2font.LoadFlags.DEFAULT):
964+
if item.char in missing_glyphs:
965+
assert Path(item.ft_object.fname).name == 'LastResortHE-Regular.ttf'
966+
elif ord(item.char) > 127:
967+
assert Path(item.ft_object.fname).name == 'DejaVuSans.ttf'
968+
else:
969+
assert Path(item.ft_object.fname).name == 'cmr10.ttf'

lib/matplotlib/textpath.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -147,15 +147,16 @@ def get_glyphs_with_font(self, font, s, glyph_map=None,
147147
glyph_map_new = glyph_map
148148

149149
xpositions = []
150+
ypositions = []
150151
glyph_ids = []
151152
for item in _text_helpers.layout(s, font, features=features, language=language):
152153
glyph_id = self._get_glyph_id(item.ft_object, item.glyph_index)
153154
glyph_ids.append(glyph_id)
154155
xpositions.append(item.x)
156+
ypositions.append(item.y)
155157
if glyph_id not in glyph_map:
156158
glyph_map_new[glyph_id] = item.ft_object.get_path()
157159

158-
ypositions = [0] * len(xpositions)
159160
sizes = [1.] * len(xpositions)
160161

161162
rects = []

0 commit comments

Comments
 (0)