-
-
Notifications
You must be signed in to change notification settings - Fork 7.5k
/
_mathtext.py
2851 lines (2434 loc) · 105 KB
/
_mathtext.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
Implementation details for :mod:`.mathtext`.
"""
from __future__ import annotations
import abc
import copy
import enum
import functools
import logging
import os
import re
import types
import unicodedata
import string
import typing as T
from typing import NamedTuple
import numpy as np
from pyparsing import (
Empty, Forward, Literal, NotAny, oneOf, OneOrMore, Optional,
ParseBaseException, ParseException, ParseExpression, ParseFatalException,
ParserElement, ParseResults, QuotedString, Regex, StringEnd, ZeroOrMore,
pyparsing_common, Group)
import matplotlib as mpl
from . import cbook
from ._mathtext_data import (
latex_to_bakoma, stix_glyph_fixes, stix_virtual_fonts, tex2uni)
from .font_manager import FontProperties, findfont, get_font
from .ft2font import FT2Font, FT2Image, KERNING_DEFAULT
from packaging.version import parse as parse_version
from pyparsing import __version__ as pyparsing_version
if parse_version(pyparsing_version).major < 3:
from pyparsing import nestedExpr as nested_expr
else:
from pyparsing import nested_expr
if T.TYPE_CHECKING:
from collections.abc import Iterable
from .ft2font import Glyph
ParserElement.enablePackrat()
_log = logging.getLogger("matplotlib.mathtext")
##############################################################################
# FONTS
def get_unicode_index(symbol: str) -> int: # Publicly exported.
r"""
Return the integer index (from the Unicode table) of *symbol*.
Parameters
----------
symbol : str
A single (Unicode) character, a TeX command (e.g. r'\pi') or a Type1
symbol name (e.g. 'phi').
"""
try: # This will succeed if symbol is a single Unicode char
return ord(symbol)
except TypeError:
pass
try: # Is symbol a TeX symbol (i.e. \alpha)
return tex2uni[symbol.strip("\\")]
except KeyError as err:
raise ValueError(
f"{symbol!r} is not a valid Unicode character or TeX/Type1 symbol"
) from err
class VectorParse(NamedTuple):
"""
The namedtuple type returned by ``MathTextParser("path").parse(...)``.
Attributes
----------
width, height, depth : float
The global metrics.
glyphs : list
The glyphs including their positions.
rect : list
The list of rectangles.
"""
width: float
height: float
depth: float
glyphs: list[tuple[FT2Font, float, int, float, float]]
rects: list[tuple[float, float, float, float]]
VectorParse.__module__ = "matplotlib.mathtext"
class RasterParse(NamedTuple):
"""
The namedtuple type returned by ``MathTextParser("agg").parse(...)``.
Attributes
----------
ox, oy : float
The offsets are always zero.
width, height, depth : float
The global metrics.
image : FT2Image
A raster image.
"""
ox: float
oy: float
width: float
height: float
depth: float
image: FT2Image
RasterParse.__module__ = "matplotlib.mathtext"
class Output:
r"""
Result of `ship`\ping a box: lists of positioned glyphs and rectangles.
This class is not exposed to end users, but converted to a `VectorParse` or
a `RasterParse` by `.MathTextParser.parse`.
"""
def __init__(self, box: Box):
self.box = box
self.glyphs: list[tuple[float, float, FontInfo]] = [] # (ox, oy, info)
self.rects: list[tuple[float, float, float, float]] = [] # (x1, y1, x2, y2)
def to_vector(self) -> VectorParse:
w, h, d = map(
np.ceil, [self.box.width, self.box.height, self.box.depth])
gs = [(info.font, info.fontsize, info.num, ox, h - oy + info.offset)
for ox, oy, info in self.glyphs]
rs = [(x1, h - y2, x2 - x1, y2 - y1)
for x1, y1, x2, y2 in self.rects]
return VectorParse(w, h + d, d, gs, rs)
def to_raster(self, *, antialiased: bool) -> RasterParse:
# Metrics y's and mathtext y's are oriented in opposite directions,
# hence the switch between ymin and ymax.
xmin = min([*[ox + info.metrics.xmin for ox, oy, info in self.glyphs],
*[x1 for x1, y1, x2, y2 in self.rects], 0]) - 1
ymin = min([*[oy - info.metrics.ymax for ox, oy, info in self.glyphs],
*[y1 for x1, y1, x2, y2 in self.rects], 0]) - 1
xmax = max([*[ox + info.metrics.xmax for ox, oy, info in self.glyphs],
*[x2 for x1, y1, x2, y2 in self.rects], 0]) + 1
ymax = max([*[oy - info.metrics.ymin for ox, oy, info in self.glyphs],
*[y2 for x1, y1, x2, y2 in self.rects], 0]) + 1
w = xmax - xmin
h = ymax - ymin - self.box.depth
d = ymax - ymin - self.box.height
image = FT2Image(np.ceil(w), np.ceil(h + max(d, 0)))
# Ideally, we could just use self.glyphs and self.rects here, shifting
# their coordinates by (-xmin, -ymin), but this yields slightly
# different results due to floating point slop; shipping twice is the
# old approach and keeps baseline images backcompat.
shifted = ship(self.box, (-xmin, -ymin))
for ox, oy, info in shifted.glyphs:
info.font.draw_glyph_to_bitmap(
image, ox, oy - info.metrics.iceberg, info.glyph,
antialiased=antialiased)
for x1, y1, x2, y2 in shifted.rects:
height = max(int(y2 - y1) - 1, 0)
if height == 0:
center = (y2 + y1) / 2
y = int(center - (height + 1) / 2)
else:
y = int(y1)
image.draw_rect_filled(int(x1), y, np.ceil(x2), y + height)
return RasterParse(0, 0, w, h + d, d, image)
class FontMetrics(NamedTuple):
"""
Metrics of a font.
Attributes
----------
advance : float
The advance distance (in points) of the glyph.
height : float
The height of the glyph in points.
width : float
The width of the glyph in points.
xmin, xmax, ymin, ymax : float
The ink rectangle of the glyph.
iceberg : float
The distance from the baseline to the top of the glyph. (This corresponds to
TeX's definition of "height".)
slanted : bool
Whether the glyph should be considered as "slanted" (currently used for kerning
sub/superscripts).
"""
advance: float
height: float
width: float
xmin: float
xmax: float
ymin: float
ymax: float
iceberg: float
slanted: bool
class FontInfo(NamedTuple):
font: FT2Font
fontsize: float
postscript_name: str
metrics: FontMetrics
num: int
glyph: Glyph
offset: float
class Fonts(abc.ABC):
"""
An abstract base class for a system of fonts to use for mathtext.
The class must be able to take symbol keys and font file names and
return the character metrics. It also delegates to a backend class
to do the actual drawing.
"""
def __init__(self, default_font_prop: FontProperties, load_glyph_flags: int):
"""
Parameters
----------
default_font_prop : `~.font_manager.FontProperties`
The default non-math font, or the base font for Unicode (generic)
font rendering.
load_glyph_flags : int
Flags passed to the glyph loader (e.g. ``FT_Load_Glyph`` and
``FT_Load_Char`` for FreeType-based fonts).
"""
self.default_font_prop = default_font_prop
self.load_glyph_flags = load_glyph_flags
def get_kern(self, font1: str, fontclass1: str, sym1: str, fontsize1: float,
font2: str, fontclass2: str, sym2: str, fontsize2: float,
dpi: float) -> float:
"""
Get the kerning distance for font between *sym1* and *sym2*.
See `~.Fonts.get_metrics` for a detailed description of the parameters.
"""
return 0.
def _get_font(self, font: str) -> FT2Font:
raise NotImplementedError
def _get_info(self, font: str, font_class: str, sym: str, fontsize: float,
dpi: float) -> FontInfo:
raise NotImplementedError
def get_metrics(self, font: str, font_class: str, sym: str, fontsize: float,
dpi: float) -> FontMetrics:
r"""
Parameters
----------
font : str
One of the TeX font names: "tt", "it", "rm", "cal", "sf", "bf",
"default", "regular", "bb", "frak", "scr". "default" and "regular"
are synonyms and use the non-math font.
font_class : str
One of the TeX font names (as for *font*), but **not** "bb",
"frak", or "scr". This is used to combine two font classes. The
only supported combination currently is ``get_metrics("frak", "bf",
...)``.
sym : str
A symbol in raw TeX form, e.g., "1", "x", or "\sigma".
fontsize : float
Font size in points.
dpi : float
Rendering dots-per-inch.
Returns
-------
FontMetrics
"""
info = self._get_info(font, font_class, sym, fontsize, dpi)
return info.metrics
def render_glyph(self, output: Output, ox: float, oy: float, font: str,
font_class: str, sym: str, fontsize: float, dpi: float) -> None:
"""
At position (*ox*, *oy*), draw the glyph specified by the remaining
parameters (see `get_metrics` for their detailed description).
"""
info = self._get_info(font, font_class, sym, fontsize, dpi)
output.glyphs.append((ox, oy, info))
def render_rect_filled(self, output: Output,
x1: float, y1: float, x2: float, y2: float) -> None:
"""
Draw a filled rectangle from (*x1*, *y1*) to (*x2*, *y2*).
"""
output.rects.append((x1, y1, x2, y2))
def get_xheight(self, font: str, fontsize: float, dpi: float) -> float:
"""
Get the xheight for the given *font* and *fontsize*.
"""
raise NotImplementedError()
def get_underline_thickness(self, font: str, fontsize: float, dpi: float) -> float:
"""
Get the line thickness that matches the given font. Used as a
base unit for drawing lines such as in a fraction or radical.
"""
raise NotImplementedError()
def get_sized_alternatives_for_symbol(self, fontname: str,
sym: str) -> list[tuple[str, str]]:
"""
Override if your font provides multiple sizes of the same
symbol. Should return a list of symbols matching *sym* in
various sizes. The expression renderer will select the most
appropriate size for a given situation from this list.
"""
return [(fontname, sym)]
class TruetypeFonts(Fonts, metaclass=abc.ABCMeta):
"""
A generic base class for all font setups that use Truetype fonts
(through FT2Font).
"""
def __init__(self, default_font_prop: FontProperties, load_glyph_flags: int):
super().__init__(default_font_prop, load_glyph_flags)
# Per-instance cache.
self._get_info = functools.cache(self._get_info) # type: ignore[method-assign]
self._fonts = {}
self.fontmap: dict[str | int, str] = {}
filename = findfont(self.default_font_prop)
default_font = get_font(filename)
self._fonts['default'] = default_font
self._fonts['regular'] = default_font
def _get_font(self, font: str | int) -> FT2Font:
if font in self.fontmap:
basename = self.fontmap[font]
else:
# NOTE: An int is only passed by subclasses which have placed int keys into
# `self.fontmap`, so we must cast this to confirm it to typing.
basename = T.cast(str, font)
cached_font = self._fonts.get(basename)
if cached_font is None and os.path.exists(basename):
cached_font = get_font(basename)
self._fonts[basename] = cached_font
self._fonts[cached_font.postscript_name] = cached_font
self._fonts[cached_font.postscript_name.lower()] = cached_font
return T.cast(FT2Font, cached_font) # FIXME: Not sure this is guaranteed.
def _get_offset(self, font: FT2Font, glyph: Glyph, fontsize: float,
dpi: float) -> float:
if font.postscript_name == 'Cmex10':
return (glyph.height / 64 / 2) + (fontsize/3 * dpi/72)
return 0.
def _get_glyph(self, fontname: str, font_class: str,
sym: str) -> tuple[FT2Font, int, bool]:
raise NotImplementedError
# The return value of _get_info is cached per-instance.
def _get_info(self, fontname: str, font_class: str, sym: str, fontsize: float,
dpi: float) -> FontInfo:
font, num, slanted = self._get_glyph(fontname, font_class, sym)
font.set_size(fontsize, dpi)
glyph = font.load_char(num, flags=self.load_glyph_flags)
xmin, ymin, xmax, ymax = [val/64.0 for val in glyph.bbox]
offset = self._get_offset(font, glyph, fontsize, dpi)
metrics = FontMetrics(
advance = glyph.linearHoriAdvance/65536.0,
height = glyph.height/64.0,
width = glyph.width/64.0,
xmin = xmin,
xmax = xmax,
ymin = ymin+offset,
ymax = ymax+offset,
# iceberg is the equivalent of TeX's "height"
iceberg = glyph.horiBearingY/64.0 + offset,
slanted = slanted
)
return FontInfo(
font = font,
fontsize = fontsize,
postscript_name = font.postscript_name,
metrics = metrics,
num = num,
glyph = glyph,
offset = offset
)
def get_xheight(self, fontname: str, fontsize: float, dpi: float) -> float:
font = self._get_font(fontname)
font.set_size(fontsize, dpi)
pclt = font.get_sfnt_table('pclt')
if pclt is None:
# Some fonts don't store the xHeight, so we do a poor man's xHeight
metrics = self.get_metrics(
fontname, mpl.rcParams['mathtext.default'], 'x', fontsize, dpi)
return metrics.iceberg
xHeight = (pclt['xHeight'] / 64.0) * (fontsize / 12.0) * (dpi / 100.0)
return xHeight
def get_underline_thickness(self, font: str, fontsize: float, dpi: float) -> float:
# This function used to grab underline thickness from the font
# metrics, but that information is just too un-reliable, so it
# is now hardcoded.
return ((0.75 / 12.0) * fontsize * dpi) / 72.0
def get_kern(self, font1: str, fontclass1: str, sym1: str, fontsize1: float,
font2: str, fontclass2: str, sym2: str, fontsize2: float,
dpi: float) -> float:
if font1 == font2 and fontsize1 == fontsize2:
info1 = self._get_info(font1, fontclass1, sym1, fontsize1, dpi)
info2 = self._get_info(font2, fontclass2, sym2, fontsize2, dpi)
font = info1.font
return font.get_kerning(info1.num, info2.num, KERNING_DEFAULT) / 64
return super().get_kern(font1, fontclass1, sym1, fontsize1,
font2, fontclass2, sym2, fontsize2, dpi)
class BakomaFonts(TruetypeFonts):
"""
Use the Bakoma TrueType fonts for rendering.
Symbols are strewn about a number of font files, each of which has
its own proprietary 8-bit encoding.
"""
_fontmap = {
'cal': 'cmsy10',
'rm': 'cmr10',
'tt': 'cmtt10',
'it': 'cmmi10',
'bf': 'cmb10',
'sf': 'cmss10',
'ex': 'cmex10',
}
def __init__(self, default_font_prop: FontProperties, load_glyph_flags: int):
self._stix_fallback = StixFonts(default_font_prop, load_glyph_flags)
super().__init__(default_font_prop, load_glyph_flags)
for key, val in self._fontmap.items():
fullpath = findfont(val)
self.fontmap[key] = fullpath
self.fontmap[val] = fullpath
_slanted_symbols = set(r"\int \oint".split())
def _get_glyph(self, fontname: str, font_class: str,
sym: str) -> tuple[FT2Font, int, bool]:
font = None
if fontname in self.fontmap and sym in latex_to_bakoma:
basename, num = latex_to_bakoma[sym]
slanted = (basename == "cmmi10") or sym in self._slanted_symbols
font = self._get_font(basename)
elif len(sym) == 1:
slanted = (fontname == "it")
font = self._get_font(fontname)
if font is not None:
num = ord(sym)
if font is not None and font.get_char_index(num) != 0:
return font, num, slanted
else:
return self._stix_fallback._get_glyph(fontname, font_class, sym)
# The Bakoma fonts contain many pre-sized alternatives for the
# delimiters. The AutoSizedChar class will use these alternatives
# and select the best (closest sized) glyph.
_size_alternatives = {
'(': [('rm', '('), ('ex', '\xa1'), ('ex', '\xb3'),
('ex', '\xb5'), ('ex', '\xc3')],
')': [('rm', ')'), ('ex', '\xa2'), ('ex', '\xb4'),
('ex', '\xb6'), ('ex', '\x21')],
'{': [('cal', '{'), ('ex', '\xa9'), ('ex', '\x6e'),
('ex', '\xbd'), ('ex', '\x28')],
'}': [('cal', '}'), ('ex', '\xaa'), ('ex', '\x6f'),
('ex', '\xbe'), ('ex', '\x29')],
# The fourth size of '[' is mysteriously missing from the BaKoMa
# font, so I've omitted it for both '[' and ']'
'[': [('rm', '['), ('ex', '\xa3'), ('ex', '\x68'),
('ex', '\x22')],
']': [('rm', ']'), ('ex', '\xa4'), ('ex', '\x69'),
('ex', '\x23')],
r'\lfloor': [('ex', '\xa5'), ('ex', '\x6a'),
('ex', '\xb9'), ('ex', '\x24')],
r'\rfloor': [('ex', '\xa6'), ('ex', '\x6b'),
('ex', '\xba'), ('ex', '\x25')],
r'\lceil': [('ex', '\xa7'), ('ex', '\x6c'),
('ex', '\xbb'), ('ex', '\x26')],
r'\rceil': [('ex', '\xa8'), ('ex', '\x6d'),
('ex', '\xbc'), ('ex', '\x27')],
r'\langle': [('ex', '\xad'), ('ex', '\x44'),
('ex', '\xbf'), ('ex', '\x2a')],
r'\rangle': [('ex', '\xae'), ('ex', '\x45'),
('ex', '\xc0'), ('ex', '\x2b')],
r'\__sqrt__': [('ex', '\x70'), ('ex', '\x71'),
('ex', '\x72'), ('ex', '\x73')],
r'\backslash': [('ex', '\xb2'), ('ex', '\x2f'),
('ex', '\xc2'), ('ex', '\x2d')],
r'/': [('rm', '/'), ('ex', '\xb1'), ('ex', '\x2e'),
('ex', '\xcb'), ('ex', '\x2c')],
r'\widehat': [('rm', '\x5e'), ('ex', '\x62'), ('ex', '\x63'),
('ex', '\x64')],
r'\widetilde': [('rm', '\x7e'), ('ex', '\x65'), ('ex', '\x66'),
('ex', '\x67')],
r'<': [('cal', 'h'), ('ex', 'D')],
r'>': [('cal', 'i'), ('ex', 'E')]
}
for alias, target in [(r'\leftparen', '('),
(r'\rightparent', ')'),
(r'\leftbrace', '{'),
(r'\rightbrace', '}'),
(r'\leftbracket', '['),
(r'\rightbracket', ']'),
(r'\{', '{'),
(r'\}', '}'),
(r'\[', '['),
(r'\]', ']')]:
_size_alternatives[alias] = _size_alternatives[target]
def get_sized_alternatives_for_symbol(self, fontname: str,
sym: str) -> list[tuple[str, str]]:
return self._size_alternatives.get(sym, [(fontname, sym)])
class UnicodeFonts(TruetypeFonts):
"""
An abstract base class for handling Unicode fonts.
While some reasonably complete Unicode fonts (such as DejaVu) may
work in some situations, the only Unicode font I'm aware of with a
complete set of math symbols is STIX.
This class will "fallback" on the Bakoma fonts when a required
symbol cannot be found in the font.
"""
# Some glyphs are not present in the `cmr10` font, and must be brought in
# from `cmsy10`. Map the Unicode indices of those glyphs to the indices at
# which they are found in `cmsy10`.
_cmr10_substitutions = {
0x00D7: 0x00A3, # Multiplication sign.
0x2212: 0x00A1, # Minus sign.
}
def __init__(self, default_font_prop: FontProperties, load_glyph_flags: int):
# This must come first so the backend's owner is set correctly
fallback_rc = mpl.rcParams['mathtext.fallback']
font_cls: type[TruetypeFonts] | None = {
'stix': StixFonts,
'stixsans': StixSansFonts,
'cm': BakomaFonts
}.get(fallback_rc)
self._fallback_font = (font_cls(default_font_prop, load_glyph_flags)
if font_cls else None)
super().__init__(default_font_prop, load_glyph_flags)
for texfont in "cal rm tt it bf sf bfit".split():
prop = mpl.rcParams['mathtext.' + texfont]
font = findfont(prop)
self.fontmap[texfont] = font
prop = FontProperties('cmex10')
font = findfont(prop)
self.fontmap['ex'] = font
# include STIX sized alternatives for glyphs if fallback is STIX
if isinstance(self._fallback_font, StixFonts):
stixsizedaltfonts = {
0: 'STIXGeneral',
1: 'STIXSizeOneSym',
2: 'STIXSizeTwoSym',
3: 'STIXSizeThreeSym',
4: 'STIXSizeFourSym',
5: 'STIXSizeFiveSym'}
for size, name in stixsizedaltfonts.items():
fullpath = findfont(name)
self.fontmap[size] = fullpath
self.fontmap[name] = fullpath
_slanted_symbols = set(r"\int \oint".split())
def _map_virtual_font(self, fontname: str, font_class: str,
uniindex: int) -> tuple[str, int]:
return fontname, uniindex
def _get_glyph(self, fontname: str, font_class: str,
sym: str) -> tuple[FT2Font, int, bool]:
try:
uniindex = get_unicode_index(sym)
found_symbol = True
except ValueError:
uniindex = ord('?')
found_symbol = False
_log.warning("No TeX to Unicode mapping for %a.", sym)
fontname, uniindex = self._map_virtual_font(
fontname, font_class, uniindex)
new_fontname = fontname
# Only characters in the "Letter" class should be italicized in 'it'
# mode. Greek capital letters should be Roman.
if found_symbol:
if fontname == 'it' and uniindex < 0x10000:
char = chr(uniindex)
if (unicodedata.category(char)[0] != "L"
or unicodedata.name(char).startswith("GREEK CAPITAL")):
new_fontname = 'rm'
slanted = (new_fontname == 'it') or sym in self._slanted_symbols
found_symbol = False
font = self._get_font(new_fontname)
if font is not None:
if (uniindex in self._cmr10_substitutions
and font.family_name == "cmr10"):
font = get_font(
cbook._get_data_path("fonts/ttf/cmsy10.ttf"))
uniindex = self._cmr10_substitutions[uniindex]
glyphindex = font.get_char_index(uniindex)
if glyphindex != 0:
found_symbol = True
if not found_symbol:
if self._fallback_font:
if (fontname in ('it', 'regular')
and isinstance(self._fallback_font, StixFonts)):
fontname = 'rm'
g = self._fallback_font._get_glyph(fontname, font_class, sym)
family = g[0].family_name
if family in list(BakomaFonts._fontmap.values()):
family = "Computer Modern"
_log.info("Substituting symbol %s from %s", sym, family)
return g
else:
if (fontname in ('it', 'regular')
and isinstance(self, StixFonts)):
return self._get_glyph('rm', font_class, sym)
_log.warning("Font %r does not have a glyph for %a [U+%x], "
"substituting with a dummy symbol.",
new_fontname, sym, uniindex)
font = self._get_font('rm')
uniindex = 0xA4 # currency char, for lack of anything better
slanted = False
return font, uniindex, slanted
def get_sized_alternatives_for_symbol(self, fontname: str,
sym: str) -> list[tuple[str, str]]:
if self._fallback_font:
return self._fallback_font.get_sized_alternatives_for_symbol(
fontname, sym)
return [(fontname, sym)]
class DejaVuFonts(UnicodeFonts, metaclass=abc.ABCMeta):
_fontmap: dict[str | int, str] = {}
def __init__(self, default_font_prop: FontProperties, load_glyph_flags: int):
# This must come first so the backend's owner is set correctly
if isinstance(self, DejaVuSerifFonts):
self._fallback_font = StixFonts(default_font_prop, load_glyph_flags)
else:
self._fallback_font = StixSansFonts(default_font_prop, load_glyph_flags)
self.bakoma = BakomaFonts(default_font_prop, load_glyph_flags)
TruetypeFonts.__init__(self, default_font_prop, load_glyph_flags)
# Include Stix sized alternatives for glyphs
self._fontmap.update({
1: 'STIXSizeOneSym',
2: 'STIXSizeTwoSym',
3: 'STIXSizeThreeSym',
4: 'STIXSizeFourSym',
5: 'STIXSizeFiveSym',
})
for key, name in self._fontmap.items():
fullpath = findfont(name)
self.fontmap[key] = fullpath
self.fontmap[name] = fullpath
def _get_glyph(self, fontname: str, font_class: str,
sym: str) -> tuple[FT2Font, int, bool]:
# Override prime symbol to use Bakoma.
if sym == r'\prime':
return self.bakoma._get_glyph(fontname, font_class, sym)
else:
# check whether the glyph is available in the display font
uniindex = get_unicode_index(sym)
font = self._get_font('ex')
if font is not None:
glyphindex = font.get_char_index(uniindex)
if glyphindex != 0:
return super()._get_glyph('ex', font_class, sym)
# otherwise return regular glyph
return super()._get_glyph(fontname, font_class, sym)
class DejaVuSerifFonts(DejaVuFonts):
"""
A font handling class for the DejaVu Serif fonts
If a glyph is not found it will fallback to Stix Serif
"""
_fontmap = {
'rm': 'DejaVu Serif',
'it': 'DejaVu Serif:italic',
'bf': 'DejaVu Serif:weight=bold',
'bfit': 'DejaVu Serif:italic:bold',
'sf': 'DejaVu Sans',
'tt': 'DejaVu Sans Mono',
'ex': 'DejaVu Serif Display',
0: 'DejaVu Serif',
}
class DejaVuSansFonts(DejaVuFonts):
"""
A font handling class for the DejaVu Sans fonts
If a glyph is not found it will fallback to Stix Sans
"""
_fontmap = {
'rm': 'DejaVu Sans',
'it': 'DejaVu Sans:italic',
'bf': 'DejaVu Sans:weight=bold',
'bfit': 'DejaVu Sans:italic:bold',
'sf': 'DejaVu Sans',
'tt': 'DejaVu Sans Mono',
'ex': 'DejaVu Sans Display',
0: 'DejaVu Sans',
}
class StixFonts(UnicodeFonts):
"""
A font handling class for the STIX fonts.
In addition to what UnicodeFonts provides, this class:
- supports "virtual fonts" which are complete alpha numeric
character sets with different font styles at special Unicode
code points, such as "Blackboard".
- handles sized alternative characters for the STIXSizeX fonts.
"""
_fontmap: dict[str | int, str] = {
'rm': 'STIXGeneral',
'it': 'STIXGeneral:italic',
'bf': 'STIXGeneral:weight=bold',
'bfit': 'STIXGeneral:italic:bold',
'nonunirm': 'STIXNonUnicode',
'nonuniit': 'STIXNonUnicode:italic',
'nonunibf': 'STIXNonUnicode:weight=bold',
0: 'STIXGeneral',
1: 'STIXSizeOneSym',
2: 'STIXSizeTwoSym',
3: 'STIXSizeThreeSym',
4: 'STIXSizeFourSym',
5: 'STIXSizeFiveSym',
}
_fallback_font = None
_sans = False
def __init__(self, default_font_prop: FontProperties, load_glyph_flags: int):
TruetypeFonts.__init__(self, default_font_prop, load_glyph_flags)
for key, name in self._fontmap.items():
fullpath = findfont(name)
self.fontmap[key] = fullpath
self.fontmap[name] = fullpath
def _map_virtual_font(self, fontname: str, font_class: str,
uniindex: int) -> tuple[str, int]:
# Handle these "fonts" that are actually embedded in
# other fonts.
font_mapping = stix_virtual_fonts.get(fontname)
if (self._sans and font_mapping is None
and fontname not in ('regular', 'default')):
font_mapping = stix_virtual_fonts['sf']
doing_sans_conversion = True
else:
doing_sans_conversion = False
if isinstance(font_mapping, dict):
try:
mapping = font_mapping[font_class]
except KeyError:
mapping = font_mapping['rm']
elif isinstance(font_mapping, list):
mapping = font_mapping
else:
mapping = None
if mapping is not None:
# Binary search for the source glyph
lo = 0
hi = len(mapping)
while lo < hi:
mid = (lo+hi)//2
range = mapping[mid]
if uniindex < range[0]:
hi = mid
elif uniindex <= range[1]:
break
else:
lo = mid + 1
if range[0] <= uniindex <= range[1]:
uniindex = uniindex - range[0] + range[3]
fontname = range[2]
elif not doing_sans_conversion:
# This will generate a dummy character
uniindex = 0x1
fontname = mpl.rcParams['mathtext.default']
# Fix some incorrect glyphs.
if fontname in ('rm', 'it'):
uniindex = stix_glyph_fixes.get(uniindex, uniindex)
# Handle private use area glyphs
if fontname in ('it', 'rm', 'bf', 'bfit') and 0xe000 <= uniindex <= 0xf8ff:
fontname = 'nonuni' + fontname
return fontname, uniindex
@functools.cache
def get_sized_alternatives_for_symbol( # type: ignore[override]
self,
fontname: str,
sym: str) -> list[tuple[str, str]] | list[tuple[int, str]]:
fixes = {
'\\{': '{', '\\}': '}', '\\[': '[', '\\]': ']',
'<': '\N{MATHEMATICAL LEFT ANGLE BRACKET}',
'>': '\N{MATHEMATICAL RIGHT ANGLE BRACKET}',
}
sym = fixes.get(sym, sym)
try:
uniindex = get_unicode_index(sym)
except ValueError:
return [(fontname, sym)]
alternatives = [(i, chr(uniindex)) for i in range(6)
if self._get_font(i).get_char_index(uniindex) != 0]
# The largest size of the radical symbol in STIX has incorrect
# metrics that cause it to be disconnected from the stem.
if sym == r'\__sqrt__':
alternatives = alternatives[:-1]
return alternatives
class StixSansFonts(StixFonts):
"""
A font handling class for the STIX fonts (that uses sans-serif
characters by default).
"""
_sans = True
##############################################################################
# TeX-LIKE BOX MODEL
# The following is based directly on the document 'woven' from the
# TeX82 source code. This information is also available in printed
# form:
#
# Knuth, Donald E.. 1986. Computers and Typesetting, Volume B:
# TeX: The Program. Addison-Wesley Professional.
#
# The most relevant "chapters" are:
# Data structures for boxes and their friends
# Shipping pages out (ship())
# Packaging (hpack() and vpack())
# Data structures for math mode
# Subroutines for math mode
# Typesetting math formulas
#
# Many of the docstrings below refer to a numbered "node" in that
# book, e.g., node123
#
# Note that (as TeX) y increases downward, unlike many other parts of
# matplotlib.
# How much text shrinks when going to the next-smallest level.
SHRINK_FACTOR = 0.7
# The number of different sizes of chars to use, beyond which they will not
# get any smaller
NUM_SIZE_LEVELS = 6
class FontConstantsBase:
"""
A set of constants that controls how certain things, such as sub-
and superscripts are laid out. These are all metrics that can't
be reliably retrieved from the font metrics in the font itself.
"""
# Percentage of x-height of additional horiz. space after sub/superscripts
script_space: T.ClassVar[float] = 0.05
# Percentage of x-height that sub/superscripts drop below the baseline
subdrop: T.ClassVar[float] = 0.4
# Percentage of x-height that superscripts are raised from the baseline
sup1: T.ClassVar[float] = 0.7
# Percentage of x-height that subscripts drop below the baseline
sub1: T.ClassVar[float] = 0.3
# Percentage of x-height that subscripts drop below the baseline when a
# superscript is present
sub2: T.ClassVar[float] = 0.5
# Percentage of x-height that sub/superscripts are offset relative to the
# nucleus edge for non-slanted nuclei
delta: T.ClassVar[float] = 0.025
# Additional percentage of last character height above 2/3 of the
# x-height that superscripts are offset relative to the subscript
# for slanted nuclei
delta_slanted: T.ClassVar[float] = 0.2
# Percentage of x-height that superscripts and subscripts are offset for
# integrals
delta_integral: T.ClassVar[float] = 0.1
class ComputerModernFontConstants(FontConstantsBase):
script_space = 0.075
subdrop = 0.2
sup1 = 0.45
sub1 = 0.2
sub2 = 0.3
delta = 0.075
delta_slanted = 0.3
delta_integral = 0.3
class STIXFontConstants(FontConstantsBase):
script_space = 0.1
sup1 = 0.8
sub2 = 0.6
delta = 0.05
delta_slanted = 0.3
delta_integral = 0.3
class STIXSansFontConstants(FontConstantsBase):
script_space = 0.05
sup1 = 0.8
delta_slanted = 0.6
delta_integral = 0.3
class DejaVuSerifFontConstants(FontConstantsBase):
pass
class DejaVuSansFontConstants(FontConstantsBase):
pass
# Maps font family names to the FontConstantBase subclass to use
_font_constant_mapping = {
'DejaVu Sans': DejaVuSansFontConstants,
'DejaVu Sans Mono': DejaVuSansFontConstants,
'DejaVu Serif': DejaVuSerifFontConstants,
'cmb10': ComputerModernFontConstants,
'cmex10': ComputerModernFontConstants,
'cmmi10': ComputerModernFontConstants,
'cmr10': ComputerModernFontConstants,
'cmss10': ComputerModernFontConstants,
'cmsy10': ComputerModernFontConstants,
'cmtt10': ComputerModernFontConstants,
'STIXGeneral': STIXFontConstants,
'STIXNonUnicode': STIXFontConstants,
'STIXSizeFiveSym': STIXFontConstants,
'STIXSizeFourSym': STIXFontConstants,
'STIXSizeThreeSym': STIXFontConstants,
'STIXSizeTwoSym': STIXFontConstants,
'STIXSizeOneSym': STIXFontConstants,
# Map the fonts we used to ship, just for good measure
'Bitstream Vera Sans': DejaVuSansFontConstants,
'Bitstream Vera': DejaVuSansFontConstants,
}
def _get_font_constant_set(state: ParserState) -> type[FontConstantsBase]:
constants = _font_constant_mapping.get(