-
Notifications
You must be signed in to change notification settings - Fork 103
/
Autopsy.py
1747 lines (1407 loc) · 66.3 KB
/
Autopsy.py
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
#MenuTitle: Autopsy 1.2
# encoding: utf-8
########################################################################
#
# Autopsy Visual Font Auditing
# 1.2.1
#
# Version for Glyphs (glyphsapp.com)
# (c) 2009 by Yanone
# 2013 Georg Seifert, porting to use CoreGraphics instead of RepordLab to write PDF
# 2015 Jens Kutilek, fixes
#
# http://www.yanone.de/typedesign/autopsy/
#
# GPLv3 or later
#
########################################################################
from Foundation import NSURL, NSMakeRect
from AppKit import NSApp, NSAttributedString, NSFont, NSFontAttributeName, NSColor, NSForegroundColorAttributeName, NSBezierPath, NSRectFill, NSOKButton, NSCancelButton, NSValueTransformerNameBindingOption, NSGraphicsContext
import time, os, string, math, random
from Quartz import CGRectMake, CGPDFContextCreateWithURL, CGPDFContextBeginPage, CGPDFContextEndPage, CGPDFContextClose
try:
from vanilla import *
from vanilla.dialogs import *
except:
Message("Missing Library", "Please install the vanilla library from https://github.com/typesupply/vanilla")
raise ImportError
cm = 72/2.54
mm = cm / 10
A4 = (595.276, 841.89)
letter = (612, 792)
##### Misc.
class Ddict(dict):
def __init__(self, default=None):
self.default = default
def __getitem__(self, key):
if not self.has_key(key):
self[key] = self.default()
return dict.__getitem__(self, key)
def setup_binding_CheckBox(self, Object, KeyPath, options = objc.nil):
self._nsObject.bind_toObject_withKeyPath_options_("value", Object, "values."+KeyPath, options)
CheckBox.binding = setup_binding_CheckBox
def setup_binding_EditText(self, Object, KeyPath, options = objc.nil):
self._nsObject.bind_toObject_withKeyPath_options_("value", Object, "values."+KeyPath, options)
EditText.binding = setup_binding_EditText
def del_binding(self, Object, KeyPath):
Object.unbind_("value")
CheckBox.unbind = del_binding
##### Settings
programname = 'Autopsy'
programversion = '1.2.1'
releasedate = '201504241241'
verbose = False
availablegraphs = ('width', 'bboxwidth', 'bboxheight', 'highestpoint', 'lowestpoint', 'leftsidebearing', 'rightsidebearing')
graphrealnames = {
'width' : 'Width',
'bboxwidth' : 'BBox Width',
'bboxheight' : 'BBox Height',
'highestpoint' : 'BBox Highest',
'lowestpoint' : 'BBox Lowest',
'leftsidebearing' : 'L Sidebearing',
'rightsidebearing' : 'R Sidebearing',
}
pagemargin = Ddict(dict)
pagemargin['left'] = 12
pagemargin['right'] = 10
pagemargin['top'] = 8
pagemargin['bottom'] = 11
scrapboard = Ddict(dict)
graphcoords = Ddict(dict)
# separator between the scrapboard and the tablesboard
headmargin = 15 # mm
separator = 8 # mm
tableseparator = 3 # mm
roundedcorners = 3 # (pt?)
guidelinedashed = (3, 3) # pt on, pt off
# Colors
colourguides = (1, .5, 0, 0)
colourglobalguides = (0, 1, 1, 0)
# Headline
headerheight = 8 # mm
headlinefontsize = 14
#pdfcolour = (0, .05, 1, 0)
pdfcolour = (.25, 0, 1, 0)
#headlinefontcolour = (.25, .25, 1, .8)
headlinefontcolour = (0, 0, 0, 1)
pdffont = Ddict(dict)
pdffont['Regular'] = 'Courier'
pdffont['Bold'] = 'Courier-Bold'
graphcolour = Ddict(dict)
graphcolour['__default__'] = pdfcolour
graphcolour['width'] = (0, .9, .9, 0)
graphcolour['bboxwidth'] = (0, .75, .9, 0)
graphcolour['bboxheight'] = (0, .5, 1, 0)
graphcolour['highestpoint'] = (0, .3, 1, 0)
graphcolour['lowestpoint'] = (0, .1, 1, 0)
graphcolour['leftsidebearing'] = (0, .75, .25, 0)
graphcolour['rightsidebearing'] = (.25, .75, .25, 0)
# Metrics
glyphcolour = (0, 0, 0, 1)
xrayfillcolour = (0, 0, 0, .4)
metricscolour = (0, 0, 0, .5)
metricslinewidth = .5 # pt
scrapboardcolour = (0, 0, 0, 1)
drawboards = False
# Graphs
#tablenamefont = pdffont['Regular']
graphnamefontsize = 8
#pointsvaluefont = pdffont['Regular']
pointsvaluefontsize = 8
############ Classes
class Report:
def __init__(self):
self.gridcolour = metricscolour
self.strokecolour = pdfcolour
self.gridwidth = metricslinewidth
self.strokewidth = 1
self.values = [] # (value, glyphwidth, glyphheight)
self.pointslist = []
# self.scope = 'local' # local or global (relative to this single glyph, or to all glyphs in the pdf)
self.glyphname = ''
self.graphname = ''
self.min = 0
self.max = 0
self.sum = 0
ratio = 0
def addvalue(self, value):
self.values.append(value)
if len(self.values) == 1:
self.min = value[0]
self.max = value[0]
if value[0] > self.max:
self.max = value[0]
if value[0] < self.min:
self.min = value[0]
self.sum += value[0]
def draw(self):
global myDialog
global globalscopemin, globalscopemax
global glyphs
drawrect(self.left * mm, self.bottom * mm, self.right * mm, self.top * mm, '', self.gridcolour, self.gridwidth, None, roundedcorners)
r = .05
mymin = self.min - int(math.fabs(self.min) * r)
mymax = self.max + int(math.fabs(self.max) * r)
if self.scope == 'global':
# Walk through the other graphs and collect their min and max values
for glyph in glyphs:
try:
if reports[glyph][self.graphname].min < mymin:
mymin = reports[glyph][self.graphname].min
except:
mymin = reports[glyph][self.graphname].min
try:
if reports[glyph][self.graphname].max > mymax:
mymax = reports[glyph][self.graphname].max
except:
mymax = reports[glyph][self.graphname].max
if mymax - mymin < 10:
mymin -= 5
mymax += 5
pointslist = []
if not Glyphs.boolDefaults["com_yanone_Autopsy_PageOrientation_landscape"]:
if Glyphs.boolDefaults["com_yanone_Autopsy_drawpointsvalues"] == 1:
DrawText(pdffont['Regular'], pointsvaluefontsize, glyphcolour, self.left * mm + 1*mm, self.bottom * mm - 3*mm, str(int(mymin)))
DrawText(pdffont['Regular'], pointsvaluefontsize, glyphcolour, self.right * mm - 5*mm, self.bottom * mm - 3*mm, str(int(mymax)))
try:
localratio = (self.right - self.left) / (mymax - mymin)
except:
localratio = 0
try:
y = self.top - (self.values[0][2] / 2 / mm * ratio)
except:
y = self.top
for i, value in enumerate(self.values):
x = self.left + (value[0] - mymin) * localratio
pointslist.append((value[0], x, y))
try:
y -= self.values[i+1][2] / mm * ratio
except:
pass
else:
if Glyphs.boolDefaults["com_yanone_Autopsy_drawpointsvalues"] == 1:
DrawText(pdffont['Regular'], pointsvaluefontsize, glyphcolour, self.right * mm + 1*mm, self.bottom * mm + 1*mm, str(int(mymin)))
DrawText(pdffont['Regular'], pointsvaluefontsize, glyphcolour, self.right * mm + 1*mm, self.top * mm - 3*mm, str(int(mymax)))
# DrawText(pdffont['Regular'], graphnamefontsize, self.gridcolour, self.left * mm + 1.7*mm, self.top * mm - 4*mm, graphrealnames[self.graphname])
try:
localratio = (self.top - self.bottom) / (mymax - mymin)
except:
localratio = 0
try:
position = self.left + (self.values[0][1] / 2 / mm * ratio)
except:
position = self.left
for i, value in enumerate(self.values):
x = position
y = self.bottom + (value[0] - mymin) * localratio
pointslist.append((value[0], x, y))
try:
position += self.values[i+1][1] / mm * ratio
except:
pass
# Calculate thickness of stroke according to scope of graph
minthickness = 2
maxthickness = 8
thickness = -.008 * (mymax - mymin) + maxthickness
if thickness < minthickness:
thickness = minthickness
elif thickness > maxthickness:
thickness = maxthickness
DrawTableLines(pointslist, self.strokecolour, thickness)
DrawText(pdffont['Regular'], graphnamefontsize, self.gridcolour, self.left * mm + 1.7*mm, self.top * mm - 4*mm, graphrealnames[self.graphname])
#################################
def SetScrapBoard(pageratio):
global myDialog
scrapboard['left'] = pagemargin['left']
scrapboard['right'] = pagewidth/mm - pagemargin['right']
scrapboard['top'] = pageheight/mm - pagemargin['top'] - headmargin
scrapboard['bottom'] = pagemargin['bottom']
graphcoords['left'] = pagemargin['left']
graphcoords['right'] = pagewidth/mm - pagemargin['right']
graphcoords['top'] = pageheight/mm - pagemargin['top'] - headmargin
graphcoords['bottom'] = pagemargin['bottom']
# Recalculate drawing boards
if not Glyphs.defaults["com_yanone_Autopsy_PageOrientation_landscape"]:
availablewidth = pagewidth/mm - pagemargin['left'] - pagemargin['right']
partial = availablewidth * pageratio
scrapboard['right'] = pagemargin['left'] + partial - separator / 2
graphcoords['left'] = scrapboard['right'] + separator
else:
availablewidth = pageheight/mm - pagemargin['top'] - pagemargin['bottom'] - headmargin
partial = availablewidth * pageratio
scrapboard['bottom'] = pageheight/mm - headmargin - partial + separator / 2
graphcoords['top'] = scrapboard['bottom'] - separator
##################################################################
#
# PDF section
#
def DrawText(font, fontsize, fontcolour, x, y, text):
attributes = {NSFontAttributeName : NSFont.fontWithName_size_(font, fontsize), NSForegroundColorAttributeName: NSColor.colorWithDeviceCyan_magenta_yellow_black_alpha_(fontcolour[0], fontcolour[1], fontcolour[2], fontcolour[3], 1)}
String = NSAttributedString.alloc().initWithString_attributes_(text, attributes)
String.drawAtPoint_((x, y))
def DrawTableLines(list, colour, thickness):
global myDialog
for i, point in enumerate(list):
try:
drawline(list[i][1]*mm, list[i][2]*mm, list[i+1][1]*mm, list[i+1][2]*mm, colour, thickness, None)
except:
pass
NSColor.colorWithDeviceCyan_magenta_yellow_black_alpha_(colour[0], colour[1], colour[2], colour[3], 1).set()
Rect = NSMakeRect(point[1]*mm-(thickness), point[2]*mm-(thickness), thickness*2, thickness*2)
NSBezierPath.bezierPathWithOvalInRect_(Rect).fill()
if Glyphs.defaults["com_yanone_Autopsy_drawpointsvalues"] == 1:
DrawText(pdffont['Regular'], pointsvaluefontsize, glyphcolour, point[1]*mm + (thickness/6+1)*mm, point[2]*mm - (thickness/6+2.5)*mm, str(int(round(point[0]))))
def DrawHeadlineIntoPage(text):
drawrect(pagemargin['left']*mm, pageheight - pagemargin['top']*mm - headerheight*mm, pagewidth - pagemargin['right']*mm, pageheight - pagemargin['top']*mm, pdfcolour, None, 0, None, roundedcorners)
DrawText(pdffont['Bold'], headlinefontsize, headlinefontcolour, 2*mm + pagemargin['left']*mm, 2.2*mm + pageheight - pagemargin['top']*mm - headerheight*mm, text)
def DrawMetrics(f, glyph, xoffset, yoffset, ratio):
global myDialog
#g = Glyph(glyph)
g = glyph.layers[0]
mywidth = g.width
if mywidth == 0:
mywidth = g.bounds.size.width
# Draw metrics
if Glyphs.defaults["com_yanone_Autopsy_drawmetrics"] == 1:
# Versalhöhe
drawline(xoffset*mm, yoffset*mm + capheight(f) * ratio, xoffset*mm + mywidth*ratio, yoffset*mm + capheight(f) * ratio, metricscolour, metricslinewidth, None)
# x-Höhe
drawline(xoffset*mm, yoffset*mm + xheight(f) * ratio, xoffset*mm + mywidth*ratio, yoffset*mm + xheight(f) * ratio, metricscolour, metricslinewidth, None)
# Grundlinie
drawline(xoffset*mm, yoffset*mm, xoffset*mm + mywidth*ratio, yoffset*mm, metricscolour, metricslinewidth, None)
# Bounding Box
drawrect(xoffset*mm, yoffset*mm + descender(f)*ratio, xoffset*mm + mywidth*ratio, yoffset*mm + ascender(f)*ratio, '', metricscolour, metricslinewidth, None, 0)
# Draw guidelines
if Glyphs.boolDefaults["com_yanone_Autopsy_drawguidelines"] == 1 and False: #GSNotImplemented
# Local vertical guides
for guide in g.vguides:
try:
a = (ascender(f)) * math.tan(math.radians(guide.angle))
except:
a = 0
x1 = guide.position / mm * ratio
y1 = (0 - descender(f)) / mm * ratio
x2 = (guide.position + a) / mm * ratio
y2 = (ascender(f) - descender(f)) / mm * ratio
drawline(xoffset*mm + x1*mm, yoffset*mm + y1*mm, xoffset*mm + x2*mm, yoffset*mm + y2*mm, colourguides, metricslinewidth, guidelinedashed)
# Global vertical guides
for guide in f.vguides:
try:
a = (ascender(f)) * math.tan(math.radians(guide.angle))
except:
a = 0
x1 = guide.position / mm * ratio
y1 = (0 - descender(f)) / mm * ratio
x2 = (guide.position + a) / mm * ratio
y2 = (ascender(f) - descender(f)) / mm * ratio
drawline(xoffset*mm + x1*mm, yoffset*mm + y1*mm, xoffset*mm + x2*mm, yoffset*mm + y2*mm, colourglobalguides, metricslinewidth, guidelinedashed)
# Local horizontal guides
for guide in g.hguides:
try:
a = g.width * math.tan(math.radians(guide.angle))
except:
a = 0
x1 = 0
y1 = (guide.position - descender(f)) / mm * ratio
x2 = g.width / mm * ratio
y2 = (guide.position - descender(f) + a) / mm * ratio
drawline(xoffset*mm + x1*mm, yoffset*mm + y1*mm, xoffset*mm + x2*mm, yoffset*mm + y2*mm, colourguides, metricslinewidth, guidelinedashed)
# Global horizontal guides
for guide in f.hguides:
try:
a = g.width * math.tan(math.radians(guide.angle))
except:
a = 0
x1 = 0
y1 = (guide.position - descender(f)) / mm * ratio
x2 = g.width / mm * ratio
y2 = (guide.position - descender(f) + a) / mm * ratio
drawline(xoffset*mm + x1*mm, yoffset*mm + y1*mm, xoffset*mm + x2*mm, yoffset*mm + y2*mm, colourglobalguides, metricslinewidth, guidelinedashed)
# Draw font names under box
if Glyphs.defaults["com_yanone_Autopsy_fontnamesunderglyph"] == 1:
DrawText(pdffont['Regular'], pointsvaluefontsize, glyphcolour, xoffset*mm + 2, yoffset*mm - 8, f.full_name)
# output(f)
def PSCommandsFromGlyph(glyph):
CommandsList = []
for path in glyph.paths:
lastNode = None
if path.closed:
lastNode = path.nodes[-1]
else:
lastNode = path.nodes[0]
CommandsList.append(('moveTo', (lastNode.x, lastNode.y)))
for i, node in enumerate(path.nodes):
if node.type == GSOFFCURVE:
CommandsList.append(('close', (node.x, node.y)))
#if node.type == nMOVE:
# CommandsList.append(('moveTo', (node.x, node.y)))
if node.type == GSLINE:
CommandsList.append(('lineTo', (node.x, node.y)))
if node.type == GSCURVE:
CurveCommandsList = []
CurveCommandsList.append('curveTo')
#for point in node.points:
CurveCommandsList.append( (node.x, node.y) )
point = path.nodes[i-2]
CurveCommandsList.append( (point.x, point.y) )
point = path.nodes[i-1]
CurveCommandsList.append( (point.x, point.y) )
CommandsList.append(CurveCommandsList)
return CommandsList
def DrawGlyph(f, glyph, PSCommands, xoffset, yoffset, ratio, fillcolour, strokecolour, strokewidth, dashed):
if not PSCommands:
type = "glyph"
# Copy glyph into memory (so remove overlap won't affect the current font)
g = glyph.layers[0]
if len(g.components) > 0:
for component in g.components:
position = component.position
DrawGlyph(f, component.component, None, xoffset+(position.x*ratio/mm), yoffset+(position.y*ratio/mm), ratio, fillcolour, strokecolour, strokewidth, dashed)
# Glyph has nodes of its own
if len(g.paths):
PSCommands = PSCommandsFromGlyph(g)
#print PSCommands
else:
PSCommands = ()
else:
type = "PScommands"
if PSCommands:
p = NSBezierPath.bezierPath()
for command in PSCommands:
if command[0] == 'moveTo':
try:
p.close()
except:
pass
x = xoffset*mm + command[1][0] * ratio
y = yoffset*mm + command[1][1] * ratio
p.moveToPoint_((x, y))
#print "('moveTo', (%s, %s))," % (command[1][0], command[1][1])
if command[0] == 'lineTo':
x = xoffset*mm + command[1][0] * ratio
y = yoffset*mm + command[1][1] * ratio
p.lineToPoint_((x, y))
#print "('lineTo', (%s, %s))," % (command[1][0], command[1][1])
if command[0] == 'curveTo':
points = []
for point in command[1:]:
points.append( (xoffset*mm + point[0] * ratio, yoffset*mm + point[1] * ratio) )
p.curveToPoint_controlPoint1_controlPoint2_(points[0], points[1], points[2])
p.closePath()
if fillcolour:
NSColor.colorWithDeviceCyan_magenta_yellow_black_alpha_(fillcolour[0], fillcolour[1], fillcolour[2], fillcolour[3], 1).set()
p.fill()
if strokecolour:
NSColor.colorWithDeviceCyan_magenta_yellow_black_alpha_(strokecolour[0], strokecolour[1], strokecolour[2], strokecolour[3], 1).set()
if dashed:
p.setLineDash_count_phase_(dashed, 2, 0.0)
p.setLineWidth_(strokewidth)
p.stroke()
######### draw primitives
def drawline(x1, y1, x2, y2, colour, strokewidth, dashed):
NSColor.colorWithDeviceCyan_magenta_yellow_black_alpha_(colour[0], colour[1], colour[2], colour[3], 1).set()
Path = NSBezierPath.bezierPath()
Path.moveToPoint_((x1, y1))
Path.lineToPoint_((x2, y2))
Path.setLineWidth_(strokewidth)
if dashed:
Path.setLineDash_count_phase_(dashed, 2, 0.0)
Path.stroke()
def drawrect(x1, y1, x2, y2, fillcolour, strokecolour, strokewidth, dashed, rounded):
Rect = NSMakeRect(x1, y1, x2 - x1, y2 - y1)
Path = NSBezierPath.bezierPathWithRoundedRect_xRadius_yRadius_(Rect, rounded, rounded)
if fillcolour:
NSColor.colorWithDeviceCyan_magenta_yellow_black_alpha_(fillcolour[0], fillcolour[1], fillcolour[2], fillcolour[3], 1).set()
Path.fill()
if strokecolour:
Path.setLineWidth_(strokewidth)
if dashed:
Path.setLineDash_count_phase_(dashed, 2, 0.0)
NSColor.colorWithDeviceCyan_magenta_yellow_black_alpha_(strokecolour[0], strokecolour[1], strokecolour[2], strokecolour[3], 1).set()
Path.stroke()
# collects the glyphs that should be displayed
# and returns list of glyph names
def collectglyphnames():
glyphlist = []
Font = Glyphs.orderedDocuments()[0].font
if Font.selectedLayers is not None:
for Layer in Font.selectedLayers:
glyphlist.append(Layer.parent.name)
return glyphlist
def capheight(f):
return f.masters[0].capHeight
def xheight(f):
return f.masters[0].xHeight
def descender(f):
return f.masters[0].descender
def ascender(f):
return f.masters[0].ascender
def unicode2hex(u):
return string.zfill(string.upper(hex(u)[2:]), 4)
errortexts = []
errors = 0
def raiseerror(text):
global errors, errorslist
errortexts.append(text)
try:
errors += 1
except:
errors = 1
def CheckForUpdates():
return
if Defaults['com_yanone_Autopsy_checkforupdates']:
import webbrowser, urllib
try:
if int(releasedate) < int(urllib.urlopen('http://www.yanone.de/typedesign/autopsy/latestreleasedate.txt').read()):
x = fl.Message('Hey, I was reincarnated as a newer version.\nDo you want to connect to my download page on the internet?')
if x == 1:
webbrowser.open('http://www.yanone.de/typedesign/autopsy/download.php', 1, 1)
except:
pass # No network connection
##### MAIN
def main():
global ratio
global myDialog
global errors, errorstexts
global glyphs
global reports
CheckForUpdates()
# Clear console
if verbose:
Glyphs.clearLog()
output('-- main --')
# Dialog stuff
result = None
NameList = []
# Check, if fonts are present
if len(Glyphs.fonts) < 1:
raiseerror("No fonts open in Glyphs.")
else:
# Check, if fonts have a full_name
# full_name_missing = 0
# for f in Glyphs.fonts:
# if not f.full_name:
# full_name_missing += 1
# if full_name_missing:
# raiseerror("Some fonts don't have a 'Full Name'. Autopsy uses the 'Full Name' for handling fonts.\nPlease fill it out in the 'Font Info' window.")
# Collect glyph names
glyphs = collectglyphnames()
if not glyphs:
raiseerror("No glyphs selected.")
# Initial sorting of fonts by width, weight
widths_plain = '''Ultra-condensed 1
Compressed 1
Extra-condensed 2
Condensed 3
Semi-condensed 4
Narrow 4
Compact 4
Medium (normal) 5
Normal 5
Regular 5
Medium 5
Semi-extended 6
Wide 6
Semi-expanded 6
Expanded 7
Extended 7
Extra-extended 8
Extra-expanded 8
Ultra-expanded 9
Ultra-extended 9'''
weights_plain = '''Thin 250
Hairline 250
Ultra Light 250
Micro 300
Extra Light 300
Fine 300
Slim 300
Dry 300
Clair 300
Skinny 300
Light 350
Semi Light 375
Plain 400
Gamma 400
Normal (Regular) 400
Regular 400
Book 450
News 450
Text 500
Medium 500
Beta 500
Median 500
DemiBold 500
SemiBold 500
Semi Bold 600
Alpha 600
Demi Bold 600
Bold 700
Boiled 700
Noir 700
Fett 700
Not That Fat 700
Extra Boiled 750
Extra Bold 750
Heavy 800
Mega 800
ExtraBold 800
Black 900
UltraBlack 900
Ultra Black 900
Fat 950
Ultra 1000
Super 1000
ExtraBlack 1000
Extra Black 1000'''
# Normal mode
if not errors:
f = Glyphs.fonts[0]
# Add fonts to NameList
if len(f.masters) == 1:
mode = 'normal'
widths = Ddict(dict)
for width in widths_plain.split("\n"):
tmp = width.split("\t")
widths[tmp[0]] = tmp[1]
weights = Ddict(dict)
for weight in weights_plain.split("\n"):
tmp = weight.split("\t")
weights[tmp[0]] = tmp[1]
FontList = []
for f in Glyphs.fonts:
# exclude MM
if len(f.masters) == 1:
# width
#if f.masters[0].width and f.masters[0].width in widths:
# width = widths[f.masters[0].width]
#else:
# width = 500
width = f.masters[0].widthValue
# weights
# weight = 0
# try:
# weight = weights[f.masters[0].weightValue]
# except:
# pass
weight = f.masters[0].weightValue
if weight < 10:
weight = 400
# # familyname
# if f.family_name:
# familyname = f.family_name
# else:
# familyname = '__default__'
familyname = f.familyName
if len(f.instances) > 0:
familyname += " "+f.instances[0].name
FontList.append((width, weight, familyname))
FontList.sort()
for listentry in FontList:
NameList.append(listentry[2])
# MM-mode
elif len(f.masters) > 1:
Message("Problem", "Autopsy for Glyphs does not jet support multiple master Fonts.")
return
mode = 'MM'
familyname = f.familyName+" "+f.masters[0].name
NameList.append(f)
# Some error handling
# if not NameList:
# raiseerror("No fonts open in FontLab.")
# Call Dialog
if NameList and not errors:
myDialog = _listMultiSelect(mode, NameList)
Result = myDialog.Run()
if Result == NSOKButton:
NameList = myDialog.selection
if NameList:
result = []
for anyName in NameList:
if mode == 'normal':
result.append(getFontByFullname(anyName))
elif mode == 'MM':
__list = anyName.split("/")
_InstanceList = []
for l in __list:
try:
_InstanceList.append(int(l))
except:
pass
instance = Font(Font, _InstanceList)
instance.full_name += ' ' + anyName
result.append(instance)
else: raiseerror("No fonts have been selected. I can't work like that.")
#else: raiseerror("Canceled by user (That's you).")
#del myDialog
# elif not NameList:
# raiseerror("No fonts open in FontLab.")
try:
fonts = result
except:
fonts = []
#if not myDialog.filename:
#print "No file name specified. Where do you expect me to save the file?."
if not errors and fonts and glyphs:
starttime = time.time()
global pagewidth, pageheight
#global myDialog
if not Glyphs.defaults["com_yanone_Autopsy_PageOrientation_landscape"]:
if not Glyphs.defaults["com_yanone_Autopsy_PageSize_a4"]:
pagewidth = letter[0]
pageheight = letter[1]
else:
pagewidth = A4[0]
pageheight = A4[1]
else:
if not Glyphs.defaults["com_yanone_Autopsy_PageSize_a4"]:
pagewidth = letter[1]
pageheight = letter[0]
else:
pagewidth = A4[1]
pageheight = A4[0]
#############
#
# Collect information about the glyphs
#
# Dimensions
reports = Ddict(dict)
glyphwidth = Ddict(dict)
maxwidthperglyph = Ddict(dict)
maxwidth = 0
maxsinglewidth = 0
glyphheight = Ddict(dict)
maxheightperglyph = Ddict(dict)
maxheight = 0
maxsingleheight = 0
for glyph in glyphs:
glyphwidth[glyph] = 0
glyphheight[glyph] = 0
maxwidthperglyph[glyph] = 0
maxheightperglyph[glyph] = 0
reports[glyph]['width'] = Report()
reports[glyph]['height'] = Report()
reports[glyph]['bboxwidth'] = Report()
reports[glyph]['bboxheight'] = Report()
reports[glyph]['highestpoint'] = Report()
reports[glyph]['lowestpoint'] = Report()
reports[glyph]['leftsidebearing'] = Report()
reports[glyph]['rightsidebearing'] = Report()
for i_f, font in enumerate(fonts):
FontMaster = font.masters[0]
if font.glyphs.has_key(glyph):
g = font.glyphs[glyph].layers[FontMaster.id]
#print "__g", g
glyphwidth[glyph] = g.width
height = ascender(font) - descender(font)
widthforgraph = glyphwidth[glyph]
if widthforgraph == 0:
widthforgraph = g.bounds.size.width
heightforgraph = height
# width of kegel
reports[glyph]['width'].addvalue((glyphwidth[glyph], widthforgraph, heightforgraph))
# sum of widths per glyph
if reports[glyph]['width'].sum > maxwidth:
maxwidth = reports[glyph]['width'].sum
if reports[glyph]['width'].max > maxsinglewidth:
maxsinglewidth = reports[glyph]['width'].max
# height of kegel
glyphheight[glyph] = height
reports[glyph]['height'].addvalue((glyphheight[glyph], widthforgraph, heightforgraph))
# sum of heights per glyph
if reports[glyph]['height'].sum > maxheight:
maxheight = reports[glyph]['height'].sum
if reports[glyph]['height'].max > maxsingleheight:
maxsingleheight = reports[glyph]['height'].max
# BBox
overthetop = 20000
bbox = g.bounds
if bbox.size.width < -1*overthetop or bbox.size.width > overthetop:
reports[glyph]['bboxwidth'].addvalue((0, widthforgraph, heightforgraph))
else:
reports[glyph]['bboxwidth'].addvalue((bbox.size.width, widthforgraph, heightforgraph))
if bbox.size.height < -1*overthetop or bbox.size.height > overthetop:
reports[glyph]['bboxheight'].addvalue((0, widthforgraph, heightforgraph))
else:
reports[glyph]['bboxheight'].addvalue((bbox.size.height, widthforgraph, heightforgraph))
if (bbox.origin.y + bbox.size.height) < -1*overthetop or (bbox.origin.y + bbox.size.height) > overthetop:
reports[glyph]['highestpoint'].addvalue((0, widthforgraph, heightforgraph))
else:
reports[glyph]['highestpoint'].addvalue((bbox.origin.y + bbox.size.height, widthforgraph, heightforgraph))
if bbox.origin.y < -1*overthetop or bbox.origin.y > overthetop:
reports[glyph]['lowestpoint'].addvalue((0, widthforgraph, heightforgraph))
else:
reports[glyph]['lowestpoint'].addvalue((bbox.origin.y, widthforgraph, heightforgraph))
# L + R sidebearing
reports[glyph]['leftsidebearing'].addvalue((g.LSB, widthforgraph, heightforgraph))
reports[glyph]['rightsidebearing'].addvalue((g.RSB, widthforgraph, heightforgraph))
# Recalculate drawing boards
numberoftables = 0
# GSNotImplemented
# for table in availablegraphs:
# if eval('myDialog.graph_' + table):
# numberoftables += 1
if numberoftables < 3:
numberoftables = 3
try:
r = 2.0 / numberoftables
except:
r = .8
SetScrapBoard(r)
# Calculate ratio
if not Glyphs.boolDefaults["com_yanone_Autopsy_PageOrientation_landscape"]:
ratio = (scrapboard['top'] - scrapboard['bottom']) / maxheight * mm
ratio2 = (scrapboard['right'] - scrapboard['left']) / maxsinglewidth * mm
maxratio = 0.3
if ratio > maxratio:
ratio = maxratio
if ratio > ratio2:
ratio = ratio2
else:
ratio = (scrapboard['right'] - scrapboard['left']) / maxwidth * mm
ratio2 = (scrapboard['top'] - scrapboard['bottom']) / maxsingleheight * mm
maxratio = 0.3
if ratio > maxratio:
ratio = maxratio
if ratio > ratio2:
ratio = ratio2
xoffset = pagewidth/mm * 1/1.61
yoffset = pageheight/mm * 1.61
# PDF Init stuff
filename = NSUserDefaults.standardUserDefaults()["com_yanone_Autopsy_filename"]
tempFileName = NSTemporaryDirectory()+"%d.pdf"%random.randint(1000,100000)
pageRect = CGRectMake (0, 0, pagewidth, pageheight)
fileURL = NSURL.fileURLWithPath_(tempFileName)
pdfContext = CGPDFContextCreateWithURL(fileURL, pageRect, None)
CGPDFContextBeginPage(pdfContext, None)
pdfNSGraphicsContext = NSGraphicsContext.graphicsContextWithGraphicsPort_flipped_(pdfContext, False)
NSGraphicsContext.saveGraphicsState()
NSGraphicsContext.setCurrentContext_(pdfNSGraphicsContext)
NSRectFill(((-100, -100), (200, 200)))
# Draw front page
output('-- font page --')
drawrect(-3*mm, -3*mm, pagewidth + 3*mm, pageheight + 3*mm, pdfcolour, None, None, None, 0)
# Try to get a random glyph from a random font with nodes
# try not more than 10000 times
glyphfound = False
randomfont = fonts[random.randint(0, len(fonts) - 1)]
randomglyphindex = random.randint(0, len(randomfont) - 1)
g = randomfont.glyphs[randomglyphindex]
if g is not None: