forked from adobe-type-tools/python-scripts
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBuildMMFont.py
More file actions
2209 lines (1955 loc) · 70.3 KB
/
BuildMMFont.py
File metadata and controls
2209 lines (1955 loc) · 70.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Copyright 2014 Adobe. All rights reserved.
__usage__ = """ BuildMMFont v1.6 Aug 27 2010
BuildMMFont [-u] [-h]
BuildMMFont [-new] [-srcEM <number>] [-dstEM <number> ] [-v]
"""
__help__ = """ BuildMMFont
Build MM font from bez files.
First builds base design single master fonts from the bez file
directories, auto-hints them, then assembles a one axis MM font from the
single-master fonts.
Options
The program asumes that is is being run in the root directory of an MM
font source data tree; that is, the directory where the mmfont.pfa file
will be built, and where the mmfontinfo file already exists. This
directory will contain a single-master sub-directory for each base
design; that is, a directory containing the font.pfa file, and the
directory of bez files for the single-master font.
The program will first parse the mmfontinfo file, and determine the base
design font directory paths. It will then look in each of these for the
'bez' directory, and will build a new 'font.pfa' file in the each parent
directory of the 'bez' directories.
The program will set all glyphs widths 1- 1000.
-new With this option, the script will derive new global hint data for
each base design from the sum of all the bez files, and will write this
single set of global data to all the new 'font.pfa' file. Existing
'font.pfa' files will get overwritten.
Without this option, the program will use the existing font.pfa files.
-srcEM <number> This option specifies the em-square size of the original
bez files. Intelligent scaling is used to scale the bez files to the
em-square of the base font. Default value is 1000.
-dstEM <number> This option specifies the target em-square size. By
default, this is 1000, or the em-size of the final row font if it
already exists. If not specified, the default is 1000
Notes: Calls the AC, type1, detype1 and tx tools.
Some bez files will have the suffix ".uc" added when written by
BezierLab. This is because neither Mac nor Windows file systems can put
two files in the same directory that differ only by case of one or more
letters. This program will remove the suffix when adding the bez file to
the font, so that the glyh name will not end with '.uc. """
__methods__ = """ Overview: 1) Read mmfontinfo file to get single master
directory names, and determine base font.
2) Build and auto-hint single-master fonts.
2.1) Make temp font out of the bez files using arbitrary font dict
values based on the origEM. - use template OTF font, and BezTools.py to
stuff bez files into temp OTF. Save temp file
2.2) Set up BlueValues
- apply Align, Stem Hist to the base font. Collect the data, use
heuristics. open with FontTools, fix hint and font dict values.
- determine example stem for each alignment and global stem width. Get
coordinates of these points from the other fonts, and apply these as the
global alignment zones and stem widths.
2.3) Hint temp fonts
2.4) Convert temp.cff to final font.ps
3) Merge fonts into template MM font.
3.1) Fix up template MM font from mmfontinfo: axis, name, etc
3.2) Use detype 1 to decompile singel-master fonts
3.3) Collect global metrics and hint values, font BBox, etc
3.4) Collect dict of charstrings. Normalize outlines for a
single glyph.
3.5) add MM charstring to text template
3.6) recompile.
"""
import copy
import math
import os
import re
import shutil
import sys
import time
from fontTools.ttLib import TTFont, getTableModule
from fontTools.misc.psCharStrings import T2CharString
from fontTools.pens.boundsPen import BoundsPen
from afdko import BezTools, FDKUtils
kMMFontInfoPath = "mmfontinfo"
kDstFileName = "font.pfa"
kWidthsFileName = "widths"
kSrcBezDir = "bez"
kUCSuffix = ".uc" # Must be kept in accordance with the suffix added by BezierLab.
kLenUC = len(kUCSuffix)
gDebug = 1
class TempFont:
xmlData = """<?xml version="1.0" encoding="ISO-8859-1"?>
<ttFont sfntVersion="OTTO" ttLibVersion="2.0b2">
<GlyphOrder>
<!-- The 'id' attribute is only for humans; it is ignored when parsed. -->
<GlyphID id="0" name=".notdef"/>
<GlyphID id="1" name="space"/>
</GlyphOrder>
<head>
<!-- Most of this table will be recalculated by the compiler -->
<tableVersion value="1.0"/>
<fontRevision value="1.02899169922"/>
<checkSumAdjustment value="0x291E4CCF"/>
<magicNumber value="0x5F0F3CF5"/>
<flags value="00000000 00000011"/>
<unitsPerEm value="1000"/>
<created value="Sun Jun 5 17:16:54 2005"/>
<modified value="Fri Oct 14 15:50:04 2005"/>
<xMin value="-166"/>
<yMin value="-283"/>
<xMax value="1021"/>
<yMax value="927"/>
<macStyle value="00000000 00000000"/>
<lowestRecPPEM value="3"/>
<fontDirectionHint value="2"/>
<indexToLocFormat value="0"/>
<glyphDataFormat value="0"/>
</head>
<hhea>
<tableVersion value="1.0"/>
<ascent value="726"/>
<descent value="-274"/>
<lineGap value="200"/>
<advanceWidthMax value="1144"/>
<minLeftSideBearing value="-166"/>
<minRightSideBearing value="-170"/>
<xMaxExtent value="1021"/>
<caretSlopeRise value="1"/>
<caretSlopeRun value="0"/>
<caretOffset value="0"/>
<reserved0 value="0"/>
<reserved1 value="0"/>
<reserved2 value="0"/>
<reserved3 value="0"/>
<metricDataFormat value="0"/>
<numberOfHMetrics value="2"/>
</hhea>
<maxp>
<tableVersion value="0x5000"/>
<numGlyphs value="2"/>
</maxp>
<OS_2>
<version value="2"/>
<xAvgCharWidth value="532"/>
<usWeightClass value="400"/>
<usWidthClass value="5"/>
<fsType value="00000000 00001000"/>
<ySubscriptXSize value="650"/>
<ySubscriptYSize value="600"/>
<ySubscriptXOffset value="0"/>
<ySubscriptYOffset value="75"/>
<ySuperscriptXSize value="650"/>
<ySuperscriptYSize value="600"/>
<ySuperscriptXOffset value="0"/>
<ySuperscriptYOffset value="350"/>
<yStrikeoutSize value="50"/>
<yStrikeoutPosition value="269"/>
<sFamilyClass value="0"/>
<panose>
<bFamilyType value="2"/>
<bSerifStyle value="4"/>
<bWeight value="5"/>
<bProportion value="2"/>
<bContrast value="5"/>
<bStrokeVariation value="5"/>
<bArmStyle value="5"/>
<bLetterForm value="3"/>
<bMidline value="3"/>
<bXHeight value="4"/>
</panose>
<ulUnicodeRange1 value="10000000 00000000 00000000 10101111"/>
<ulUnicodeRange2 value="01010000 00000000 00100000 01001010"/>
<ulUnicodeRange3 value="00000000 00000000 00000000 00000000"/>
<ulUnicodeRange4 value="00000000 00000000 00000000 00000000"/>
<achVendID value="ADBE"/>
<fsSelection value="00000000 01000000"/>
<fsFirstCharIndex value="32"/>
<fsLastCharIndex value="64258"/>
<sTypoAscender value="726"/>
<sTypoDescender value="-274"/>
<sTypoLineGap value="200"/>
<usWinAscent value="927"/>
<usWinDescent value="283"/>
<ulCodePageRange1 value="00000000 00000000 00000000 00000001"/>
<ulCodePageRange2 value="00000000 00000000 00000000 00000000"/>
<sxHeight value="449"/>
<sCapHeight value="689"/>
<usDefaultChar value="32"/>
<usBreakChar value="32"/>
<usMaxContex value="4"/>
</OS_2>
<name>
<namerecord nameID="0" platformID="1" platEncID="0" langID="0x0">
Copyright © 2005 Adobe Systems Incorporated. All Rights Reserved.
</namerecord>
<namerecord nameID="1" platformID="1" platEncID="0" langID="0x0">
Temp Font
</namerecord>
<namerecord nameID="2" platformID="1" platEncID="0" langID="0x0">
Regular
</namerecord>
<namerecord nameID="3" platformID="1" platEncID="0" langID="0x0">
1.001;ADBE;TempFont-Regular
</namerecord>
<namerecord nameID="4" platformID="1" platEncID="0" langID="0x0">
Temp Font Regular
</namerecord>
<namerecord nameID="5" platformID="1" platEncID="0" langID="0x0">
Version 1.00
</namerecord>
<namerecord nameID="6" platformID="1" platEncID="0" langID="0x0">
TempFont-Regular
</namerecord>
<namerecord nameID="0" platformID="3" platEncID="1" langID="0x409">
Copyright © 2005 Adobe Systems Incorporated. All Rights Reserved.
</namerecord>
<namerecord nameID="1" platformID="3" platEncID="1" langID="0x409">
Temp Font
</namerecord>
<namerecord nameID="2" platformID="3" platEncID="1" langID="0x409">
Regular
</namerecord>
<namerecord nameID="3" platformID="3" platEncID="1" langID="0x409">
1.001;ADBE;TempFont-Regular
</namerecord>
<namerecord nameID="4" platformID="3" platEncID="1" langID="0x409">
TempFont-Regular
</namerecord>
<namerecord nameID="5" platformID="3" platEncID="1" langID="0x409">
Version 1.00
</namerecord>
<namerecord nameID="6" platformID="3" platEncID="1" langID="0x409">
TempFont-Regular
</namerecord>
</name>
<cmap>
<tableVersion version="0"/>
<cmap_format_4 platformID="0" platEncID="3" language="0">
<map code="0x20" name="space"/><!-- SPACE -->
</cmap_format_4>
<cmap_format_6 platformID="1" platEncID="0" language="0">
<map code="0x9" name="space"/>
</cmap_format_6>
<cmap_format_4 platformID="3" platEncID="1" language="0">
<map code="0x20" name="space"/><!-- SPACE -->
</cmap_format_4>
</cmap>
<post>
<formatType value="3.0"/>
<italicAngle value="0.0"/>
<underlinePosition value="-75"/>
<underlineThickness value="50"/>
<isFixedPitch value="0"/>
<minMemType42 value="0"/>
<maxMemType42 value="0"/>
<minMemType1 value="0"/>
<maxMemType1 value="0"/>
</post>
<CFF>
<CFFFont name="TempFont-Regular">
<version value="001.001"/>
<Notice value="Copyright 2005 Adobe Systems. All Rights Reserved. This software is the property of Adobe Systems Incorporated and its licensors, and may not be reproduced, used, displayed, modified, disclosed or transferred without the express written approval of Adobe. "/>
<FullName value="Temp Font"/>
<FamilyName value="TempFont"/>
<Weight value="Regular"/>
<isFixedPitch value="0"/>
<ItalicAngle value="0"/>
<UnderlineThickness value="50"/>
<PaintType value="0"/>
<CharstringType value="2"/>
<FontMatrix value="0.001 0 0 0.001 0 0"/>
<FontBBox value="-166 -283 1021 927"/>
<StrokeWidth value="0"/>
<!-- charset is dumped separately as the 'GlyphOrder' element -->
<Encoding>
</Encoding>
<Private>
<BlueValues value="-20 0 689 709 459 469 726 728"/>
<BlueScale value="0.039625"/>
<BlueShift value="7"/>
<BlueFuzz value="1"/>
<StdHW value="1"/>
<StdVW value="1"/>
<ForceBold value="0"/>
<LanguageGroup value="0"/>
<ExpansionFactor value="0.06"/>
<initialRandomSeed value="0"/>
<defaultWidthX value="0"/>
<nominalWidthX value="0"/>
</Private>
<CharStrings>
<CharString name=".notdef">
1000 0 50 600 50 hstem
0 50 400 50 vstem
0 vmoveto
500 700 -500 hlineto
250 -305 rmoveto
-170 255 rlineto
340 hlineto
-140 -300 rmoveto
170 255 rlineto
-510 vlineto
-370 -45 rmoveto
170 255 170 -255 rlineto
-370 555 rmoveto
170 -255 -170 -255 rlineto
endchar
</CharString>
<CharString name="space">
1000 endchar
</CharString>
</CharStrings>
</CFFFont>
<GlobalSubrs>
<!-- The 'index' attribute is only for humans; it is ignored when parsed. -->
</GlobalSubrs>
</CFF>
<hmtx>
<mtx name=".notdef" width="500" lsb="0"/>
<mtx name="space" width="250" lsb="0"/>
</hmtx>
</ttFont>
"""
class CBOptions:
def __init__(self):
self.mmFontInfo = None
self.makeNewFonts = 0
self.srcEM = 1000
self.dstEM = 1000
class FDKEnvironmentError(AttributeError):
pass
class CBOptionParseError(KeyError):
pass
class CBFontError(KeyError):
pass
class CBError(KeyError):
pass
def logMsg(*args):
noNewLine = 0
if args[-1] == "noNewLine":
noNewLine = 1
args = args[:-1]
for s in args[:-1]:
print s,
if noNewLine:
print args[-1],
else:
print args[-1]
class SupressMsg:
def write(self, *args):
pass
def makeTempFont(fontPath, supressMsg):
ttFont = None
tempFont = TempFont()
try:
xf = file(fontPath, "wt")
xf.write(tempFont.xmlData)
xf.close()
except(IOError, OSError), e:
logMsg(e)
logMsg("Failed to open temp file '%s': please check directory permissions." % (fontPath))
raise CBError
try:
ttFont = TTFont()
# supress fontTools messages:
stdout = sys.stdout
stderr = sys.stderr
sys.stdout = supressMsg
sys.stderr = supressMsg
ttFont.importXML(fontPath)
sys.stdout = stdout
sys.stderr = stderr
ttFont.save(fontPath) # This is now actually an OTF font file
ttFont.close()
except:
import traceback
traceback.print_exc()
return
def getOptions():
options = CBOptions()
i = 1 # skip the program name.
numOptions = len(sys.argv)
try:
while i < numOptions:
arg = sys.argv[i]
if arg == "-h":
print __help__
sys.exit(0)
elif arg == "-u":
print __help__
sys.exit(0)
elif arg == "-new":
options.makeNewFonts = 1
elif arg == "-srcEM":
i += 1
options.srcEM = eval(sys.argv[i])
elif arg == "-dstEM":
i += 1
options.dstEM = eval(sys.argv[i])
else:
logMsg("Option Error: unknown option : '%s' ." % (arg))
raise CBOptionParseError
i += 1
except IndexError:
logMsg("Option Error: argument '%s' must be followed by a value." % (arg))
raise CBOptionParseError
options.mmFontInfo = MMFontInfo(kMMFontInfoPath)
return options
class MMFontInfo:
def __init__(self, infoPath):
try:
fp = open(infoPath, "rt")
data = fp.read()
fp.close()
except (IOError,OSError):
logMsg( "Error: could not open file %s." % (infoPath))
raise CBOptionParseError
lines = data.splitlines()
self.baseDirs = []
numLines = len(lines)
i = 0
while i < numLines:
line = lines[i]
i += 1
tokenList = line.split(None,1)
key = tokenList[0]
if key == "AxisLabels1":
continue
elif key == "PrimaryInstances":
while 1:
line = lines[i]
i += 1
tokenList = line.split(None, 1)
key = tokenList[0]
if key == "EndInstances":
break
elif key == "MasterDirs":
while 1:
line = lines[i]
i += 1
tokenList = line.split(None, 1)
key = tokenList[0]
if key == "EndDirs":
break
if key[0] != "%":
continue
baseDir = line.split("%")[-1].strip()
self.baseDirs.append(baseDir)
elif key:
value = tokenList[1]
if value.startswith("["):
value = re.sub(r"\]\s*\[", "], [", value)
value = re.sub(r"(-*\d+)\s+(-*\d+)", r"\1, \2", value)
if value [0] == "(":
value = value[1:-1]
elif value == "false":
value = 0
elif value == "true":
value = 1
else:
value = eval(value)
exec("self.%s = value" % (key))
foundAll = 1
for bezDir in self.baseDirs:
if not os.path.exists(bezDir):
logMsg( "Error: Failed to find bez directory %s." % (os.path.baspath(bezDir)))
foundAll = 0
if not foundAll:
raise CBOptionParseError
class FontEntry:
def __init__(self, fontPath, localBezList):
self.fontPath = fontPath
self.bezDirs = localBezList
self.widthsDict = None
self.tempFontPath = None
self.tempFontScaledPath = None
self.ttFont = None
self.mappingFilePath = None
class GlobalHints:
def __init__(self):
self.BlueValues = [-250, -250, 1100, 1100] # For Kanji glyphs, this is the default. we do NOT want x-height.capheight control/overshoot supression.
self.OtherBlues = None
self.StdHW = None
self.StdVW = None
self.StemSnapH = None
self.StemSnapV = None
class ToolPaths:
def __init__(self):
try:
self.exe_dir, fdkSharedDataDir = FDKUtils.findFDKDirs()
except FDKUtils.FDKEnvError:
raise FDKEnvironmentError
if not os.path.exists(self.exe_dir ):
logMsg("The FDK executable dir \"%s\" does not exist." % (self.exe_dir))
logMsg("Please re-instal. Quitting.")
raise FDKEnvironmentError
toolList = ["tx", "autoHint", "IS", "mergeFonts", "stemHist"]
missingTools = []
for name in toolList:
toolPath = name
exec("self.%s = toolPath" % (name))
command = "%s -u 2>&1" % toolPath
pipe = os.popen(command)
report = pipe.read()
pipe.close()
if ("options" not in report) and ("Option" not in report):
print report
print command, len(report), report
missingTools.append(name)
if missingTools:
logMsg("Please re-install the FDK. The executable directory \"%s\" is missing the tools: < %s >." % (self.exe_dir, ", ". join(missingTools)))
logMsg("or the files referenced by the shell scripts are missing.")
raise FDKEnvironmentError
def mergeBezFiles(bezDir, widthsDict, fontPath, srcEM):
"""
First, fix the ttFont's em-box, and put in useless but hopefully safe alignment zone values.
Then, for each bez file, convert it to a T2 string, and add it to the font.
"""
# Collect list of bez files
ttFont = TTFont(fontPath)
bezFileList = []
dirPath = os.path.abspath(os.path.dirname(bezDir))
list = os.listdir(bezDir)
list = filter(lambda name: not name.endswith("BAK"), list)
bezFileList += map(lambda name: os.path.join(bezDir, name), list)
if not bezFileList:
logMsg("Error. No bez files were found in '%s'. " % (bezDir))
# Merge the bez files.
glyphList = ttFont.getGlyphOrder() #force loading of charstring index table
ttFont.getGlyphID(glyphList[-1])
cffTable = ttFont['CFF ']
pTopDict = cffTable.cff.topDictIndex[0]
if srcEM == 1000:
invEM = 0.001
scaleFactor = 1.0
else:
invEM = 1.0/srcEM
scaleFactor = srcEM/1000
pTopDict.FontMatrix = [invEM, 0, 0, invEM, 0, 0];
pTopDict.rawDict["FontMatrix"] = pTopDict.FontMatrix
if not hasattr(pTopDict, "UnderlineThickness"):
pTopDict.UnderlineThickness = 50
pTopDict.UnderlineThickness = pTopDict.UnderlineThickness*scaleFactor
pTopDict.rawDict["UnderlineThickness"] = pTopDict.UnderlineThickness
if not hasattr(pTopDict, "UnderlinePosition"):
pTopDict.UnderlinePosition = -100
pTopDict.UnderlinePosition = pTopDict.UnderlinePosition*scaleFactor
pTopDict.rawDict["UnderlinePosition"] = pTopDict.UnderlinePosition
pChar = pTopDict.CharStrings
pCharIndex = pChar.charStringsIndex
pHmtx = ttFont['hmtx']
for path in bezFileList:
glyphName = os.path.basename(path)
if (glyphName[0] == ".") and (glyphName !=" .notdef"):
continue
if glyphName[0] < 32:
continue
# Check if glyph name has kUCSuffix. If so, we need to remove it
# when inserting this glyph into the font. The suffix is added by BezierLab
# to avoid conflict between UC/lc file names, which neither Mac nor Win can handle.
finalName = glyphName
if finalName[-kLenUC:] == kUCSuffix:
finalName = finalName[:kLenUC]
width = srcEM
if widthsDict:
try:
width = widthsDict[glyphName] # widthsDict is keyed by bez file name, not finalName
except KeyError:
logMsg("Warning: bez file name %s not found in the widths.unscaled file: assigning default width.", glyphName)
pHmtx.metrics[finalName] = [width, 0] # assign arbitrary LSB of 0
bf = open(path, 'rb')
bezData = bf.read()
bf.close()
if BezTools.needsDecryption(bezData):
bezData = BezTools.bezDecrypt(bezData)
t2Program = [width] + BezTools.convertBezToT2(bezData)
newCharstring = T2CharString(program = t2Program)
nameExists = pChar.has_key(finalName)
# Note that since the ttFont was read from XML, its properties are somewhat different than
# when decompiled from an OTF font file: topDict.charset is None, and the charstrings are not indexed.
if nameExists:
gid = pChar.charStrings[finalName]
pCharIndex.items[gid] = newCharstring
else:
# update CFF
pCharIndex.append(newCharstring)
gid = len(pTopDict.charset)
pChar.charStrings[finalName] = gid # haven't appended the name to charset yet.
pTopDict.charset.append(finalName)
# Now update the font's BBox.
for key in ttFont.keys():
table = ttFont[key]
ttFont.save(fontPath) # Compile charstrings, so that charstrings array is all up to date.
ttFont.close()
ttFont = TTFont(fontPath)
cffTable = ttFont['CFF ']
pTopDict = cffTable.cff.topDictIndex[0]
bbox = [srcEM, srcEM, -srcEM, -srcEM ]
glyphSet = ttFont.getGlyphSet()
pen = BoundsPen(glyphSet)
for glyphName in glyphSet.keys():
glyph = glyphSet[glyphName]
glyph.draw(pen)
if pen.bounds:
x0, y0, x1,y1 = pen.bounds
if x0 < bbox[0]:
bbox[0] = x0
if y0 < bbox[1]:
bbox[1] = y0
if x1 > bbox[2]:
bbox[2] = x1
if y1 > bbox[3]:
bbox[3] = y1
pTopDict.FontBBox = bbox
pTopDict.rawDict["FontBBox"] = bbox
for key in ttFont.keys():
table = ttFont[key]
ttFont.save(fontPath)
ttFont.close()
return
def getHintData(reportPath, dict):
try:
hf = file(reportPath, "rt")
data = hf.read()
hf.close()
except (IOError, OSError), e:
logMsg("Failed to open hint report '%s'. System error <%s>." % (reportPath, e))
raise CBError
hintList = re.findall(r"(\d+)\s+(-*\d+)\s+\[[^]\r\n]+\]", data)
for entry in hintList:
dict[ eval(entry[1]) ] = eval(entry[0])
return
def cmpWidth(first, last):
first = first[2]
last = last[2]
return cmp(first,last)
def getBestValues(stemDict, ptSizeRange, srcResolution, dstResolution):
"""
For each of a range of point sizes, a hint will cover +- a delta, which may include other hints.
I want to construct an optimal StemW hint by finding the hint which covers the largest hint count, for all
the point sizes of intterest
I keep the current count total in countDict[stemWdith] = currrentCount. I initially set all the values to 0.
for each point size
calculate the delta
for each stem width
add up all the counts for all the stem widths which are within +/- delta of the stem width;
add this to the countDict[stemWdith] value.
Normalize the count values by the number of pt size we tried
Pick the stem width the maximum count value.
Pick all the stems with a count greater than 1 for the StemSnap array, up to a max of 12, that do not overlap with the
main stem width
"""
countDict = {}
widthList = stemDict.keys()
for width in widthList:
countDict[width] = 0
maxDelta = 0
for ptSize in ptSizeRange:
delta = (0.35*72*srcResolution)/(ptSize*dstResolution)
if maxDelta < delta:
maxDelta = delta
for width in widthList:
top = int(round(width+delta))
bottom = int(round(width-delta))
if bottom == top:
top +=1
for i in range(bottom, top):
if stemDict.has_key(i):
countDict[width] = countDict[width] + stemDict[i]
countList = countDict.items()
countList = map(lambda entry: [entry[1], stemDict[ entry[0]], entry[0]], countList)
countList.sort()
countList.reverse()
# This is so that it will sort in order by
# entry[0] = total count for width, i.e. the sum of all the counts of the widths that it overlaps +/- the delta
# etnry[1] = the original count for the width
# entry[2] = the width
bestStem = countList[0][2]
bestStemList = [bestStem]
numPtSizes = len(ptSizeRange)
tempList = [countList[0]]
for entry in countList[1:]:
if not entry[0] > numPtSizes:
break # Weed out any stem width that was represented only once in one glyph
tempList.append(entry)
# Now we need to weed out the entries that overlap
#Sort by ascending width, and then save each succesive width only if does nto overlap with the last saved width.
countList = tempList
if len(tempList) > 1:
tempList = [countList[0]] # save the most popular width
countList = countList[1:] # remove it from the list
countList.sort(cmpWidth)
# Some of these may overlap with the tolerance of +/- maxDelta. Weed out the ones that overlap
lastWidth = countList[0][2]
for entry in countList:
width = entry[2]
if ((float(width)*dstResolution)/srcResolution) < 1: # don't copy over any values that will be less than 1 in the final font.
continue
if width > (lastWidth + maxDelta):
tempList.append(entry)
lastWidth = width
tempList.sort() # sort them in order of decreasing popularity again.
tempList.reverse()
bestStemList = tempList[:12] # Allow a max of 12 StemSnap values
bestStemList = map(lambda entry: entry[2], bestStemList)
bestStemList.sort()
return bestStem, bestStemList
def getNewHintInfo(toolPaths, options, fontPath, ptSizeRange, srcResolution, dstResolutiion):
"""
This is being called to collect new hint info from one or more fonts. From
each temp font in turn, we collect the stem info,tracking the total count
for each stem or zone., and extarct the best stem width and StemSnap list.
"""
globalHints = GlobalHints()
hStemDict = {}
vStemDict= {}
extensionList = [ ".hstem.txt", ".vstem.txt"]
logMsg( "\tDeriving new hints from temp font: ", fontPath)
hstemPath = fontPath+".hstm.txt"
vstemPath = fontPath+".vstm.txt"
if os.path.exists(hstemPath):
os.remove(hstemPath)
if os.path.exists(vstemPath):
os.remove(vstemPath)
command = "%s \"%s\" 2>&1" % ( toolPaths.stemHist, fontPath)
pipe = os.popen(command)
report = pipe.read()
pipe.close()
getHintData(hstemPath, hStemDict)
getHintData(vstemPath, vStemDict)
if not gDebug:
if os.path.exists(hstemPath):
os.remove(hstemPath)
if os.path.exists(vstemPath):
os.remove(vstemPath)
if hStemDict:
globalHints.StdHW, globalHints.StemSnapH = getBestValues(hStemDict, ptSizeRange, srcResolution, dstResolutiion)
if vStemDict:
globalHints.StdVW, globalHints.StemSnapV = getBestValues(vStemDict, ptSizeRange, srcResolution, dstResolutiion)
return globalHints
def getOldHintInfo(toolPaths, options, fontPath):
globalHints = GlobalHints()
srcEM = float(options.srcEM)
dstEM = float(options.dstEM)
seenFont = 0
if os.path.exists(fontPath):
command = "%s -0 \"%s\" 2>&1" % ( toolPaths.tx, fontPath)
pipe = os.popen(command)
report = pipe.read()
pipe.close()
match = re.search(r"BlueValues\s+\{(.+?)\}", report)
if match:
globalHints.BlueValues = eval( "[" + match.group(1) + "]")
globalHints.BlueValues = map(lambda val: int(round(val*srcEM/dstEM)), globalHints.BlueValues)
else:
logMsg("Error. The row font '%s' did not have a BlueValues entry in its font dict." % (fontPath))
raise CBError
match = re.search(r"OtherBlues\s+\{(.+?)\}", report)
if match:
globalHints.OtherBlues = eval( "[" + match.group(1) + "]")
globalHints.OtherBlues = map(lambda val: int(round(val*srcEM/dstEM)), globalHints.OtherBlues)
match = re.search(r"StdHW\s+(\d+)", report)
if match:
globalHints.StdHW = int(round(eval(match.group(1))) * srcEM/dstEM)
match = re.search(r"StdVW\s+(\d+)", report)
if match:
globalHints.StdVW = int(round(eval(match.group(1))) * srcEM/dstEM)
match = re.search(r"StemSnapH\s+\{(.+?)\}", report)
if match:
globalHints.StemSnapH = eval( "[" + match.group(1) + "]")
globalHints.StemSnapH = map(lambda val: int(round(val*srcEM/dstEM)), globalHints.StemSnapH)
match = re.search(r"StemSnapV\s+\{(.+?)\}", report)
if match:
globalHints.StemSnapV = eval( "[" + match.group(1) + "]")
globalHints.StemSnapV = map(lambda val: int(round(val*srcEM/dstEM)), globalHints.StemSnapV)
seenFont = 1
logMsg("\tTaking global hint metrics from font %s." % (os.path.abspath(fontPath)))
#fields = dir(globalHints)
#fields = filter(lambda name: name[0] != "_", fields)
#for name in fields:
# print "\t%s: %s" % (name, eval("globalHints.%s" % name))
if not seenFont:
logMsg("Could not find existing row font from which to take hint values.")
raise CBError
return globalHints
def openFileAsTTFont(path, txPath):
# If input font is CFF or PS, build a dummy ttFont in memory for use by AC.
# return ttFont, and flag if is a real OTF font Return flag is 0 if OTF, 1 if CFF, and 2 if PS/
fontType = 0 # OTF
tempPath = os.path.dirname(path)
tempPathBase = os.path.join(tempPath, "temp.autoHint")
tempPathCFF = tempPathBase + ".cff"
try:
ff = file(path, "rb")
data = ff.read(10)
ff.close()
except (IOError, OSError):
logMsg("Failed to open and read font file %s." % path)
if data[:4] == "OTTO": # it is an OTF font, can process file directly
try:
ttFont = TTFont(path)
except (IOError, OSError):
raise ACFontError("Error opening or reading from font file <%s>." % path)
except TTLibError:
raise ACFontError("Error parsing font file <%s>." % path)
try:
cffTable = ttFont["CFF "]
except KeyError:
raise ACFontError("Error: font is not a CFF font <%s>." % fontFileName)
return ttFont, fontType
# It is not an OTF file.
if (data[0] == '\1') and (data[1] == '\0'): # CFF file
fontType = 1
tempPathCFF = path
elif not "%" in data:
#not a PS file either
logMsg("Font file must be a PS, CFF or OTF fontfile: %s." % path)
raise ACFontError("Font file must be PS, CFF or OTF file: %s." % path)
else: # It is a PS file. Convert to CFF.
fontType = 2
command="%s -cff \"%s\" \"%s\" 2>&1" % (txPath, path, tempPathCFF)
pipe = os.popen(command)
report = pipe.read()
pipe.close()
if "fatal" in report:
logMsg("Attempted to convert font %s from PS to a temporary CFF data file." % path)
logMsg(report)
raise ACFontError("Failed to convert PS font %s to a temp CFF font." % path)
# now package the CFF font as an OTF font for use by AC.
ff = file(tempPathCFF, "rb")
data = ff.read()
ff.close()
try:
ttFont = TTFont()
cffModule = getTableModule('CFF ')
cffTable = cffModule.table_C_F_F_('CFF ')
ttFont['CFF '] = cffTable
cffTable.decompile(data, ttFont)
except:
import traceback
traceback.print_exc()
logMsg("Attempted to read font %s as CFF." % path)
raise ACFontError("Error parsing font file <%s>." % fontFileName)
return ttFont, fontType
def saveFileFromTTFont(ttFont, inputPath, outputPath, fontType, txPath):
overwriteOriginal = 0
if inputPath == outputPath:
overwriteOriginal = 1
tempPath = os.path.dirname(inputPath)
tempPath = os.path.join(tempPath, "temp.autoHint")
if fontType == 0: # OTF
if overwriteOriginal:
ttFont.save(tempPath)
shutil.copyfile(tempPath, inputPath)
else:
ttFont.save(outputPath)
ttFont.close()
else:
data = ttFont["CFF "].compile(ttFont)
if fontType == 1: # CFF
if overwriteOriginal:
tf = file(tempPath, "wb")
tf.write(data)
tf.close()
shutil.copyfile(tempPath, inputPath)
else:
tf = file(outputPath, "wb")
tf.write(data)
tf.close()
elif fontType == 2: # PS.
tf = file(tempPath, "wb")
tf.write(data)
tf.close()
if overwriteOriginal:
command="%s -t1 \"%s\" \"%s\" 2>&1" % (txPath, tempPath, inputPath)
else:
command="%s -t1 \"%s\" \"%s\" 2>&1" % (txPath, tempPath, outputPath)
pipe = os.popen(command)
report = pipe.read()
pipe.close()
logMsg(report)
if "fatal" in report:
raise IOError("Failed to convert hinted font temp file with tx %s" % tempPath)
if overwriteOriginal:
os.remove(tempPath)
# remove temp file left over from openFile.
os.remove(tempPath + ".cff")
def addHints(globalHints, fontPath, txPath):
ttFont, fontType = openFileAsTTFont(fontPath, txPath)
privateDict = ttFont['CFF '].cff.topDictIndex[0].Private
fields = dir(globalHints)
fields = filter(lambda name: name[0] != "_", fields)
for name in fields:
val = eval("globalHints.%s" % name)
#print name,val, eval("privateDict.%s" % (name)
if val != None:
exec("privateDict.%s = val" % (name))
elif eval("hasattr(privateDict, \"%s\")" % name):
exec("del privateDict.%s" % name)