-
Notifications
You must be signed in to change notification settings - Fork 1
/
KerningAssistant-007-beta.py
1822 lines (1589 loc) · 85.7 KB
/
KerningAssistant-007-beta.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
# -*- coding: UTF-8 -*-
#
# Kerning Assistant for RoboFont4
# It works on the current font.
#
# Keyboard driven alterations of spacing and kerning.
# Selection from multiple kerning samples
# Generating sample line file for FontGoggles
# Support for various open type feature sets
# Support for glyph-glyph, group-glyph, glyph-group and group-group kerning
# Find function by glyph name
# Shows kerning groups for the current selected pairs
# Show kerning line samples in the Editor Window
# Alloes selection by clicking on the sample line.
#
# Install Similarity from Mechanic and run it once, after RoboFont starts.
# The initial window can be closed. This way the library "cosoneSimilarity"
# becomes available for this Assistant.
#
# No need to import KernNet for AI assistent kerning. That will be available as local webserver.
#
import sys
import os
import codecs
import vanilla
import merz
import weakref
import importlib
from random import choice
from copy import copy
from math import *
from AppKit import *
import drawBot
from mojo.events import extractNSEvent
from mojo.UI import OpenGlyphWindow
from mojo.roboFont import AllFonts, OpenFont, RGlyph, RPoint
from mojo.subscriber import Subscriber, WindowController, registerGlyphEditorSubscriber, unregisterGlyphEditorSubscriber
from fontTools.misc.transform import Transform
# Add paths to libs in sibling repositories
PATHS = ['../TYPETR-Assistants/']
for path in PATHS:
if not path in sys.path:
print('@@@ Append to sys.path', path)
sys.path.append(path)
import assistantLib
importlib.reload(assistantLib)
import assistantLib.kerningSamples
importlib.reload(assistantLib.kerningSamples)
import assistantLib.kerningSamples.ulcwords
importlib.reload(assistantLib.kerningSamples.ulcwords)
import assistantLib.tp_kerningManager
importlib.reload(assistantLib.tp_kerningManager)
from assistantLib.kerningSamples.ulcwords import ULCWORDS
from assistantLib.tp_kerningManager import KerningManager, SPACING_TYPES_LEFT, SPACING_TYPES_RIGHT
ARROW_KEYS = [NSUpArrowFunctionKey, NSDownArrowFunctionKey,
NSLeftArrowFunctionKey, NSRightArrowFunctionKey, NSPageUpFunctionKey,
NSPageDownFunctionKey, NSHomeFunctionKey, NSEndFunctionKey]
FUNCTION_KEYS = (
'Uu', # Decrement left margin
'Ii', # Increment left margin
'Oo', # Decrement right margin
'Pp', # Increment right margin
';', # Set left pair kerning to self.predictedKerning1
"'", # Set right pair kerning to self.predictedKerning2
'Nn', # Increment left kerning
'Mm', # Decrement left kerning
'.<', # Decrement right kerning
',>', # Increment right kerning
)
VERBOSE = False
VERBOSE2 = False
KERNING_SAMPLE_SELECT_LIB = 'TYPETR-Presti-Assistant-KerningSampleIndex'
KERNING_SAMPLE_X = 'KerningAssistant-GG-Sample'
GROUPGLYPH_COLOR = (0, 0, 0.6, 1)
GLYPHGLYPH_COLOR = (0, 0.4, 0, 1)
# Initial template string. The /? gets replaced by the unicode of the current glyph.
# Replace /??W by random word
SAMPLES = (
# Force to capitals [clig] trigger
' /?A/?B/?C/?D/?E/?F/?G/?H/?I/?J/?K/?L/?M/?N/?O/?P/?Q/?R/?S/?T/?U/?V/?W/?X/?Y/?Z/?',
' /?a/?b/?c/?d/?e/?f/?g/?h/?i/?j/?k/?l/?m/?n/?o/?p/?q/?r/?s/?t/?u/?v/?w/?x/?y/?z/?',
' A/? B/? C/? D/? E/? F/? G/? H/? I/? J/? K/? L/? M/? N/? O/? P/? Q/? R/? S/? T/? U/? V/? W/? X/? Y/? Z/?',
' a/? b/? c/? d/? e/? f/? g/? h/? i/? j/? k/? l/? m/? n/? o/? p/? q/? r/? s/? t/? u/? v/? w/? x/? y/? z/?',
' I/?~T1~B1 I/?~mlu1~mru1 I/?~mld1~mrd1 I/?~tlu1~tru1 I/?~tld1~trd1 I/?~bld1~brd1 I/?~blu1~bru1 I/?io/?on/?n Hamburgefons/?tiv H/?HAMBURG/?RGER',
'/??d /??W /??K /?I/?IO/?H/?i/?io/?on/?n ',
'/??d /??K /??W /?I/?IO/?H/?i/?io/?on/?n ',
'/??d I/?IO/?H/?i/?io/?on/?n /?/??W/?Hamburgefonstiv',
'/??d I/?IO/?H/?i/?io/?on/?n Hamburgefons/?tiv/?HAMBURG/?RGER',
' /?~T1~B1 /?~mlu1~mru1 /?~mld1~mrd1 /?~tlu1~tru1 /?~tld1~trd1 /?~bld1~brd1 /?~blu1~bru1 /?io/?on/?n Hamburgefons/?tiv/?HAMBURG/?RGER',
' /?~T2~B2 /?~mlu2~mru2 /?~mld2~mrd2 /?~tlu2~tru2 /?~tld2~trd2 /?~bld2~brd2 /?~blu2~bru2 /?io/?on/?n Hamburgefons/?tiv/?HAMBURG/?RGER',
' /?~T3~B3 /?~mlu3~mru3 /?~mld3~mrd3 /?~tlu3~tru3 /?~tld3~trd3 /?~bld3~brd3 /?~blu3~bru3 /?io/?on/?n Hamburgefons/?tiv/?HAMBURG/?RGER',
' /?~T4~B4 /?~mlu4~mru4 /?~mld4~mrd4 /?~tlu4~tru4 /?~tld4~trd4 /?~bld4~brd4 /?~blu4~bru4 /?io/?on/?n Hamburgefons/?tiv/?HAMBURG/?RGER',
' /?~T5~B5 /?~mlu5~mru5 /?~mld5~mrd5 /?~tlu5~tru5 /?~tld5~trd5 /?~bld5~brd5 /?~blu5~bru5 /?io/?on/?n Hamburgefons/?tiv/?HAMBURG/?RGER',
' /?~T1~B1 I/?~mlu1~mru1IO/?~tlu1~tru1H/?~bld1~brd1i/?io/?on/?n Hamburgefons/?tiv/?HAMBURG/?RGER',
' /?~tlu1~tru1~mlu1~mru1~bld1~brd1~T1~B1 I/?IO/?H/?i/?io/?on/?n Hamburgefons/?tiv/?HAMBURG/?RGER',
'I/?IO/?H/?i/?io/?on/?n Hamburgefons/?tiv/?HAMBURG/?RGER',
'0/?1/?2/?3/?4/?5/?6/?7/?8/?9/?0/?H/?HO/?O/?n/?o/?Hamburg',
'0/?/0 1/?/0 2/?/0 3/?/0 4/?/0 5/?/0 6/?/0 7/?/0 8/?/0 9/?/0 0//?0 1//?0 2//?0 3//?0 4//?0 5//?0 6//?0 7//?0 8//?0 9//?0 Hamburg',
'A/?AH/?HO/?OV/?Va/?ai/?io/?ov/?v',
'A/?Æ/?B/?C/?D/?E/?F/?G/?H/?I/?J/?K/?L/?M/?N/?O/?Ø/?Œ/?P/?Q/?R/?S/?T/?U/?V/?W/?X/?Y/?Z/?',
'A/?Á/?Ä/?Æ/?B/?C/?Ç/?D/?E/?É/?F/?G/?H/?I/?J/?K/?L/?M/?N/?O/?Ø/?Œ/?P/?Q/?R/?S/?T/?U/?V/?W/?X/?Y/?Z/?',
'I/?IO/?H/?i/?io/?on/?n Hamburgefons/?tiv/?HAMBURG/?',
'a/?æ/?b/?c/?d/?e/?f/?g/?h/?i/?j/?k/?l/?m/?n/?o/?ø/?œ/?p/?q/?r/?s/?t/?u/?v/?w/?x/?y/?z/?',
'f/?fiflftfnfmfufhfkflfbffifflfafàfáfâfãfäfåfāfăfąfǻfæfǽfefèféfêfëfēfĕfėfęfěfufùfúfûfüfũfūfŭfůfűfofòfófôfõföfōfŏfőføfǿfifìfífîfïfĩfīfĭfįfij/? Hamburgefons',
'point. points de suspension… point-virgule; deux-points: point d’exclamation! apostrophe’ virgule, {accolades} (parenthèses) <chevrons> [crochets] «guillemets» ou “hey” ou ‘ho’ ou “ha„ ou ‘hé‚ ou ‹hi› barre oblique/ slash/ barre oblique inversée\\ barre verticale| verticale brisée¦ point médian· point d’interrogation? ¡espagnol! ¿espagnol? trait d’union- tiret n dash– ou m dash— -–—',
'ďaďáďkďmďnďoďsďtďuďžđďiďjď!ľ?ľ!ľiľjť?ť!ťiťj',
"""A'A"A‘A“A 7.7 F.OF.TF.UF.VF.YF.“F.’ P.OP.TP.UP.VP.YP.“P.’ T.OT.T.UT.VT.YT.“T.’ U.OU.TU.UU.VU.YU.“U.’ V.V.OV.TV.UV.YV.“V.’ Y.OY.TY.UY.VY.YY.“Y.’ """,
'l.’nn.” “nn,” “nn”. “nn”, r.” v.” w.” y.” F.” P.” T.” V.” W.” Y.”',
'loďka ďábelska ďatlov ďábel objížďka buďto Nunatuĸavut',
'břeťa cenťák žesťový řiťka opúšťať hradišťský tchaj-ťi šťuka dvanásťročný',
'ď.ď,ď:ď;ď?ď!ď”ď“ď™ď®ď)ď}ď]ť.ť,ť;ť:ť?ť!ť”ť“ť™ť®ť)ť}ť]ľ.ľ,ľ:ľ;ľ?ľ!ľ”ľ“ľ™ľ®ľ)ľ}ľ]',
'ïlïbïkïl"ī"/ī/\\ī\\(ī)[ī]{ī}ïlïbïkïl"ï"/ï/\\ï\\(ï)[ï]{ï}fífìfîfïfīffĩfíffìffîffïffīffĩfþ',
'fît(French), fìsica(Corsican), fīča(Latvian), ffïon(Welsh)',
'ĻļM̧ajelm̧ŅņO̧o̧ĀāN̄n̄ŌōŪūĄąĄ́ą́ĘęĘ́ę́ĮįĮ́į́ǪǫǪ́ǫ́G̃g̃',
'hradišťský tchaj-ťi šťuka aukščiausiųjų',
)
# ULCWORDS has list of words
W, H = 460, 400
M = 32
SPACE_MARKER_R = 16
POINT_MARKER_R = 6
FAR = 100000 # Put drawing stuff outside the window
KERN_LINE_SIZE = 32 # Number of glyphs on kerning line
KERN_SCALE = 0.15 #0.2
INTERPOLATION_ERROR_MARKER = (1, 0, 0, 1)
NO_MARKER = (1, 1, 1, 1)
#VISITED_MARKER = (0, 0.5, 0.5, 0.5)
if __file__.startswith('/Users/petr/Desktop/TYPETR-git'):
VISITED_MARKER = 40/255, 120/255, 255/255, 1 # "Final" marker Blue (for others)
print('Using Petr color')
else:
VISITED_MARKER = 92/255, 149/255, 190/255, 1 # "Final" marker (for Petr)
print('Using Tilmann/Graeme color')
#KERNING = KERNING_START + KERNING # Basic set, as used for Segoe, without feature glyphs
#KERNING = KERNING_START + KERNING_SIMPLE # Relatively small samplt with only one glyph per group
#KerningSample = KERNING
# Total number of kerning lines in this sample
KerningNumLines = KERNING_NUM_LINES = int(round(KERN_LINE_SIZE / KERN_LINE_SIZE))
WindowClass = vanilla.Window
#WindowClass = vanilla.FloatingWindow
kerningAssistant = None # Little cheat, to make the assistant available from the window
class KerningAssistant(Subscriber):
debug = True
controller = None
# B U I L D I N G
def build(self):
global kerningAssistant
kerningAssistant = self
self.kerningManagers = {} # Key is f.path, value is KerningManager instance. Will be initialized by self.getKerningSample(f)
self.kerningSample = None
f = CurrentFont()
if f is not None:
self.getKerningManager(f) # Initialize self.kerningSample
self.capLock = False # Used for creating glyph/group or group/glyph or glyph/glyph kerning (showing in blue and green)
self.isUpdating = False
self.fixingAnchors = False
self.predictedKerning1 = '-'
self.predictedKerning2 = '-'
# Store selected glyphs for (kern1, kern2) if the preview char changed value
#self.previewKern1 = self.previewKern2 = None
self.mouseClickPoint = None
self.mouseDraggedPoint = None
# Currently dragging this terminal
self.selectedTerminal = None
self.terminals = [] # Updated but self.draw with the terminal-data found
self._dValues = None # Caching diagonal values from Dimensioneer glyph analyzer.
glyphEditor = self.getGlyphEditor()
self.foregroundContainer = container = glyphEditor.extensionContainer(
identifier="com.roboFont.Assistant.foreground",
location="foreground",
clear=True
)
self.backgroundContainer = glyphEditor.extensionContainer(
identifier="com.roboFont.Assistant.background",
location="background",
clear=True
)
self.kernGlyph1 = None # Name of glyph on left side, if kerning is on
self.kernGlyph2 = None # Name of glyph on right side, if kerning is on
self.groupTextLayer_colW = colW = 500
colH = f.info.capHeight
# Showing the left and groups of the current glyp
self.group1TextLeftLayer = container.appendTextBoxSublayer(name="group1Left",
position=(FAR, 0), # Will be changed to width of current glyph
backgroundColor=(1, 1, 1, 0.5),
text='Group1-Left',
size=(colW, colH),
font='Courier',
pointSize=14,
lineHeight=18,
fillColor=(0, 0, 0, 1),
)
self.group2TextLeftLayer = container.appendTextBoxSublayer(name="group2Left",
position=(FAR, 0), # Will be changed to width of current glyph
backgroundColor=(1, 1, 1, 0.5),
text='Group2-Left',
size=(colW, colH),
font='Courier',
pointSize=14,
lineHeight=18,
fillColor=(0, 0, 0, 1),
)
self.group1TextRightLayer = container.appendTextBoxSublayer(name="group1Right",
position=(FAR, 0), # Will be changed to width of current glyph
backgroundColor=(1, 1, 1, 0.5),
text='Group1-Right',
size=(colW, colH),
font='Courier',
pointSize=14,
lineHeight=18,
fillColor=(0, 0, 0, 1),
)
self.group2TextRightLayer = container.appendTextBoxSublayer(name="group2Right",
position=(FAR, 0), # Will be changed to width of current glyph
backgroundColor=(1, 1, 1, 0.5),
text='Group2-Right',
size=(colW, colH),
font='Courier',
pointSize=14,
lineHeight=18,
fillColor=(0, 0, 0, 1),
)
# The KerningManagers is just doing margins according the available glyph.lib dependecies
# and to the groups.
self.fixedSpaceMarkerLeft = container.appendOvalSublayer(name="spaceMarkerLeft",
position=(-SPACE_MARKER_R, -SPACE_MARKER_R),
size=(SPACE_MARKER_R*2, SPACE_MARKER_R*2),
fillColor=None,
strokeColor=None,
strokeWidth=1,
)
self.leftSpaceSourceLabel = container.appendTextLineSublayer(name="leftSpaceSourceLabel",
position=(FAR, -SPACE_MARKER_R*2),
text='LSB',
font='Courier',
pointSize=14,
fillColor=(0, 0, 0, 1),
)
self.leftSpaceSourceLabel.setHorizontalAlignment('center')
self.fixedSpaceMarkerRight = container.appendOvalSublayer(name="spaceMarkerRight",
position=(1000-SPACE_MARKER_R, -SPACE_MARKER_R),
size=(SPACE_MARKER_R*2, SPACE_MARKER_R*2),
fillColor=None,
strokeColor=None,
strokeWidth=1,
)
self.rightSpaceSourceLabel = container.appendTextLineSublayer(name="rightSpaceSourceLabel",
position=(FAR, -SPACE_MARKER_R*2),
text='RSB',
font='Courier',
pointSize=14,
fillColor=(0, 0, 0, 1),
)
self.rightSpaceSourceLabel.setHorizontalAlignment('center')
# Kerning
self.kerningLine = [] # List of kerned glyph image layers
self.kerningLineValues = [] # List of kerning value layers
self.kerningLineBoxes = [] # List of kerned glyph em-boxes
self.kerningSelectedGlyph = None # Name of the glyph selected by the kerning editor
for gIndex in range(KERN_LINE_SIZE):
# Previewing current glyphs on left/right side.
im = self.backgroundContainer.appendPathSublayer(
name='kernedGlyph-%d' % gIndex,
position=(FAR, 0),
fillColor=(0, 0, 0, 1),
)
im.addScaleTransformation(KERN_SCALE)
self.kerningLine.append(im)
kerningLineValue = self.backgroundContainer.appendTextLineSublayer(
name='kernedValue-%d' % gIndex,
position=(FAR, 0),
text='xxx\nxxx',
font='Courier',
pointSize=16,
fillColor=(0, 0, 0, 1), # Can be red (negative kerning) or green (positive kerning)
)
kerningLineValue.addScaleTransformation(KERN_SCALE)
kerningLineValue.setHorizontalAlignment('center')
self.kerningLineValues.append(kerningLineValue)
kerningLineBox = self.backgroundContainer.appendRectangleSublayer(
name='kernedBox-%d' % gIndex,
position=(FAR, 0),
size=(1, 1),
fillColor=None,
strokeColor=(0, 0, 0, 0.5),
strokeWidth=1,
)
kerningLineBox.addScaleTransformation(KERN_SCALE)
self.kerningLineBoxes.append(kerningLineBox)
self.kerningSelectedGlyphMarker = self.backgroundContainer.appendRectangleSublayer(
name='kerningSelectedGlyphMarker',
position=(FAR, 0),
size=(1, 20),
fillColor=(1, 0, 0, 1),
strokeColor=None,
strokeWidth=1,
)
self.kerningSelectedGlyphMarker.addScaleTransformation(KERN_SCALE)
self.kerning1Value = self.backgroundContainer.appendTextLineSublayer(
name="kerning1Value",
position=(FAR, 0),
text='xxx\nxxx',
font='Courier',
pointSize=32,
fillColor=(1, 0, 0, 1),
)
self.kerning1Value.setHorizontalAlignment('center')
self.kerning2Value = self.backgroundContainer.appendTextLineSublayer(
name="kerning2Value",
position=(FAR, 0),
text='xxx\nxxx',
font='Courier',
pointSize=32,
fillColor=(1, 0, 0, 1),
)
self.kerning2Value.setHorizontalAlignment('center')
self.kerningCursorBox = self.backgroundContainer.appendTextLineSublayer(
name="kerningCursorBox",
position=(FAR, 0),
text='xxx\nxxx',
font='Courier',
pointSize=14,
fillColor=(0.6, 0.6, 0.6, 1),
)
self.kernGlyphImage1 = self.backgroundContainer.appendPathSublayer(
name='kernGlyphImage1',
position=(FAR, 0),
fillColor=(0, 0, 0, 1), # Sets to light gray if not equal to current glyph.
)
self.kernGlyphImage = self.backgroundContainer.appendPathSublayer(
name='kernGlyphImage',
position=(FAR, 0),
fillColor=(0, 0, 0, 1), # Sets to light gray if not equal to current glyph.
)
self.kernGlyphImage2 = self.backgroundContainer.appendPathSublayer(
name='kernGlyphImage2',
position=(FAR, 0),
fillColor=(0, 0, 0, 1), # Sets to light gray if not equal to current glyph.
)
self.similarGlyphImage1 = self.backgroundContainer.appendPathSublayer(
name='similarGlyphImage1',
position=(0, 0),
fillColor=(0.5, 0.5, 0.5, 0.2),
strokeColor=(1, 0, 0, 1),
strokeWidth=1,
)
self.similarGlyphImage2 = self.backgroundContainer.appendPathSublayer(
name='similarGlyphImage2',
position=(0, 0),
fillColor=(0.5, 0.5, 0.5, 0.2),
strokeColor=(1, 0, 0, 1),
strokeWidth=1,
)
# E V E N T S
def started(self):
self.sampleText = None # Initialize sample text storage for FontGoggles file.
self.randomWord = choice(ULCWORDS)
#print("subscription started")
#self.controller.addInfo("subscription started")
def destroy(self):
#print("stop subscription")
self.foregroundContainer.clearSublayers()
#self.controller.addInfo("stop subscription")
def predictKerning(self, gName1, gName2):
"""Generate a kerning test image for the based of the groups that gName1 and gName2 are in.
If there is no group for those glyphs, then use the glyphs themselves."""
f = CurrentFont()
km = self.getKerningManager(f)
imageName = 'test.png'
kernImagePath = '/'.join(__file__.split('/')[:-1]) + '/assistantLib/kernnet7/_imagePredict/' + imageName
iw = ih = 32
scale = ih/f.info.unitsPerEm
y = -f.info.descender
if 'Italic' in f.path:
italicOffset = -50 # Calibrate HH shows in the middle
else:
italicOffset = 0
im1 = g1.getRepresentation("defconAppKit.NSBezierPath")
im2 = g2.getRepresentation("defconAppKit.NSBezierPath")
s = iw / g1.font.info.unitsPerEm
y = -g1.font.info.descender
#if abs(k) >= 4 and not os.path.exists(imagePath): # Ignore k == 0
drawBot.newDrawing()
drawBot.newPage(iw, ih)
#drawBot.fill(1, 0, 0, 1)
#drawBot.rect(0, 0, iw, ih)
drawBot.fill(0)
drawBot.scale(s, s)
drawBot.save()
drawBot.translate(iw/s/2 - g1.width + italicOffset, y)
drawBot.drawPath(im1)
drawBot.restore()
drawBot.save()
drawBot.translate(iw/s/2 + italicOffset, y)
drawBot.drawPath(im2)
drawBot.restore()
# If flag is set, clip space above capHeight and below baseline
if 0 and self.controller.w.cropKernImage.get():
drawBot.fill(1, 0, 0, 1)
drawBot.rect(0, f.info.capHeight+600, iw/s, ih/s)
drawBot.fill(0, 0, 1, 1)
drawBot.rect(0, -ih/s, iw/s, ih/s-300)
drawBot.saveImage(kernImagePath)
page = urllib.request.urlopen(f'http://localhost:8080/{g1.name}/{g2.name}/{imageName}')
# Returns value is glyphName1/glyphName2/predictedKerningValue
# The glyph names are returned to check validity of the kerning value.
# Since the call is ansynchronic to the server, we may get the answer here from a previous query.
parts = str(page.read())[2:-1].split('/')
if not len(parts) == 3 or parts[0] != g1.name or parts[1] != g2.name:
print('### Predicted kerning query not value', parts)
return None
try:
factor = float(self.controller.w.factor.get())
except ValueError:
factor = 1
try:
calibrate = float(self.controller.w.calibrate.get())
except ValueError:
calibrate = 0
k = float(parts[-1])
#print(k, k - abs(factor * k), abs(factor * k), int(round(k * f.info.unitsPerEm/1000/step))*step)
k = k * factor + calibrate
# Calculate the rouned-truncated value of the floating
ki = int(round(k * f.info.unitsPerEm/1000/step))*step # Scale the kerning value to our Em-size.
if abs(ki) <= step:
ki = 0 # Apply threshold for very small kerning values
print(f'... Predicted kerning {g1.name} -- {g2.name} k={k} kk={ki}')
return ki
def glyphEditorDidSetGlyph(self, info):
#self.backgroundContainer.clearSublayers()
#self.foregroundContainer.clearSublayers()
g = info["glyph"]
if g is None:
self.controller.w.setTitle('Kerning Assistant')
return
f = g.font
if VERBOSE:
print('--- glyphEditorDidSetGlyph', g.name)
# Unselect points to avoid moving them on kerning-cursor keys
if 0:
for contour in g.contours:
for p in contour.points:
p.selected = False
for component in g.components:
component.selected = False
# Get the kerning manager instance for this glyph
km = self.getKerningManager(f)
# Find first of current glyph in the kerning sample
#self.findKerningSample(g.name)
# Set spacing dependency parameters from glyph.lib
d = km.getSpacingDependencyLib(g)
self.controller.w.setTitle(f'Kerning Assistant /{g.name}')
# Set dependency UI labels according to the selected values
typeLeft = d.get('typeLeft')
left = d.get('left', '')
self.controller.w.spacingTypeLeft.setItem(typeLeft)
if left and left in f:
self.controller.w.spacingLeft.set(left)
if typeLeft == 'l': # Left margin of base component, if it exists.
label = f'Left from base /{left}'
elif typeLeft == 'ml': # Left margin of whole glyph
label = f'Left from /{left}'
elif typeLeft == 'r2l':
label = f'Right-->Left /{left}'
else:
label = 'Left'
self.controller.w.spacingLeftLabel.set(label)
else:
self.controller.w.spacingLeft.set('')
self.controller.w.spacingLeftLabel.set('Left')
typeRight = d.get('typeRight', '-')
right = d.get('right', '')
self.controller.w.spacingTypeRight.setItem(typeRight)
if right and right in f:
self.controller.w.spacingRight.set(right)
if typeRight == 'r': # Right margin of base component, if it exists.
label = f'Right from base /{right}'
elif typeRight == 'mr': # Right margin of whole glyph
label = f'Right from /{right}'
elif typeLeft == 'l2r':
label = f'Left-->Right /{right}'
else:
label = 'Right'
self.controller.w.spacingRightLabel.set(label)
else:
self.controller.w.spacingRight.set('')
self.controller.w.spacingRightLabel.set('Right')
#self.updateGroupLists(g)
self.updateGlyph(g)
self.updatePreview(g)
#self.glyphEditorGlyphDidChange(info)
#self.glyphEditorGlyphDidChangeInfo(info)
#self.glyphEditorGlyphDidChangeOutline(info)
#self.glyphEditorGlyphDidChangeComponents(info)
#self.glyphEditorGlyphDidChangeAnchors(info)
#self.glyphEditorGlyphDidChangeGuidelines(info)
#self.glyphEditorGlyphDidChangeImage(info)
#self.glyphEditorGlyphDidChangeMetrics(info)
#self.glyphEditorGlyphDidChangeContours(info)
def updateGroupLists(self, g):
f = g.font
# Get the kerning manager instance for this glyph
km = self.getKerningManager(f)
# Set controller groups names for current glyph
sample = km.sample
cursor = int(round(self.controller.w.kerningSampleSelectSlider.get())) + 16
gName1 = km.sample[cursor-1]
gName2 = km.sample[cursor+1]
#self.predictedKerning1 = self.predictKerning(gName1, g.name)
#self.predictedKerning2 = self.predictKerning(g.name, gName2)
#print('@@@', gName1, self.predictedKerning1, g.name, self.predictedKerning2, gName2)
#print((gName1, g.name), k1, (g.name, gName2), k2)
# Lists with similar groups
simGroups2 = km.getSimilarGroupsNames2(g) #[] # List of group names
self.controller.w.groupNameList2.set(simGroups2)
if simGroups2:
self.controller.w.groupNameList2.setSelection([0])
self.controller.groupNameListSelectCallback2()
simGroups1 = km.getSimilarGroupsNames1(g) #[] # List of group names
self.controller.w.groupNameList1.set(simGroups1)
if simGroups1:
self.controller.w.groupNameList1.setSelection([0])
self.controller.groupNameListSelectCallback1()
# Left side of glyph
groupName2 = km.glyphName2GroupName2.get(g.name)
if groupName2 is not None:
label2 = f'{groupName2} ({len(f.groups[groupName2])})'
else:
label2 = '---'
self.controller.w.groupName2.set(label2) # Left side of the current glyph
# Right side of glyph
groupName1 = km.glyphName2GroupName1.get(g.name)
if groupName1 is not None:
label1 = f'{groupName1} ({len(f.groups[groupName1])})'
else:
label1 = '---'
self.controller.w.groupName1.set(label1) # Right side of the current glyph
def glyphEditorDidKeyDown(self, info):
g = info['glyph']
if VERBOSE:
print('--- glyphEditorDidKeyDown', g.name)
event = extractNSEvent(info['NSEvent'])
characters = event['keyDown']
#print(event.keys())
#print(characters)
commandDown = event['commandDown']
shiftDown = event['shiftDown']
controlDown = event['controlDown']
optionDown = event['optionDown']
self.capLock = event['capLockDown']
changed = False
updatePreview = False
#elif characters in 'Hh': # Toggle show frozen
# self.controller.w.showFrozenUfo.set(not self.controller.w.showFrozenUfo.get())
# self.lastFrozen = None
# changed = True
#print('... Key down', info['locationInGlyph'], info['NSEvent'].characters)
if characters in 'Pp': # Increment right margin
if shiftDown:
self._adjustRightMargin(g, 5)
else:
self._adjustRightMargin(g, 1)
changed |= self.checkSpacingDependencies(g) # Update the spacing consistency for all glyphs in the kerning line
updatePreview = True
elif characters in 'Oo': # Decrement right margin
if shiftDown:
self._adjustRightMargin(g, -5)
else:
self._adjustRightMargin(g, -1)
changed |= self.checkSpacingDependencies(g) # Update the spacing consistency for all glyphs in the kerning line
updatePreview = True
elif characters in 'Ii': # Increment left margin
if shiftDown:
self._adjustLeftMargin(g, 5)
else:
self._adjustLeftMargin(g, 1)
changed |= self.checkSpacingDependencies(g) # Update the spacing consistency for all glyphs in the kerning line
updatePreview = True
elif characters in 'Uu': # Decrement left margin
if shiftDown:
self._adjustLeftMargin(g, -5)
else:
self._adjustLeftMargin(g, -1)
changed |= self.checkSpacingDependencies(g) # Update the spacing consistency for all glyphs in the kerning line
updatePreview = True
# Adjust to predicted kerning
#elif characters == ';': # Set left pair to predicted kerning
# self._adjustLeftKerning(g, newK=self.predictedKerning1)
# changed |= self.checkSpacingDependencies(g) # Update the spacing consistency for all glyphs in the kerning line
# updatePreview = True
#elif characters == "'": # Set right pair to predicted kerning
# self._adjustRightKerning(g, newK=self.predictedKerning2)
# changed |= self.checkSpacingDependencies(g) # Update the spacing consistency for all glyphs in the kerning line
# updatePreview = True
# Adjust kerning
elif characters in '.>': # Increment right kerning
if shiftDown:
self._adjustRightKerning(g, 5) # 20
else:
self._adjustRightKerning(g, 1) # 4
changed |= self.checkSpacingDependencies(g) # Update the spacing consistency for all glyphs in the kerning line
updatePreview = True
elif characters in ',<': # Decrement right kerning
if shiftDown:
self._adjustRightKerning(g, -5) # 20
else:
self._adjustRightKerning(g, -1) # 4
changed |= self.checkSpacingDependencies(g) # Update the spacing consistency for all glyphs in the kerning line
updatePreview = True
elif characters in 'Mm': # Decrement left kerning
if shiftDown:
self._adjustLeftKerning(g, -5) # 20
else:
self._adjustLeftKerning(g, -1) # 4
changed |= self.checkSpacingDependencies(g) # Update the spacing consistency for all glyphs in the kerning line
updatePreview = True
elif characters in 'Nn': # Increment left kerning
if shiftDown:
self._adjustLeftKerning(g, 5) # 20
else:
self._adjustLeftKerning(g, 1) # 4
changed |= self.checkSpacingDependencies(g) # Update the spacing consistency for all glyphs in the kerning line
updatePreview = True
elif optionDown and characters == NSUpArrowFunctionKey:
kerningSample = self.getKerningSample(g.font)
currentCursor = int(round(self.controller.w.kerningSampleSelectSlider.get()))
if shiftDown:
cursor = max(0, currentCursor - 8*KERN_LINE_SIZE)
else:
cursor = max(0, currentCursor - KERN_LINE_SIZE)
self.controller.w.kerningSampleSelectSlider.set(cursor)
self.controller.w.kerningSampleSelectSlider.setMaxValue(len(kerningSample))
self.controller.w.kerningSampleSelectLabel.set('Kerning sample %d/%d lines' % (int(round(cursor/KERN_LINE_SIZE)), len(kerningSample)/KERN_LINE_SIZE))
changed |= self.checkSpacingDependencies(g) # Update the spacing consistency for all glyphs in the kerning line
self.randomWord = choice(ULCWORDS) # Random word changed on up/down cursor
self.saveKerningCursor()
updatePreview = True
elif optionDown and characters == NSDownArrowFunctionKey:
kerningSample = self.getKerningSample(g.font)
currentCursor = int(round(self.controller.w.kerningSampleSelectSlider.get()))
if shiftDown:
cursor = min(len(kerningSample)- KERN_LINE_SIZE, currentCursor + 8*KERN_LINE_SIZE)
else:
cursor = min(len(kerningSample)- KERN_LINE_SIZE, currentCursor + KERN_LINE_SIZE)
self.controller.w.kerningSampleSelectSlider.set(cursor)
self.controller.w.kerningSampleSelectSlider.setMaxValue(len(kerningSample))
self.controller.w.kerningSampleSelectLabel.set('Kerning sample %d/%d lines' % (int(round(cursor/KERN_LINE_SIZE)), len(kerningSample)/KERN_LINE_SIZE))
changed |= self.checkSpacingDependencies(g) # Update the spacing consistency for all glyphs in the kerning line
self.randomWord = choice(ULCWORDS) # Random word changed on up/down cursor
self.saveKerningCursor()
updatePreview = True
elif optionDown and characters == NSLeftArrowFunctionKey:
kerningSample = self.getKerningSample(g.font)
currentCursor = int(round(self.controller.w.kerningSampleSelectSlider.get()))
if shiftDown:
cursor = max(0, currentCursor - 8)
self.randomWord = choice(ULCWORDS) # Random word changed on left-shift cursor
else:
cursor = max(0, currentCursor - 1)
self.controller.w.kerningSampleSelectSlider.set(cursor)
self.controller.w.kerningSampleSelectSlider.setMaxValue(len(kerningSample))
self.controller.w.kerningSampleSelectLabel.set('Kerning sample %d/%d lines' % (int(round(cursor/KERN_LINE_SIZE)), len(kerningSample)/KERN_LINE_SIZE))
changed |= self.checkSpacingDependencies(g) # Update the spacing consistency for all glyphs in the kerning line
#self.saveKerningCursor()
updatePreview = True
elif optionDown and characters == NSRightArrowFunctionKey:
kerningSample = self.getKerningSample(g.font)
currentCursor = int(round(self.controller.w.kerningSampleSelectSlider.get()))
if shiftDown:
cursor = min(len(kerningSample) - KERN_LINE_SIZE, currentCursor + 8)
self.randomWord = choice(ULCWORDS) # Random word changed onright-shift cursor
else:
cursor = min(len(kerningSample) - KERN_LINE_SIZE, currentCursor + 1)
self.controller.w.kerningSampleSelectSlider.set(cursor)
self.controller.w.kerningSampleSelectSlider.setMaxValue(len(kerningSample))
self.controller.w.kerningSampleSelectLabel.set('Kerning sample %d/%d lines' % (int(round(cursor/KERN_LINE_SIZE)), len(kerningSample)/KERN_LINE_SIZE))
changed |= self.checkSpacingDependencies(g) # Update the spacing consistency for all glyphs in the kerning line
#self.saveKerningCursor()
updatePreview = True
if changed:
if VERBOSE:
print('... Update', g.name)
self.updateGlyph(g)
if updatePreview:
if VERBOSE:
print('Preview key down', g.name)
self.updatePreview(g)
def saveKerningCursor(self):
f = CurrentFont() # Only save the current kerning cursor in the curren font
kerningSampleIndex = self.controller.w.kerningSampleSelectSlider.get()
if f.lib.get(KERNING_SAMPLE_SELECT_LIB) != kerningSampleIndex:
#print('... Saving kerning select index %d (%d) in f.lib[%s]=%d for %s' % (kerningSampleIndex, kerningSampleIndex/KERN_LINE_SIZE, KERNING_SAMPLE_SELECT_LIB, kerningSampleIndex, f.path.split('/')[-1]))
f.lib[KERNING_SAMPLE_SELECT_LIB] = kerningSampleIndex
f.lib[KERNING_SAMPLE_X] = self.controller.w.kerningLeftX.get()
def glyphEditorDidMouseDown(self, info):
#event = extractNSEvent(info['NSEvent'])
g = info['glyph']
if g is None:
return
if VERBOSE:
print('--- glyphEditorDidMouseDown', g.name)
g.prepareUndo()
self.selectedTerminal = None
self.mouseClickPoint = p = info['locationInGlyph']
for terminal in self.terminals:
ox, oy = terminal['anchor']
if ox-5 <= p.x <= ox+5 and oy-5 <= p.y <= oy+5:
self.selectedTerminal = terminal
break
# Check on anchors
#if self.controller.w.fixAnchors.get() and gd.fixAnchors:
# self.fixAnchors(g)
#self.showFrozen(g)
#self.showItalicRoman(g)
#print('... Mouse down', info['locationInGlyph'], info['NSEvent'])
self.updatePreview(g)
def glyphEditorDidMouseUp(self, info):
# Reset terminal stuff
g = info['glyph']
if VERBOSE:
print('--- glyphEditorDidMouseDown', g.name)
self.selectedTerminal = None
self.mouseClickPoint = None
self.mouseDraggedPoint = None
#print('... Mouse up', info['locationInGlyph'], info['NSEvent'])
self.updatePreview(g)
def glyphEditorDidMouseMove(self, info):
pass
#print('... Mouse move', info['locationInGlyph'], info['NSEvent'])
def glyphEditorDidMouseDrag(self, info):
g = info['glyph']
#if VERBOSE:
# print('--- glyphEditorDidMouseDrag-RETURN', g.name)
def glyphEditorGlyphDidChange(self, info):
g = info['glyph']
if g is None:
return
if VERBOSE:
print('--- glyphEditorGlyphDidChange', g.name)
self.updatePreview(g)
def glyphEditorGlyphDidChangeInfo(self, info):
g = info['glyph']
if g is None:
return
if VERBOSE:
print('--- glyphEditorGlyphDidChangeInfo', g.name)
self.updatePreview(g)
def glyphEditorGlyphDidChangeOutline(self, info):
g = info['glyph']
if g is None:
return
if VERBOSE:
print('--- glyphEditorGlyphDidChangeOutline', g.name)
self.updateGlyph(g)
self.updatePreview(g)
def glyphEditorGlyphDidChangeContours(self, info):
"""Event also calls glyphEditorGlyphDidChangeOutline"""
g = info['glyph']
if g is None:
return
if VERBOSE:
print('--- glyphEditorGlyphDidChangeContours', g.name)
self.updateGlyph(g)
self.updatePreview(g)
def glyphEditorGlyphDidChangeComponents(self, info):
"""Event also calls glyphEditorGlyphDidChangeOutline"""
g = info['glyph']
if g is None:
return
if VERBOSE:
print('--- glyphEditorGlyphDidChangeComponents', g.name)
self.updateGlyph(g)
self.updatePreview(g)
def glyphEditorGlyphDidChangeAnchors(self, info):
g = info['glyph']
if g is None:
return
if VERBOSE:
print('--- glyphEditorGlyphDidChangeAnchors', g.name)
self.updateGlyph(g)
self.updatePreview(g)
#def glyphEditorGlyphDidChangeSelection(self, info):
# g = info['glyph']
# if g is None:
# return
# #if VERBOSE:
# print('--- glyphEditorGlyphDidChangeSelection', g.name)
# K E R N I N G
def getKerningManager(self, f):
if f.path:
if f.path not in self.kerningManagers:
self.kerningManagers[f.path] = KerningManager(f, sample=self.kerningSample) # First sample will be initialzed, others will be copied
km = self.kerningManagers[f.path]
self.kerningSample = km.sample
return km
return None
def getKerningSample(self, f):
km = self.getKerningManager(f)
if km is not None:
return km.sample
return ''
def autoKernAll(self):
f = CurrentFont()
km = self.getKerningManager(f)
km.setKerning('H', 'H', 0)
for gIndex, gName2 in enumerate(km.sample):
gName1 = km.sample[gIndex-1]
k = self.predictKerning(gName1, gName2)
print(gName1, gName2, k)
#if gIndex > 20:
# break
# S P A C I N G
def _adjustLeftMargin(self, g, value):
if self.isUpdating:
return
km = self.getKerningManager(g.font)
unit = 4
lm = km.getLeftMargin(g) # Margin from dependency
g1 = km.getLeftMarginGroupBaseGlyph(g) # Margin from group
# Only if no dependency and no group or g is a group base, then we can alter the margin
if lm is None and (g1 is None or g1.name == g.name):
g.angledleftMargin = int(round(g.angledLeftMargin/unit) + value) * unit
def _adjustRightMargin(self, g, value):
if self.isUpdating:
return
km = self.getKerningManager(g.font)
unit = 4
rm = km.getRightMargin(g) # Margin from dependency
g2 = km.getRightMarginGroupBaseGlyph(g) # Margin from group
# Only if no dependency and no group or g is a group base, then we can alter the margin
if rm is None and (g2 is None or g2.name == g.name):
g.angledRightMargin = int(round(g.angledRightMargin/unit) + value) * unit
# K E R N I N G
def _adjustLeftKerning(self, g, value=None, newK=None):
"""
Two ways of usage:
• value is relative adjustment
• newK is setting new kerning value.
3 = glyph<-->glyph # Not used
2 = group<-->glyph
1 = glyph<-->group
0 or None = group<-->group
"""
assert value is not None or newK is not None
f = g.font
km = self.getKerningManager(f)
unit = 4
if self.kernGlyph1 is None:
return
k, groupK, kerningType = km.getKerning(self.kernGlyph1, g.name)
if newK is not None:
k = newK # Set this value, probably predicted.
else: # Adjust relative by rounded value
k = int(round(k/unit))*unit + value * unit
if not kerningType and self.capLock:
kerningType = 2 # group<-->glyph
elif kerningType == 2 and self.capLock:
kerningType = 3 # glyph<-->glyph
km.setKerning(self.kernGlyph1, g.name, k, kerningType)
def _adjustRightKerning(self, g, value=None, newK=None):
"""
Two ways of usage:
• value is relative adjustment
• newK is setting new kerning value.
3 = glyph<-->glyph # Not used
2 = group<-->glyph
1 = glyph<-->group
0 or None = group<-->group
"""