forked from ryanoasis/nerd-fonts
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfont-patcher
executable file
·1459 lines (1312 loc) · 79 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
# Change the script version when you edit this script:
script_version = "4.16.1"
version = "3.3.0"
projectName = "Nerd Fonts"
debug = False
import sys
import os
import errno
import psMat
import fontforge
import random
import string
import re
import shutil
from enum import Enum
import logging
import math
import json
from fontmeta import *
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 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 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_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 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):
self.sym_font_args = []
self.sourceFont = None # class 'fontforge.font'
self.patch_set = None # class 'list'
self.font_dim = None # class 'dict'
self.symbolsonly = False # Are we generating the SymbolsOnly font?
self.onlybitmaps = 0
self.essential = set()
self.glyphnames = fetch_glyphnames()
def patch(self, font, family, variation):
self.sourceFont = font
self.setup_version(family, variation)
self.manipulate_hints(family)
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
# 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 some Windows applications (e.g. 'cmd') that is not enough. But they seem to honour the Panose table
# https://forum.high-logic.com/postedfiles/Panose.pdf
force_panose_monospaced(self.sourceFont)
panose = list(self.sourceFont.os2_panose)
if panose[0] == 0 or panose[0] == 2: # 0 (1st value) = family kind; 0 = any (default); 2 = latin text and display
panose[0] = 2 # Assert kind
panose[3] = 9 # 3 (4th value) = propotion; 9 = monospaced
self.sourceFont.os2_panose = tuple(panose)
# Prevent opening and closing the fontforge font. Makes things faster when patching
# multiple ranges using the same symbol font.
PreviousSymbolFilename = ""
symfont = None
if variation == "Nerd":
for patch in self.patch_set:
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 = fontforge.open(os.path.join("src/glyphs", patch['Filename']))
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, infile, family, variation):
sourceFont = sourceFonts[0]
# the `PfEd-comments` flag is required for Fontforge to save '.comment' and '.fontlog'.
gen_flags = (str('opentype'), str('PfEd-comments'), str('no-FFTM-table'))
fontname = sourceFont.fullname
if not fontname:
fontname = sourceFont.cidfontname
outfile = os.path.normpath(os.path.join(
sanitize_filename("PatchedFonts\\" + family + variation + "\\", True),
sanitize_filename(fontname) + ".otf"))
# the `PfEd-comments` flag is required for Fontforge to save '.comment' and '.fontlog'.
bitmaps = str()
if len(self.sourceFont.bitmapSizes):
print("Preserving bitmaps {}".format(self.sourceFont.bitmapSizes))
bitmaps = str('otf') # otf/ttf, both is bf_ttf
sourceFont.generate(outfile, bitmap_type=bitmaps, flags=gen_flags)
message = " {}\n ===> '{}'".format(sourceFont.fullname, outfile)
# Adjust flags that can not be changed via fontforge
source_font = TableHEADWriter(infile)
dest_font = TableHEADWriter(outfile)
for idx in range(source_font.num_fonts):
logger.debug("Tweaking %d/%d", idx + 1, source_font.num_fonts)
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()
source_font.close()
dest_font.close()
logger.debug(message)
def setup_font_names(self, font, family, variation, splitcollection=True):
isItalic = font.fontname.endswith("Italic")
style = font.fontname.split("-")[1].removesuffix("Italic")
# the weight here is not following guideline !!!
if splitcollection:
familyname = family + " " + variation + " " + fsuffix[family][style]
weight = fweight[family][style]
else:
familyname = family + " " + variation
weight = weight[family][style]
if isItalic:
if weight == "Regular":
subFamily = "Italic"
else:
subFamily = weight + " Italic"
else:
subFamily = weight
fontname = (familyname + "-" + subFamily).replace(" ", "")
fullname = (familyname + " " + subFamily).replace(" ", " ")
familyname = familyname.removesuffix(" ")
if variation == "Nerd":
projectInfo = (
"* " + family + " Version: " + fontversion[family] + "\n"
"* Nerd Version: " + version + "\n"
"\n"
"Patched by LNKLEO"
)
else:
projectInfo = (
"* " + family + " Version: " + fontversion[family] + "\n"
"\n"
"Patched by LNKLEO"
)
while (font.sfnt_names[1][2] != familyname
or font.sfnt_names[2][2] != subFamily
or font.sfnt_names[-2][2] != familyname
or font.sfnt_names[-1][2] != subFamily
or font.fontname != fontname
or font.fullname != fullname
or font.familyname != familyname):
trick = lambda : ''.join(random.choice(string.ascii_letters) for i in range(len(subFamily)))
font.fontname = trick()
font.fullname = trick()
font.familyname = trick()
font.appendSFNTName(str('English (US)'), str('Fullname'), fullname)
font.appendSFNTName(str('English (US)'), str('SubFamily'), subFamily)
font.appendSFNTName(str('English (US)'), str('Family'), familyname)
font.appendSFNTName(str('English (US)'), str('Preferred Family'), familyname)
# font.appendSFNTName(str('English (US)'), str('Compatible Full'), fullname)
font.appendSFNTName(str('English (US)'), str('Preferred Styles'), subFamily)
font.fontname = fontname
font.fullname = fullname
font.familyname = familyname
if variation == "Nerd":
uniqueID = fontversion[family] + ";N" + version + ";" + uid[family] + ";NERD;LNKL;" + fontname
else:
uniqueID = fontversion[family] + "" + ";" + uid[family] + ";LNKL;" + fontname
font.appendSFNTName(str('English (US)'), str('UniqueID'), uniqueID)
font.appendSFNTName(str('English (US)'), str('Version'), self.sourceFont.version)
font.appendSFNTName(str('English (US)'), str('SubFamily'), subFamily)
font.os2_stylemap = 0
if weight == "Bold": # weight = "bold" or weight == "Heavy":
font.os2_stylemap = 0b1 << 5
elif weight == "Regular" and not isItalic:
font.os2_stylemap = 0b1 << 6
if isItalic:
font.os2_stylemap |= 0b1
font.weight = weight
font.comment = projectInfo
font.fontlog = projectInfo
def setup_version(self, family, variation):
""" Add the Nerd Font version to the original version """
print("Version was {}".format(self.sourceFont.version))
self.sourceFont.version = fontversion[family]
if variation == 'Nerd':
self.sourceFont.version += "[N" + version + "]"
self.sourceFont.sfntRevision = None # Auto-set (refreshed) by fontforge
self.sourceFont.appendSFNTName(str('English (US)'), str('Version'), "Version " + self.sourceFont.version)
print("Version now is {}".format(self.sourceFont.version))
def manipulate_hints(self, family):
""" Redo the hinting on some problematic glyphs """
if family in rehint.keys():
redo = rehint[family]
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 setup_patch_set(self):
if (debug):
self.patch_set = []
return
""" Creates list of dicts to with instructions on copying glyphs from each symbol font into self.sourceFont """
box_enabled = not self.symbolsonly # Box glyph only for monospaced and not for Symbols Only
box_keep = False
if box_enabled:
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:
# 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': True}}
}
# 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)
#
# The ScaleGlyph method: You set 'ScaleGlyph' to the unicode of the reference glyph.
# Note that there can be only one per patch-set.
# Additionally you set 'GlyphsToScale' that contains all the glyphs that shall be
# handled (scaled) like the reference glyph.
# It is a List of: ((glyph code) or (tuple of two glyph codes that form a closed range))
# 'GlyphsToScale': [
# 0x0100, 0x0300, 0x0400, # The single glyphs 0x0100, 0x0300, and 0x0400
# (0x0200, 0x0210), # All glyphs 0x0200 to 0x0210 including both 0x0200 and 0x0210
# ]}
# If you want to not only scale but also shift as the refenerce glyph you give the
# data as 'GlyphsToScale+'. Note that only one set is used and the plus version is preferred.
#
# For the ScaleGroup method you define any number groups of glyphs and each group is
# handled separately. The combined bounding box of all glyphs in the group is determined
# and based on that the scale and shift (see bottom) for all the glyphs in the group.
# You define the groups as value of 'ScaleGroups'.
# It is a List of: ((lists of glyph codes) or (ranges of glyph codes))
# 'ScaleGroups': [
# [0x0100, 0x0300, 0x0400], # One group consists of glyphs 0x0100, 0x0300, and 0x0400
# range(0x0200, 0x0210 + 1), # Another group contains glyphs 0x0200 to 0x0210 incl.
#
# Note the subtle differences: tuple vs. range; closed vs open range; etc
# See prepareScaleRules() for some more details.
# For historic reasons ScaleGroups is sometimes called 'new method' and ScaleGlyph 'old'.
# The codepoints mentioned here are symbol-font-codepoints.
#
# Shifting:
# If we have a combined bounding box stored in a range, that
# box is used to align all symbols in the range identically.
# - If the symbol font is proportinal only the v alignment is synced.
# - If the symbol font is monospaced v and h alignemnts are synced.
# To make sure the behavior is as expected you are required to set a ShiftMode property
# accordingly. It just checks, you can not (!) select what is done with that property.
BOX_SCALE_LIST = {'ShiftMode': 'xy', 'ScaleGroups': [
[*range(0x2500, 0x2570 + 1), *range(0x2574, 0x257f + 1)], # box drawing
range(0x2571, 0x2573 + 1), # diagonals
range(0x2580, 0x259f + 1), # blocks and greys (greys are less tall originally, so overlap will be less)
]}
CODI_SCALE_LIST = {'ShiftMode': 'xy', 'ScaleGroups': [
[0xea61, 0xeb13], # lightbulb
range(0xeab4, 0xeab7 + 1), # chevrons
[0xea7d, *range(0xea99, 0xeaa1 + 1), 0xebcb], # arrows
[0xeaa2, 0xeb9a, 0xec08, 0xec09], # bells
range(0xead4, 0xead6 + 1), # dot and arrow
[0xeb43, 0xec0b, 0xec0c], # (pull) request changes
range(0xeb6e, 0xeb71 + 1), # triangles
[*range(0xeb89, 0xeb8b + 1), 0xec07], # smallish dots
range(0xebd5, 0xebd7 + 1), # compasses
]}
DEVI_SCALE_LIST = None
FONTA_SCALE_LIST = {'ShiftMode': '', 'ScaleGroups': [
[0xf005, 0xf006, 0xf089], # star, star empty, half star
range(0xf026, 0xf028 + 1), # volume off, down, up
range(0xf02b, 0xf02c + 1), # tag, tags
range(0xf031, 0xf035 + 1), # font et al
range(0xf044, 0xf046 + 1), # edit, share, check (boxes)
range(0xf048, 0xf052 + 1), # multimedia buttons
range(0xf060, 0xf063 + 1), # arrows
[0xf053, 0xf054, 0xf077, 0xf078], # chevron all directions
range(0xf07d, 0xf07e + 1), # resize
range(0xf0a4, 0xf0a7 + 1), # pointing hands
[0xf0d7, 0xf0d8, 0xf0d9, 0xf0da, 0xf0dc, 0xf0dd, 0xf0de], # caret all directions and same looking sort
range(0xf100, 0xf107 + 1), # angle
range(0xf130, 0xf131 + 1), # mic
range(0xf141, 0xf142 + 1), # ellipsis
range(0xf153, 0xf15a + 1), # currencies
range(0xf175, 0xf178 + 1), # long arrows
range(0xf182, 0xf183 + 1), # male and female
range(0xf221, 0xf22d + 1), # gender or so
range(0xf255, 0xf25b + 1), # hand symbols
]}
HEAVY_SCALE_LIST = {'ShiftMode': 'y', 'ScaleGlyph': 0x2771, # widest bracket, horizontally
'GlyphsToScale': [
(0x276c, 0x2771) # all
]}
OCTI_SCALE_LIST = {'ShiftMode': '', 'ScaleGroups': [
[*range(0xf03d, 0xf040 + 1), 0xf019, 0xf030, 0xf04a, 0xf051, 0xf071, 0xf08c ], # arrows
[0xF0E7, # Smily and ...
0xf044, 0xf05a, 0xf05b, 0xf0aa, # triangles
0xf052, 0xf053, 0xf296, 0xf2f0, # small stuff
0xf078, 0xf0a2, 0xf0a3, 0xf0a4, # chevrons
0xf0ca, 0xf081, 0xf092, # dash, X, github-text
],
[0xf09c, 0xf09f, 0xf0de], # bells
range(0xf2c2, 0xf2c5 + 1), # move to
[0xf07b, 0xf0a1, 0xf0d6, 0xf306], # bookmarks
]}
PROGR_SCALE_LIST = {'ShiftMode': 'xy', 'ScaleGroups': [
range(0xedff, 0xee05 + 1), # boxes... with helper glyph for Y padding
range(0xee06, 0xee0b + 1), # circles
]}
WEATH_SCALE_LIST = {'ShiftMode': '', 'ScaleGroups': [
[0xf03c, 0xf042, 0xf045 ], # degree signs
[0xf043, 0xf044, 0xf048, 0xf04b, 0xf04c, 0xf04d, 0xf057, 0xf058, 0xf087, 0xf088], # arrows
range(0xf053, 0xf055 + 1), # thermometers
[*range(0xf059, 0xf061 + 1), 0xf0b1], # wind directions
range(0xf089, 0xf094 + 1), # clocks
range(0xf095, 0xf0b0 + 1), # moon phases
range(0xf0b7, 0xf0c3 + 1), # wind strengths
[0xf06e, 0xf070 ], # solar/lunar eclipse
[0xf051, 0xf052, 0xf0c9, 0xf0ca, 0xf072 ], # sun/moon up/down
[0xf049, 0xf056, 0xf071, *range(0xf073, 0xf07c + 1), 0xf08a], # other things
# Note: Codepoints listed before that are also in the following range
# will take the scaling of the previous group (the ScaleGroups are
# searched through in definition order).
# But be careful, the combined bounding box for the following group
# _will_ include all glyphs in its definition: Make sure the exempt
# glyphs from above are smaller (do not extend) the combined bounding
# box of this range:
[ *range(0xf000, 0xf041 + 1),
*range(0xf064, 0xf06d + 1),
*range(0xf07d, 0xf083 + 1),
*range(0xf085, 0xf086 + 1),
*range(0xf0b2, 0xf0b6 + 1)
], # lots of clouds (weather states) (Please read note above!)
]}
MDI_SCALE_LIST = None # Maybe later add some selected ScaleGroups
# Define the character ranges
# Symbol font ranges
self.patch_set = [
{'Name': "SetiUI", 'Filename': "original-source.otf", 'Exact': False, 'SymStart': 0xE4FA, 'SymEnd': 0xE5FF, 'SrcStart': 0xE5FA, 'ScaleRules': None, 'Attributes': SYM_ATTR_DEFAULT},
{'Name': "HeavyAngleBrackets", 'Filename': "extraglyphs.sfd", 'Exact': True, 'SymStart': 0x276C, 'SymEnd': 0x2771, 'SrcStart': None, 'ScaleRules': HEAVY_SCALE_LIST, 'Attributes': SYM_ATTR_HEAVYBRACKETS},
{'Name': "BoxDrawing", 'Filename': "extraglyphs.sfd", 'Exact': True, 'SymStart': 0x2500, 'SymEnd': 0x259F, 'SrcStart': None, 'ScaleRules': BOX_SCALE_LIST, 'Attributes': SYM_ATTR_BOX},
{'Name': "ProgressIndicators", 'Filename': "extraglyphs.sfd", 'Exact': True, 'SymStart': 0xEE00, 'SymEnd': 0xEE0B, 'SrcStart': None, 'ScaleRules': PROGR_SCALE_LIST, 'Attributes': SYM_ATTR_PROGRESS},
{'Name': "Devicons", 'Filename': "devicons/devicons.ttf", 'Exact': False, 'SymStart': 0xE600, 'SymEnd': 0xE7E3, 'SrcStart': 0xE700, 'ScaleRules': DEVI_SCALE_LIST, 'Attributes': SYM_ATTR_DEFAULT},
{'Name': "Powerline", 'Filename': "powerline-symbols/PowerlineSymbols.otf", 'Exact': True, 'SymStart': 0xE0A0, 'SymEnd': 0xE0A2, 'SrcStart': None, 'ScaleRules': None, 'Attributes': SYM_ATTR_POWERLINE},
{'Name': "Powerline", 'Filename': "powerline-symbols/PowerlineSymbols.otf", 'Exact': True, 'SymStart': 0xE0B0, 'SymEnd': 0xE0B3, 'SrcStart': None, 'ScaleRules': None, 'Attributes': SYM_ATTR_POWERLINE},
{'Name': "PowerlineExtra", 'Filename': "powerline-extra/PowerlineExtraSymbols.otf", 'Exact': True, 'SymStart': 0xE0A3, 'SymEnd': 0xE0A3, 'SrcStart': None, 'ScaleRules': None, 'Attributes': SYM_ATTR_POWERLINE},
{'Name': "PowerlineExtra", 'Filename': "powerline-extra/PowerlineExtraSymbols.otf", 'Exact': True, 'SymStart': 0xE0B4, 'SymEnd': 0xE0C8, 'SrcStart': None, 'ScaleRules': None, 'Attributes': SYM_ATTR_POWERLINE},
{'Name': "PowerlineExtra", 'Filename': "powerline-extra/PowerlineExtraSymbols.otf", 'Exact': True, 'SymStart': 0xE0CA, 'SymEnd': 0xE0CA, 'SrcStart': None, 'ScaleRules': None, 'Attributes': SYM_ATTR_POWERLINE},
{'Name': "PowerlineExtra", 'Filename': "powerline-extra/PowerlineExtraSymbols.otf", 'Exact': True, 'SymStart': 0xE0CC, 'SymEnd': 0xE0D7, 'SrcStart': None, 'ScaleRules': None, 'Attributes': SYM_ATTR_POWERLINE},
{'Name': "PowerlineExtra", 'Filename': "powerline-extra/PowerlineExtraSymbols.otf", 'Exact': True, 'SymStart': 0x2630, 'SymEnd': 0x2630, 'SrcStart': None, 'ScaleRules': None, 'Attributes': SYM_ATTR_TRIGRAPH},
{'Name': "Pomicons", 'Filename': "pomicons/Pomicons.otf", 'Exact': True, 'SymStart': 0xE000, 'SymEnd': 0xE00A, 'SrcStart': None, 'ScaleRules': None, 'Attributes': SYM_ATTR_DEFAULT},
{'Name': "FontAwesome", 'Filename': "font-awesome/FontAwesome.otf", 'Exact': True, 'SymStart': 0xED00, 'SymEnd': 0xF2FF, 'SrcStart': None, 'ScaleRules': FONTA_SCALE_LIST, 'Attributes': SYM_ATTR_FONTA},
{'Name': "FontAwesomeExtension", 'Filename': "font-awesome-extension.ttf", 'Exact': False, 'SymStart': 0xE000, 'SymEnd': 0xE0A9, 'SrcStart': 0xE200, 'ScaleRules': None, 'Attributes': SYM_ATTR_DEFAULT}, # Maximize
{'Name': "Power", 'Filename': "Unicode_IEC_symbol_font.otf", 'Exact': True, 'SymStart': 0x23FB, 'SymEnd': 0x23FE, 'SrcStart': None, 'ScaleRules': None, 'Attributes': SYM_ATTR_DEFAULT}, # Power, Power On/Off, Power On, Sleep
{'Name': "Power", 'Filename': "Unicode_IEC_symbol_font.otf", 'Exact': True, 'SymStart': 0x2B58, 'SymEnd': 0x2B58, 'SrcStart': None, 'ScaleRules': None, 'Attributes': SYM_ATTR_DEFAULT}, # Heavy Circle (aka Power Off)
{'Name': "Material", 'Filename': "materialdesign/MaterialDesignIconsDesktop.ttf", 'Exact': True, 'SymStart': 0xF0001,'SymEnd': 0xF1AF0,'SrcStart': None, 'ScaleRules': MDI_SCALE_LIST, 'Attributes': SYM_ATTR_DEFAULT},
{'Name': "Weather", 'Filename': "weather-icons/weathericons-regular-webfont.ttf", 'Exact': False, 'SymStart': 0xF000, 'SymEnd': 0xF0EB, 'SrcStart': 0xE300, 'ScaleRules': None, 'Attributes': SYM_ATTR_DEFAULT},
{'Name': "Logos", 'Filename': "font-logos.ttf", 'Exact': True, 'SymStart': 0xF300, 'SymEnd': 0xF381, 'SrcStart': None, 'ScaleRules': None, 'Attributes': SYM_ATTR_DEFAULT},
{'Name': "Octicons", 'Filename': "octicons/octicons.ttf", 'Exact': False, 'SymStart': 0xF000, 'SymEnd': 0xF105, 'SrcStart': 0xF400, 'ScaleRules': OCTI_SCALE_LIST, 'Attributes': SYM_ATTR_DEFAULT}, # Magnifying glass
{'Name': "Octicons", 'Filename': "octicons/octicons.ttf", 'Exact': True, 'SymStart': 0x2665, 'SymEnd': 0x2665, 'SrcStart': None, 'ScaleRules': OCTI_SCALE_LIST, 'Attributes': SYM_ATTR_DEFAULT}, # Heart
{'Name': "Octicons", 'Filename': "octicons/octicons.ttf", 'Exact': True, 'SymStart': 0x26A1, 'SymEnd': 0x26A1, 'SrcStart': None, 'ScaleRules': OCTI_SCALE_LIST, 'Attributes': SYM_ATTR_DEFAULT}, # Zap
{'Name': "Octicons", 'Filename': "octicons/octicons.ttf", 'Exact': False, 'SymStart': 0xF27C, 'SymEnd': 0xF306, 'SrcStart': 0xF4A9, 'ScaleRules': OCTI_SCALE_LIST, 'Attributes': SYM_ATTR_DEFAULT},
{'Name': "Codicons", 'Filename': "codicons/codicon.ttf", 'Exact': True, 'SymStart': 0xEA60, 'SymEnd': 0xEC1E, 'SrcStart': None, 'ScaleRules': CODI_SCALE_LIST, 'Attributes': SYM_ATTR_DEFAULT},
]
def improve_line_dimensions(self):
# Make the total line size even. This seems to make the powerline separators
# center more evenly.
if (self.sourceFont.os2_winascent + self.sourceFont.os2_windescent) % 2 != 0:
# All three are equal before due to get_sourcefont_dimensions()
self.sourceFont.hhea_ascent += 1
self.sourceFont.os2_typoascent += 1
self.sourceFont.os2_winascent += 1
def add_glyphrefs_to_essential(self, unicode):
self.essential.add(unicode)
# According to fontforge spec, altuni is either None or a tuple of tuples
# Those tuples contained in altuni are of the following "format":
# (unicode-value, variation-selector, reserved-field)
altuni = self.sourceFont[unicode].altuni
if altuni is not None:
for altcode in [ v for v, s, r in altuni if v >= 0 ]:
# If alternate unicode already exists in self.essential,
# that means it has gone through this function before.
# Therefore we skip it to avoid infinite loop.
# A unicode value of -1 basically means unused and is also worth skipping.
if altcode not in self.essential:
self.add_glyphrefs_to_essential(altcode)
# From fontforge documentation:
# glyph.references return a tuple of tuples containing, for each reference in foreground,
# a glyph name, a transformation matrix, and (depending on ff version) whether the
# reference is currently selected.
references = self.sourceFont[unicode].references
for refcode in [ self.sourceFont[n].unicode for n, *_ in references ]: # tuple of 2 or 3 depending on ff version
if refcode not in self.essential and refcode >= 0:
self.add_glyphrefs_to_essential(refcode)
def get_essential_references(self):
"""Find glyphs that are needed for the basic glyphs"""
# Sometimes basic glyphs are constructed from multiple other glyphs.
# Find out which other glyphs are also needed to keep the basic
# glyphs intact.
# 0x0000-0x017f is the Latin Extended-A range
# 0xfb00-0xfb06 are 'fi' and other ligatures
basic_glyphs = { c for c in range(0x21, 0x17f + 1) if c in self.sourceFont }
# Collect substitution destinations
for glyph in list(basic_glyphs) + [*range(0xfb00, 0xfb06 + 1)]:
if not glyph in self.sourceFont:
continue
for possub in self.sourceFont[glyph].getPosSub('*'):
if possub[1] == 'Substitution' or possub[1] == 'Ligature':
basic_glyphs.add(glyph)
basic_glyphs.add(self.sourceFont[possub[2]].unicode)
basic_glyphs.discard(-1) # the .notdef glyph
for glyph in basic_glyphs:
self.add_glyphrefs_to_essential(glyph)
def get_sourcefont_dimensions(self):
""" This gets the font dimensions (cell width and height), and makes them equal on all platforms """
# Step 1
# There are three ways to discribe the baseline to baseline distance
# (a.k.a. line spacing) of a font. That is all a kuddelmuddel
# and we try to sort this out here
# See also https://glyphsapp.com/learn/vertical-metrics
# See also https://github.com/source-foundry/font-line
(hhea_btb, typo_btb, win_btb, win_gap) = get_btb_metrics(self.sourceFont)
use_typo = self.sourceFont.os2_use_typo_metrics != 0
Metric = Enum('Metric', ['HHEA', 'TYPO', 'WIN'])
# We use either TYPO (1) or WIN (2) and compare with HHEA
# and use HHEA (0) if the fonts seems broken - no WIN, see #1056
our_btb = typo_btb if use_typo else win_btb
if our_btb == hhea_btb:
metrics = Metric.TYPO if use_typo else Metric.WIN # conforming font
elif abs(our_btb - hhea_btb) / our_btb < 0.03:
logger.info("Font vertical metrics slightly off (%.1f%)", (our_btb - hhea_btb) / our_btb * 100.0)
metrics = Metric.TYPO if use_typo else Metric.WIN
else:
# Try the other metric
our_btb = typo_btb if not use_typo else win_btb
if our_btb == hhea_btb:
metrics = Metric.TYPO if use_typo else Metric.WIN # conforming font
elif abs(our_btb - hhea_btb) / our_btb < 0.03:
logger.info("Font vertical metrics slightly off (%.1f%%)", (our_btb - hhea_btb) / our_btb * 100.0)
metrics = Metric.TYPO if use_typo else Metric.WIN
else:
# We trust the WIN metric more, see experiments in #1056
logger.warning("Font vertical metrics inconsistent (HHEA %d / TYPO %d / WIN %d), using WIN", hhea_btb, typo_btb, win_btb)
our_btb = win_btb
metrics = Metric.WIN
# print("FINI hhea {} typo {} win {} use {} {} {}".format(hhea_btb, typo_btb, win_btb, use_typo, our_btb != hhea_btb, self.sourceFont.fontname))
self.font_dim = {'xmin': 0, 'ymin': 0, 'xmax': 0, 'ymax': 0, 'width' : 0, 'height': 0, 'iconheight': 0, 'ypadding': 0}
if metrics == Metric.HHEA:
self.font_dim['ymin'] = self.sourceFont.hhea_descent - half_gap(self.sourceFont.hhea_linegap, False)
self.font_dim['ymax'] = self.sourceFont.hhea_ascent + half_gap(self.sourceFont.hhea_linegap, True)
elif metrics == Metric.TYPO:
self.font_dim['ymin'] = self.sourceFont.os2_typodescent - half_gap(self.sourceFont.os2_typolinegap, False)
self.font_dim['ymax'] = self.sourceFont.os2_typoascent + half_gap(self.sourceFont.os2_typolinegap, True)
elif metrics == Metric.WIN:
self.font_dim['ymin'] = -self.sourceFont.os2_windescent - half_gap(win_gap, False)
self.font_dim['ymax'] = self.sourceFont.os2_winascent + half_gap(win_gap, True)
else:
logger.debug("Metrics is strange")
pass # Will fail the metrics check some line later
# Calculate font height
self.font_dim['height'] = -self.font_dim['ymin'] + self.font_dim['ymax']
if self.font_dim['height'] == 0:
# This can only happen if the input font is empty
# Assume we are using our prepared templates
self.symbolsonly = True
self.font_dim = {
'xmin' : 0,
'ymin' : -self.sourceFont.descent,
'xmax' : self.sourceFont.em,
'ymax' : self.sourceFont.ascent,
'width' : self.sourceFont.em,
'height' : self.sourceFont.descent + self.sourceFont.ascent,
'iconheight': self.sourceFont.descent + self.sourceFont.ascent,
'ypadding' : 0,
}
our_btb = self.sourceFont.descent + self.sourceFont.ascent
if self.font_dim['height'] <= 0:
logger.critical("Can not detect sane font height")
sys.exit(1)
self.font_dim['iconheight'] = self.font_dim['height']
if self.sourceFont.capHeight > 0:
# Limit the icon height on monospaced fonts because very slender and tall icons render
# excessivly tall otherwise. We ignore that effect for the other variants because it
# does not look so much out of place there.
# Icons can be bigger than the letter capitals, but not the whole cell:
self.font_dim['iconheight'] = (self.sourceFont.capHeight * 2 + self.font_dim['height']) / 3
# Make all metrics equal
self.sourceFont.os2_typolinegap = 0
self.sourceFont.os2_typoascent = self.font_dim['ymax']
self.sourceFont.os2_typodescent = self.font_dim['ymin']
self.sourceFont.os2_winascent = self.sourceFont.os2_typoascent
self.sourceFont.os2_windescent = -self.sourceFont.os2_typodescent
self.sourceFont.hhea_ascent = self.sourceFont.os2_typoascent
self.sourceFont.hhea_descent = self.sourceFont.os2_typodescent
self.sourceFont.hhea_linegap = self.sourceFont.os2_typolinegap
self.sourceFont.os2_use_typo_metrics = 1
(check_hhea_btb, check_typo_btb, check_win_btb, _) = get_btb_metrics(self.sourceFont)
if check_hhea_btb != check_typo_btb or check_typo_btb != check_win_btb or check_win_btb != our_btb:
logger.critical("Error in baseline to baseline code detected")
sys.exit(1)
# Step 2
# Find the biggest char width and advance width
# 0x00-0x17f is the Latin Extended-A range
for glyph in range(0x21, 0x17f):
if glyph in range(0x7F, 0xBF) or glyph in [
0x132, 0x133, # IJ, ij (in Overpass Mono)
0x022, 0x027, 0x060, # Single and double quotes in Inconsolata LGC
0x0D0, 0x10F, 0x110, 0x111, 0x127, 0x13E, 0x140, 0x165, # Eth and others with stroke or caron in RobotoMono
0x149, # napostrophe in DaddyTimeMono
0x02D, # hyphen for Monofur
]:
continue # ignore special characters like '1/4' etc and some specifics
try:
(_, _, xmax, _) = self.sourceFont[glyph].boundingBox()
except TypeError:
continue
# print("WIDTH {:X} {} ({} {})".format(glyph, self.sourceFont[glyph].width, self.font_dim['width'], xmax))
if self.font_dim['width'] < self.sourceFont[glyph].width:
self.font_dim['width'] = self.sourceFont[glyph].width
# print("New MAXWIDTH-A {:X} {} -> {} {}".format(glyph, self.sourceFont[glyph].width, self.font_dim['width'], xmax))
if xmax > self.font_dim['xmax']:
self.font_dim['xmax'] = xmax
# print("New MAXWIDTH-B {:X} {} -> {} {}".format(glyph, self.sourceFont[glyph].width, self.font_dim['width'], xmax))
if self.font_dim['width'] < self.font_dim['xmax']:
logger.debug("Font has negative right side bearing in extended glyphs")
self.font_dim['xmax'] = self.font_dim['width'] # In fact 'xmax' is never used
if self.font_dim['width'] <= 0:
logger.critical("Can not detect sane font width")
sys.exit(1)
logger.debug("Final font cell dimensions %d w x %d h%s",
self.font_dim['width'], self.font_dim['height'],
' (with icon cell {} h)'.format(int(self.font_dim['iconheight'])) if self.font_dim['iconheight'] != self.font_dim['height'] else '')
def get_scale_factors(self, sym_dim, stretch, overlap=None):
""" Get scale in x and y as tuple """
# It is possible to have empty glyphs, so we need to skip those.
if not sym_dim['width'] or not sym_dim['height']:
return (1.0, 1.0)
target_width = self.font_dim['width']
if overlap:
target_width += self.font_dim['width'] * overlap
scale_ratio_x = target_width / sym_dim['width']
# font_dim['height'] represents total line height, keep our symbols sized based upon font's em
# Use the font_dim['height'] only for explicit 'y' scaling (not 'pa')
target_height = self.font_dim['height'] if '^' in stretch else self.font_dim['iconheight']
target_height *= 1.0 - self.font_dim['ypadding']
if overlap:
target_height *= 1.0 + min(0.01, overlap) # never aggressive vertical overlap
scale_ratio_y = target_height / sym_dim['height']
if 'pa' in stretch:
# We want to preserve x/y aspect ratio, so find biggest scale factor that allows symbol to fit
scale_ratio_x = min(scale_ratio_x, scale_ratio_y)
scale_ratio_y = scale_ratio_x
else:
# Keep the not-stretched direction
if not 'x' in stretch:
scale_ratio_x = 1.0
if not 'y' in stretch:
scale_ratio_y = 1.0
return (scale_ratio_x, scale_ratio_y)
def copy_glyphs(self, sourceFontStart, symbolFont, symbolFontStart, symbolFontEnd, exactEncoding, scaleRules, setName, attributes):
""" Copies symbol glyphs into self.sourceFont """
progressText = ''
careful = False
sourceFontCounter = 0
# Create glyphs from symbol font
#
# If we are going to copy all Glyphs, then assume we want to be careful
# and only copy those that are not already contained in the source font
if symbolFontStart == 0:
symbolFont.selection.all()
careful = True
else:
symbolFont.selection.select((str("ranges"), str("unicode")), symbolFontStart, symbolFontEnd)
# Get number of selected non-empty glyphs with codes >=0 (i.e. not -1 == notdef)
symbolFontSelection = [ x for x in symbolFont.selection.byGlyphs if x.unicode >= 0 ]
glyphSetLength = len(symbolFontSelection)
modify = attributes['default']['params'].get('dont_copy')
sys.stdout.write("{} {} Glyphs from {} Set\n".format(
"Adding" if not modify else "Rescaling", glyphSetLength, setName))
currentSourceFontGlyph = -1 # initialize for the exactEncoding case
for index, sym_glyph in enumerate(symbolFontSelection):
sym_attr = attributes.get(sym_glyph.unicode)
if sym_attr is None:
sym_attr = attributes['default']
if exactEncoding:
# Use the exact same hex values for the source font as for the symbol font.
# Problem is we do not know the codepoint of the sym_glyph and because it
# came from a selection.byGlyphs there might be skipped over glyphs.
# The iteration is still in the order of the selection by codepoint,
# so we take the next allowed codepoint of the current glyph
possible_codes = [ ]
if sym_glyph.unicode > currentSourceFontGlyph:
possible_codes += [ sym_glyph.unicode ]
if sym_glyph.altuni:
possible_codes += [ v for v, s, r in sym_glyph.altuni if v > currentSourceFontGlyph ]
if len(possible_codes) == 0:
logger.warning("Can not determine codepoint of %X. Skipping...", sym_glyph.unicode)
continue
currentSourceFontGlyph = min(possible_codes)
else:
# use source font defined hex values based on passed in start (fills gaps; symbols are packed)
currentSourceFontGlyph = sourceFontStart + sourceFontCounter
sourceFontCounter += 1
# For debugging process only limited glyphs
# if currentSourceFontGlyph != 0xe7bd:
# continue
ypadding = sym_attr['params'].get('ypadding')
self.font_dim['ypadding'] = ypadding or 0.0
update_progress(round(float(index + 1) / glyphSetLength, 4))
# check if a glyph already exists in this location
do_careful = sym_attr['params'].get('careful', careful) # params take precedence
if do_careful or currentSourceFontGlyph in self.essential:
if currentSourceFontGlyph in self.sourceFont: