-
Notifications
You must be signed in to change notification settings - Fork 103
/
objectsGS.py
executable file
·1406 lines (1178 loc) · 41.7 KB
/
objectsGS.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
"""RoboFab for Glyphs"""
# -*- coding: utf-8 -*-
import sys
import objc
import weakref
from GlyphsApp import *
from GlyphsApp import Proxy, UserDataProxy, GSElement, GSGlyph, GSClass, GSLayer, GSComponent, GSAnchor, GSPath, GSNode
from AppKit import NSView, NSColor, NSRectFill, NSChangeCleared
from Foundation import NSNumber, NSMutableArray, NSAffineTransform, NSClassFromString, NSMinX, NSMinY, NSMaxX, NSMaxY
from WebKit import WebView
import traceback
from robofab import RoboFabError, RoboFabWarning, ufoLib
from robofab.objects.objectsBase import BaseFont, BaseKerning, BaseGroups, BaseInfo, BaseFeatures, BaseLib,\
BaseGlyph, BaseContour, BaseSegment, BasePoint, BaseBPoint, BaseAnchor, BaseGuide, \
relativeBCPIn, relativeBCPOut, absoluteBCPIn, absoluteBCPOut, _box,\
_interpolate, _interpolatePt, roundPt, addPt,\
MOVE, LINE, CORNER, CURVE, QCURVE, OFFCURVE,\
BasePostScriptFontHintValues, postScriptHintDataLibKey, BasePostScriptGlyphHintValues
import os, traceback
from warnings import warn
__all__ = ["CurrentFont", "AllFonts", "CurrentGlyph", 'OpenFont', 'RFont', 'RGlyph', 'RContour', 'RPoint', 'RAnchor', 'RComponent', "NewFont", "GSMOVE", "GSLINE", "GSCURVE", "GSQCURVE", "GSOFFCURVE", "GSSHARP", "GSSMOOTH", "GlyphPreview"]
GSMOVE_ = 17
GSLINE_ = 1
GSCURVE_ = 35
GSOFFCURVE_ = 65
GSSHARP = 0
GSSMOOTH = 100
GSMOVE = MOVE
GSLINE = LINE
GSCURVE = CURVE
GSQCURVE = QCURVE
GSOFFCURVE = OFFCURVE
LOCAL_ENCODING = "macroman"
# This is for compatibility until the proper implementaion is shipped.
if type(GSElement.parent) != type(GSGlyph.parent):
GSElement.parent = property(lambda self: self.valueForKey_("parent"))
def CurrentFont():
"""Return a RoboFab font object for the currently selected font."""
doc = Glyphs.currentFontDocument()
if doc:
try:
return RFont(doc.font, doc.windowControllers()[0].masterIndex())
except:
traceback.print_exc()
pass
return None
def AllFonts():
"""Return a list of all open fonts."""
all = []
for doc in Glyphs.documents:
for master_index, master_object in enumerate(doc.font.masters):
all.append(RFont(doc.font, master_index))
return all
def CurrentGlyph():
"""Return a RoboFab glyph object for the currently selected glyph."""
doc = Glyphs.currentDocument
Layer = doc.selectedLayers()[0]
if Layer is None:
return None
else:
master_index = doc.windowControllers()[0].masterIndex()
rg = RGlyph(Layer.parent, master_index)
rg.setParent(RFont(doc.font, master_index))
return rg
def OpenFont(path=None, note=None):
"""Open a font from a path."""
if path == None:
#from robofab.interface.all.dialogs import GetFile
path = GetFile(note, filetypes=["ufo", "glyphs", "otf", "ttf"])
if path:
if path[-7:].lower() == '.glyphs' or path[-3:].lower() in ["ufo", "otf", "ttf"]:
doc = Glyphs.openDocumentWithContentsOfFile_display_(path, False) #chrashed !!
if doc != None:
return RFont(doc.font)
return None
def NewFont(familyName=None, styleName=None):
"""Make a new font"""
doc = Glyphs.documentController().openUntitledDocumentAndDisplay_error_(True, None)[0]
rf = RFont(doc.font)
if familyName:
rf.info.familyName = familyName
if styleName:
rf.info.styleName = styleName
return rf
class PostScriptFontHintValues(BasePostScriptFontHintValues):
""" Font level PostScript hints object for objectsRF usage.
If there are values in the lib, use those.
If there are no values in the lib, use defaults.
The psHints attribute for objectsRF.RFont is basically just the
data read from the Lib. When the object saves to UFO, the
hints are written back to the lib, which is then saved.
"""
def __init__(self, aFont=None, data=None):
self.setParent(aFont)
BasePostScriptFontHintValues.__init__(self)
if aFont is not None:
# in version 1, this data was stored in the lib
# if it is still there, guess that it is correct
# move it to font info and remove it from the lib.
libData = aFont.lib.get(postScriptHintDataLibKey)
if libData is not None:
self.fromDict(libData)
del libData[postScriptHintDataLibKey]
if data is not None:
self.fromDict(data)
def getPostScriptHintDataFromLib(aFont, fontLib):
hintData = fontLib.get(postScriptHintDataLibKey)
psh = PostScriptFontHintValues(aFont)
psh.fromDict(hintData)
return psh
class PostScriptGlyphHintValues(BasePostScriptGlyphHintValues):
""" Glyph level PostScript hints object for objectsRF usage.
If there are values in the lib, use those.
If there are no values in the lib, be empty.
"""
def __init__(self, aGlyph=None, data=None):
# read the data from the glyph.lib, it won't be anywhere else
BasePostScriptGlyphHintValues.__init__(self)
if aGlyph is not None:
self.setParent(aGlyph)
self._loadFromLib(aGlyph.lib)
if data is not None:
self.fromDict(data)
class KerningProxy(Proxy, BaseKerning):
def _convertKeys(self, keys):
firstKey, secondKey = keys
if firstKey[0] != "@":
firstKey = self._owner._font.glyphForName_(firstKey).id
if firstKey == None:
raise KeyError, "glyph with name %s not found" % keys[0]
if secondKey[0] != "@":
secondKey = self._owner._font.glyphForName_(secondKey).id
if secondKey == None:
raise KeyError, "glyph with name %s not found" % keys[1]
return (firstKey, secondKey)
def __getitem__(self, keys):
if (type(keys) == list or type(keys) == tuple) and len(keys) == 2:
FontMaster = self._owner._font.masters[self._owner._masterIndex]
firstKey, secondKey = self._convertKeys(keys)
value = self._owner._font.kerningForFontMasterID_LeftKey_RightKey_(FontMaster.id, firstKey, secondKey)
if value > 100000: # NSNotFound
value = None
return value
else:
raise KeyError, 'kerning pair must be a tuple: (left, right)'
def get(self, pair, default=None):
try:
return self.__getitem__(pair)
except:
return default
def items(self):
return self._dict().items()
def __setitem__(self, keys, value):
if not isinstance(value, (int, float)):
raise ValueError
if (type(keys) == list or type(keys) == tuple) and len(keys) == 2:
FontMaster = self._owner._font.masters[self._owner._masterIndex]
firstKey, secondKey = self._convertKeys(keys)
self._owner._font.setKerningForFontMasterID_LeftKey_RightKey_Value_(FontMaster.id, firstKey, secondKey, value)
else:
raise KeyError, 'kerning pair must be a tuple: (left, right)'
def __delitem__(self, keys):
if (type(keys) == list or type(keys) == tuple) and len(keys) == 2:
FontMaster = self._owner._font.masters[self._owner._masterIndex]
firstKey, secondKey = self._convertKeys(keys)
self._owner._font.removeKerningForFontMasterID_LeftKey_RightKey_(FontMaster.id, firstKey, secondKey)
else:
raise KeyError, 'kerning pair must be a tuple: (left, right)'
def clear(self):
FontMaster = self._owner._font.masters[self._owner._masterIndex]
GSKerning = self._owner._font.kerning.objectForKey_(FontMaster.id)
if GSKerning is not None:
GSKerning.clear()
def remove(self, keys):
self.__delitem__(keys)
def __repr__(self):
font = "unnamed_font"
fontParent = self.getParent()
if fontParent is not None:
try:
font = fontParent.info.postscriptFullName
except AttributeError: pass
return "<RKerning for %s>" % font
def keys(self):
return self._dict().keys()
def values(self):
return self._dict().values()
def __iter__(self):
for key in self.keys():
yield key
def _dict(self):
FontMaster = self._owner._font.masters[self._owner._masterIndex]
GSKerning = self._owner._font.kerning.objectForKey_(FontMaster.id)
kerning = {}
if GSKerning != None:
for LeftKey in GSKerning.allKeys():
LeftKerning = GSKerning.objectForKey_(LeftKey)
if LeftKey[0] != '@':
LeftKey = self._owner._font.glyphForId_(LeftKey).name
for RightKey in LeftKerning.allKeys():
RightKerning = LeftKerning.objectForKey_(RightKey)
if RightKey[0] != '@':
RightKey = self._owner._font.glyphForId_(RightKey).name
kerning[(str(LeftKey), str(RightKey))] = RightKerning
return kerning
class RFont(BaseFont):
"""RoboFab UFO wrapper for GS Font object"""
_title = "GSFont"
def __init__(self, font=None, master=0):
BaseFont.__init__(self)
if font != None:
doc = font.parent
else:
doc = None
self._document = doc
self._font = font
self._masterIndex = master
self._masterKey = font.masters[master].id
self.features = RFeatures(font)
self.info = RInfo(self)
self._supportHints = False
self._RGlyphs = {}
def copy(self):
return RFont(self._font.copy())
def keys(self):
keys = {}
for glyph in self._font.glyphs:
glyphName = glyph.name
if glyphName in keys:
raise KeyError, "Duplicate glyph name in RFont: %r" % glyphName
keys[glyphName] = None
return keys.keys()
def has_key(self, glyphName):
glyph = self._font.glyphForName_(glyphName)
if glyph is None:
return False
else:
return True
__contains__ = has_key
def __setitem__(self, glyphName, glyph):
self._font.addGlyph_( glyph.naked() )
def __getitem__(self, glyphName):
GGlyph = self._font.glyphForName_(glyphName)
if GGlyph is None:
raise KeyError("Glyph '%s' not in font." % glyphName)
else:
glyph = RGlyph(GGlyph, self._masterIndex)
glyph.setParent(self)
return glyph
def __cmp__(self, other):
if not hasattr(other, '_document'):
return -1
return self._compare(other)
if self._document.fileName() == other._document.fileName():
# so, names match.
# this will falsely identify two distinct "Untitled"
# let's check some more
return 0
else:
return -1
def __len__(self):
if self._font.glyphs is None:
return 0
return len(self._font.glyphs)
def close(self):
self._document.close()
lib = property(lambda self: UserDataProxy(self._font))
def _hasNotChanged(self, doGlyphs=True):
raise NotImplementedError
def _get_path(self):
if self._document.fileURL() is None:
raise ValueError("Font is not saved yet")
return self._document.fileURL().path()
path = property(_get_path, doc="path of the font")
def _get_groups(self):
Dictionary = {}
for currGlyph in self._font.glyphs:
if currGlyph.leftKerningGroupId():
Group = Dictionary.get(currGlyph.leftKerningGroupId(), None)
if not Group:
Group = []
Dictionary[currGlyph.leftKerningGroupId()] = Group
Group.append(currGlyph.name)
if currGlyph.rightKerningGroupId():
Group = Dictionary.get(currGlyph.rightKerningGroupId(), None)
if not Group:
Group = []
Dictionary[currGlyph.rightKerningGroupId()] = Group
Group.append(currGlyph.name)
for aClass in self._font.classes:
Dictionary[aClass.name] = aClass.code.split(" ")
return Dictionary
def _set_groups(self, GroupsDict):
for currGroupKey in GroupsDict.keys():
if currGroupKey.startswith("@MMK_L_"):
Group = GroupsDict[currGroupKey]
if Group:
for GlyphName in Group:
if ChangedGlyphNames.has_key(currGroupKey):
currGroupKey = ChangedGlyphNames[currGroupKey]
if ChangedGlyphNames.has_key(GlyphName):
GlyphName = ChangedGlyphNames[GlyphName]
self._font.glyphForName_(GlyphName).setRightKerningGroupId_( currGroupKey )
elif currGroupKey.startswith("@MMK_R_"):
Group = GroupsDict[currGroupKey]
if Group:
for GlyphName in Group:
self._font.glyphForName_(GlyphName).setLeftKerningGroupId_(currGroupKey)
else:
newClass = GSClass()
newClass.setName_( currGroupKey )
newClass.setCode_( " ".join(GroupsDict[currGroupKey]))
newClass.setAutomatic_( False )
self._font.addClass_(newClass)
groups = property(_get_groups, _set_groups, doc="groups")
kerning = property( lambda self: KerningProxy(self),
lambda self, value: KerningProxy(self).setter(value))
#
# methods for imitating GlyphSet?
#
def getWidth(self, glyphName):
if self._font.glyphForName_(glyphName):
return self._font.glyphForName_(glyphName).layerForKey_(self._masterKey).width()
raise IndexError # or return None?
def save(self, path=None):
"""Save the font, path is required."""
self._font.save(path)
def close(self, save=False):
"""Close the font, saving is optional."""
if save:
self.save()
else:
self._document.updateChangeCount_(NSChangeCleared)
self._document.close()
def _get_glyphOrder(self):
return self._font.valueForKeyPath_("glyphs.name")
glyphOrder = property(_get_glyphOrder, doc="groups")
def getGlyph(self, glyphName):
# XXX getGlyph may have to become private, to avoid duplication
# with __getitem__
n = None
if self._RGlyphs.has_key(glyphName):
# have we served this glyph before? it should be in _object
n = self._RGlyphs[glyphName]
else:
# haven't served it before, is it in the glyphSet then?
n = RGlyph(self._font.glyphForName_(glyphName), self._masterIndex)
n.setParent(self)
self._RGlyphs[glyphName] = n
if n is None:
raise KeyError, glyphName
return n
def newGlyph(self, glyphName, clear=True):
"""Make a new glyph"""
g = self._font.glyphForName_(glyphName)
if g is None:
g = GSGlyph(glyphName)
self._font.addGlyph_(g)
elif clear:
g.layers[self._masterKey] = GSLayer()
return self[glyphName]
def insertGlyph(self, glyph, newGlyphName=None):
"""returns a new glyph that has been inserted into the font"""
if newGlyphName is None:
name = glyph.name
else:
name = newGlyphName
glyph = glyph.copy()
glyph.name = name
glyph.setParent(self)
glyph._hasChanged()
self._RGlyphs[name] = glyph
# is the user adding a glyph that has the same
# name as one that was deleted earlier?
#if name in self._scheduledForDeletion:
# self._scheduledForDeletion.remove(name)
return self.getGlyph(name)
def removeGlyph(self, glyphName):
"""remove a glyph from the font"""
# XXX! Potential issue with removing glyphs.
# if a glyph is removed from a font, but it is still referenced
# by a component, it will give pens some trouble.
# where does the resposibility for catching this fall?
# the removeGlyph method? the addComponent method
# of the various pens? somewhere else? hm... tricky.
#
# we won't actually remove it, we will just store it for removal
# but only if the glyph does exist
# if self.has_key(glyphName) and glyphName not in self._scheduledForDeletion:
# self._scheduledForDeletion.append(glyphName)
# now delete the object
if glyphName in self._font.glyphs:
del self._font[glyphName]
self._hasChanged()
def _get_selection(self):
"""return a list of glyph names for glyphs selected in the font window """
l=[]
for Layer in self._document.selectedLayers():
l.append(Layer.parent.name)
return l
def _set_selection(self, list):
raise NotImplementedError
return
selection = property(_get_selection, _set_selection, doc="list of selected glyph names")
class RGlyph(BaseGlyph):
_title = "GSGlyph"
preferedSegmentType = "curve"
def __init__(self, glyph = None, master = 0, layer = None):
self.masterIndex = master;
self._layer = None
if type(glyph) == RGlyph:
self._object = glyph._object
self._layer = glyph._layer.copy()
self._layerID = glyph._layerID
if hasattr(glyph, "masterIndex"):
self.masterIndex = glyph.masterIndex
return
if layer is not None:
glyph = layer.parent
if glyph is None:
glyph = GSGlyph()
elif glyph.parent is not None:
self.setParent(RFont(glyph.parent, self.masterIndex))
self._object = glyph
self._layerID = None
if layer is None:
try:
if glyph.parent:
self._layerID = glyph.parent.masters[master].id
elif (glyph.layers[master]):
self._layerID = glyph.layers[master].layerId
except:
pass
self.masterIndex = master
if self._layerID:
self._layer = glyph.layerForKey_(self._layerID)
else:
self._layer = layer
self._layerID = layer.associatedMasterId
if self._layer is None:
self._layerID = "undefined"
self._layer = GSLayer()
glyph.setLayer_forKey_(self._layer, self._layerID)
def __repr__(self):
font = "unnamed_font"
glyph = "unnamed_glyph"
fontParent = self.getParent()
if fontParent is not None:
try:
font = fontParent.info.postscriptFullName
except AttributeError:
pass
try:
glyph = self.name
except AttributeError:
pass
return "<RGlyph %s for %s>" %(self._object.name, font)
def setParent(self, parent):
self._parent = weakref.proxy(parent)
def getParent(self):
try:
return self._parent()
except:
return None
def __getitem__(self, index):
return self.contours[index]
def __delitem__(self, index):
self._layer.removePathAtIndex_(index)
self._invalidateContours()
def _invalidateContours(self):
self._contours = None
if self._layer:
self._layer.updatePath()
def __iter__(self):
Values = self._layer.paths
if Values is not None:
for element in Values:
yield element
def __len__(self):
return len(self._layer.paths)
def copy(self):
Copy = RGlyph(self._object.copy(), self.masterIndex)
Copy._layerID = self._layerID
Copy._layer = Copy._object.layerForKey_(self._layerID)
return Copy
def _get_contours(self):
return self._layer.paths
contours = property(_get_contours, doc="allow for iteration through glyph.contours")
def _hasNotChanged(self):
raise NotImplementedError
def _get_box(self):
bounds = self._layer.bounds
bounds = (int(round(NSMinX(bounds))), int(round(NSMinY(bounds))), int(round(NSMaxX(bounds))), int(round(NSMaxY(bounds))))
return bounds
box = property(_get_box, doc="the bounding box of the glyph: (xMin, yMin, xMax, yMax)")
#
# attributes
#
def _get_lib(self):
try:
return self._object.userData()
except:
return None
def _set_lib(self, key, obj):
if self._object.userData() is objc.nil:
self._object.setUserData_(NSMutableDictionary.dictionary())
self._object.userData().setObject_forKey_(obj, key)
lib = property(_get_lib, _set_lib, doc="Glyph Lib")
def _set_name(self, newName):
prevName = self.name
if newName == prevName:
return
self._object.name = newName
name = property(lambda self: self._object.name, _set_name)
def _get_unicodes(self):
if self._object.unicode is not None:
return [int(self._object.unicode, 16)]
return []
def _set_unicodes(self, value):
if not isinstance(value, list):
raise RoboFabError, "unicodes must be a list"
try:
self._object.setUnicode = value[0]
except:
pass
unicodes = property(_get_unicodes, _set_unicodes, doc="all unicode values for the glyph")
def _get_unicode(self):
if self._object.unicode is None:
return None
return self._object.unicodeChar()
def _set_unicode(self, value):
if type(value) == str:
if value is not None and value is not self._object.unicode:
self._object.setUnicode_(value)
elif type(value) == int:
strValue = "%0.4X" % value
if strValue is not None and strValue is not self._object.unicode:
self._object.setUnicode_(strValue)
else:
raise(KeyError)
unicode = property(_get_unicode, _set_unicode, doc="first unicode value for the glyph")
index = property(lambda self: self._object.parent.indexOfGlyph_(self._object))
note = property(lambda self: self._object.valueForKey_("note"),
lambda self, value: self._object.setNote_(value))
leftMargin = property(lambda self: self._layer.LSB,
lambda self, value: self._layer.setLSB_(value), doc="Left Side Bearing")
rightMargin = property(lambda self: self._layer.RSB,
lambda self, value: self._layer.setRSB_(value), doc="Right Side Bearing")
width = property(lambda self: self._layer.width,
lambda self, value: self._layer.setWidth_(value), doc="width")
components = property(lambda self: self._layer.components, doc="List of components")
guides = property(lambda self: self._layer.guides, doc="List of guides")
def appendComponent(self, baseGlyph, offset=(0, 0), scale=(1, 1)):
"""append a component to the glyph"""
new = GSComponent(baseGlyph, offset, scale)
self._layer.addComponent_(new)
def removeComponent(self, component):
"""remove a specific component from the glyph"""
self._layer.removeComponent_(component)
def getPointPen(self):
# if "GSPen" in sys.modules.keys():
# del(sys.modules["GSPen"])
from GSPen import GSPointPen
return GSPointPen(self, self._layer)
def appendAnchor(self, name, position, mark=None):
"""append an anchor to the glyph"""
new = GSAnchor(name=name, pt=position)
self._layer.addAnchor_(new)
def removeAnchor(self, anchor):
"""remove a specific anchor from the glyph"""
self._layer.removeAnchor_(anchor)
def removeContour(self, index):
"""remove a specific contour from the glyph"""
if type(index) == type(int):
self._layer.removePathAtIndex_(index)
else:
self._layer.removePath_(index)
def center(self, padding=None):
"""Equalize sidebearings, set to padding if wanted."""
left = self._layer.LSB
right = self._layer.RSB
if padding:
e_left = e_right = padding
else:
e_left = (left + right)/2
e_right = (left + right) - e_left
self._layer.setLSB_(e_left)
self._layer.setRSB_(e_right)
def decompose(self):
"""Decompose all components"""
self._layer.decomposeComponents()
def clear(self, contours=True, components=True, anchors=True, guides=True):
"""Clear all items marked as True from the glyph"""
if contours:
self.clearContours()
if components:
self.clearComponents()
if anchors:
self.clearAnchors()
if guides:
self.clearGuides()
def clearContours(self):
"""clear all contours"""
while len(self._layer.paths) > 0:
self._layer.removePathAtIndex_(0)
def clearComponents(self):
"""clear all components"""
self._layer.setComponents_(NSMutableArray.array())
def clearAnchors(self):
"""clear all anchors"""
self._layer.setAnchors_(NSMutableDictionary.dictionary())
def clearGuides(self):
"""clear all horizontal guides"""
self._layer.setGuideLines_(NSMutableArray.array())
def update(self):
self._contours = None
#GSGlyphsInfo.updateGlyphInfo_changeName_(self._object, False)
def correctDirection(self, trueType=False):
self._layer.correctPathDirection()
def removeOverlap(self):
removeOverlapFilter = NSClassFromString("GlyphsFilterRemoveOverlap").alloc().init()
removeOverlapFilter.runFilterWithLayer_error_(self._layer, None)
def _mathCopy(self):
""" copy self without contour, component and anchor data """
glyph = self._getMathDestination()
glyph.name = self.name
glyph.unicodes = list(self.unicodes)
glyph.width = self.width
glyph.note = self.note
try:
glyph.lib = dict(self.lib)
except:
pass
return glyph
anchors = property(lambda self: self._layer.anchors)
def getRepresentation(self, representaion):
if representaion == "defconAppKit.NSBezierPath":
return self._layer.bezierPath.copy()
return None
def performUndo(self):
pass
def prepareUndo(self, undoTitle):
pass
def getLayer(self, name):
return RGlyph(layer = self._object.layerForName_(name))
#############
#
# GSPath/Contour
#
#############
RContour = GSPath
def __GSElement__get_box__(self):
rect = self.bounds
return (NSMinX(rect), NSMinY(rect), NSMaxX(rect), NSMaxY(rect))
GSPath.box = property(__GSElement__get_box__, doc="get the contour bounding box as a tuple of lower left x, lower left y, width, height coordinates")
GSPath.points = GSPath.nodes
def __GSPath__get_bPoints(self):
bPoints = []
for segment in self.segments:
segType = segment.type
if segType == MOVE or segType == LINE or segType == CURVE:
b = RBPoint(segment)
bPoints.append(b)
else:
raise RoboFabError, "encountered unknown segment type"
return bPoints
GSPath.bPoints = property(__GSPath__get_bPoints, doc="view the contour as a list of bPoints")
class RSegment(BaseSegment):
def __init__(self, index, contoure, node):
BaseSegment.__init__(self)
self._object = node
self.parent = contoure
self.index = index
self.isMove = False # to store if the segment is a move segment
def __repr__(self):
return "<RSegment %s (%d), r>"%(self.type, self.smooth)#, self.points)
def getParent(self):
return self.parent
def __len__(self):
if self._object.type == CURVE:
return 4
return 2
def __getitem__(self, Key):
if type(Key) != int:
raise KeyError
return self.points[Key]
def _get_type(self):
if self.isMove: return MOVE
return self._object.type
def _set_type(self, pointType):
if pointType == MOVE:
self.isMove = True
return
raise NotImplementedError
return
onCurve = self.points[-1]
ocType = onCurve.type
if ocType == pointType:
return
#we are converting a cubic line into a cubic curve
if pointType == CURVE and ocType == LINE:
onCurve.type = pointType
parent = self.getParent()
prev = parent._prevSegment(self.index)
p1 = RPoint(prev.onCurve.x, prev.onCurve.y, pointType=OFFCURVE)
p1.setParent(self)
p2 = RPoint(onCurve.x, onCurve.y, pointType=OFFCURVE)
p2.setParent(self)
self.points.insert(0, p2)
self.points.insert(0, p1)
#we are converting a cubic move to a curve
elif pointType == CURVE and ocType == MOVE:
onCurve.type = pointType
parent = self.getParent()
prev = parent._prevSegment(self.index)
p1 = RPoint(prev.onCurve.x, prev.onCurve.y, pointType=OFFCURVE)
p1.setParent(self)
p2 = RPoint(onCurve.x, onCurve.y, pointType=OFFCURVE)
p2.setParent(self)
self.points.insert(0, p2)
self.points.insert(0, p1)
#we are converting a quad curve to a cubic curve
elif pointType == CURVE and ocType == QCURVE:
onCurve.type == CURVE
#we are converting a cubic curve into a cubic line
elif pointType == LINE and ocType == CURVE:
p = self.points.pop(-1)
self.points = [p]
onCurve.type = pointType
self.smooth = False
#we are converting a cubic move to a line
elif pointType == LINE and ocType == MOVE:
onCurve.type = pointType
#we are converting a quad curve to a line:
elif pointType == LINE and ocType == QCURVE:
p = self.points.pop(-1)
self.points = [p]
onCurve.type = pointType
self.smooth = False
# we are converting to a quad curve where just about anything is legal
elif pointType == QCURVE:
onCurve.type = pointType
else:
raise RoboFabError, 'unknown segment type'
type = property(_get_type, _set_type, doc="type of the segment")
def _get_smooth(self):
return self._object.connection == GSSMOOTH
def _set_smooth(self, smooth):
raise NotImplementedError
smooth = property(_get_smooth, _set_smooth, doc="smooth of the segment")
def insertPoint(self, index, pointType, point):
x, y = point
p = RPoint(x, y, pointType=pointType)
p.setParent(self)
self.points.insert(index, p)
self._hasChanged()
def removePoint(self, index):
del self.points[index]
self._hasChanged()
def _get_points(self):
Path = self._object.parent
index = Path.indexOfNode_(self._object)
points = []
if index < len(Path.nodes):
if self._object.type == GSCURVE:
points.append(Path.nodes[index-3])
points.append(Path.nodes[index-2])
points.append(Path.nodes[index-1])
points.append(Path.nodes[index])
elif self._object.type == GSLINE:
points.append(Path.nodes[index-1])
points.append(Path.nodes[index])
return points
points = property(_get_points, doc="index of the segment")
def _get_selected(self):
Path = self._object.parent
index = Path.indexOfNode_(self._object)
Layer = Path.parent
if self._object.type == GSCURVE:
return Path.nodes[index-2] in Layer.selection or Path.nodes[index-1] in Layer.selection or Path.nodes[index] in Layer.selection
elif self._object.type == GSLINE:
return Path.nodes[index] in Layer.selection
def _set_selected(self, select):
Path = self._object.parent
index = Path.indexOfNode_(self._object)
Layer = Path.parent
if self._object.type == GSCURVE:
if select:
Layer.addObjectsFromArrayToSelection_([Path.nodes[index-2], Path.nodes[index-1], Path.nodes[index] ] )
else:
Layer.removeObjectsFromSelection_([Path.nodes[index-2], Path.nodes[index-1], Path.nodes[index] ] )
elif self._object.type == GSLINE:
if select:
Layer.addSelection_( Path.nodes[index] )
else:
Layer.removeObjectFromSelection_( Path.nodes[index] )
selected = property(_get_selected, _set_selected, doc="if segment is selected")
def __GSPath_get_segments(self):
if not len(self.nodes):
return []
segments = []
index = 0
node = None
for i in range(len(self.nodes)):
node = self.nodeAtIndex_(i)
if node.type != OFFCURVE:
_Segment = RSegment(index, self, node)
_Segment.parent = self
_Segment.index = index
segments.append(_Segment)
index += 1
if self.closed:
# TODO fix this out properly.
# _Segment = RSegment(0, self, node)
# _Segment.type = MOVE
# segments.insert(0, _Segment)
pass
else:
_Segment = RSegment(0, self, self.nodeAtIndex_(0))
_Segment.type = MOVE
segments.insert(0, _Segment)
return segments
def __GSPath_set_segments(self, segments):
points = []
for segment in segments:
points.append(segment.points)
GSPath.segments = property(__GSPath_get_segments, __GSPath_set_segments, doc="A list of all points in the contour organized into segments.")
def __GSPath__removeSegment__(self, index):
segmentIndex = 0
for i in range(len(self.nodes)):
node = self.nodeAtIndex_(i)
if node.type != OFFCURVE:
if index == segmentIndex:
self.removeNodeAtIndex_(i)
if node.type != LINE:
self.removeNodeAtIndex_(i)
i -= 1
while self.nodeAtIndex_(i).type == OFFCURVE:
self.removeNodeAtIndex_(i)
i -= 1
return
segmentIndex += 1
GSPath.removeSegment = __GSPath__removeSegment__
def __GSPath__reverseContour__(self):