-
Notifications
You must be signed in to change notification settings - Fork 3.6k
/
font-patcher
executable file
·2216 lines (1990 loc) · 120 KB
/
font-patcher
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
#!/usr/bin/env python
# coding=utf8
# Nerd Fonts Version: 3.3.0
# Script version is further down
from __future__ import absolute_import, print_function, unicode_literals
# Change the script version when you edit this script:
script_version = "4.16.1"
version = "3.3.0"
projectName = "Nerd Fonts"
projectNameAbbreviation = "NF"
projectNameSingular = projectName[:-1]
import sys
import re
import os
import argparse
from argparse import RawTextHelpFormatter
import errno
import subprocess
import json
from enum import Enum
import logging
try:
import configparser
except ImportError:
sys.exit(projectName + ": configparser module is probably not installed. Try `pip install configparser` or equivalent")
try:
import psMat
import fontforge
except ImportError:
sys.exit(
projectName + (
": FontForge module could not be loaded. Try installing fontforge python bindings "
"[e.g. on Linux Debian or Ubuntu: `sudo apt install fontforge python3-fontforge`]"
)
)
sys.path.insert(0, os.path.abspath(os.path.dirname(sys.argv[0])) + '/bin/scripts/name_parser/')
try:
from FontnameParser import FontnameParser
from FontnameTools import FontnameTools
FontnameParserOK = True
except ImportError:
FontnameParserOK = False
class TableHEADWriter:
""" Access to the HEAD table without external dependencies """
def getlong(self, pos = None):
""" Get four bytes from the font file as integer number """
if pos:
self.goto(pos)
return (ord(self.f.read(1)) << 24) + (ord(self.f.read(1)) << 16) + (ord(self.f.read(1)) << 8) + ord(self.f.read(1))
def getshort(self, pos = None):
""" Get two bytes from the font file as integer number """
if pos:
self.goto(pos)
return (ord(self.f.read(1)) << 8) + ord(self.f.read(1))
def putlong(self, num, pos = None):
""" Put number as four bytes into font file """
if pos:
self.goto(pos)
self.f.write(bytearray([(num >> 24) & 0xFF, (num >> 16) & 0xFF ,(num >> 8) & 0xFF, num & 0xFF]))
self.modified = True
def putshort(self, num, pos = None):
""" Put number as two bytes into font file """
if pos:
self.goto(pos)
self.f.write(bytearray([(num >> 8) & 0xFF, num & 0xFF]))
self.modified = True
def calc_checksum(self, start, end, checksum = 0):
""" Calculate a font table checksum, optionally ignoring another embedded checksum value (for table 'head') """
self.f.seek(start)
for i in range(start, end - 4, 4):
checksum += self.getlong()
checksum &= 0xFFFFFFFF
i += 4
extra = 0
for j in range(4):
extra = extra << 8
if i + j <= end:
extra += ord(self.f.read(1))
checksum = (checksum + extra) & 0xFFFFFFFF
return checksum
def find_table(self, tablenames, idx):
""" Search all tables for one of the tables in tablenames and store its metadata """
# Use font with index idx if this is a font collection file
self.f.seek(0, 0)
tag = self.f.read(4)
if tag == b'ttcf':
self.f.seek(2*2, 1)
self.num_fonts = self.getlong()
if (idx >= self.num_fonts):
raise Exception('Trying to access subfont index {} but have only {} fonts'.format(idx, num_fonts))
for _ in range(idx + 1):
offset = self.getlong()
self.f.seek(offset, 0)
elif idx != 0:
raise Exception('Trying to access subfont but file is no collection')
else:
self.f.seek(0, 0)
self.num_fonts = 1
self.f.seek(4, 1)
numtables = self.getshort()
self.f.seek(3*2, 1)
for i in range(numtables):
tab_name = self.f.read(4)
self.tab_check_offset = self.f.tell()
self.tab_check = self.getlong()
self.tab_offset = self.getlong()
self.tab_length = self.getlong()
if tab_name in tablenames:
return True
return False
def find_head_table(self, idx):
""" Search all tables for the HEAD table and store its metadata """
# Use font with index idx if this is a font collection file
found = self.find_table([ b'head' ], idx)
if not found:
raise Exception('No HEAD table found in font idx {}'.format(idx))
def goto(self, where):
""" Go to a named location in the file or to the specified index """
if isinstance(where, str):
positions = {'checksumAdjustment': 2+2+4,
'flags': 2+2+4+4+4,
'lowestRecPPEM': 2+2+4+4+4+2+2+8+8+2+2+2+2+2,
'avgWidth': 2,
}
where = self.tab_offset + positions[where]
self.f.seek(where)
def calc_full_checksum(self, check = False):
""" Calculate the whole file's checksum """
self.f.seek(0, 2)
self.end = self.f.tell()
full_check = self.calc_checksum(0, self.end, (-self.checksum_adj) & 0xFFFFFFFF)
if check and (0xB1B0AFBA - full_check) & 0xFFFFFFFF != self.checksum_adj:
sys.exit("Checksum of whole font is bad")
return full_check
def calc_table_checksum(self, check = False):
tab_check_new = self.calc_checksum(self.tab_offset, self.tab_offset + self.tab_length - 1, (-self.checksum_adj) & 0xFFFFFFFF)
if check and tab_check_new != self.tab_check:
sys.exit("Checksum of 'head' in font is bad")
return tab_check_new
def reset_table_checksum(self):
new_check = self.calc_table_checksum()
self.putlong(new_check, self.tab_check_offset)
def reset_full_checksum(self):
new_adj = (0xB1B0AFBA - self.calc_full_checksum()) & 0xFFFFFFFF
self.putlong(new_adj, 'checksumAdjustment')
def close(self):
self.f.close()
def __init__(self, filename):
self.modified = False
self.f = open(filename, 'r+b')
self.find_head_table(0)
self.flags = self.getshort('flags')
self.lowppem = self.getshort('lowestRecPPEM')
self.checksum_adj = self.getlong('checksumAdjustment')
def check_panose_monospaced(font):
""" Check if the font's Panose flags say it is monospaced """
# https://forum.high-logic.com/postedfiles/Panose.pdf
panose = list(font.os2_panose)
if panose[0] < 2 or panose[0] > 5:
return -1 # invalid Panose info
panose_mono = ((panose[0] == 2 and panose[3] == 9) or
(panose[0] == 3 and panose[3] == 3))
return 1 if panose_mono else 0
def panose_check_to_text(value, panose = False):
""" Convert value from check_panose_monospaced() to human readable string """
if value == 0:
return "Panose says \"not monospaced\""
if value == 1:
return "Panose says \"monospaced\""
return "Panose is invalid" + (" ({})".format(list(panose)) if panose else "")
def panose_proportion_to_text(value):
""" Interpret a Panose proportion value (4th value) for family 2 (latin text) """
proportion = {
0: "Any", 1: "No Fit", 2: "Old Style", 3: "Modern", 4: "Even Width",
5: "Extended", 6: "Condensed", 7: "Very Extended", 8: "Very Condensed",
9: "Monospaced" }
return proportion.get(value, "??? {}".format(value))
def is_monospaced(font):
""" Check if a font is probably monospaced """
# Some fonts lie (or have not any Panose flag set), spot check monospaced:
width = -1
width_mono = True
for glyph in [ 0x49, 0x4D, 0x57, 0x61, 0x69, 0x6d, 0x2E ]: # wide and slim glyphs 'I', 'M', 'W', 'a', 'i', 'm', '.'
if not glyph in font:
# A 'strange' font, believe Panose
return (check_panose_monospaced(font) == 1, None)
# print(" -> {} {}".format(glyph, font[glyph].width))
if width < 0:
width = font[glyph].width
continue
if font[glyph].width != width:
# Exception for fonts like Code New Roman Regular or Hermit Light/Bold:
# Allow small 'i' and dot to be smaller than normal
# I believe the source fonts are buggy
if glyph in [ 0x69, 0x2E ]:
if width > font[glyph].width:
continue
(xmin, _, xmax, _) = font[glyph].boundingBox()
if width > xmax - xmin:
continue
width_mono = False
break
# We believe our own check more then Panose ;-D
return (width_mono, None if width_mono else glyph)
def force_panose_monospaced(font):
""" Forces the Panose flag to monospaced if they are unset or halfway ok already """
# For some Windows applications (e.g. 'cmd'), they seem to honour the Panose table
# https://forum.high-logic.com/postedfiles/Panose.pdf
panose = list(font.os2_panose)
if panose[0] == 0: # 0 (1st value) = family kind; 0 = any (default)
panose[0] = 2 # make kind latin text and display
logger.info("Setting Panose 'Family Kind' to 'Latin Text and Display' (was 'Any')")
font.os2_panose = tuple(panose)
if panose[0] == 2 and panose[3] != 9:
logger.info("Setting Panose 'Proportion' to 'Monospaced' (was '%s')", panose_proportion_to_text(panose[3]))
panose[3] = 9 # 3 (4th value) = proportion; 9 = monospaced
font.os2_panose = tuple(panose)
def get_advance_width(font, extended, minimum):
""" Get the maximum/minimum advance width in the extended(?) range """
width = 0
if not extended:
r = range(0x021, 0x07e)
else:
r = range(0x07f, 0x17f)
for glyph in r:
if not glyph in font:
continue
if glyph in range(0x7F, 0xBF):
continue # ignore special characters like '1/4' etc
if width == 0:
width = font[glyph].width
continue
if not minimum and width < font[glyph].width:
width = font[glyph].width
elif minimum and width > font[glyph].width:
width = font[glyph].width
return width
def report_advance_widths(font):
return "Advance widths (base/extended): {} - {} / {} - {}".format(
get_advance_width(font, False, True), get_advance_width(font, False, False),
get_advance_width(font, True, True), get_advance_width(font, True, False))
def get_btb_metrics(font):
""" Get the baseline to baseline distance for all three metrics """
hhea_height = font.hhea_ascent - font.hhea_descent
typo_height = font.os2_typoascent - font.os2_typodescent
win_height = font.os2_winascent + font.os2_windescent
win_gap = max(0, font.hhea_linegap - win_height + hhea_height)
hhea_btb = hhea_height + font.hhea_linegap
typo_btb = typo_height + font.os2_typolinegap
win_btb = win_height + win_gap
return (hhea_btb, typo_btb, win_btb, win_gap)
def get_metrics_names():
""" Helper to get the line metrics names consistent """
return ['HHEA','TYPO','WIN']
def get_old_average_x_width(font):
""" Determine xAvgCharWidth of the OS/2 table """
# Fontforge can not create fonts with old (i.e. prior to OS/2 version 3)
# table values, but some very old applications do need them sometimes
# https://learn.microsoft.com/en-us/typography/opentype/spec/os2#xavgcharwidth
s = 0
weights = {
'a': 64, 'b': 14, 'c': 27, 'd': 35, 'e': 100, 'f': 20, 'g': 14, 'h': 42, 'i': 63,
'j': 3, 'k': 6, 'l': 35, 'm': 20, 'n': 56, 'o': 56, 'p': 17, 'q': 4, 'r': 49,
's': 56, 't': 71, 'u': 31, 'v': 10, 'w': 18, 'x': 3, 'y': 18, 'z': 2, 32: 166,
}
for g in weights:
if g not in font:
logger.critical("Can not determine ancient style xAvgCharWidth")
sys.exit(1)
s += font[g].width * weights[g]
return int(s / 1000)
def create_filename(fonts):
""" Determine filename from font object(s) """
# Only consider the standard (i.e. English-US) names
sfnt = { k: v for l, k, v in fonts[0].sfnt_names if l == 'English (US)' }
sfnt_pfam = sfnt.get('Preferred Family', sfnt['Family'])
sfnt_psubfam = sfnt.get('Preferred Styles', sfnt['SubFamily'])
if len(fonts) > 1:
return sfnt_pfam
if len(sfnt_psubfam) > 0:
sfnt_psubfam = '-' + sfnt_psubfam
return (sfnt_pfam + sfnt_psubfam).replace(' ', '')
def fetch_glyphnames():
""" Read the glyphname database and put it into a dictionary """
try:
glyphnamefile = os.path.abspath(os.path.dirname(sys.argv[0])) + '/glyphnames.json'
with open(glyphnamefile, 'r') as f:
namelist = json.load(f)
return { int(v['code'], 16): k for k, v in namelist.items() if 'code' in v }
except Exception as error:
logger.warning("Can not read glyphnames file (%s)", repr(error))
return {}
class font_patcher:
def __init__(self, args, conf):
self.args = args # class 'argparse.Namespace'
self.sym_font_args = []
self.config = conf # class 'configparser.ConfigParser'
self.sourceFont = None # class 'fontforge.font'
self.patch_set = None # class 'list'
self.font_dim = None # class 'dict'
self.font_extrawide = False
self.source_monospaced = None # Later True or False
self.symbolsonly = False # Are we generating the SymbolsOnly font?
self.onlybitmaps = 0
self.essential = set()
self.xavgwidth = [] # list of ints
self.glyphnames = fetch_glyphnames()
def patch(self, font):
self.sourceFont = font
self.setup_version()
self.assert_monospace()
self.remove_ligatures()
self.manipulate_hints()
self.get_essential_references()
self.get_sourcefont_dimensions()
self.setup_patch_set()
self.improve_line_dimensions()
self.sourceFont.encoding = 'UnicodeFull' # Update the font encoding to ensure that the Unicode glyphs are available
self.onlybitmaps = self.sourceFont.onlybitmaps # Fetch this property before adding outlines. NOTE self.onlybitmaps initialized and never used
if self.args.single:
# Force width to be equal on all glyphs to ensure the font is considered monospaced on Windows.
# This needs to be done on all characters, as some information seems to be lost from the original font file.
self.set_sourcefont_glyph_widths()
# For very wide (almost square or wider) fonts we do not want to generate 2 cell wide Powerline glyphs
if self.font_dim['height'] * 1.8 < self.font_dim['width'] * 2:
logger.warning("Very wide and short font, disabling 2 cell Powerline glyphs")
self.font_extrawide = True
# Prevent opening and closing the fontforge font. Makes things faster when patching
# multiple ranges using the same symbol font.
PreviousSymbolFilename = ""
symfont = None
if not os.path.isdir(self.args.glyphdir):
logger.critical("Can not find symbol glyph directory %s "
"(probably you need to download the src/glyphs/ directory?)", self.args.glyphdir)
sys.exit(1)
if self.args.dry_run:
return
for patch in self.patch_set:
if patch['Enabled']:
if PreviousSymbolFilename != patch['Filename']:
# We have a new symbol font, so close the previous one if it exists
if symfont:
symfont.close()
symfont = None
symfont_file = os.path.join(self.args.glyphdir, patch['Filename'])
if not os.path.isfile(symfont_file):
logger.critical("Can not find symbol source for '%s' (i.e. %s)",
patch['Name'], symfont_file)
sys.exit(1)
if not os.access(symfont_file, os.R_OK):
logger.critical("Can not open symbol source for '%s' (i.e. %s)",
patch['Name'], symfont_file)
sys.exit(1)
symfont = fontforge.open(symfont_file)
symfont.encoding = 'UnicodeFull'
# Match the symbol font size to the source font size
symfont.em = self.sourceFont.em
PreviousSymbolFilename = patch['Filename']
# If patch table doesn't include a source start, re-use the symbol font values
SrcStart = patch['SrcStart']
if not SrcStart:
SrcStart = patch['SymStart']
self.copy_glyphs(SrcStart, symfont, patch['SymStart'], patch['SymEnd'], patch['Exact'], patch['ScaleRules'], patch['Name'], patch['Attributes'])
if symfont:
symfont.close()
# The grave accent and fontforge:
# If the type is 'auto' fontforge changes it to 'mark' on export.
# We can not prevent this. So set it to 'baseglyph' instead, as
# that resembles the most common expectations.
# This is not needed with fontforge March 2022 Release anymore.
if "grave" in self.sourceFont:
self.sourceFont["grave"].glyphclass="baseglyph"
def generate(self, sourceFonts):
sourceFont = sourceFonts[0]
# the `PfEd-comments` flag is required for Fontforge to save '.comment' and '.fontlog'.
if int(fontforge.version()) >= 20201107:
gen_flags = (str('opentype'), str('PfEd-comments'), str('no-FFTM-table'))
else:
gen_flags = (str('opentype'), str('PfEd-comments'))
if len(sourceFonts) > 1:
layer = None
# use first non-background layer
for l in sourceFont.layers:
if not sourceFont.layers[l].is_background:
layer = l
break
outfile = os.path.normpath(os.path.join(
sanitize_filename(self.args.outputdir, True),
sanitize_filename(create_filename(sourceFonts)) + ".ttc"))
sourceFonts[0].generateTtc(outfile, sourceFonts[1:], flags=gen_flags, layer=layer)
message = " Generated {} fonts\n \\===> '{}'".format(len(sourceFonts), outfile)
else:
fontname = create_filename(sourceFonts)
if not fontname:
fontname = sourceFont.cidfontname
outfile = os.path.normpath(os.path.join(
sanitize_filename(self.args.outputdir, True),
sanitize_filename(fontname) + self.args.extension))
bitmaps = str()
if len(sourceFont.bitmapSizes):
logger.debug("Preserving bitmaps %s", repr(sourceFont.bitmapSizes))
bitmaps = str('otf') # otf/ttf, both is bf_ttf
if self.args.dry_run:
logger.debug("=====> Filename '%s'", outfile)
return
sourceFont.generate(outfile, bitmap_type=bitmaps, flags=gen_flags)
message = " {}\n \\===> '{}'".format(sourceFont.fullname, outfile)
# Adjust flags that can not be changed via fontforge
if re.search(r'\.[ot]tf$', self.args.font, re.IGNORECASE) and re.search(r'\.[ot]tf$', outfile, re.IGNORECASE):
if not os.path.isfile(outfile) or os.path.getsize(outfile) < 1:
logger.critical("Something went wrong and Fontforge did not generate the new font - look for messages above")
sys.exit(1)
try:
source_font = TableHEADWriter(self.args.font)
dest_font = TableHEADWriter(outfile)
for idx in range(source_font.num_fonts):
logger.debug("Tweaking %d/%d", idx + 1, source_font.num_fonts)
xwidth_s = ''
xwidth = self.xavgwidth[idx] if len(self.xavgwidth) > idx else None
if isinstance(xwidth, int):
if isinstance(xwidth, bool) and xwidth:
source_font.find_table([b'OS/2'], idx)
xwidth = source_font.getshort('avgWidth')
xwidth_s = ' (copied from source)'
dest_font.find_table([b'OS/2'], idx)
d_xwidth = dest_font.getshort('avgWidth')
if d_xwidth != xwidth:
logger.debug("Changing xAvgCharWidth from %d to %d%s", d_xwidth, xwidth, xwidth_s)
dest_font.putshort(xwidth, 'avgWidth')
dest_font.reset_table_checksum()
source_font.find_head_table(idx)
dest_font.find_head_table(idx)
if source_font.flags & 0x08 == 0 and dest_font.flags & 0x08 != 0:
logger.debug("Changing flags from 0x%X to 0x%X", dest_font.flags, dest_font.flags & ~0x08)
dest_font.putshort(dest_font.flags & ~0x08, 'flags') # clear 'ppem_to_int'
if source_font.lowppem != dest_font.lowppem:
logger.debug("Changing lowestRecPPEM from %d to %d", dest_font.lowppem, source_font.lowppem)
dest_font.putshort(source_font.lowppem, 'lowestRecPPEM')
if dest_font.modified:
dest_font.reset_table_checksum()
if dest_font.modified:
dest_font.reset_full_checksum()
except Exception as error:
logger.error("Can not handle font flags (%s)", repr(error))
finally:
try:
source_font.close()
dest_font.close()
except:
pass
if self.args.is_variable:
logger.critical("Source font is a variable open type font (VF) and the patch results will most likely not be what you want")
print(message)
if self.args.postprocess:
subprocess.call([self.args.postprocess, outfile])
print("\n")
logger.info("Post Processed: %s", outfile)
def setup_name_backup(self, font):
""" Store the original font names to be able to rename the font multiple times """
font.persistent = {
"fontname": font.fontname,
"fullname": font.fullname,
"familyname": font.familyname,
}
def setup_font_names(self, font):
font.fontname = font.persistent["fontname"]
if isinstance(font.persistent["fullname"], str):
font.fullname = font.persistent["fullname"]
if isinstance(font.persistent["familyname"], str):
font.familyname = font.persistent["familyname"]
verboseAdditionalFontNameSuffix = ""
additionalFontNameSuffix = ""
if not self.args.complete:
# NOTE not all symbol fonts have appended their suffix here
if self.args.fontawesome:
additionalFontNameSuffix += " A"
verboseAdditionalFontNameSuffix += " Plus Font Awesome"
if self.args.fontawesomeextension:
additionalFontNameSuffix += " AE"
verboseAdditionalFontNameSuffix += " Plus Font Awesome Extension"
if self.args.octicons:
additionalFontNameSuffix += " O"
verboseAdditionalFontNameSuffix += " Plus Octicons"
if self.args.powersymbols:
additionalFontNameSuffix += " PS"
verboseAdditionalFontNameSuffix += " Plus Power Symbols"
if self.args.codicons:
additionalFontNameSuffix += " C"
verboseAdditionalFontNameSuffix += " Plus Codicons"
if self.args.pomicons:
additionalFontNameSuffix += " P"
verboseAdditionalFontNameSuffix += " Plus Pomicons"
if self.args.fontlogos:
additionalFontNameSuffix += " L"
verboseAdditionalFontNameSuffix += " Plus Font Logos"
if self.args.material:
additionalFontNameSuffix += " MDI"
verboseAdditionalFontNameSuffix += " Plus Material Design Icons"
if self.args.weather:
additionalFontNameSuffix += " WEA"
verboseAdditionalFontNameSuffix += " Plus Weather Icons"
# add mono signifier to beginning of name suffix
if self.args.single:
variant_abbrev = "M"
variant_full = " Mono"
elif self.args.nonmono and not self.symbolsonly:
variant_abbrev = "P"
variant_full = " Propo"
else:
variant_abbrev = ""
variant_full = ""
ps_suffix = projectNameAbbreviation + variant_abbrev + additionalFontNameSuffix
# add 'Nerd Font' to beginning of name suffix
verboseAdditionalFontNameSuffix = " " + projectNameSingular + variant_full + verboseAdditionalFontNameSuffix
additionalFontNameSuffix = " " + projectNameSingular + variant_full + additionalFontNameSuffix
if FontnameParserOK and self.args.makegroups > 0:
user_supplied_name = False # User supplied names are kept unchanged
if not isinstance(self.args.force_name, str):
use_fullname = isinstance(font.fullname, str) # Usually the fullname is better to parse
# Use fullname if it is 'equal' to the fontname
if font.fullname:
use_fullname |= font.fontname.lower() == FontnameTools.postscript_char_filter(font.fullname).lower()
# Use fullname for any of these source fonts (that are impossible to disentangle from the fontname, we need the blanks)
for hit in [ 'Meslo' ]:
use_fullname |= font.fontname.lower().startswith(hit.lower())
parser_name = font.fullname if use_fullname else font.fontname
# Gohu fontnames hide the weight, but the file names are ok...
if parser_name.startswith('Gohu'):
parser_name = os.path.splitext(os.path.basename(self.args.font))[0]
else:
if self.args.force_name == 'full':
parser_name = font.fullname
elif self.args.force_name == 'postscript':
parser_name = font.fontname
elif self.args.force_name == 'filename':
parser_name = os.path.basename(font.path).split('.')[0]
else:
parser_name = self.args.force_name
user_supplied_name = True
if not isinstance(parser_name, str) or len(parser_name) < 1:
logger.critical("Specified --name not usable because the name will be empty")
sys.exit(2)
n = FontnameParser(parser_name, logger)
if not n.parse_ok:
logger.warning("Have only minimal naming information, check resulting name. Maybe specify --makegroups 0")
n.drop_for_powerline()
n.enable_short_families(not user_supplied_name, self.args.makegroups in [ 2, 3, 5, 6, ], self.args.makegroups in [ 3, 6, ])
if not n.set_expect_no_italic(self.args.noitalic):
logger.critical("Detected 'Italic' slant but --has-no-italic specified")
sys.exit(1)
# All the following stuff is ignored in makegroups-mode
# basically split the font name around the dash "-" to get the fontname and the style (e.g. Bold)
# this does not seem very reliable so only use the style here as a fallback if the font does not
# have an internal style defined (in sfnt_names)
# using '([^-]*?)' to get the item before the first dash "-"
# using '([^-]*(?!.*-))' to get the item after the last dash "-"
fontname, fallbackStyle = re.match("^([^-]*).*?([^-]*(?!.*-))$", font.fontname).groups()
# dont trust 'font.familyname'
familyname = fontname
# fullname (filename) can always use long/verbose font name, even in windows
if font.fullname != None:
fullname = font.fullname + verboseAdditionalFontNameSuffix
else:
fullname = font.cidfontname + verboseAdditionalFontNameSuffix
fontname = fontname + additionalFontNameSuffix.replace(" ", "")
# let us try to get the 'style' from the font info in sfnt_names and fallback to the
# parse fontname if it fails:
try:
# search tuple:
subFamilyTupleIndex = [x[1] for x in font.sfnt_names].index("SubFamily")
# String ID is at the second index in the Tuple lists
sfntNamesStringIDIndex = 2
# now we have the correct item:
subFamily = font.sfnt_names[subFamilyTupleIndex][sfntNamesStringIDIndex]
except IndexError:
sys.stderr.write("{}: Could not find 'SubFamily' for given font, falling back to parsed fontname\n".format(projectName))
subFamily = fallbackStyle
# some fonts have inaccurate 'SubFamily', if it is Regular let us trust the filename more:
if subFamily == "Regular" and len(fallbackStyle):
subFamily = fallbackStyle
# This is meant to cover the case where the SubFamily is "Italic" and the filename is *-BoldItalic.
if len(subFamily) < len(fallbackStyle):
subFamily = fallbackStyle
if len(subFamily) == 0:
subFamily = "Regular"
familyname += " " + projectNameSingular + variant_full
# Don't truncate the subfamily to keep fontname unique. MacOS treats fonts with
# the same name as the same font, even if subFamily is different. Make sure to
# keep the resulting fontname (PostScript name) valid by removing spaces.
fontname += '-' + subFamily.replace(' ', '')
# rename font
#
# comply with SIL Open Font License (OFL)
reservedFontNameReplacements = {
'source' : 'sauce',
'Source' : 'Sauce',
'Bitstream Vera Sans Mono' : 'Bitstrom Wera',
'BitstreamVeraSansMono' : 'BitstromWera',
'bitstream vera sans mono' : 'bitstrom wera',
'bitstreamverasansmono' : 'bitstromwera',
'hermit' : 'hurmit',
'Hermit' : 'Hurmit',
'hasklig' : 'hasklug',
'Hasklig' : 'Hasklug',
'Share' : 'Shure',
'share' : 'shure',
'IBMPlex' : 'Blex',
'ibmplex' : 'blex',
'IBM-Plex' : 'Blex',
'IBM Plex' : 'Blex',
'terminus' : 'terminess',
'Terminus' : 'Terminess',
'liberation' : 'literation',
'Liberation' : 'Literation',
'iAWriter' : 'iMWriting',
'iA Writer' : 'iM Writing',
'iA-Writer' : 'iM-Writing',
'Anka/Coder' : 'AnaConder',
'anka/coder' : 'anaconder',
'Cascadia Code' : 'Caskaydia Cove',
'cascadia code' : 'caskaydia cove',
'CascadiaCode' : 'CaskaydiaCove',
'cascadiacode' : 'caskaydiacove',
'Cascadia Mono' : 'Caskaydia Mono',
'cascadia mono' : 'caskaydia mono',
'CascadiaMono' : 'CaskaydiaMono',
'cascadiamono' : 'caskaydiamono',
'Fira Mono' : 'Fura Mono',
'Fira Sans' : 'Fura Sans',
'FiraMono' : 'FuraMono',
'FiraSans' : 'FuraSans',
'fira mono' : 'fura mono',
'fira sans' : 'fura sans',
'firamono' : 'furamono',
'firasans' : 'furasans',
'IntelOneMono' : 'IntoneMono',
'IntelOne Mono' : 'Intone Mono',
'Intel One Mono' : 'Intone Mono',
}
# remove overly verbose font names
# particularly regarding Powerline sourced Fonts (https://github.com/powerline/fonts)
additionalFontNameReplacements = {
'for Powerline': '',
'ForPowerline': ''
}
additionalFontNameReplacements2 = {
'Powerline': ''
}
projectInfo = (
"Patched with '" + projectName + " Patcher' (https://github.com/ryanoasis/nerd-fonts)\n\n"
"* Website: https://www.nerdfonts.com\n"
"* Version: " + version + "\n"
"* Development Website: https://github.com/ryanoasis/nerd-fonts\n"
"* Changelog: https://github.com/ryanoasis/nerd-fonts/blob/-/changelog.md"
)
familyname = replace_font_name(familyname, reservedFontNameReplacements)
fullname = replace_font_name(fullname, reservedFontNameReplacements)
fontname = replace_font_name(fontname, reservedFontNameReplacements)
familyname = replace_font_name(familyname, additionalFontNameReplacements)
fullname = replace_font_name(fullname, additionalFontNameReplacements)
fontname = replace_font_name(fontname, additionalFontNameReplacements)
familyname = replace_font_name(familyname, additionalFontNameReplacements2)
fullname = replace_font_name(fullname, additionalFontNameReplacements2)
fontname = replace_font_name(fontname, additionalFontNameReplacements2)
if self.args.makegroups < 0:
logger.warning("Renaming disabled! Make sure to comply with font license, esp RFN clause!")
elif not (FontnameParserOK and self.args.makegroups > 0):
# replace any extra whitespace characters:
font.familyname = " ".join(familyname.split())
font.fullname = " ".join(fullname.split())
font.fontname = " ".join(fontname.split())
font.appendSFNTName(str('English (US)'), str('Preferred Family'), font.familyname)
font.appendSFNTName(str('English (US)'), str('Family'), font.familyname)
font.appendSFNTName(str('English (US)'), str('Compatible Full'), font.fullname)
font.appendSFNTName(str('English (US)'), str('SubFamily'), subFamily)
else:
# Add Nerd Font suffix unless user specifically asked for some excplicit name via --name
if not user_supplied_name:
short_family = projectNameAbbreviation + variant_abbrev if self.args.makegroups >= 4 else projectNameSingular + variant_full
# inject_suffix(family, ps_fontname, short_family)
n.inject_suffix(verboseAdditionalFontNameSuffix, ps_suffix, short_family)
n.rename_font(font)
font.comment = projectInfo
font.fontlog = projectInfo
def setup_version(self):
""" Add the Nerd Font version to the original version """
# print("Version was {}".format(sourceFont.version))
if self.sourceFont.version != None:
self.sourceFont.version += ";" + projectName + " " + version
else:
self.sourceFont.version = str(self.sourceFont.cidversion) + ";" + projectName + " " + version
self.sourceFont.sfntRevision = None # Auto-set (refreshed) by fontforge
self.sourceFont.appendSFNTName(str('English (US)'), str('Version'), "Version " + self.sourceFont.version)
# The Version SFNT name is later reused by the NameParser for UniqueID
# print("Version now is {}".format(sourceFont.version))
def remove_ligatures(self):
# let's deal with ligatures (mostly for monospaced fonts)
# Usually removes 'fi' ligs that end up being only one cell wide, and 'ldot'
if self.args.removeligatures:
logger.info("Removing ligatures from configfile `Subtables` section")
if 'Subtables' not in self.config:
logger.warning("No ligature data (config file missing?)")
return
ligature_subtables = json.loads(self.config.get('Subtables', 'ligatures', fallback='[]'))
for subtable in ligature_subtables:
logger.debug("Removing subtable: %s", subtable)
try:
self.sourceFont.removeLookupSubtable(subtable)
logger.debug("Successfully removed subtable: %s", subtable)
except Exception:
logger.error("Failed to remove subtable: %s", subtable)
def manipulate_hints(self):
""" Redo the hinting on some problematic glyphs """
if 'Hinting' not in self.config:
return
redo = json.loads(self.config.get('Hinting', 're_hint', fallback='[]'))
if not len(redo):
return
logger.debug("Working on {} rehinting rules (this may create a lot of fontforge warnings)".format(len(redo)))
count = 0
for gname in self.sourceFont:
for regex in redo:
if re.fullmatch(regex, gname):
glyph = self.sourceFont[gname]
glyph.autoHint()
glyph.autoInstr()
count += 1
break
logger.info("Rehinted {} glyphs".format(count))
def assert_monospace(self):
# Check if the sourcefont is monospaced
width_mono, offending_char = is_monospaced(self.sourceFont)
self.source_monospaced = width_mono
if self.args.nonmono:
return
panose_mono = check_panose_monospaced(self.sourceFont)
logger.debug("Monospace check: %s; glyph-width-mono %s",
panose_check_to_text(panose_mono, self.sourceFont.os2_panose), repr(width_mono))
# The following is in fact "width_mono != panose_mono", but only if panose_mono is not 'unknown'
if (width_mono and panose_mono == 0) or (not width_mono and panose_mono == 1):
logger.warning("Monospaced check: Panose assumed to be wrong")
logger.warning("Monospaced check: %s and %s",
report_advance_widths(self.sourceFont),
panose_check_to_text(panose_mono, self.sourceFont.os2_panose))
if self.args.single and not width_mono:
logger.warning("Sourcefont is not monospaced - forcing to monospace not advisable, "
"results might be useless%s",
" - offending char: {:X}".format(offending_char) if offending_char is not None else "")
if self.args.single <= 1:
logger.critical("Font will not be patched! Give --mono (or -s, or --use-single-width-glyphs) twice to force patching")
sys.exit(1)
if width_mono:
force_panose_monospaced(self.sourceFont)
def setup_patch_set(self):
""" Creates list of dicts to with instructions on copying glyphs from each symbol font into self.sourceFont """
box_enabled = self.source_monospaced and not self.symbolsonly # Box glyph only for monospaced and not for Symbols Only
box_keep = False
if box_enabled or self.args.forcebox:
self.sourceFont.selection.select(("ranges",), 0x2500, 0x259f)
box_glyphs_target = len(list(self.sourceFont.selection))
box_glyphs_current = len(list(self.sourceFont.selection.byGlyphs))
if box_glyphs_target > box_glyphs_current or self.args.forcebox:
# Sourcefont does not have all of these glyphs, do not mix sets (overwrite existing)
if box_glyphs_current > 0:
logger.debug("%d/%d box drawing glyphs will be replaced",
box_glyphs_current, box_glyphs_target)
box_enabled = True
else:
# Sourcefont does have all of these glyphs
# box_keep = True # just scale do not copy (need to scale to fit new cell size)
box_enabled = False # Cowardly not scaling existing glyphs, although the code would allow this
# Stretch 'xz' or 'pa' (preserve aspect ratio)
# Supported params: overlap | careful | xy-ratio | dont_copy | ypadding
# Overlap value is used horizontally but vertically limited to 0.01
# Careful does not overwrite/modify existing glyphs
# The xy-ratio limits the x-scale for a given y-scale to make the ratio <= this value (to prevent over-wide glyphs)
# '1' means occupu 1 cell (default for 'xy')
# '2' means occupy 2 cells (default for 'pa')
# '!' means do the 'pa' scaling even with non mono fonts (else it just scales down, never up)
# '^' means that scaling shall fill the whole cell and not only the icon-cap-height (for mono fonts, other always use the whole cell)
# Dont_copy does not overwrite existing glyphs but rescales the preexisting ones
#
# Be careful, stretch may not change within a ScaleRule!
SYM_ATTR_DEFAULT = {
'default': {'align': 'c', 'valign': 'c', 'stretch': 'pa', 'params': {}}
}
SYM_ATTR_POWERLINE = {
'default': {'align': 'c', 'valign': 'c', 'stretch': '^pa', 'params': {}},
# Arrow tips
0xe0b0: {'align': 'l', 'valign': 'c', 'stretch': '^xy', 'params': {'overlap': 0.06, 'xy-ratio': 0.7}},
0xe0b1: {'align': 'l', 'valign': 'c', 'stretch': '^xy', 'params': {'xy-ratio': 0.7}},
0xe0b2: {'align': 'r', 'valign': 'c', 'stretch': '^xy', 'params': {'overlap': 0.06, 'xy-ratio': 0.7}},
0xe0b3: {'align': 'r', 'valign': 'c', 'stretch': '^xy', 'params': {'xy-ratio': 0.7}},
# Inverse arrow tips
0xe0d6: {'align': 'l', 'valign': 'c', 'stretch': '^xy', 'params': {'overlap': 0.05, 'xy-ratio': 0.7}},
0xe0d7: {'align': 'r', 'valign': 'c', 'stretch': '^xy', 'params': {'overlap': 0.05, 'xy-ratio': 0.7}},
# Rounded arcs
0xe0b4: {'align': 'l', 'valign': 'c', 'stretch': '^xy', 'params': {'overlap': 0.06, 'xy-ratio': 0.59}},
0xe0b5: {'align': 'l', 'valign': 'c', 'stretch': '^xy', 'params': {'xy-ratio': 0.5}},
0xe0b6: {'align': 'r', 'valign': 'c', 'stretch': '^xy', 'params': {'overlap': 0.06, 'xy-ratio': 0.59}},
0xe0b7: {'align': 'r', 'valign': 'c', 'stretch': '^xy', 'params': {'xy-ratio': 0.5}},
# Bottom Triangles
0xe0b8: {'align': 'l', 'valign': 'c', 'stretch': '^xy', 'params': {'overlap': 0.05}},
0xe0b9: {'align': 'l', 'valign': 'c', 'stretch': '^xy', 'params': {}},
0xe0ba: {'align': 'r', 'valign': 'c', 'stretch': '^xy', 'params': {'overlap': 0.05}},
0xe0bb: {'align': 'r', 'valign': 'c', 'stretch': '^xy', 'params': {}},
# Top Triangles
0xe0bc: {'align': 'l', 'valign': 'c', 'stretch': '^xy', 'params': {'overlap': 0.05}},
0xe0bd: {'align': 'l', 'valign': 'c', 'stretch': '^xy', 'params': {}},
0xe0be: {'align': 'r', 'valign': 'c', 'stretch': '^xy', 'params': {'overlap': 0.05}},
0xe0bf: {'align': 'r', 'valign': 'c', 'stretch': '^xy', 'params': {}},
# Flames
0xe0c0: {'align': 'l', 'valign': 'c', 'stretch': '^xy2', 'params': {'overlap': 0.05}},
0xe0c1: {'align': 'l', 'valign': 'c', 'stretch': '^xy2', 'params': {}},
0xe0c2: {'align': 'r', 'valign': 'c', 'stretch': '^xy2', 'params': {'overlap': 0.05}},
0xe0c3: {'align': 'r', 'valign': 'c', 'stretch': '^xy2', 'params': {}},
# Small squares
0xe0c4: {'align': 'l', 'valign': 'c', 'stretch': '^xy2', 'params': {'overlap': -0.03, 'xy-ratio': 0.86}},
0xe0c5: {'align': 'r', 'valign': 'c', 'stretch': '^xy2', 'params': {'overlap': -0.03, 'xy-ratio': 0.86}},
# Bigger squares
0xe0c6: {'align': 'l', 'valign': 'c', 'stretch': '^xy2', 'params': {'overlap': -0.03, 'xy-ratio': 0.78}},
0xe0c7: {'align': 'r', 'valign': 'c', 'stretch': '^xy2', 'params': {'overlap': -0.03, 'xy-ratio': 0.78}},
# Waveform
0xe0c8: {'align': 'l', 'valign': 'c', 'stretch': '^xy2', 'params': {'overlap': 0.05}},
0xe0ca: {'align': 'r', 'valign': 'c', 'stretch': '^xy2', 'params': {'overlap': 0.05}},
# Hexagons
0xe0cc: {'align': 'l', 'valign': 'c', 'stretch': '^xy2', 'params': {'overlap': 0.02, 'xy-ratio': 0.85}},
0xe0cd: {'align': 'l', 'valign': 'c', 'stretch': '^xy2', 'params': {'xy-ratio': 0.865}},
# Legos
0xe0ce: {'align': 'l', 'valign': 'c', 'stretch': '^pa', 'params': {}},
0xe0cf: {'align': 'c', 'valign': 'c', 'stretch': '^pa', 'params': {}},
0xe0d0: {'align': 'l', 'valign': 'c', 'stretch': '^pa', 'params': {}},
0xe0d1: {'align': 'l', 'valign': 'c', 'stretch': '^pa', 'params': {}},
# Top and bottom trapezoid
0xe0d2: {'align': 'l', 'valign': 'c', 'stretch': '^xy', 'params': {'overlap': 0.02, 'xy-ratio': 0.7}},
0xe0d4: {'align': 'r', 'valign': 'c', 'stretch': '^xy', 'params': {'overlap': 0.02, 'xy-ratio': 0.7}}
}
SYM_ATTR_TRIGRAPH = {
'default': {'align': 'c', 'valign': 'c', 'stretch': 'pa1!', 'params': {'overlap': -0.10, 'careful': True}}
}
SYM_ATTR_FONTA = {
# 'pa' == preserve aspect ratio
'default': {'align': 'c', 'valign': 'c', 'stretch': 'pa', 'params': {}},
# Don't center these arrows vertically
0xf0dc: {'align': 'c', 'valign': '', 'stretch': 'pa', 'params': {}},
0xf0dd: {'align': 'c', 'valign': '', 'stretch': 'pa', 'params': {}},
0xf0de: {'align': 'c', 'valign': '', 'stretch': 'pa', 'params': {}}
}
SYM_ATTR_HEAVYBRACKETS = {
'default': {'align': 'c', 'valign': 'c', 'stretch': '^pa1!', 'params': {'ypadding': 0.3, 'careful': True}}
}
SYM_ATTR_BOX = {
'default': {'align': 'c', 'valign': 'c', 'stretch': '^xy', 'params': {'overlap': 0.02, 'dont_copy': box_keep}},
# No overlap with checkered greys (commented out because that raises problems on rescaling clients)
# 0x2591: {'align': 'c', 'valign': 'c', 'stretch': 'xy', 'params': {'dont_copy': box_keep}},
# 0x2592: {'align': 'c', 'valign': 'c', 'stretch': 'xy', 'params': {'dont_copy': box_keep}},
# 0x2593: {'align': 'c', 'valign': 'c', 'stretch': 'xy', 'params': {'dont_copy': box_keep}},
}
SYM_ATTR_PROGRESS = {
'default': {'align': 'c', 'valign': 'c', 'stretch': '^pa1!', 'params': {'overlap': -0.03, 'careful': True}}, # Cirles
# All the squares:
0xee00: {'align': 'r', 'valign': 'c', 'stretch': '^xy', 'params': {'overlap': 0.05, 'careful': True}},
0xee01: {'align': 'c', 'valign': 'c', 'stretch': '^xy', 'params': {'overlap': 0.10, 'careful': True}},
0xee02: {'align': 'l', 'valign': 'c', 'stretch': '^xy', 'params': {'overlap': 0.05, 'careful': True}},
0xee03: {'align': 'r', 'valign': 'c', 'stretch': '^xy', 'params': {'overlap': 0.05, 'careful': True}},
0xee04: {'align': 'c', 'valign': 'c', 'stretch': '^xy', 'params': {'overlap': 0.10, 'careful': True}},
0xee05: {'align': 'l', 'valign': 'c', 'stretch': '^xy', 'params': {'overlap': 0.05, 'careful': True}},
}
CUSTOM_ATTR = {
# previous custom scaling => do not touch the icons
# 'default': {'align': 'c', 'valign': '', 'stretch': '', 'params': {}}
'default': {'align': 'c', 'valign': 'c', 'stretch': 'pa', 'params': {'careful': self.args.careful}}
}
# Most glyphs we want to maximize (individually) during the scale
# However, there are some that need to be small or stay relative in
# size to each other.
# The glyph-specific behavior can be given as ScaleRules in the patch-set.
#
# ScaleRules can contain two different kind of rules (possibly in parallel):
# - ScaleGlyph:
# Here one specific glyph is used as 'scale blueprint'. Other glyphs are
# scaled by the same factor as this glyph. This is useful if you have one
# 'biggest' glyph and all others should stay relatively in size.
# Shifting in addition to scaling can be selected too (see below).
# - ScaleGroups:
# Here you specify a group of glyphs that should be handled together
# with the same scaling and shifting (see bottom). The basis for it is
# a 'combined bounding box' of all glyphs in that group. All glyphs are
# handled as if they fill that combined bounding box.
# (- ScaleGroupsVert: Removed with this commit)
#