Coverage for /usr/lib/python3/dist-packages/matplotlib/_text_helpers.py: 96%
23 statements
« prev ^ index » next coverage.py v7.9.1, created at 2025-06-14 15:55 +0200
« prev ^ index » next coverage.py v7.9.1, created at 2025-06-14 15:55 +0200
1"""
2Low-level text helper utilities.
3"""
5import dataclasses
7from . import _api
8from .ft2font import KERNING_DEFAULT, LOAD_NO_HINTING
11LayoutItem = dataclasses.make_dataclass(
12 "LayoutItem", ["ft_object", "char", "glyph_idx", "x", "prev_kern"])
15def warn_on_missing_glyph(codepoint):
16 _api.warn_external(
17 "Glyph {} ({}) missing from current font.".format(
18 codepoint,
19 chr(codepoint).encode("ascii", "namereplace").decode("ascii")))
20 block = ("Hebrew" if 0x0590 <= codepoint <= 0x05ff else
21 "Arabic" if 0x0600 <= codepoint <= 0x06ff else
22 "Devanagari" if 0x0900 <= codepoint <= 0x097f else
23 "Bengali" if 0x0980 <= codepoint <= 0x09ff else
24 "Gurmukhi" if 0x0a00 <= codepoint <= 0x0a7f else
25 "Gujarati" if 0x0a80 <= codepoint <= 0x0aff else
26 "Oriya" if 0x0b00 <= codepoint <= 0x0b7f else
27 "Tamil" if 0x0b80 <= codepoint <= 0x0bff else
28 "Telugu" if 0x0c00 <= codepoint <= 0x0c7f else
29 "Kannada" if 0x0c80 <= codepoint <= 0x0cff else
30 "Malayalam" if 0x0d00 <= codepoint <= 0x0d7f else
31 "Sinhala" if 0x0d80 <= codepoint <= 0x0dff else
32 None)
33 if block:
34 _api.warn_external(
35 f"Matplotlib currently does not support {block} natively.")
38def layout(string, font, *, kern_mode=KERNING_DEFAULT):
39 """
40 Render *string* with *font*. For each character in *string*, yield a
41 (glyph-index, x-position) pair. When such a pair is yielded, the font's
42 glyph is set to the corresponding character.
44 Parameters
45 ----------
46 string : str
47 The string to be rendered.
48 font : FT2Font
49 The font.
50 kern_mode : int
51 A FreeType kerning mode.
53 Yields
54 ------
55 glyph_index : int
56 x_position : float
57 """
58 x = 0
59 prev_glyph_idx = None
60 char_to_font = font._get_fontmap(string)
61 base_font = font
62 for char in string:
63 # This has done the fallback logic
64 font = char_to_font.get(char, base_font)
65 glyph_idx = font.get_char_index(ord(char))
66 kern = (
67 base_font.get_kerning(prev_glyph_idx, glyph_idx, kern_mode) / 64
68 if prev_glyph_idx is not None else 0.
69 )
70 x += kern
71 glyph = font.load_glyph(glyph_idx, flags=LOAD_NO_HINTING)
72 yield LayoutItem(font, char, glyph_idx, x, kern)
73 x += glyph.linearHoriAdvance / 65536
74 prev_glyph_idx = glyph_idx