forked from fabiocaccamo/python-fontbro
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfont.py
More file actions
2343 lines (2105 loc) · 86.3 KB
/
Copy pathfont.py
File metadata and controls
2343 lines (2105 loc) · 86.3 KB
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
from __future__ import annotations
import copy
import math
import os
import re
import sys
import tempfile
from collections import Counter
from collections.abc import Generator
from curses import ascii
from io import BytesIO
from pathlib import Path
from typing import IO, Any, cast
import fsutil
import ots
from fontTools import unicodedata
from fontTools.pens.svgPathPen import SVGPathPen
from fontTools.subset import Options as SubsetterOptions
from fontTools.subset import Subsetter
from fontTools.ttLib import TTCollection, TTFont, TTLibError
from fontTools.varLib import instancer
from fontTools.varLib.instancer import OverlapMode
from PIL import Image, ImageDraw, ImageFont
from fontbro.exceptions import (
ArgumentError,
DataError,
OperationError,
SanitizationError,
)
from fontbro.flags import get_flag, set_flag
from fontbro.math import get_euclidean_distance
from fontbro.subset import parse_unicodes
from fontbro.utils import (
concat_names,
find_item,
read_json,
remove_spaces,
slugify,
)
class Font:
"""
friendly font operations on top of fontTools.
"""
# Family Classification:
# https://learn.microsoft.com/en-us/typography/opentype/spec/ibmfc
_FAMILY_CLASSIFICATIONS: dict[str, list[dict[str, Any]]] = read_json(
"data/family-classifications.json"
)
# fmt: off
FAMILY_CLASSIFICATION_NO_CLASSIFICATION: dict[str, int] = {'class_id': 0}
FAMILY_CLASSIFICATION_OLDSTYLE_SERIFS: dict[str, int] = {'class_id': 1}
FAMILY_CLASSIFICATION_OLDSTYLE_SERIFS_NO_CLASSIFICATION: dict[str, int] = {'class_id':1, 'subclass_id':0}
FAMILY_CLASSIFICATION_OLDSTYLE_SERIFS_IBM_ROUNDED_LEGIBILITY: dict[str, int] = {'class_id':1, 'subclass_id':1}
FAMILY_CLASSIFICATION_OLDSTYLE_SERIFS_GARALDE: dict[str, int] = {'class_id':1, 'subclass_id':2}
FAMILY_CLASSIFICATION_OLDSTYLE_SERIFS_VENETIAN: dict[str, int] = {'class_id':1, 'subclass_id':3}
FAMILY_CLASSIFICATION_OLDSTYLE_SERIFS_MODIFIED_VENETIAN: dict[str, int] = {'class_id':1, 'subclass_id':4}
FAMILY_CLASSIFICATION_OLDSTYLE_SERIFS_DUTCH_MODERN: dict[str, int] = {'class_id':1, 'subclass_id':5}
FAMILY_CLASSIFICATION_OLDSTYLE_SERIFS_DUTCH_TRADITIONAL: dict[str, int] = {'class_id':1, 'subclass_id':6}
FAMILY_CLASSIFICATION_OLDSTYLE_SERIFS_CONTEMPORARY: dict[str, int] = {'class_id':1, 'subclass_id':7}
FAMILY_CLASSIFICATION_OLDSTYLE_SERIFS_CALLIGRAPHIC: dict[str, int] = {'class_id':1, 'subclass_id':8}
FAMILY_CLASSIFICATION_OLDSTYLE_SERIFS_MISCELLANEOUS: dict[str, int] = {'class_id':1, 'subclass_id':15}
FAMILY_CLASSIFICATION_TRANSITIONAL_SERIFS: dict[str, int] = {'class_id': 2}
FAMILY_CLASSIFICATION_TRANSITIONAL_SERIFS_NO_CLASSIFICATION: dict[str, int] = {'class_id':2, 'subclass_id':0}
FAMILY_CLASSIFICATION_TRANSITIONAL_SERIFS_DIRECT_LINE: dict[str, int] = {'class_id':2, 'subclass_id':1}
FAMILY_CLASSIFICATION_TRANSITIONAL_SERIFS_SCRIPT: dict[str, int] = {'class_id':2, 'subclass_id':2}
FAMILY_CLASSIFICATION_TRANSITIONAL_SERIFS_MISCELLANEOUS: dict[str, int] = {'class_id':2, 'subclass_id':15}
FAMILY_CLASSIFICATION_MODERN_SERIFS: dict[str, int] = {'class_id': 3}
FAMILY_CLASSIFICATION_MODERN_SERIFS_NO_CLASSIFICATION: dict[str, int] = {'class_id':3, 'subclass_id':0}
FAMILY_CLASSIFICATION_MODERN_SERIFS_ITALIAN: dict[str, int] = {'class_id':3, 'subclass_id':1}
FAMILY_CLASSIFICATION_MODERN_SERIFS_SCRIPT: dict[str, int] = {'class_id':3, 'subclass_id':2}
FAMILY_CLASSIFICATION_MODERN_SERIFS_MISCELLANEOUS: dict[str, int] = {'class_id':3, 'subclass_id':15}
FAMILY_CLASSIFICATION_CLARENDON_SERIFS: dict[str, int] = {'class_id': 4}
FAMILY_CLASSIFICATION_CLARENDON_SERIFS_NO_CLASSIFICATION: dict[str, int] = {'class_id':4, 'subclass_id':0}
FAMILY_CLASSIFICATION_CLARENDON_SERIFS_CLARENDON: dict[str, int] = {'class_id':4, 'subclass_id':1}
FAMILY_CLASSIFICATION_CLARENDON_SERIFS_MODERN: dict[str, int] = {'class_id':4, 'subclass_id':2}
FAMILY_CLASSIFICATION_CLARENDON_SERIFS_TRADITIONAL: dict[str, int] = {'class_id':4, 'subclass_id':3}
FAMILY_CLASSIFICATION_CLARENDON_SERIFS_NEWSPAPER: dict[str, int] = {'class_id':4, 'subclass_id':4}
FAMILY_CLASSIFICATION_CLARENDON_SERIFS_STUB_SERIF: dict[str, int] = {'class_id':4, 'subclass_id':5}
FAMILY_CLASSIFICATION_CLARENDON_SERIFS_MONOTONE: dict[str, int] = {'class_id':4, 'subclass_id':6}
FAMILY_CLASSIFICATION_CLARENDON_SERIFS_TYPEWRITER: dict[str, int] = {'class_id':4, 'subclass_id':7}
FAMILY_CLASSIFICATION_CLARENDON_SERIFS_MISCELLANEOUS: dict[str, int] = {'class_id':4, 'subclass_id':15}
FAMILY_CLASSIFICATION_SLAB_SERIFS: dict[str, int] = {'class_id': 5}
FAMILY_CLASSIFICATION_SLAB_SERIFS_NO_CLASSIFICATION: dict[str, int] = {'class_id':5, 'subclass_id':0}
FAMILY_CLASSIFICATION_SLAB_SERIFS_MONOTONE: dict[str, int] = {'class_id':5, 'subclass_id':1}
FAMILY_CLASSIFICATION_SLAB_SERIFS_HUMANIST: dict[str, int] = {'class_id':5, 'subclass_id':2}
FAMILY_CLASSIFICATION_SLAB_SERIFS_GEOMETRIC: dict[str, int] = {'class_id':5, 'subclass_id':3}
FAMILY_CLASSIFICATION_SLAB_SERIFS_SWISS: dict[str, int] = {'class_id':5, 'subclass_id':4}
FAMILY_CLASSIFICATION_SLAB_SERIFS_TYPEWRITER: dict[str, int] = {'class_id':5, 'subclass_id':5}
FAMILY_CLASSIFICATION_SLAB_SERIFS_MISCELLANEOUS: dict[str, int] = {'class_id':5, 'subclass_id':15}
FAMILY_CLASSIFICATION_FREEFORM_SERIFS: dict[str, int] = {'class_id': 7}
FAMILY_CLASSIFICATION_FREEFORM_SERIFS_NO_CLASSIFICATION: dict[str, int] = {'class_id':7, 'subclass_id':0}
FAMILY_CLASSIFICATION_FREEFORM_SERIFS_MODERN: dict[str, int] = {'class_id':7, 'subclass_id':1}
FAMILY_CLASSIFICATION_FREEFORM_SERIFS_MISCELLANEOUS: dict[str, int] = {'class_id':7, 'subclass_id':15}
FAMILY_CLASSIFICATION_SANS_SERIF: dict[str, int] = {'class_id': 8}
FAMILY_CLASSIFICATION_SANS_SERIF_NO_CLASSIFICATION: dict[str, int] = {'class_id':8, 'subclass_id':0}
FAMILY_CLASSIFICATION_SANS_SERIF_IBM_NEO_GROTESQUE_GOTHIC: dict[str, int] = {'class_id':8, 'subclass_id':1}
FAMILY_CLASSIFICATION_SANS_SERIF_HUMANIST: dict[str, int] = {'class_id':8, 'subclass_id':2}
FAMILY_CLASSIFICATION_SANS_SERIF_LOW_X_ROUND_GEOMETRIC: dict[str, int] = {'class_id':8, 'subclass_id':3}
FAMILY_CLASSIFICATION_SANS_SERIF_HIGH_X_ROUND_GEOMETRIC: dict[str, int] = {'class_id':8, 'subclass_id':4}
FAMILY_CLASSIFICATION_SANS_SERIF_NEO_GROTESQUE_GOTHIC: dict[str, int] = {'class_id':8, 'subclass_id':5}
FAMILY_CLASSIFICATION_SANS_SERIF_MODIFIED_NEO_GROTESQUE_GOTHIC: dict[str, int] = {'class_id':8, 'subclass_id':6}
FAMILY_CLASSIFICATION_SANS_SERIF_TYPEWRITER_GOTHIC: dict[str, int] = {'class_id':8, 'subclass_id':9}
FAMILY_CLASSIFICATION_SANS_SERIF_MATRIX: dict[str, int] = {'class_id':8, 'subclass_id':10}
FAMILY_CLASSIFICATION_SANS_SERIF_MISCELLANEOUS: dict[str, int] = {'class_id':8, 'subclass_id':15}
FAMILY_CLASSIFICATION_ORNAMENTALS: dict[str, int] = {'class_id': 9}
FAMILY_CLASSIFICATION_ORNAMENTALS_NO_CLASSIFICATION: dict[str, int] = {'class_id':9, 'subclass_id':0}
FAMILY_CLASSIFICATION_ORNAMENTALS_ENGRAVER: dict[str, int] = {'class_id':9, 'subclass_id':1}
FAMILY_CLASSIFICATION_ORNAMENTALS_BLACK_LETTER: dict[str, int] = {'class_id':9, 'subclass_id':2}
FAMILY_CLASSIFICATION_ORNAMENTALS_DECORATIVE: dict[str, int] = {'class_id':9, 'subclass_id':3}
FAMILY_CLASSIFICATION_ORNAMENTALS_THREE_DIMENSIONAL: dict[str, int] = {'class_id':9, 'subclass_id':4}
FAMILY_CLASSIFICATION_ORNAMENTALS_MISCELLANEOUS: dict[str, int] = {'class_id':9, 'subclass_id':15}
FAMILY_CLASSIFICATION_SCRIPTS: dict[str, int] = {'class_id': 10}
FAMILY_CLASSIFICATION_SCRIPTS_NO_CLASSIFICATION: dict[str, int] = {'class_id':10, 'subclass_id':0}
FAMILY_CLASSIFICATION_SCRIPTS_UNCIAL: dict[str, int] = {'class_id':10, 'subclass_id':1}
FAMILY_CLASSIFICATION_SCRIPTS_BRUSH_JOINED: dict[str, int] = {'class_id':10, 'subclass_id':2}
FAMILY_CLASSIFICATION_SCRIPTS_FORMAL_JOINED: dict[str, int] = {'class_id':10, 'subclass_id':3}
FAMILY_CLASSIFICATION_SCRIPTS_MONOTONE_JOINED: dict[str, int] = {'class_id':10, 'subclass_id':4}
FAMILY_CLASSIFICATION_SCRIPTS_CALLIGRAPHIC: dict[str, int] = {'class_id':10, 'subclass_id':5}
FAMILY_CLASSIFICATION_SCRIPTS_BRUSH_UNJOINED: dict[str, int] = {'class_id':10, 'subclass_id':6}
FAMILY_CLASSIFICATION_SCRIPTS_FORMAL_UNJOINED: dict[str, int] = {'class_id':10, 'subclass_id':7}
FAMILY_CLASSIFICATION_SCRIPTS_MONOTONE_UNJOINED: dict[str, int] = {'class_id':10, 'subclass_id':8}
FAMILY_CLASSIFICATION_SCRIPTS_MISCELLANEOUS: dict[str, int] = {'class_id':10, 'subclass_id':15}
FAMILY_CLASSIFICATION_SYMBOLIC: dict[str, int] = {'class_id': 12}
FAMILY_CLASSIFICATION_SYMBOLIC_NO_CLASSIFICATION: dict[str, int] = {'class_id':12, 'subclass_id':0}
FAMILY_CLASSIFICATION_SYMBOLIC_MIXED_SERIF: dict[str, int] = {'class_id':12, 'subclass_id':3}
FAMILY_CLASSIFICATION_SYMBOLIC_OLDSTYLE_SERIF: dict[str, int] = {'class_id':12, 'subclass_id':6}
FAMILY_CLASSIFICATION_SYMBOLIC_NEO_GROTESQUE_SANS_SERIF: dict[str, int] = {'class_id':12, 'subclass_id':7}
FAMILY_CLASSIFICATION_SYMBOLIC_MISCELLANEOUS: dict[str, int] = {'class_id':12, 'subclass_id':15}
# fmt: on
# Features:
# https://docs.microsoft.com/en-gb/typography/opentype/spec/featurelist
# https://developer.mozilla.org/en-US/docs/Web/CSS/font-feature-settings
_FEATURES_LIST: list[dict[str, Any]] = read_json("data/features.json")
_FEATURES_BY_TAG: dict[str, dict[str, Any]] = {
feature["tag"]: feature for feature in _FEATURES_LIST
}
# Formats:
FORMAT_OTF: str = "otf"
FORMAT_TTF: str = "ttf"
FORMAT_WOFF: str = "woff"
FORMAT_WOFF2: str = "woff2"
_FORMATS_LIST: list[str] = [FORMAT_OTF, FORMAT_TTF, FORMAT_WOFF, FORMAT_WOFF2]
# Names:
NAME_COPYRIGHT_NOTICE: str = "copyright_notice"
NAME_FAMILY_NAME: str = "family_name"
NAME_SUBFAMILY_NAME: str = "subfamily_name"
NAME_UNIQUE_IDENTIFIER: str = "unique_identifier"
NAME_FULL_NAME: str = "full_name"
NAME_VERSION: str = "version"
NAME_POSTSCRIPT_NAME: str = "postscript_name"
NAME_TRADEMARK: str = "trademark"
NAME_MANUFACTURER_NAME: str = "manufacturer_name"
NAME_DESIGNER: str = "designer"
NAME_DESCRIPTION: str = "description"
NAME_VENDOR_URL: str = "vendor_url"
NAME_DESIGNER_URL: str = "designer_url"
NAME_LICENSE_DESCRIPTION: str = "license_description"
NAME_LICENSE_INFO_URL: str = "license_info_url"
NAME_RESERVED: str = "reserved"
NAME_TYPOGRAPHIC_FAMILY_NAME: str = "typographic_family_name"
NAME_TYPOGRAPHIC_SUBFAMILY_NAME: str = "typographic_subfamily_name"
NAME_COMPATIBLE_FULL: str = "compatible_full"
NAME_SAMPLE_TEXT: str = "sample_text"
NAME_POSTSCRIPT_CID_FINDFONT_NAME: str = "postscript_cid_findfont_name"
NAME_WWS_FAMILY_NAME: str = "wws_family_name"
NAME_WWS_SUBFAMILY_NAME: str = "wws_subfamily_name"
NAME_LIGHT_BACKGROUND_PALETTE: str = "light_background_palette"
NAME_DARK_BACKGROUND_PALETTE: str = "dark_background_palette"
NAME_VARIATIONS_POSTSCRIPT_NAME_PREFIX: str = "variations_postscript_name_prefix"
_NAMES: list[dict[str, Any]] = [
{"id": 0, "key": NAME_COPYRIGHT_NOTICE},
{"id": 1, "key": NAME_FAMILY_NAME},
{"id": 2, "key": NAME_SUBFAMILY_NAME},
{"id": 3, "key": NAME_UNIQUE_IDENTIFIER},
{"id": 4, "key": NAME_FULL_NAME},
{"id": 5, "key": NAME_VERSION},
{"id": 6, "key": NAME_POSTSCRIPT_NAME},
{"id": 7, "key": NAME_TRADEMARK},
{"id": 8, "key": NAME_MANUFACTURER_NAME},
{"id": 9, "key": NAME_DESIGNER},
{"id": 10, "key": NAME_DESCRIPTION},
{"id": 11, "key": NAME_VENDOR_URL},
{"id": 12, "key": NAME_DESIGNER_URL},
{"id": 13, "key": NAME_LICENSE_DESCRIPTION},
{"id": 14, "key": NAME_LICENSE_INFO_URL},
{"id": 15, "key": NAME_RESERVED},
{"id": 16, "key": NAME_TYPOGRAPHIC_FAMILY_NAME},
{"id": 17, "key": NAME_TYPOGRAPHIC_SUBFAMILY_NAME},
{"id": 18, "key": NAME_COMPATIBLE_FULL},
{"id": 19, "key": NAME_SAMPLE_TEXT},
{"id": 20, "key": NAME_POSTSCRIPT_CID_FINDFONT_NAME},
{"id": 21, "key": NAME_WWS_FAMILY_NAME},
{"id": 22, "key": NAME_WWS_SUBFAMILY_NAME},
{"id": 23, "key": NAME_LIGHT_BACKGROUND_PALETTE},
{"id": 24, "key": NAME_DARK_BACKGROUND_PALETTE},
{"id": 25, "key": NAME_VARIATIONS_POSTSCRIPT_NAME_PREFIX},
]
_NAMES_BY_ID: dict[int, dict[str, Any]] = {item["id"]: item for item in _NAMES}
_NAMES_BY_KEY: dict[str, dict[str, Any]] = {item["key"]: item for item in _NAMES}
_NAMES_MAC_IDS: dict[str, Any] = {"platformID": 3, "platEncID": 1, "langID": 0x409}
_NAMES_WIN_IDS: dict[str, Any] = {"platformID": 1, "platEncID": 0, "langID": 0x0}
# Style Flags:
# https://docs.microsoft.com/en-us/typography/opentype/spec/head
# https://docs.microsoft.com/en-us/typography/opentype/spec/os2#fsselection
STYLE_FLAG_REGULAR: str = "regular"
STYLE_FLAG_BOLD: str = "bold"
STYLE_FLAG_ITALIC: str = "italic"
STYLE_FLAG_UNDERLINE: str = "underline"
STYLE_FLAG_OUTLINE: str = "outline"
STYLE_FLAG_SHADOW: str = "shadow"
STYLE_FLAG_CONDENSED: str = "condensed"
STYLE_FLAG_EXTENDED: str = "extended"
_STYLE_FLAGS: dict[str, dict[str, Any]] = {
STYLE_FLAG_REGULAR: {"bit_head_mac": None, "bit_os2_fs": 6},
STYLE_FLAG_BOLD: {"bit_head_mac": 0, "bit_os2_fs": 5},
STYLE_FLAG_ITALIC: {"bit_head_mac": 1, "bit_os2_fs": 0},
STYLE_FLAG_UNDERLINE: {"bit_head_mac": 2, "bit_os2_fs": None},
STYLE_FLAG_OUTLINE: {"bit_head_mac": 3, "bit_os2_fs": 3},
STYLE_FLAG_SHADOW: {"bit_head_mac": 4, "bit_os2_fs": None},
STYLE_FLAG_CONDENSED: {"bit_head_mac": 5, "bit_os2_fs": None},
STYLE_FLAG_EXTENDED: {"bit_head_mac": 6, "bit_os2_fs": None},
}
_STYLE_FLAGS_KEYS: list[str] = list(_STYLE_FLAGS.keys())
# Unicode blocks/scripts data:
_UNICODE_BLOCKS: list[dict[str, Any]] = read_json("data/unicode-blocks.json")
_UNICODE_SCRIPTS: list[dict[str, Any]] = read_json("data/unicode-scripts.json")
# Variable Axes:
_VARIABLE_AXES: list[dict[str, Any]] = [
{"tag": "ital", "name": "Italic"},
{"tag": "opsz", "name": "Optical Size"},
{"tag": "slnt", "name": "Slant"},
{"tag": "wdth", "name": "Width"},
{"tag": "wght", "name": "Weight"},
# https://fonts.google.com/variablefonts#axis-definitions
{"tag": "ARRR", "name": "AR Retinal Resolution"},
{"tag": "YTAS", "name": "Ascender Height"},
{"tag": "BLED", "name": "Bleed"},
{"tag": "BNCE", "name": "Bounce"},
{"tag": "CASL", "name": "Casual"},
{"tag": "CTRS", "name": "Contrast"},
{"tag": "XTRA", "name": "Counter Width"},
{"tag": "CRSV", "name": "Cursive"},
{"tag": "YTDE", "name": "Descender Depth"},
{"tag": "EHLT", "name": "Edge Highlight"},
{"tag": "ELXP", "name": "Element Expansion"},
{"tag": "ELGR", "name": "Element Grid"},
{"tag": "ELSH", "name": "Element Shape"},
{"tag": "EDPT", "name": "Extrusion Depth"},
{"tag": "YTFI", "name": "Figure Height"},
# Removed: https://github.com/google/fonts/pull/2594
{"tag": "XPRN", "name": "Expression"},
{"tag": "FILL", "name": "Fill"},
{"tag": "FLAR", "name": "Flare"},
{"tag": "GRAD", "name": "Grade"},
{"tag": "XELA", "name": "Horizontal Element Alignment"},
{"tag": "XPN1", "name": "Horizontal Position of Paint 1"},
{"tag": "XPN2", "name": "Horizontal Position of Paint 2"},
{"tag": "HEXP", "name": "Hyper Expansion"},
{"tag": "INFM", "name": "Informality"},
{"tag": "YTLC", "name": "Lowercase Height"},
{"tag": "MONO", "name": "Monospace"},
{"tag": "MORF", "name": "Morph"},
{"tag": "XROT", "name": "Rotation in X"},
{"tag": "YROT", "name": "Rotation in Y"},
{"tag": "ZROT", "name": "Rotation in Z"},
{"tag": "ROND", "name": "Roundness"},
{"tag": "SCAN", "name": "Scanlines"},
{"tag": "SHLN", "name": "Shadow Length"},
{"tag": "SHRP", "name": "Sharpness"},
{"tag": "SZP1", "name": "Size of Paint 1"},
{"tag": "SZP2", "name": "Size of Paint 2"},
{"tag": "SOFT", "name": "Softness"},
{"tag": "SPAC", "name": "Spacing"},
{"tag": "XOPQ", "name": "Thick Stroke"},
{"tag": "YOPQ", "name": "Thin Stroke"},
{"tag": "YTUC", "name": "Uppercase Height"},
{"tag": "YELA", "name": "Vertical Element Alignment"},
{"tag": "YEXT", "name": "Vertical Extension"},
{"tag": "YPN1", "name": "Vertical Position of Paint 1"},
{"tag": "YPN2", "name": "Vertical Position of Paint 2"},
{"tag": "VOLM", "name": "Volume"},
{"tag": "WONK", "name": "Wonky"},
{"tag": "YEAR", "name": "Year"},
]
_VARIABLE_AXES_BY_TAG: dict[str, Any] = {
axis["tag"]: axis for axis in _VARIABLE_AXES
}
# Vertical Metrics:
VERTICAL_METRIC_UNITS_PER_EM: str = "units_per_em"
VERTICAL_METRIC_Y_MAX: str = "y_max"
VERTICAL_METRIC_Y_MIN: str = "y_min"
VERTICAL_METRIC_ASCENT: str = "ascent"
VERTICAL_METRIC_DESCENT: str = "descent"
VERTICAL_METRIC_LINE_GAP: str = "line_gap"
VERTICAL_METRIC_TYPO_ASCENDER: str = "typo_ascender"
VERTICAL_METRIC_TYPO_DESCENDER: str = "typo_descender"
VERTICAL_METRIC_TYPO_LINE_GAP: str = "typo_line_gap"
VERTICAL_METRIC_CAP_HEIGHT: str = "cap_height"
VERTICAL_METRIC_X_HEIGHT: str = "x_height"
VERTICAL_METRIC_WIN_ASCENT: str = "win_ascent"
VERTICAL_METRIC_WIN_DESCENT: str = "win_descent"
# fmt: off
_VERTICAL_METRICS: list[dict[str, Any]] = [
{"table": "head", "attr": "unitsPerEm", "key": VERTICAL_METRIC_UNITS_PER_EM},
{"table": "head", "attr": "yMax", "key": VERTICAL_METRIC_Y_MAX},
{"table": "head", "attr": "yMin", "key": VERTICAL_METRIC_Y_MIN},
{"table": "hhea", "attr": "ascent", "key": VERTICAL_METRIC_ASCENT},
{"table": "hhea", "attr": "descent", "key": VERTICAL_METRIC_DESCENT},
{"table": "hhea", "attr": "lineGap", "key": VERTICAL_METRIC_LINE_GAP},
{"table": "OS/2", "attr": "sTypoAscender", "key": VERTICAL_METRIC_TYPO_ASCENDER},
{"table": "OS/2", "attr": "sTypoDescender", "key": VERTICAL_METRIC_TYPO_DESCENDER},
{"table": "OS/2", "attr": "sTypoLineGap", "key": VERTICAL_METRIC_TYPO_LINE_GAP},
{"table": "OS/2", "attr": "sCapHeight", "key": VERTICAL_METRIC_CAP_HEIGHT},
{"table": "OS/2", "attr": "sxHeight", "key": VERTICAL_METRIC_X_HEIGHT},
{"table": "OS/2", "attr": "usWinAscent", "key": VERTICAL_METRIC_WIN_ASCENT},
{"table": "OS/2", "attr": "usWinDescent", "key": VERTICAL_METRIC_WIN_DESCENT},
]
# fmt: on
# Weights:
# https://docs.microsoft.com/en-us/typography/opentype/otspec170/os2#usweightclass
WEIGHT_EXTRA_THIN: str = "Extra-thin" # (Hairline)
WEIGHT_THIN: str = "Thin"
WEIGHT_EXTRA_LIGHT: str = "Extra-light" # (Ultra-light)
WEIGHT_LIGHT: str = "Light"
WEIGHT_REGULAR: str = "Regular" # (Normal)
WEIGHT_BOOK: str = "Book"
WEIGHT_MEDIUM: str = "Medium"
WEIGHT_SEMI_BOLD: str = "Semi-bold" # (Demi-bold)
WEIGHT_BOLD: str = "Bold"
WEIGHT_EXTRA_BOLD: str = "Extra-bold" # (Ultra-bold)
WEIGHT_BLACK: str = "Black" # (Heavy)
WEIGHT_EXTRA_BLACK: str = "Extra-black" # (Nord)
_WEIGHTS: list[dict[str, Any]] = [
{"value": 50, "name": WEIGHT_EXTRA_THIN},
{"value": 100, "name": WEIGHT_THIN},
{"value": 200, "name": WEIGHT_EXTRA_LIGHT},
{"value": 300, "name": WEIGHT_LIGHT},
{"value": 400, "name": WEIGHT_REGULAR},
{"value": 450, "name": WEIGHT_BOOK},
{"value": 500, "name": WEIGHT_MEDIUM},
{"value": 600, "name": WEIGHT_SEMI_BOLD},
{"value": 700, "name": WEIGHT_BOLD},
{"value": 800, "name": WEIGHT_EXTRA_BOLD},
{"value": 900, "name": WEIGHT_BLACK},
{"value": 950, "name": WEIGHT_EXTRA_BLACK},
]
_WEIGHTS_BY_VALUE: dict[int, dict[str, Any]] = {
weight["value"]: weight for weight in _WEIGHTS
}
# Widths:
# https://docs.microsoft.com/en-us/typography/opentype/otspec170/os2#uswidthclass
WIDTH_ULTRA_CONDENSED: str = "Ultra-condensed"
WIDTH_EXTRA_CONDENSED: str = "Extra-condensed"
WIDTH_CONDENSED: str = "Condensed"
WIDTH_SEMI_CONDENSED: str = "Semi-condensed"
WIDTH_MEDIUM: str = "Medium" # (Normal)
WIDTH_SEMI_EXPANDED: str = "Semi-expanded"
WIDTH_EXPANDED: str = "Expanded"
WIDTH_EXTRA_EXPANDED: str = "Extra-expanded"
WIDTH_ULTRA_EXPANDED: str = "Ultra-expanded"
_WIDTHS: list[dict[str, Any]] = [
{"value": 1, "perc": 50.0, "name": WIDTH_ULTRA_CONDENSED},
{"value": 2, "perc": 62.5, "name": WIDTH_EXTRA_CONDENSED},
{"value": 3, "perc": 75.0, "name": WIDTH_CONDENSED},
{"value": 4, "perc": 87.5, "name": WIDTH_SEMI_CONDENSED},
{"value": 5, "perc": 100.0, "name": WIDTH_MEDIUM},
{"value": 6, "perc": 112.5, "name": WIDTH_SEMI_EXPANDED},
{"value": 7, "perc": 125.0, "name": WIDTH_EXPANDED},
{"value": 8, "perc": 150.0, "name": WIDTH_EXTRA_EXPANDED},
{"value": 9, "perc": 200.0, "name": WIDTH_ULTRA_CONDENSED},
]
_WIDTHS_BY_VALUE: dict[int, dict[str, Any]] = {
width["value"]: width for width in _WIDTHS
}
def __init__(
self,
filepath: str | Path | IO[Any] | TTFont | Font,
**kwargs: Any,
) -> None:
"""
Constructs a new Font instance loading a font file from the given filepath.
:param filepath: The filepath from which to load the font
:type filepath: string or file object or TTFont or Font
:raises ValueError: if the filepath is not a valid font
"""
super().__init__()
self._filepath: str | Path | None = None
self._fileobject: IO[Any] | None = None
self._ttfont: TTFont | None = None
self._kwargs: dict[str, Any] = {}
if isinstance(filepath, (Path, str)):
self._init_with_filepath(str(filepath), **kwargs)
elif hasattr(filepath, "read"):
self._init_with_fileobject(cast(IO[Any], filepath), **kwargs)
elif isinstance(filepath, Font):
self._init_with_font(filepath, **kwargs)
elif isinstance(filepath, TTFont):
self._init_with_ttfont(filepath, **kwargs)
else:
filepath_type = type(filepath).__name__
raise ArgumentError(
"Invalid filepath type: "
"expected str or pathlib.Path or file object or TTFont or Font, "
f"found '{filepath_type}'."
)
def _init_with_filepath(
self,
filepath: str | Path,
**kwargs: Any,
) -> None:
try:
self._filepath = filepath
self._kwargs = kwargs
self._ttfont = TTFont(self._filepath, **kwargs)
except TTLibError as error:
raise ArgumentError(f"Invalid font at filepath: '{filepath}'.") from error
def _init_with_fileobject(
self,
fileobject: IO[Any],
**kwargs: Any,
) -> None:
try:
self._fileobject = fileobject
self._kwargs = kwargs
self._ttfont = TTFont(self._fileobject, **kwargs)
except TTLibError as error:
raise ArgumentError(
f"Invalid font at fileobject: '{fileobject}'."
) from error
def _init_with_font(
self,
font: Font,
**kwargs: Any,
) -> None:
self._init_with_ttfont(font.get_ttfont())
def _init_with_ttfont(
self,
ttfont: TTFont,
**kwargs: Any,
) -> None:
self._fileobject = BytesIO()
ttfont.save(self._fileobject)
self._fileobject.seek(0)
self._ttfont = TTFont(self._fileobject, **kwargs)
self._kwargs = kwargs
def __enter__(
self,
) -> Font:
return self
def __exit__( # type: ignore
self,
e_type,
e_value,
e_traceback,
) -> None:
self.close()
def clone(
self,
) -> Font:
"""
Creates a new Font instance reading the same binary file.
"""
return Font(self._filepath or self._fileobject, **self._kwargs)
def close(
self,
) -> None:
"""
Close the wrapped TTFont instance.
"""
font = self.get_ttfont()
font.close()
@classmethod
def from_collection(
cls,
filepath: str | Path,
**kwargs: Any,
) -> list[Font]:
"""
Gets a list of Font objects from a font collection file (.ttc / .otc)
:param filepath: The filepath
:type filepath: str or pathlib.Path
:returns: A list of Font objects.
:rtype: list
"""
filepath = str(filepath)
fonts = []
with TTCollection(filepath) as font_collection:
fonts = [cls(font, **kwargs) for font in font_collection]
return fonts
def get_characters(
self,
*,
ignore_blank: bool = False,
) -> Generator[dict[str, Any]]:
"""
Gets the font characters.
:param ignore_blank: If True, characters without contours will not be returned.
:type ignore_blank: bool
:returns: The characters.
:rtype: generator of dicts
:raises TypeError: If it's not possible to find the 'best' unicode cmap dict.
"""
font = self.get_ttfont()
cmap = font.getBestCmap()
if cmap is None:
raise DataError("Unable to find the 'best' unicode cmap dict.")
glyfs = font.get("glyf")
for code, char_name in cmap.items():
code_hex = f"{code:04X}"
if 0 <= code < 0x110000:
char = chr(code)
else:
continue
if ascii.iscntrl(char):
continue
if glyfs and ignore_blank:
glyf = glyfs.get(char_name)
if glyf and glyf.numberOfContours == 0:
continue
unicode_name = unicodedata.name(char, None)
unicode_block_name = unicodedata.block(code)
unicode_script_tag = unicodedata.script(code)
unicode_script_name = unicodedata.script_name(unicode_script_tag)
yield {
"character": char,
"character_name": char_name,
"code": code,
"escape_sequence": f"\\u{code_hex}",
"html_code": f"&#{code};",
"unicode": f"U+{code_hex}",
"unicode_code": code,
"unicode_name": unicode_name,
"unicode_block_name": unicode_block_name,
"unicode_script_name": unicode_script_name,
"unicode_script_tag": unicode_script_tag,
}
def get_characters_count(
self,
*,
ignore_blank: bool = False,
) -> int:
"""
Gets the font characters count.
:param ignore_blank: If True, characters without contours will not be counted.
:type ignore_blank: bool
:returns: The characters count.
:rtype: int
"""
return len(list(self.get_characters(ignore_blank=ignore_blank)))
def _get_family_classification_items(
self,
class_id: int | str,
subclass_id: int | str,
) -> tuple[dict[str, Any], dict[str, Any]]:
classes_list = self._FAMILY_CLASSIFICATIONS["classes"]
class_item = find_item(
items_list=classes_list,
key=lambda item: item.get("id") == class_id,
)
subclasses_list = class_item.get("subclasses", [])
subclass_item = find_item(
items_list=subclasses_list,
key=lambda item: item.get("id") == subclass_id,
)
return (class_item, subclass_item)
def get_family_classification(
self,
) -> dict[str, Any] | None:
"""
Gets the font family classification info reading
the sFamilyClass field from the OS/2 table.
If the OS/2 table is not available None is returned.
:returns: A dictionary containing the font family classification info, e.g.
{
"full_name": "Sans Serif / Neo-grotesque Gothic",
"class_id": 8,
"class_name": "Sans Serif",
"subclass_id": 5,
"subclass_name": "Neo-grotesque Gothic",
}
:rtype: dict
"""
font = self.get_ttfont()
os2 = font.get("OS/2")
if not os2:
return None
class_id = os2.sFamilyClass >> 8 # (or // 256)
subclass_id = os2.sFamilyClass & 0xFF # (or % 256)
class_item, subclass_item = self._get_family_classification_items(
class_id=class_id,
subclass_id=subclass_id,
)
# class_id = class_item.get("id", "")
class_name = class_item.get("name", "")
# subclass_id = subclass_item.get("id", "")
subclass_name = subclass_item.get("name", "")
full_name = concat_names(class_name, subclass_name, separator=" / ")
return {
"full_name": full_name,
"class_id": class_id,
"class_name": class_name,
"subclass_id": subclass_id,
"subclass_name": subclass_name,
}
def get_family_name(
self,
) -> str:
"""
Gets the family name reading the name records with priority order (16, 21, 1).
:returns: The font family name.
:rtype: str
"""
return (
self.get_name(self.NAME_TYPOGRAPHIC_FAMILY_NAME)
or self.get_name(self.NAME_WWS_FAMILY_NAME)
or self.get_name(self.NAME_FAMILY_NAME)
or ""
)
def get_features(
self,
) -> list[dict[str, Any]]:
"""
Gets the font opentype features.
:returns: The features list.
:rtype: list of dict
"""
features_tags = self.get_features_tags()
return [
self._FEATURES_BY_TAG.get(features_tag, {}).copy()
for features_tag in features_tags
if features_tag in self._FEATURES_BY_TAG
]
def get_features_tags(
self,
) -> list[str]:
"""
Gets the font opentype features tags.
:returns: The features tags list.
:rtype: list of str
"""
font = self.get_ttfont()
features_tags = set()
for table_tag in ["GPOS", "GSUB"]:
if table_tag in font:
table = font[table_tag].table
try:
feature_record = table.FeatureList.FeatureRecord or []
except AttributeError:
feature_record = []
for feature in feature_record:
features_tags.add(feature.FeatureTag)
return sorted(features_tags)
def get_filename(
self,
*,
variable_suffix: str = "Variable",
variable_axes_tags: bool = True,
variable_axes_values: bool = False,
) -> str:
"""
Gets the filename to use for saving the font to file-system.
:param variable_suffix: The variable suffix, default "Variable"
:type variable_suffix: str
:param variable_axes_tags: The variable axes tags flag,
if True, the axes tags will be appended, eg '[wght,wdth]'
:type variable_axes_tags: bool
:param variable_axes_values: The variable axes values flag
if True, each axis values will be appended, eg '[wght(100,100,900),wdth(75,100,125)]'
:type variable_axes_values: bool
:returns: The filename.
:rtype: str
"""
if self.is_variable():
family_name = self.get_family_name()
family_name = remove_spaces(family_name)
subfamily_name = self.get_name(Font.NAME_SUBFAMILY_NAME) or ""
basename = family_name
# append subfamily name
if subfamily_name.lower() in ("bold", "bold italic", "italic"):
subfamily_name = remove_spaces(subfamily_name.lower().title())
basename = f"{basename}-{subfamily_name}"
# append variable suffix
variable_suffix = (variable_suffix or "").strip()
if variable_suffix:
if variable_suffix.lower() not in basename.lower():
basename = f"{basename}-{variable_suffix}"
# append axis tags stringified suffix, eg. [wdth,wght,slnt]
if variable_axes_tags:
axes = self.get_variable_axes() or []
axes_str_parts = []
for axis in axes:
axis_tag = axis["tag"]
axis_str = f"{axis_tag}"
if variable_axes_values:
axis_min_value = int(axis["min_value"])
axis_default_value = int(axis["default_value"])
axis_max_value = int(axis["max_value"])
axis_str += (
f"({axis_min_value},{axis_default_value},{axis_max_value})"
)
axes_str_parts.append(axis_str)
axes_str = ",".join(axes_str_parts)
axes_str = f"[{axes_str}]"
basename = f"{basename}{axes_str}"
else:
family_name = self.get_family_name()
family_name = remove_spaces(family_name)
style_name = self.get_style_name()
style_name = remove_spaces(style_name)
basename = concat_names(family_name, style_name, separator="-")
extension = self.get_format()
filename = f"{basename}.{extension}"
return filename
def get_fingerprint( # type: ignore
self,
*,
text: str = "",
):
"""
Gets the font fingerprint: an hash calculated from an image representation of the font.
Changing the text option affects the returned fingerprint.
:param text: The text used for generating the fingerprint,
default value: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789".
:type text: str
:returns: The fingerprint hash.
:rtype: imagehash.ImageHash
"""
import imagehash
text = text or "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
img = self.get_image(text=text, size=72)
img_size = img.size
img = img.resize((img_size[0] // 2, img_size[1] // 2))
img = img.resize((img_size[0], img_size[1]), Image.Resampling.NEAREST)
img = img.quantize(colors=8)
# img.show()
hash = imagehash.average_hash(img, hash_size=64)
return hash
def get_fingerprint_match( # type: ignore
self,
other: Font | str,
*,
tolerance: int = 10,
text: str = "",
):
"""
Gets the fingerprint match between this font and another one.
by checking if their fingerprints are equal (difference <= tolerance).
:param other: The other font, can be either a filepath or a Font instance.
:type other: str or Font
:param tolerance: The diff tolerance, default 3.
:type tolerance: int
:param text: The text used for generating the fingerprint,
default value: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789".
:type text: str
:returns: A tuple containing the match info (match, diff, hash, other_hash).
:rtype: tuple
"""
other_font = None
if isinstance(other, str):
other_font = Font(other)
elif isinstance(other, Font):
other_font = other
else:
other_type = type(other).__name__
raise ArgumentError(
"Invalid other filepath/font: expected str or Font instance, "
f"found '{other_type}'."
)
hash = self.get_fingerprint(text=text)
other_hash = other_font.get_fingerprint(text=text)
diff = hash - other_hash
match = diff <= tolerance
match = match and self.is_variable() == other_font.is_variable()
return (match, diff, hash, other_hash)
def get_format(
self,
*,
ignore_flavor: bool = False,
) -> str:
"""
Gets the font format: otf, ttf, woff, woff2.
:param ignore_flavor: If True, the original format without compression will be returned.
:type ignore_flavor: bool
:returns: The format.
:rtype: str
"""
font = self.get_ttfont()
version = font.sfntVersion
flavor = font.flavor
format_ = ""
if flavor in [self.FORMAT_WOFF, self.FORMAT_WOFF2] and not ignore_flavor:
format_ = str(flavor)
elif version == "OTTO" and ("CFF " in font or "CFF2" in font):
format_ = self.FORMAT_OTF
elif version == "\0\1\0\0":
format_ = self.FORMAT_TTF
elif version == "wOFF":
format_ = self.FORMAT_WOFF
elif version == "wOF2":
format_ = self.FORMAT_WOFF2
if not format_:
raise DataError("Unable to get the font format.")
return format_
def get_glyphs(
self,
) -> Generator[dict[str, Any]]:
"""
Gets the font glyphs and their own composition.
:returns: The glyphs.
:rtype: generator of dicts
"""
font = self.get_ttfont()
glyfs = font["glyf"]
glyphset = font.getGlyphSet()
for name in glyphset.keys():
glyf = glyfs[name]
yield {
"name": name,
"components_names": glyf.getComponentNames(glyfs),
}
def get_glyphs_count(
self,
) -> int:
"""
Gets the font glyphs count.
:returns: The glyphs count.
:rtype: int
"""
font = self.get_ttfont()
glyphset = font.getGlyphSet()
count = len(glyphset)
return count
def get_image( # type: ignore
self,
*,
text: str,
size: int,
color: tuple[int, int, int, int] = (0, 0, 0, 255),
background_color: tuple[int, int, int, int] = (255, 255, 255, 255),
):
"""
Gets an image representation of the font rendering
some text using the given options.
:param text: The text rendered in the image
:type text: str
:param size: The font size
:type size: int
:param color: The text color
:type color: tuple
:param background_color: The background color
:type background_color: tuple
:returns: The image.
:rtype: PIL.Image
"""
with tempfile.TemporaryDirectory() as dest:
filepath = self.save(dest)
img = Image.new("RGBA", (2, 2), background_color)
draw = ImageDraw.Draw(img)
img_font = ImageFont.truetype(filepath, size)
img_bbox = draw.textbbox((0, 0), text, font=img_font)
img_width = img_bbox[2] - img_bbox[0]
img_height = img_bbox[3] - img_bbox[1]
img_size = (img_width, img_height)
img = img.resize(img_size)
draw = ImageDraw.Draw(img)
draw.text((-img_bbox[0], -img_bbox[1]), text, font=img_font, fill=color)
del img_font
return img
def get_italic_angle(
self,
) -> dict[str, Any] | None:
"""
Gets the font italic angle.
:returns: The angle value including backslant, italic and roman flags.
:rtype: dict or None
"""
font = self.get_ttfont()
post = font.get("post")
if not post:
return None
italic_angle_value = post.italicAngle
italic_angle = {
"backslant": italic_angle_value > 0,
"italic": italic_angle_value < 0,
"roman": italic_angle_value == 0,
"value": italic_angle_value,
}
return italic_angle
@classmethod
def _get_name_id(
cls,
key: int | str,
) -> int:
if isinstance(key, int):
return key
elif isinstance(key, str):
return int(cls._NAMES_BY_KEY[key]["id"])
else:
key_type = type(key).__name__
raise ArgumentError(
f"Invalid key type, expected int or str, found '{key_type}'."
)
def get_name(
self,
key: str,
) -> str | None:
"""
Gets the name by its identifier from the font name table.
:param key: The name id or key (eg. 'family_name')
:type key: int or str
:returns: The name.
:rtype: str or None
:raises KeyError: if the key is not a valid name key/id
"""
font = self.get_ttfont()
name_id = self._get_name_id(key)
name_table = font["name"]
name = name_table.getName(name_id, **self._NAMES_MAC_IDS)