forked from adobe-type-tools/python-scripts
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathkernCheck.py
More file actions
1990 lines (1759 loc) · 65.9 KB
/
kernCheck.py
File metadata and controls
1990 lines (1759 loc) · 65.9 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
#!/bin/env python
__copyright__ = """Copyright 2017 Adobe Systems Incorporated (http://www.adobe.com/). All Rights Reserved.
"""
__doc__ = """
kernCheck performs several (lengthy) checks on the GPOS table kern
feature in an OpenType font.
It first looks for glyph pairs that collide/overlap. It uses the 'tx'
tool to rasterize glyphs at 200 pts, and uses the 'spot -t GPOS=7
<font>" command to get the kerning data. It then checks every glyph
pair by overlapping the bitmaps at the (advance width + kern
adjustment) to see if any pixels overlap. By default, it checks only
kerned glyph pairs, but with an option it will check all possible glyph
pairs.
If the doAll option is used, kernCheck will check all the
possible glyph pairs for collisions.
if the -doMore option is used, kernCheck will check all the kern
pairs for overlap, and it will check all the glyph pairs that do not
meet any of the following criteria:
- either left or right glyph is a swash glyph: suffix is ".swsh"
or ".swash".
- the right and left glyphs belong to different scripts. This is
tested by trying to extract a Unicode value for both glyphs, and
assigning a script according to groups of Unicode block ranges.
- the right glyphs is intended only to begin a word (suffix
ends in '.init' or '.begin'), and the left glyph is not punctuation.
- the left glyph is lowercase, and the right glyph is uppercase
or smallcaps
The kernCheck script then looks to see if any class kern statements block
any other kern statements. This is an issue only when subtable breaks
are used, or when regular kerning and contextual kerning is used. The
script can only deal with contextual kern pos statements that use a
single marked glyph.
NOTE! the time needed is related to the square of the number of glyphs.
This script will run in a few minutes for a font with 300 glyphs, but can
take more than hour for a font with 3000 glyphs.
For those interested in programming, this script also contains a
disabled method for automatically calculating line-spacing. My idea was
to use the calculated line-spacing to detect bad kern values. However,
the method has so many bad results that it generated far too many false
positives to be useful. I still have hope that the methods can be
improved enough to be useful, but that will have to wait. This is not
the InDesign method, which actually works less well.
"""
__usage__ = """kernCheck v 1.6 January 16 2014
kernCheck [-u] [-h]
kernCheck [-ppEM <integer>] [-doAll] [-log <path to output log file>] -limit <number> -sortByName -sortByArea <path to font file>
kernCheck -ptSize <number> -limit <number> -sortByName -sortByArea -makePDF <font file path> [<log file path>] [<pdf file path>]
kernCheck -subtableCheck [-log <path to output log file>] <path to font file>
Note that with the -makePDf option, kernCheck requires as input the
log file which is made by running kernCheck previously with the -log
option.
-u : write usage
-h : show help: explains logic for ignoring some glyph pairs.
-ppEM <integer> : Sets the size of the bitmaps used for the glyph overlap checks. Default value is 100 pixels per em-square.
-doMore : The glyph overlap check will check most of the possible glyph pairs; by default, only kerned pairs are checked.
-doAll : The glyph overlap check will check all possible glyph pairs; by default, only kerned pairs are checked.
-log< path to output log file>
: Write output to the named log file. By default, the log file has same name and location as font file, but with suffix ".kc.txt".
-limit <integer> : Omit all glyph pairs with an overlap less than the limit.
-sortByArea : Sort output by size of overlap area; default is the log file order. Affects log file and PDF, but not messages during processing.
-sortByName : Sort output by left and right glyph names; default is the log file order. Affects log file and PDF, but not messages during processing.
-subtableCheck : Do only the check of subtables to see if any GPOS table kerning rules mask other rules.
-makePDF <font file path> [<log file path>] [<pdf file path>]
: Write a PDF file of the glyph overlaps. This option
works on data from the log file in order to allow the
user to edit and sort the data before making a PDF. If
the log file path is omitted, then a default path is
formed by adding the suffix 'kc.txt" to the font file
path. If the path to the output PDF file is omitted,
it is constructed by adding ".pdf" to the log file
path.
-ptSize <number> : Set the point size of the glyph pair outline in the PDF report.
"""
__help__ = __doc__
__methods__ = """
"""
import sys
import os
import re
import math
import traceback
from afdko import agd, FDKUtils, ProofPDF, otfPDF, ttfPDF
from afdko.fontPDF import FontPDFParams, makeKernPairPDF, kDrawTag, kDrawPointTag, kShowMetaTag
kDefaultppEM = 100
kLogFileExt = ".kc.txt"
kPDFExt = ".pdf"
gAGDDict = {}
kAllGlyphs = "AllGlyphNames" # A key in seenLeftSideDict indicating that the left side was a regular class name, and will mask all subsequent kerns
# in the same lookup with the same left-side glyphs.
class Reporter:
def __init__(self,logFileName = None):
self.fp = None
self.fileName = logFileName
if logFileName:
try:
self.fp = open(logFileName, "wt")
except (OSError,IOError):
print "Error: could not open file <%s>. Will not save log." % (logFileName)
print "\t%s" % (traceback.format_exception_only(sys.exc_type, sys.exc_value)[-1])
def write(self, *args):
hasFP = self.fp
for arg in args:
print arg
def close(self, fontPath, sortType, overlapList, conflictMsgList):
fontName = os.path.basename(fontPath)
if self.fp:
if sortType == 1:
overlapList = map(lambda entry: (entry[2:] + entry[:2]), overlapList)
overlapList.sort()
overlapList = map(lambda entry: (entry[3:] + entry[:3]), overlapList)
elif sortType == 2:
overlapList.sort()
overlapList.reverse()
textList = map(lambda entry: "\tError: %s pixels overlap at %s ppem In glyph pair '%s %s with kern %s'." % (entry[0], entry[1], entry[2], entry[3], entry[4]), overlapList)
data = os.linesep.join(textList)
self.fp.write("# kernCheck report for font: %s. %s" % (fontName, os.linesep))
self.fp.write("%s### Glyph pairs with overlapping contours.%s" % (os.linesep, os.linesep))
if not data.strip():
data = "\tNone" + os.linesep
self.fp.write(data)
self.fp.write("%s### Conflicting GPOS kern rules.%s" % (os.linesep, os.linesep))
data = os.linesep.join(conflictMsgList)
if not data.strip():
data = "\tNone" + os.linesep
self.fp.write(data)
self.fp.close()
print "Log saved to file <%s>." % (self.fileName)
logMsg = None
class KernSubtable:
def __init__(self, leftClassDict, rightClassDict, kernPairDict, backTrack = None, lookAhead = None):
self.leftClassDict = leftClassDict
self.rightClassDict = rightClassDict
self.backTrack = backTrack
self.lookAhead = lookAhead
self.kernPairDict = kernPairDict
def __repr__(self):
return os.linesep.join(["", "Kern Subtable:", "Left Classes: " + repr(self.leftClassDict), "Right Classes: " + repr(self.rightClassDict), "Kern Dict: " + repr(self.kernPairDict)])
def parseContextPos(line):
backTrack = lookAhead = leftSide = rightSide = valueRecord = None
tokens = line.split()
tokens = tokens[1:] # get rid of initial pos.
if 0: # len(tokens) == 133:
import pdb
pdb.set_trace()
numTokens = len(tokens)
i = 0
runRecords = [] # Each run record is a [ [glyph list}, value-record]
classList = None
while i < numTokens:
token = tokens[i]
i += 1
glyphRun = None
tokenIsMarked = 0
if token[-1] == "'":
tokenIsMarked = 1
token = token[:-1]
if token[0] == "[":
if classList != None:
raise ValueError("Error: saw beginning of class without ending previous class.")
token = token[1:]
classList = []
if not token:
continue
if len(token) > 1:
if token[-1] == "]":
token = token[:-1]
classList.append(token)
glyphRun = classList
classList = None
else:
classList.append(token)
elif token[-1] == "]":
if classList == None:
raise ValueError("Error: saw end of class without beginning class.")
if len(token) > 1:
token = token[:-1]
classList.append(token)
glyphRun = classList
classList = None
elif classList != None:
classList.append(token)
else:
glyphRun = token
if tokenIsMarked and not glyphRun:
raise ValueError("Error: saw marked token without defining a glyph run!.")
if not glyphRun:
continue
if not tokenIsMarked:
if not runRecords:
if not backTrack:
backTrack = []
backTrack.append(glyphRun)
else:
if token == "lookup": # Just skip this, and the following looup[ index.
token = tokens[i]
i += 1
continue
if not lookAhead:
lookAhead = []
lookAhead.append(glyphRun)
glyphRun = None
else:
# we have a marked record
if lookAhead:
raise ValueError("Error: seeing a seond marked glyph run.")
# Next token may be the value record, either an integer or a value record in the form < a b c d >
token = tokens[i]
i += 1
valueRecord = None
if not token[0] == "<":
try:
# maybe it is an integer.
valueRecord = eval(token)
except (ValueError, NameError, SyntaxError):
# it must be a new glyph/class token
i -= 1
runRecords.append([glyphRun, [0,0,0,0]])
glyphRun = None
continue
else:
# token begins with "<".
valueList = []
numValues = 0
if len(token) > 1:
valueList.append(token[1:])
numValues = 1
while numValues < 4:
numValues +=1
token = tokens[i]
valueList.append(token)
i +=1
if token[-1] == ">":
token = token[:-1]
valueList[-1] = token
else:
token = tokens[i]
i += 1
if not token == ">":
logMsg("\tError:value record < a b c d > is not terminated! '%s'." % (line))
return None, None, None, None, None
for j in range(4):
try:
valueList[j] = eval(valueList[j])
except (ValueError, NameError):
logMsg("\tError:value record < a b c d > has value which is not an integer! '%s'." % (line))
return None, None, None, None, None
valueRecord = valueList
runRecords.append([glyphRun, valueRecord])
glyphRun = None
if not runRecords:
logMsg("\tError:Failed to find marked runs in contextual pos statement! '%s'." % (line))
raise ValueError("Hello")
return None, None, None, None, None
if backTrack and (len(runRecords) == 1):
# usual format pos A B' value;
leftSide = backTrack[-1]
backTrack = backTrack[:-1]
if not backTrack:
backTrack = None
if type(leftSide) != type(""):
leftSide = tuple(leftSide)
rightSide = runRecords[0][0]
if type(rightSide) != type(""):
rightSide = tuple(rightSide)
valueRecord = runRecords[0][1]
elif len(runRecords) == 2:
leftSide = runRecords[0][0]
if type(leftSide) != type(""):
leftSide = tuple(leftSide)
rightSide = runRecords[1][0]
if type(rightSide) != type(""):
rightSide = tuple(rightSide)
if runRecords[1][1]:
valueRecord = runRecords[1][1]
if (runRecords[0][1]):
logMsg("\tError: Can deal only with value record at end of marked glyph run. ! '%s'." % (line))
return backTrack, lookAhead, leftSide, rightSide, valueRecord
def parseKernLookup(featureText, fontFlatKernTable, lookup):
# leftTupleDict is keyed by glyph class defintion, and the value is a class name. Same for rightTupleDict
# leftDict is keyed by unique class name, and the value is the class glyph name list as a tuple.
# kernPairDict is keyed by left-side names, class or otherwise. Value is rightSideDict. This is keyed by
# right side names, class or otherwise, and values are a value record.
# fontFlatKernTable is the same idea as kernPairDict, but with classes flattened, every left-side glyph in any class def
# is a key, as is any right-side glyph.
textBlocks = featureText.split("# -------- SubTable")
subtableList = []
if textBlocks:
sti = -1
for textBlock in textBlocks:
sti +=1
isClassPair = 0
contextEntry = None
if re.search(r"pos\s+[^;]+?'", textBlock):
# it is a contextual positioning rule
isContextual = 1
posList = re.findall(r"\s(pos\s+[^;]+);", textBlock)
leftDict = {}
leftTupleDict = {}
rightDict = {}
rightTupleDict = {}
kernPairs = []
for line in posList:
backTrack, lookAhead, leftSide, rightSide, valueRecord = parseContextPos(line)
if leftSide == None:
continue
if type(leftSide) == type(()):
try:
leftName = leftTupleDict[leftSide]
except KeyError:
leftName = "@CONTEXT_LEFT_CLASS_%s" % (len(leftDict))
leftDict[leftName] = leftSide
leftTupleDict[leftSide] = leftName
else:
leftName = leftSide
leftSide = None
if type(rightSide) == type(()):
try:
rightName = rightTupleDict[rightSide]
except KeyError:
rightName = "@CONTEXT_RIGHT_CLASS_%s" % (len(rightDict))
rightDict[rightName] = rightSide
rightTupleDict[rightSide] = rightName
else:
rightName = rightSide
rightSide = None
kernPairs.append( [leftName, rightName, str(valueRecord)])
contextEntry = [backTrack, lookAhead, leftSide, rightSide]
elif re.search(r"@", textBlock):
# it is a class kern subtable.
isClassPair = 1
glyphLeftClasses = re.findall(r"[\r\n](@LEFT\S+)\s*=\s*\[([^]]+)\]", textBlock)
leftDict = {}
for classEntry in glyphLeftClasses:
leftDict[classEntry[0] ] = classEntry[1].split()
rightDict = {}
glyphRightClasses = re.findall(r"[\r\n](@RIGHT\S+)\s*=\s*\[([^]]+)\]", textBlock)
for classEntry in glyphRightClasses:
rightDict[classEntry[0] ] = classEntry[1].split()
kernPairs = re.findall(r"pos\s+(\S+)\s+(\S+)\s+(-*\d+)", textBlock)
kernPairs = filter(lambda kernPair: kernPair[2] != "0", kernPairs)
else:
# it is a non-class kern subtable.
leftDict = rightDict = None
kernPairs = re.findall(r"pos\s+(\S+)\s+(\S+)\s+(-*\d+)", textBlock)
kernPairs = filter(lambda kernPair: kernPair[2] != "0", kernPairs)
kernPairDict = {}
for pairEntry in kernPairs:
leftName = pairEntry[0]
rightName = pairEntry[1]
value = eval(pairEntry[2])
if type(value) != type(0):
#value = value[0] + value[2]
temp = 0
for v in value:
temp += abs(v)
if temp:
value = str(value)
else:
value = 0
rightSideDict = kernPairDict.get(leftName, {})
rightSideDict[rightName] = value
kernPairDict[leftName] = rightSideDict
# Now add define fontFlatKernTable, using the full expansion of the classes.
leftClassName = rightClassName = None
try:
leftList = leftDict[leftName]
leftClassName = leftName
except (TypeError,KeyError):
leftList = [leftName]
try:
rightList = rightDict[rightName]
rightClassName = rightName
except (TypeError,KeyError):
rightList = [rightName]
for leftGlyphName in leftList:
try:
rightSideGlyphDict = fontFlatKernTable[leftGlyphName]
except KeyError:
rightSideGlyphDict = {}
fontFlatKernTable[leftGlyphName] = rightSideGlyphDict
for rightGlyphName in rightList:
try:
valueList = rightSideGlyphDict[rightGlyphName]
valueList.append((sti, lookup, leftClassName, rightClassName, value, contextEntry))
# Don't overwrite a value we have already seen.
except KeyError:
rightSideGlyphDict[rightGlyphName] = [(sti, lookup, leftClassName, rightClassName, value, contextEntry)]
if isClassPair:
try:
# Rather than specifying an entry for every other glyph in the font
# with a kern value of 0, I add one entry with this name.
valueList = rightSideGlyphDict[kAllGlyphs]
valueList.append((sti, lookup, leftClassName, rightClassName, 0, None))
# Don't overwrite a value we have already seen.
except KeyError:
rightSideGlyphDict[kAllGlyphs] = [(sti, lookup, leftClassName, rightClassName, 0, None)]
if kernPairDict:
subtable = KernSubtable(leftDict, rightDict, kernPairDict)
subtableList.append(subtable)
return subtableList, fontFlatKernTable
def collectKernData(fontpath):
""" return:
nameDict[leftGlyphName][rightGlyphName] = kern value
tableList[classDicts], where classDict[leftClassNameList][rightClassNameList] = value
"""
scriptDict = {}
lookupIndexDict = {}
command = "spot -t GPOS=7 \"%s\"" % (fontpath)
report = FDKUtils.runShellCmd(command)
featureText = ""
fontFlatKernTable = {}
# pick out the feature blocks
while 1:
m = re.search("# (Printing|Skipping) lookup (\S+) in feature 'kern' for script '([^']+)' language '([^']+).*(\s+# because already dumped in script '([^']+)', language '([^']+)')*", report)
if m:
report = report[m.end(0):]
lookup = m.group(2)
script = m.group(3)
lang = m.group(4)
langDict = scriptDict.get(script, {})
lookupDict = langDict.get(lang, {})
lookupEntry = lookupDict.get(lookup, None)
lookupDict[lookup] = lookupEntry
langDict[lang] = lookupDict
scriptDict[script] = langDict
if m.group(1) == "Skipping":
srcScript = m.group(6)
scrLang = m.group(7)
lookupDict[lookup] = scriptDict[srcScript][scrLang][lookup]
if not lookupDict[lookup]:
logMsg("\tProgram Error: already seen lookup is empty.")
continue
# m.group(1) == "Printing" we collect real feature data.
endm = re.search("# (Printing|Skipping) lookup", report)
if endm:
endmPos = endm.start(0)
featureText = report[:endmPos]
else:
featureText = report
subtableList, fontFlatKernTable = parseKernLookup(featureText, fontFlatKernTable, lookup)
# since spot is printing out the definition here, it has not done so before.
lookupDict[lookup] = lookup
if lookupIndexDict.has_key(lookup):
logMsg("\tProgram Error: lookupIndexDict already has new lookup index.")
lookupIndexDict[lookup] = subtableList
continue
else:
break
if not scriptDict:
logMsg("Error: did not find any kern feature text in the output of the command '%s'." % (command))
return None, None, None
# Now build the dict mapping unique lookup sequences to script/language pairs.
lookupSequenceDict = {}
for script in scriptDict.keys():
langDict = scriptDict[script]
for langTag in langDict.keys():
lookupDict = langDict[langTag]
lookupSequence = tuple(lookupDict.keys())
slList = lookupSequenceDict.get(lookupSequence, [])
slList.append( (script, langTag) )
lookupSequenceDict[lookupSequence] = slList
return lookupIndexDict, lookupSequenceDict, fontFlatKernTable
class TXBitMap:
kIndexPat = re.compile(r"(-*\d+)")
kAdvWidthPath = re.compile(r"(-*\d+),(-*\d+)")
def __init__(self,glyphName, txReport, ppEM):
"""
A tx bit map is a series of scan lines that covers the vertical
extent of the glyph bounding box (BBox).
Each scan line is the same length.
The length of the scan line is the advance width, plus the
number of pixels by which the glyph BBox extends beyond the
origin to the left, and plus the amount by which the glyph Bbox
extends beyond the end of the advance width to the right. Within
each scan line, pixels that are on are represented by the
character '#'. Off pixels between the origin and the advance
width are rpresented by '.'; off pixels outside this range are
represented by spaces.
Each scan line in the output from 'tx'is terminated by a space
and the line number, counting up from the base-line in dex of 0.
The base-line has an additional suffix, an integer pair
representing the left side bearing and the advance width.
"""
# Since the lines in the report are indexed up from 0 at the base-line, the index
# in the report of the top line is the lineindex of the base-line
self.baseLineIndex = eval(self.kIndexPat.search(txReport).group(1))
m = self.kAdvWidthPath.search(txReport)
self.lsb = eval(m.group(1))
self.advanceWidth = eval(m.group(2))
self.ppEM = ppEM
self.glyphName = glyphName
self.center = None
# get scan lines, remove indices from end, find x pos of bbox right.
bboxRight = 0
self.scanLines = scanLines = re.findall(r"[\r\n]([ .#]+)", txReport)
lineLen = min(len(scanLines[-1]), len(scanLines[0]))
# The lines have different numbers of spaces, depending on the number and sign of the line index integer.
for scanLine in scanLines:
i = lineLen-1
while (i > bboxRight) and (scanLine[i] != "#"):
i -= 1
bboxRight = max(bboxRight, i)
self.bboxHeight = len(self.scanLines)
self.bboxTopIndex = self.baseLineIndex # This is the index of the top line, if you start indexing with the base line as line 0.
self.bboxBottomIndex = self.bboxTopIndex + 1 - self.bboxHeight
self.rsb = self.advanceWidth - (bboxRight + 1)
if self.lsb < 0:
self.rsb -= self.lsb
# This is because we want the rsb to be relative to (0,0) and the advance width.
# However, when the lsb is negative, the scan-line starts with abs(lsb) space chars before the (0,0) origin point.
# so that the bboxRight index is actually at BBox.right + abs(lsb)
# get rid of extra spaces and line indices at end of lines.
if self.rsb < 0:
lineLength = bboxRight+1
else:
lineLength = self.advanceWidth
if self.lsb < 0:
lineLength -= self.lsb
self.scanLines = map(lambda line: line[:lineLength], scanLines) # get rid of the final spaces and line indices.
setGlyphClasses(self)
def getCenter(self):
if self.center == None:
center = 0
numI = 0.0
for scanLine in self.scanLines:
lineLen = len(scanLine)
for i in range(lineLen):
if scanLine[i] == "#":
center += i
numI += 1
if numI == 0.0:
center = self.advanceWidth/2.0 + self.lsb
else:
center = center/numI
self.center = int(0.5 + center)
self.area = numI
logMsg(self.glyphName, self.lsb, self.advanceWidth, self.rsb, center)
return self.center
kClassInfoDict = { # glyph name ; (case value, needs extra space)
# 1 means is upper case, 0 means it is lowercase, -1 means unclassified.
"a" : (0, 0),
"A" : (1, 0),
"aacute" : (0, 0),
"Aacute" : (1, 0),
"acircumflex" : (0, 0),
"Acircumflex" : (1, 0),
"adieresis" : (0, 0),
"Adieresis" : (1, 0),
"ae" : (0, 0),
"AE" : (1, 0),
"agrave" : (0, 0),
"Agrave" : (1, 0),
"ampersand" : (-1,1),
"aring" : (0, 0),
"Aring" : (1, 0),
"at" : (-1,1),
"atilde" : (0, 0),
"Atilde" : (1, 0),
"b" : (0, 0),
"B" : (1, 0),
"backslash" : (-1,1),
"braceleft" : (-1,1),
"braceright" : (-1,1),
"bracketleft" : (-1,1),
"bracketright" : (-1,1),
"bullet" : (-1,1),
"c" : (0, 0),
"C" : (1, 0),
"ccedilla" : (0, 0),
"Ccedilla" : (1, 0),
"cent" : (0, 1),
"colon" : (-1,1),
"currency" : (-1,1),
"d" : (0, 0),
"D" : (1, 0),
"dagger" : (-1,1),
"daggerdbl" : (-1,1),
"divide" : (-1,1),
"dollar" : (1, 1),
"e" : (0, 0),
"E" : (1, 0),
"eacute" : (0, 0),
"Eacute" : (1, 0),
"ecircumflex" : (0, 0),
"Ecircumflex" : (1, 0),
"edieresis" : (0, 0),
"Edieresis" : (1, 0),
"egrave" : (0, 0),
"Egrave" : (1, 0),
"eight" : (1, 0),
"ellipsis" : (-1,1),
"equal" : (-1,1),
"eth" : (0, 0),
"Eth" : (1, 0),
"euro" : (1, 1),
"Euro" : (1, 1),
"exclam" : (1,1),
"exclamdown" : (1, 1),
"f" : (0, 0),
"F" : (1, 0),
"five" : (1, 0),
"florin" : (1, 1),
"four" : (1, 0),
"g" : (0, 0),
"G" : (1, 0),
"germandbls" : (0, 0),
"greater" : (-1,1),
"h" : (0, 0),
"H" : (1, 0),
"i" : (0, 0),
"I" : (1, 0),
"iacute" : (0, 0),
"Iacute" : (1, 0),
"icircumflex" : (0, 0),
"Icircumflex" : (1, 0),
"idieresis" : (0, 0),
"Idieresis" : (1, 0),
"igrave" : (0, 0),
"Igrave" : (1, 0),
"j" : (0, 0),
"J" : (1, 0),
"k" : (0, 0),
"K" : (1, 0),
"l" : (0, 0),
"L" : (1, 0),
"less" : (-1,1),
"m" : (0, 0),
"M" : (1, 0),
"multiply" : (-1,1),
"n" : (0, 0),
"N" : (1, 0),
"nine" : (1, 0),
"ntilde" : (0, 0),
"Ntilde" : (1, 0),
"numbersign" : (-1,1),
"o" : (0, 0),
"O" : (1, 0),
"oacute" : (0, 0),
"Oacute" : (1, 0),
"ocircumflex" : (0, 0),
"Ocircumflex" : (1, 0),
"odieresis" : (0, 0),
"Odieresis" : (1, 0),
"oe" : (0, 0),
"OE" : (1, 0),
"ograve" : (0, 0),
"Ograve" : (1, 0),
"one" : (1, 0),
"oslash" : (0, 0),
"Oslash" : (1, 0),
"otilde" : (0, 0),
"Otilde" : (1, 0),
"p" : (0, 0),
"P" : (1, 0),
"paragraph" : (-1,1),
"parenleft" : (-1,1),
"parenright" : (-1,1),
"percent" : (1, 1),
"periodcentered" : (-1,1),
"perthousand" : (1, 1),
"plus" : (-1,1),
"plusminus" : (-1,1),
"q" : (0, 0),
"Q" : (1, 0),
"question" : (1, 1),
"questiondown" : (1, 1),
"r" : (0, 0),
"R" : (1, 0),
"s" : (0, 0),
"S" : (1, 0),
"scaron" : (0, 0),
"Scaron" : (1, 0),
"section" : (-1,1),
"semicolon" : (-1,1),
"seven" : (1, 0),
"six" : (1, 0),
"slash" : (-1,1),
"sterling" : (1, 1),
"t" : (0, 0),
"T" : (1, 0),
"thorn" : (0, 0),
"Thorn" : (1, 0),
"three" : (1, 0),
"two" : (1, 0),
"u" : (0, 0),
"U" : (1, 0),
"uacute" : (0, 0),
"Uacute" : (1, 0),
"ucircumflex" : (0, 0),
"Ucircumflex" : (1, 0),
"udieresis" : (0, 0),
"Udieresis" : (1, 0),
"ugrave" : (0, 0),
"Ugrave" : (1, 0),
"v" : (0, 0),
"V" : (1, 0),
"w" : (0, 0),
"W" : (1, 0),
"x" : (0, 0),
"X" : (1, 0),
"y" : (0, 0),
"Y" : (1, 0),
"yacute" : (0, 0),
"Yacute" : (1, 0),
"ydieresis" : (0, 0),
"Ydieresis" : (1, 0),
"yen" : (1, 1),
"z" : (0, 0),
"Z" : (1, 0),
"zcaron" : (0, 0),
"Zcaron" : (1, 0),
"zero" : (1, 0),
}
def setGlyphClasses(bitMap):
glyphName = bitMap.glyphName
parts = glyphName.split(".", 1)
baseName = parts[0]
try:
suffix = parts[1]
except IndexError:
suffix = None
bitMap.needsExtraSpace = 0 # used in auto-kerning algorithms, not yet done.
if suffix:
bitMap.isBegin = suffix.startswith("init") or suffix.startswith("begin")
bitMap.isEnd = suffix.startswith("falt") or suffix.startswith("fin")
bitMap.isSwash = suffix.startswith("swsh") or suffix.startswith("swash")
bitMap.isSC = suffix.startswith("sc") or suffix.startswith("smcp") or suffix.startswith("c2sc")
else:
bitMap.isBegin =0
bitMap.isEnd =0
bitMap.isSwash =0
bitMap.isSC =0
bitMap.isLig = bitMap.isUC = bitMap.isLC = 0
if not bitMap.isSC: # if glyph is Sc, assume isUC and isLC is 0, and doesn't matter if it is a ligature.
# before doing upper/lower case, have to figure out if it is a ligature.
# as ligatures may have different case on each side.
ligParts = baseName.split("_")
numLigParts = len(ligParts)
if (numLigParts == 1):
if baseName.startswith("uni"):
hexString = baseName[3:]
numLigParts = len(hexString)/4
if numLigParts > 1:
leftLigName = "uni" + hexString[:4]
rightLigName = "uni" + hexString[-4:]
else:
leftLigName = ligParts[0]
rightLigName = ligParts[1]
if numLigParts > 1:
bitMap.isLig = 1
bitMap.LeftisUC, bitMap.LeftisLC = getCase(leftLigName)
bitMap.RightisUC, bitMap.RightisLC = getCase(leftLigName)
else:
bitMap.isLig = 0
bitMap.isUC, bitMap.isLC = getCase(baseName)
# Now set the script value.
uv = None
m = agd.re_uni.match(baseName)
if m:
uv = eval("0x" + m.group(1))
else:
m = agd.re_u.match(baseName)
if m:
uv = eval("0x" +m.group(1))
if uv == None:
dictGlyph = gAGDDict.glyph(baseName)
if dictGlyph and dictGlyph.uni:
uv = eval("0x" + dictGlyph.uni)
if uv:
bitMap.script = agd.getscript(uv)
bitMap.isPunc = agd.kPunctuation.has_key(uv)
if not bitMap.isPunc:
bitMap.isPunc = bitMap.script == "Punctuation"
else:
bitMap.isPunc =0
bitMap.script = agd.kUnknownScript
def getCase(glyphName):
isUC = isLC = 0
# try the hard-coded list.
if kClassInfoDict.has_key(glyphName):
isUpper, needsExtraSpace = kClassInfoDict[glyphName]
if isUpper == 1:
isUC = 1
elif isUpper == 0:
isLC = 1
return isUC, isLC
#Refer to the AGD.
dictGlyph = gAGDDict.glyph(glyphName)
if dictGlyph:
if dictGlyph.maj:
isUC = 1
elif dictGlyph.min:
isLC = 1
return isUC, isLC
def checkGlyphOverlap(leftBitMap, rightBitMap, value, limitVal):
"""
If the sum of the left RSB and the right bitmap LSB and the kern
value are greater than zero, there cannot be an overlap.
If this is not the case, then we need to examine the region of
overlap in each line. On the right side, we start at the edge of the
BBox left, and index to the left. On the left side, we start at the
Bbox right in the overlap, and index to the left. If at each index,
a pixel is on in both bitmaps, there is overlap.
"""
ppEM = leftBitMap.ppEM
origValue = value
if value >= 0:
value = int(0.5 + value*ppEM/1000.0)
else:
value = int(-0.5 + value*ppEM/1000.0)
overlapRange = leftBitMap.rsb + rightBitMap.lsb + value
if overlapRange >= 0:
return None # Can't have an overlap - there is space between the glyph bounding boxes
bboxTopIndex = min(leftBitMap.bboxTopIndex, rightBitMap.bboxTopIndex)
bboxBottomIndex = max(leftBitMap.bboxBottomIndex, rightBitMap.bboxBottomIndex)
bboxHeight = 1 + bboxTopIndex - bboxBottomIndex
if bboxHeight <=0:
return None # Can't have an overlap - the top of one glyph's BBox is below the bottom of hte other glyph's BBox.
leftLineIndex = leftBitMap.bboxTopIndex - bboxTopIndex
rightLineIndex = rightBitMap.bboxTopIndex - bboxTopIndex
# Get the start of the overlap region in the left and right side lines.
if rightBitMap.lsb > 0:
rsStart = rightBitMap.lsb # the lsb is the width of the lsb, so it is also the index of the first 'on' pixel in the line.
rsEnd = rightBitMap.advanceWidth -1
else:
rsStart = 0 # if the rsb is negative, then the first pixel is on.
rsEnd = rightBitMap.advanceWidth -1 - rightBitMap.lsb
lsStart = leftBitMap.advanceWidth + overlapRange - (1 + leftBitMap.rsb)
lsEnd = leftBitMap.advanceWidth - leftBitMap.rsb
if leftBitMap.lsb < 0:
lsStart -= leftBitMap.lsb
lsEnd -= leftBitMap.lsb
if lsStart < 0: # very long swashes on the right side can extend further than the left side of the left bitmap.
lsStart = 0
# this is because leftBBoxRight needs to be char index in the line,
# and when lsb < 0, the line starts with the lsb, not at (0,0).
testRange = -overlapRange
if testRange >= rsEnd - rsStart: # very long swashes on the left side can extend further than the right side of the right bitmap.
testRange = rsEnd - rsStart
if testRange >= lsEnd - lsStart: # very long swashes on the left side can extend further than the right side of the right bitmap.
testRange = lsEnd - lsStart
overlapArea = 0
lineCount = 0
while lineCount < bboxHeight:
leftLine = leftBitMap.scanLines[leftLineIndex]
rightLine = rightBitMap.scanLines[rightLineIndex]
leftLineIndex += 1
rightLineIndex += 1
lineCount += 1
lsi = lsStart
rsi = rsStart
for i in range(testRange):
if (leftLine[lsi] == "#") and (rightLine[rsi] == "#"):
overlapArea +=1
lsi += 1
rsi +=1
if overlapArea >= limitVal:
logMsg("\tError: %s pixels overlap at %s ppem In glyph pair '%s %s with kern %s'." % (overlapArea, ppEM, leftBitMap.glyphName, rightBitMap.glyphName, origValue))
return overlapArea, ppEM, leftBitMap.glyphName, rightBitMap.glyphName, origValue
return None
def skipGlyphPair(leftBitMap, rightBitMap):
skip = 0
if (rightBitMap.script != leftBitMap.script):
return 1
if rightBitMap.isBegin and not leftBitMap.isPunc:
return 1
if leftBitMap.isLig:
leftLC = leftBitMap.LeftisLC
leftUC = leftBitMap.LeftisUC
else:
leftLC = leftBitMap.isLC
leftUC = leftBitMap.isUC
if rightBitMap.isLig:
rightLC = rightBitMap.LeftisLC
rightUC = rightBitMap.LeftisUC
else:
rightLC = rightBitMap.isLC
rightUC = rightBitMap.isUC
if leftLC and (rightUC or rightBitMap.isSC) and (leftBitMap.glyphName[0] != 'n') and (rightBitMap.glyphName[0] != 'T'):
return 1
return 0
def checkForOverlap(fontFlatKernTable, fontPath, ppEM, glyphBitMapDict, doAll, limitVal):