-
Notifications
You must be signed in to change notification settings - Fork 1
/
KernNetAssistant-008.py
1010 lines (853 loc) · 42.8 KB
/
KernNetAssistant-008.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 -*-
#
# Using KernNet and Similarity for automatic sides and kerning
# Also it auto fixes the position of anchor, depending on the (changed) spacing.
#
# Path of working
# X Check spacing and margins for all diacritics and tab glyphs. Mark them in glyph.lib a locked spacing.
# • Calibrate the side(s) of /H and /O (and other symmetric glyphs)to such a value that the kerning
# for the glyphs is k = 0
# • Do the same for a special symmetric /ispace in case, in case the /idotless is not symmetric
# (a in serif or italic with tail)
# • For all glyph:
# • Automate position of anchors
# • Adjust manually and lock anchor positions from automatic.
# • For all glyphs:
# • If the glyph is symmetric, then use the calibrate function instead of the spacing function
# • If the side(s) of the glyph is similar to the side(s) of a glyph that was already processed,
# then simply copy the margin().
# • Otherwise use KernNet to calibrate glyphs a /H<glyph>/H and /O<glyph>/O into k = 0.
# The margins of the glyps are then the differece with the margins of /H and /O
# Store these margins as base for next similar glyphs
# • For all kerning combinations:
# • Use similarity to generate groups, splitting into scripts.
# • Use KernNet to kern the main of group-group combinations (not crossing script boundaries)
# • Write current glyph selection into FontGoggles sample file
#
#
#
import sys
import codecs
import importlib
from math import *
import urllib.request
from AppKit import *
from vanilla import *
import drawBot
from mojo.subscriber import Subscriber, WindowController, registerGlyphEditorSubscriber, unregisterGlyphEditorSubscriber
from mojo.events import extractNSEvent
import assistantLib
importlib.reload(assistantLib)
# Decide on the type of window for the Assistant.
#WindowClass = Window # Will hide behind other windows, if not needed.
WindowClass = FloatingWindow # Is always available, but it can block the view of other windows if the Asistant window grows in size.
# Add paths to libs in sibling repositories. The assistantLib module contains generic code for Asistanta.s
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
SAMPLE_FILE_NAME = 'FontGoggles-KernNet-Sample.txt' # Set in .gitIgnore to avoid change conflicts
VERBOSE = False
W, H = 400, 300
M = 20
BW = 200 - 2*M # Button width
BH = 24 # Button height
FAR = 100000 # Put drawing stuff outside the window
MAX_DIACRITICS = 150
TAB_WIDTH = 1170
KERN_GLYPH_COLOR = (0, 0, 0, 0.7)
LIB_KEY = 'TYPETR-AnchorAssistant' # Key to store application settings in the glyph.lib
ARROW_KEYS = [NSUpArrowFunctionKey, NSDownArrowFunctionKey,
NSLeftArrowFunctionKey, NSRightArrowFunctionKey, NSPageUpFunctionKey,
NSPageDownFunctionKey, NSHomeFunctionKey, NSEndFunctionKey]
VISITED_MARKER = (15/256, 180/256, 240/256, 1)
CALIBRATOR = 'H' # Calibrator glyph, that is used on both sides to get standard kerning and spacing.
SYMMETRIC_GLYPHS = (# Valid to calibrate
#'period',
'quotesingle', 'slash', 'fraction', 'clickdental', 'clicklateral',
'Hsmall', 'Vturmed',
'ispace',
'zero',
'A', 'H', 'I', 'M', 'N', 'O', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',
'o', 's', 'x', 'v', 'w', 'z',
'Xi', 'Phi', 'Tau', 'Chi', 'Iota', 'Theta', 'Upsilon', 'Pi', 'Lambda', 'Delta',
'San',
)
def getLib(g):
"""Get the dictionary of flags that is stored in g.lib"""
if not LIB_KEY in g.lib:
g.lib[LIB_KEY] = {}
return g.lib[LIB_KEY]
class FontData:
def __init__(self, f):
"""Build X-ref data from the from. Don't store the font itself, as it may be close by the calling application."""
self.path = f.path
# Fins all glyphs that use this glyph as component
self.base = {} # Key is glyphName. Value is list of component.baseGlyph names
# Find all diacritics and match them with the referring glyphs.
self.diacritics = {} # Key is diacritics name. Value is list of glyph names that use this diacritic as component.
# All glyphs that are in the same cloud of diacritics (affected by the position of the same anchor)
self.diacriticsCloud = {} # Key is glyhName
# Collection of tab glyphs
self.tabs = []
# All glyphs usage of anchors
self.glyphAnchors = {} # Key is glyphName, Value is dict of ancbhor.name --> (x, y).
self.anchors = {} # Key is anchor name. Value is list of glyphs that use this anchor
# Unicode --> Glyph name
self.unicodes = {} # Key is unicode (if it exists). Value is glyph name.
# Collect the glyphs that are used as diacritics. These need to have anchors and width = 0.
for g in f:
self.base[g.name] = [] # These glyphs have components refering to g.
if g.name.endswith('cmb') or g.name.endswith('comb'):
if g.unicode and g.name not in self.diacritics: # Only for real floating diacritics that have a unicode
self.diacritics[g.name] = []
elif g.name.endswith['tnum']:
self.tabs.append(g.name)
for g in f:
self.base[g.name] = bb = []
for component in g.components:
bb.append(component.baseGlyph)
if component.baseGlyph in self.diacritics: # Only for real diacritics (that have a unicode)
self.diacritics[component.baseGlyph].append(g.name)
# glyphName --> dict of anchors
self.glyphAnchors[g.name] = aa = {}
for a in g.anchors:
aa[a.name] = a.x, a.y
# anchorName --> List of glyph that are using it
if a.name not in self.anchors:
self.anchors[a.name] = []
self.anchors[a.name].append(g.name)
if g.unicode:
self.unicodes[g.unicode] = g.name
def __repr__(self):
return f'<{self.__class__.__name__}: {self.path.split("/")[-1]}>'
assistant = None # Little cheat, to make the assistant available from the window
class KernNetSpacingAssistant(Subscriber):
def build(self):
global assistant
assistant = self
self.isUpdating = False
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.fontDatas = {} # Key is font path, value is FontData instance that holds mined X-ref data on the font.
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.kernGlyphImage1 = self.backgroundContainer.appendPathSublayer(
name='kernGlyphImage1',
position=(FAR, 0),
fillColor=KERN_GLYPH_COLOR, # Opaque diacritics cloud
)
self.kernGlyphImage = self.backgroundContainer.appendPathSublayer(
name='kernGlyphImage',
position=(FAR, 0),
fillColor=KERN_GLYPH_COLOR, # Sets to light gray if not equal to current glyph.
)
self.kernGlyphImage2 = self.backgroundContainer.appendPathSublayer(
name='kernGlyphImage2',
position=(FAR, 0),
fillColor=KERN_GLYPH_COLOR, # Opaque diacritics cloud
)
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.leftMarginValue = self.backgroundContainer.appendTextLineSublayer(
name="leftMarginValue",
position=(FAR, 0),
text='xxx\nxxx',
font='Courier',
pointSize=32,
fillColor=(1, 0, 0, 1),
)
self.rightMarginValue = self.backgroundContainer.appendTextLineSublayer(
name="rightMarginValue",
position=(FAR, 0),
text='xxx\nxxx',
font='Courier',
pointSize=32,
fillColor=(1, 0, 0, 1),
)
#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 getFontData(self, f):
"""Answer the cached FontData instance. If it does not exist, create it and let it in mine X-refs from the @f. """
if not f.path in self.fontDatas:
self.fontDatas[f.path] = FontData(f)
return self.fontDatas[f.path]
def glyphEditorGlyphDidChange(self, info):
g = info['glyph']
self.updateSampleText(g)
self.getLibFlags(g)
self.update(g)
def glyphEditorDidSetGlyph(self, info):
g = info['glyph']
#fd = self.getFontData(g.font)
#print(g.name, fd.components)
#print('-----', fd.glyphAnchors)
#print('-----', fd.unicodes)
self.adjustRightMargin(g)
self.adjustLeftMargin(g)
self.getLibFlags(g)
if g.markColor != VISITED_MARKER: # NO_MARKER
g.markColor = VISITED_MARKER
self.update(g)
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
if characters in 'Ee': # Calibration of symmwrix glyphs
if g.name not in SYMMETRIC_GLYPHS: # Don't do asymmetric glyph this way
return
self.calibrate(g) # Update the spacing consistency for all glyphs in left/right kerning = 0.
changed = True
if characters in 'Dd': # Autospace by KernNet
self.space(g, ignoreLockSpacing=characters=='D') # Update the spacing consistency for all glyphs in the kerning line
changed = True
#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 = True #|= self.checkSpacingDependencies(g) # Update the spacing consistency for all glyphs in the kerning line
elif characters in 'Oo': # Decrement right margin
if shiftDown:
self.adjustRightMargin(g, -5)
else:
self.adjustRightMargin(g, -1)
changed = True # |= self.checkSpacingDependencies(g) # Update the spacing consistency for all glyphs in the kerning line
elif characters in 'Ii': # Increment left margin
if shiftDown:
self.adjustLeftMargin(g, 5)
else:
self.adjustLeftMargin(g, 1)
changed = True # |= self.checkSpacingDependencies(g) # Update the spacing consistency for all glyphs in the kerning line
elif characters in 'Uu': # Decrement left margin
if shiftDown:
self.adjustLeftMargin(g, -5)
else:
self.adjustLeftMargin(g, -1)
changed = True # |= self.checkSpacingDependencies(g) # Update the spacing consistency for all glyphs in the kerning line
# 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
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
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
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
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()
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()
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
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
if changed:
if VERBOSE:
print('... Update', g.name)
self.update(g)
# G L Y P H L I B
def getLibFlags(self, g):
"""Update the lock checkboxes from info stored in the glyph.lib"""
d = getLib(g)
# Use baseGlyph for positioning anchors
self.controller.w.lockedSpacing.set(d.get('lockedSpacing', False))
def saveLibFlags(self, g):
"""Save the anchor lock checkboxes info stored in the glyph.lib"""
d = getLib(g)
d['lockedSpacing'] = self.controller.w.lockedSpacing.get()
def lockSpacing(self, g):
d = getLib(g)
d['lockedSpacing'] = True
self.controller.w.lockedSpacing.set(True)
def getLockedSpacing(self, g):
d = getLib(g)
return d.get('lockedSpacing', False)
# S P A C I N G
def adjustLeftMargin(self, g, value=0):
if self.isUpdating:
return
self.lockSpacing(g)
km = self.getKerningManager(g.font)
unit = 4
alm = int(round(g.angledLeftMargin/unit) + value) * unit
g.angledLeftMargin = alm
print('LLLLL', km.getSimilarNames2(g))
print('MMMMM', g.name, km.similar2Base2.get(g.name))
#for ggName in km.getSimilarBaseNames2(g): # Future: Get the names that are similar to the base that is similar to g
for ggName in km.getSimilarNames2(g):
gg = g.font[ggName]
#print('LEFT', ggName, gg.name, not gg.components)
if not gg.components:
if abs(gg.angledLeftMargin - alm) < 1:
print(f'... Set left margin of /{ggName} from {gg.angledLeftMargin} to {alm}')
gg.angledLeftMargin = alm
gg.changed()
#for ggName in km.getSimilarNames2(g): # Get the names that are similar to the base that is similar to g
for ggName in km.getSimilarNames2(g):
gg = g.font[ggName]
#print('LEFT', ggName, gg.name, not gg.components)
if gg.components:
if abs(gg.angledLeftMargin - alm) < 1:
print(f'... Set left margin of /{ggName} from {gg.angledLeftMargin} to {alm}')
gg.angledLeftMargin = alm
gg.changed()
g.changed()
def adjustRightMargin(self, g, value=0):
if self.isUpdating:
return
self.lockSpacing(g)
km = self.getKerningManager(g.font)
unit = 4
arm = int(round(g.angledRightMargin/unit) + value) * unit
g.angledRightMargin = arm
print('RRRRR', km.getSimilarNames1(g))
print('WWWWW', g.name, km.similar2Base1.get(g.name))
#for ggName in km.getSimilarBaseNames1(g): # Future: Get the names that are similar to the base that is similar to g
for ggName in km.getSimilarNames1(g): # Get the names that are similar to the base that is similar to g
gg = g.font[ggName]
#print('RIGHT', ggName, gg.name, not gg.components)
if not gg.components:
if abs(gg.angledRightMargin - arm) < 1:
print(f'... Set right margin of /{ggName} from {gg.angledRightMargin} to {arm}')
gg.angledRightMargin = arm
gg.changed()
#for ggName in km.getSimilarBaseNames1(g): # Future: Get the names that are similar to the base that is similar to g
for ggName in km.getSimilarNames1(g): # Get the names that are similar to the base that is similar to g
gg = g.font[ggName]
#print('RIGHT', ggName, gg.name, not gg.components)
if gg.components:
if abs(gg.angledRightMargin - arm) < 1:
print(f'... Set right margin of /{ggName} from {gg.angledRightMargin} to {arm}')
gg.angledRightMargin = arm
gg.changed()
g.changed()
# F O N T G O G G L E S S A M P L E T E X T
def updateSampleText(self, g):
"""
current Sample == sampleText != popup: Popup changed
current Sample != sampleText != popup: Sample text change manually
"""
sample = 'HHOOI/?IO/?H/?i/?io/?on/?n Hamburgefons/?tiv/?HAMBURG/?RGER'
if g.font is None or g.font.path is None:
return
#self.randomWord = choice(ULCWORDS) # Random word changed on up/down cursor
# FontGoggles can only show characters with unicode. Stylistic sets will show alternatives.
if g.name.startswith('.'):
return
if g.unicode:
c = chr(g.unicode)
font = g.font # Get the font to know where to write the file
# Get the path of the current font and calculate the output file path local to it.
path = '/'.join(font.path.split('/')[:-1]) + '/' + SAMPLE_FILE_NAME
#compositeChars = ''
#if g.name in COMPOSITES_BASE_ITALIC:
# for compositeName in COMPOSITES_BASE_ITALIC[g.name]:
# if font[compositeName].unicode:
# compositeChars += chr(font[compositeName].unicode)
#sample = sample.replace('/??C', compositeChars) # Replace by all composite glyphs that use the current glyph as component
sample = sample.replace('/?', c) # Get the sample and replace pattern /?
f = codecs.open(path, 'w', encoding='utf-8') # Open file, for unicode/UTF-8
f.write(sample)
f.close()
# 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, simT=0.95 ,simSameCategory=False, simSameScript=False, simClip=150) # 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
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
"""
assert value is not None or newK is not None
f = g.font
km = self.getKerningManager(f)
unit = 4
if self.kernGlyph2 is None:
return
k, groupK, kerningType = km.getKerning(g.name, self.kernGlyph2)
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 = 1 # glyph<-->group
elif kerningType == 1 and self.capLock:
kerningType = 3 # glyph<-->glyph
km.setKerning(g.name, self.kernGlyph2, k, kerningType)
# E V E N T
def update(self, g):
f = g.font
self.controller.w.currentGlyph.set(g.name)
#self.space(g)
gName1 = self.controller.w.kerningGlyph1.get()
gName2 = self.controller.w.kerningGlyph2.get()
if gName1 is not None and gName1 in f and gName2 is not None and gName2 in f:
k1, k2 = self.predictKerning(gName1, g, gName2)
self.controller.w.kerningGlyph1_mr.set('R'+str(round(f[gName1].angledRightMargin)))
self.controller.w.kerningGlyph1_k.set('K'+str(round(k1)))
self.controller.w.currentGlyph_ml.set('L'+str(round(g.angledLeftMargin)))
self.controller.w.currentGlyph_mr.set('R'+str(round(g.angledRightMargin)))
self.controller.w.kerningGlyph2_k.set('K'+str(round(k2)))
self.controller.w.kerningGlyph2_ml.set('L'+str(round(f[gName2].angledLeftMargin)))
# Enabling buttons
self.controller.w.calibrateButton.enable((g.name in SYMMETRIC_GLYPHS or self.controller.w.calibrateAll.get()) and not self.getLockedSpacing(g))
self.controller.w.spaceButton.enable(not self.controller.w.lockedSpacing.get())
y = f.info.capHeight + 200
if g.angledLeftMargin is not None:
x = 0 + tan(radians(-f.info.italicAngle or 0)) * y
lm = str(int(round(g.angledLeftMargin)))
self.leftMarginValue.setText(lm)
self.leftMarginValue.setPosition((x, y))
else:
self.leftMarginValue.setPosition((FAR, y))
if g.angledRightMargin is not None:
x = g.width + tan(radians(-f.info.italicAngle or 0)) * y
rm = str(int(round(g.angledRightMargin)))
self.rightMarginValue.setText(rm)
self.rightMarginValue.setPosition((x, y))
else:
self.rightMarginValue.setPosition((FAR, y))
def calibrate(self, g, margin=500):
"""Calibrate the margins, starting at lm=0 and rm=0, then increase, until the k reaches a local minimum.
The glyph is supposed to be sumetrics, as the predicted kerning is dived by 2 to get the margins."""
if self.getLockedSpacing(g):
return
g.angledRightMargin = g.angledLeftMargin = 0
for m in range(500): # Number of iterations, avoid infinite loop
#gName1 = self.controller.w.kerningGlyph1.get()
#if not gName1 or gName1 not in g.font:
# gName1 = g.name
gName1 = g.name ######
#gName2 = self.controller.w.kerningGlyph2.get()
#if not gName2 or gName2 not in g.font:
# gName2 = g.name
gName2 = g.name #####
k1, k2 = self.predictKerning(gName1, g, gName2, step=1)
g.angledLeftMargin += k1/2
g.angledRightMargin += k2/2
if abs(k1) <= 1 and abs(k2) <= 1: #or abs(k1) == abs(prevK):
break
g.changed()
# S P A C I N G B Y K E R N N E T
def center(self, g):
ml = g.angledLeftMargin
if ml is not None:
w = g.width
g.angledLeftMargin = (g.angledLeftMargin + g.angledRightMargin)/2
g.width = w # Overwrite any roundings
g.changed()
DIACRITICS = ('perispomeni', 'arrowheadrightheaddownbelow', 'lefttorightmark', 'righttoleftmark', 'zerowidthnonjoiner', 'zerowidthjoiner',
'zerowidthnonjoiner', 'zerowidthjoiner')
def space(self, g, margin=200, step=1, ignoreLockSpacing=False):
"""Try to guess what the margins for @h should be, based on the Similarity groups and on /H/H kerning == 0."""
if not ignoreLockSpacing and self.getLockedSpacing(g):
return
if g.name.endswith('tab') or g.name.endswith('tnum'): # Fixed with
self.lockSpacing(g)
g.width = TAB_WIDTH # Needs differentation by weight/width
self.center(g)
g.changed()
self.adjustRightMargin(g)
self.adjustLeftMargin(g)
elif 'keycap' in g.name:
self.lockSpacing(g)
g.angledLeftMargin = g.angledRightMargin = 0
self.controller.w.lockedSpacing.set(True)
g.changed()
elif 'comp' in g.name or 'comb' in g.name or 'component' in g.name or g.name in self.DIACRITICS:
self.lockSpacing(g)
g.width = 0
self.center(g)
g.changed()
#elif g.name in SYMMETRIC_GLYPHS:
# self.calibrate(g)
else:
g.angledLeftMargin = g.angledRightMargin = 50 # Start with neuitral value
for n in range(5): # Do some iterations
k1, k2 = self.predictKerning(CALIBRATOR, g, CALIBRATOR, step=step)
g.angledLeftMargin += k1 # Correct the margins by the amount of predicted kerning it would need.
g.angledRightMargin += k2
if g.angledLeftMargin <= 0 or g.angledRightMargin <= 0:
break
if abs(k1) <= 2 and abs(k2) <= 2:
break
g.changed()
self.adjustRightMargin(g)
self.adjustLeftMargin(g)
# K E R N N E T
def predictKerning(self, gName1, g, gName2, step=None):
k1 = k2 = 0
f = g.font
if gName1 and gName1 in f:
g1 = f[gName1]
k1 = self.getKernNetKerning(g1, g, step=step)
self.kernGlyphImage1.setPath(g1.getRepresentation("merz.CGPath"))
self.kernGlyphImage1.setPosition((-g1.width - k1, 0))
else:
self.kernGlyphImage1.setPosition((FAR, 0))
self.kernGlyphImage.setPath(g.getRepresentation("merz.CGPath"))
self.kernGlyphImage.setPosition((0, 0))
if gName2 and gName2 in f:
g2 = f[gName2]
k2 = self.getKernNetKerning(g, g2, step=step)
self.kernGlyphImage2.setPath(g2.getRepresentation("merz.CGPath"))
self.kernGlyphImage2.setPosition((g.width + k2, 0))
else:
self.kernGlyphImage2.setPosition((FAR, 0))
y4 = -150 # Position of current kerning values
if k1 < 0:
kernColor = 1, 0, 0, 1
if k1 > 0:
kernColor = 0, 0.5, 0, 1
else:
kernColor = 0.6, 0.6, 0.6, 1
self.kerning1Value.setFillColor(kernColor)
self.kerning1Value.setPosition((k1, y4))
self.kerning1Value.setText(f'{k1}')
if k2 < 0:
kernColor = 1, 0, 0, 1
if k2 > 0:
kernColor = 0, 0.5, 0, 1
else:
kernColor = 0.6, 0.6, 0.6, 1
self.kerning2Value.setFillColor(kernColor)
self.kerning2Value.setPosition((g.width + k2, y4))
self.kerning2Value.setText(f'{k2}')
return k1, k2
#FACTOR = 0.8
#FACTOR = 1.4
UNIT = 2
def getKernNetKerning(self, g1, g2, step=None):
"""Gernerate the kerning test image.
Answer the KernNet predicted kerning for @g1 amd @g2. This assumes the KernNet server to be running on localhost:8080"""
if step is None:
step = self.UNIT
f = g1.font
imageName = 'test.png'
kernImagePath = '/'.join(__file__.split('/')[:-1]) + '/assistantLib/kernnet6/_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}')
print('dasads', page)
# 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
L = 22
M = 8 # Margin of UI and gutter of colums
CW = (W-4*M)/3
C0 = M
C1 = C0 + CW + M
C15 = C0 + (CW + M) * 1.5
C2 = C1 + CW + M
class KernNetSpacingAssistantController(WindowController):
assistantGlyphEditorSubscriberClass = KernNetSpacingAssistant
NAME = 'KernNet Assistant'
def build(self):
f = CurrentFont()
tbw = 5 * M
y = M
self.w = WindowClass((450, 50, W, H), self.NAME, minSize=(W, H))
self.w.kerningGlyph1 = EditText((C0, y, CW, L), callback=self.updateKerningCallback) # Use kerning find button to go there.
self.w.currentGlyph = TextBox((C1, y, CW, L), '')
self.w.kerningGlyph2 = EditText((C2, y, CW, L), callback=self.updateKerningCallback)
self.w.kerningGlyph1.set(CALIBRATOR)
self.w.kerningGlyph2.set(CALIBRATOR)
y += L
self.w.kerningGlyph1_mr = TextBox((C1-1.5*tbw, y, tbw, L), '0')
self.w.kerningGlyph1_k = TextBox((C1-tbw/2, y, tbw, L), '0')
self.w.currentGlyph_ml = TextBox((C1+tbw/2, y, tbw, L), '0')
self.w.currentGlyph_mr = TextBox((C2-1.5*tbw, y, tbw, L), '0')
self.w.kerningGlyph2_k = TextBox((C2-tbw/2, y, tbw, L), '0')
self.w.kerningGlyph2_ml = TextBox((C2+tbw/2, y, tbw, L), '0')
y += 2*L
self.w.cropKernImage = CheckBox((C2, y, CW, L), 'Crop kern image', value=True, callback=self.updateKerningCallback)
self.w.factor = EditText((C0, y, CW, L), callback=self.updateKerningCallback) # Use kerning find button to go there.
self.w.factor.set('1') # No calibration factor by default
y += L
self.w.useSimilarity = CheckBox((C2, y, CW, L), 'Use Similarity', value=True, callback=self.updateKerningCallback)
self.w.calibrate = EditText((C0, y, CW, L), callback=self.updateKerningCallback)
self.w.calibrate.set('-6') # Linear correction to k
y += 2*L
self.w.lockedSpacing = CheckBox((C2, y, CW, L), 'Lock spacing', value=True, callback=self.updateKerningCallback)
y = H - M - BH - L
self.w.calibrateAll = CheckBox((M, y, CW, L), 'All', value=False, callback=self.updateKerningCallback)
self.w.spaceAll = CheckBox((C1, y, CW, L), 'All', value=False, callback=self.updateKerningCallback)
y = H - M - BH
self.w.calibrateButton = Button((M, y, CW, BH), 'Calibrate', callback=self.calibrateButtonCallback)
self.w.spaceButton = Button((C1, y, CW, BH), 'Space', callback=self.spaceButtonCallback)
self.w.open()
def started(self):
#print("started")
self.assistantGlyphEditorSubscriberClass.controller = self
registerGlyphEditorSubscriber(self.assistantGlyphEditorSubscriberClass)
def destroy(self):
#print("windowClose")
unregisterGlyphEditorSubscriber(self.assistantGlyphEditorSubscriberClass)
self.assistantGlyphEditorSubscriberClass.controller = None
def updateKerningCallback(self, sender):
g = CurrentGlyph()
if g is not None:
assistant.saveLibFlags(g)
g.changed()
def calibrateButtonCallback(self, sender):
g = CurrentGlyph()
if g is not None:
if self.w.calibrateAll.get():
for gName in SYMMETRIC_GLYPHS:
if gName in g.font:
print(f'... Calibrating margins of /{gName}')
assistant.calibrate(g.font[gName])
elif g.name in SYMMETRIC_GLYPHS:
assistant.calibrate(g)
else:
print(f'### Not a calibrating glyph /{g.name}')
def spaceButtonCallback(self, sender):
g = CurrentGlyph()
if g is not None:
if self.w.spaceAll.get():
for ggName in sorted(g.font.keys()):
gg = g.font[ggName]
if not gg.components:
print(f'... Calibrating margins of non-component glyph /{gName}')
assistant.space(gg) # First do all glyphs without components, since these will alther the component positions