-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathbackend.py
More file actions
1794 lines (1469 loc) · 62.4 KB
/
Copy pathbackend.py
File metadata and controls
1794 lines (1469 loc) · 62.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import asyncio
import hashlib
import io
import logging
import pathlib
import uuid
from collections import OrderedDict, defaultdict
from copy import deepcopy
from dataclasses import replace
from os import PathLike
from types import SimpleNamespace
from typing import Any
import glyphsLib
import openstep_plist
from fontra.backends.base import WritableBaseBackend
from fontra.backends.filewatcher import Change
from fontra.backends.includedfeaturefiles import extractIncludedFeatureFiles
from fontra.backends.watchable import WatchableBackend
from fontra.core import kernutils
from fontra.core.classes import (
Anchor,
Axes,
Component,
DiscreteFontAxis,
FontAxis,
FontInfo,
FontSource,
GlyphAxis,
GlyphSource,
Guideline,
ImageData,
Kerning,
Layer,
LineMetric,
OpenTypeFeatures,
StaticGlyph,
VariableGlyph,
)
from fontra.core.discretevariationmodel import findNearestLocationIndex
from fontra.core.path import PackedPathPointPen
from fontra.core.protocols import WritableFontBackend
from fontra.core.subprocess import runInSubProcess
from fontra.core.threading import runInThread
from fontra.core.varutils import (
locationToTuple,
makeDenseLocation,
mapAxesFromUserSpaceToSourceSpace,
)
from fontTools.designspaceLib import DesignSpaceDocument
from fontTools.feaLib.error import FeatureLibError, IncludedFeaNotFound
from fontTools.feaLib.parser import Parser as FeatureParser
from fontTools.misc.transform import DecomposedTransform
from fontTools.ufoLib.filenames import userNameToFileName
from glyphsLib.builder.axes import (
get_axis_definitions,
get_regular_master,
to_designspace_axes,
)
from glyphsLib.builder.smart_components import Pole
from glyphsLib.types import Transform as GSTransform
from .utils import (
convertMatchesToTuples,
matchTreeFont,
matchTreeGlyph,
openstepPlistDumps,
openstepPlistFromPath,
splitLocation,
)
logger = logging.getLogger(__name__)
class GlyphsBackendError(Exception):
pass
rootInfoNames = [
"familyName",
"versionMajor",
"versionMinor",
]
infoNamesMapping = [
# (Fontra, Glyphs)
("copyright", "copyrights"),
("designer", "designers"),
("designerURL", "designerURL"),
("licenseDescription", "licenses"),
# ("licenseInfoURL", "licensesURL"), # Not defined in glyphsLib
("manufacturer", "manufacturers"),
("manufacturerURL", "manufacturerURL"),
("trademark", "trademarks"),
("vendorID", "vendorID"),
]
GS_KERN_GROUP_PREFIXES = {
side: f"@MMK_{side[0].upper()}_" for side in ["left", "right", "top", "bottom"]
}
GS_FORMAT_2_KERN_SIDES = [
# pair side, glyph side
("left", "rightKerningGroup"),
("right", "leftKerningGroup"),
("top", "bottomKerningGroup"),
("bottom", "topKerningGroup"),
]
GS_FORMAT_3_KERN_SIDES = [
# pair side, glyph side
("left", "kernRight"),
("right", "kernLeft"),
("top", "kernBottom"),
("bottom", "kernTop"),
]
invalidFeaturesUserDataKey = "xyz.fontra.invalid-features"
class GlyphsBackend(WatchableBackend, WritableBaseBackend):
@classmethod
def fromPath(cls, path: PathLike) -> WritableFontBackend:
self = cls()
self._setupFromPath(path)
return self
def __init__(self) -> None:
super().__init__()
self._writeLock = asyncio.Lock()
self._includedFeaturePaths: list[pathlib.Path] = []
def _setupFromPath(self, path: PathLike) -> None:
self.path = pathlib.Path(path)
rawFontData, rawGlyphsData = self._loadFiles()
self._setupWithRawData(rawFontData, rawGlyphsData)
def _setupWithRawData(self, rawFontData, rawGlyphsData) -> None:
gsFont = glyphsLib.classes.GSFont()
parser = glyphsLib.parser.Parser(current_type=gsFont.__class__)
parser.parse_into_object(gsFont, rawFontData)
self.gsFont = gsFont
self.rawFontData = rawFontData
self._updateRawGlyphsData(rawGlyphsData)
dsAxes = [
dsAxis
for dsAxis in gsAxesToDesignSpaceAxes(self.gsFont)
# Ignore axes without any range
if dsAxis.minimum != dsAxis.maximum
]
self.axisNames = {axis.name for axis in dsAxes}
self.locationByMasterID = {}
self.masterIDByLocationTuple = {}
for master in self.gsFont.masters:
location = {}
for axisDef in get_axis_definitions(self.gsFont):
if axisDef.name in self.axisNames:
location[axisDef.name] = axisDef.get_design_loc(master)
self.locationByMasterID[master.id] = location
self.masterIDByLocationTuple[locationToTuple(location)] = master.id
axis: FontAxis | DiscreteFontAxis
axes: list[FontAxis | DiscreteFontAxis] = []
for dsAxis in dsAxes:
axis = FontAxis(
minValue=dsAxis.minimum,
defaultValue=dsAxis.default,
maxValue=dsAxis.maximum,
label=dsAxis.name,
name=dsAxis.name,
tag=dsAxis.tag,
hidden=dsAxis.hidden,
)
if dsAxis.map:
axis.mapping = [[a, b] for a, b in dsAxis.map]
axes.append(axis)
self.axes = axes
axesSourceSpace = mapAxesFromUserSpaceToSourceSpace(self.axes)
self.defaultLocation = {
axis.name: axis.defaultValue for axis in axesSourceSpace
}
self._cachedFeatures: OpenTypeFeatures | None = None
self._cachedGlyphClassifications: tuple[set[str], set[str]] | None = None
def _updateRawGlyphsData(self, rawGlyphsData) -> None:
# Fill the glyphs list with dummy placeholder glyphs
self.gsFont.glyphs = [
glyphsLib.classes.GSGlyph() for i in range(len(rawGlyphsData))
]
self.rawGlyphsData = rawGlyphsData
self._updateGlyphNameToIndex()
self.originalGlyphNameToIndex = dict(self.glyphNameToIndex)
self.parsedGlyphNames: set[str] = set()
self.glyphMap, self.glyphInfos, self.kerningGroups = self._readGlyphInfos()
def _loadFiles(self) -> tuple[dict[str, Any], list[Any]]:
rawFontData = openstepPlistFromPath(self.path)
# We separate the "glyphs" list from the rest, so we can prevent glyphsLib
# from eagerly parsing all glyphs
rawGlyphsData = rawFontData["glyphs"]
rawFontData["glyphs"] = []
return rawFontData, rawGlyphsData
def _updateGlyphNameToIndex(self):
self.glyphNameToIndex = {
glyphData["glyphname"]: i for i, glyphData in enumerate(self.rawGlyphsData)
}
@property
def _kerningSideAttrs(self):
return (
GS_FORMAT_2_KERN_SIDES
if self.gsFont.format_version == 2
else GS_FORMAT_3_KERN_SIDES
)
def _readGlyphInfos(
self,
) -> tuple[dict[str, list[int]], dict[str, Any], dict[str, dict[str, list[str]]]]:
glyphMap = {}
glyphInfos: dict[str, Any] = defaultdict(dict)
kerningGroups: dict = defaultdict(lambda: defaultdict(list))
for glyphData in self.rawGlyphsData:
glyphName = glyphData["glyphname"]
# extract code points
codePoints = glyphData.get("unicode")
if codePoints is None:
codePoints = []
elif self.gsFont.format_version == 2:
if isinstance(codePoints, str):
codePoints = [
int(codePoint, 16) for codePoint in codePoints.split(",")
]
else:
assert isinstance(codePoints, int)
# The plist parser turned it into an int, but it was a hex string
codePoints = [int(str(codePoints), 16)]
elif isinstance(codePoints, int):
codePoints = [codePoints]
else:
assert all(isinstance(codePoint, int) for codePoint in codePoints)
glyphMap[glyphName] = codePoints
# extract infos
for gFieldName, fFieldname in [
("category", "category"),
("subCategory", "subcategory"),
]:
fieldValue = glyphData.get(gFieldName)
if fieldValue:
glyphInfos[glyphName][fFieldname] = fieldValue
# extract kern groups
for pairSide, glyphSideAttr in self._kerningSideAttrs:
groupName = glyphData.get(glyphSideAttr)
if groupName is not None:
kerningGroups[pairSide][groupName].append(glyphName)
return glyphMap, dict(glyphInfos), kerningGroups
def _updateKerningGroups(self):
changedGlyphs = set()
for glyphData in self.rawGlyphsData:
glyphName = glyphData["glyphname"]
for pairSide, glyphSideAttr in self._kerningSideAttrs:
groups = self.kerningGroups.get(pairSide)
currentGroupName = glyphData.get(glyphSideAttr)
newGroupName = None
for groupName, group in groups.items():
if glyphName in group:
newGroupName = groupName
break
if currentGroupName != newGroupName:
changedGlyphs.add(glyphName)
self.parsedGlyphNames.discard(glyphName)
if newGroupName:
glyphData[glyphSideAttr] = newGroupName
else:
glyphData.pop(glyphSideAttr, None)
return changedGlyphs
async def getGlyphMap(self) -> dict[str, list[int]]:
return deepcopy(self.glyphMap)
async def putGlyphMap(self, value: dict[str, list[int]]) -> None:
pass
async def deleteGlyph(self, glyphName: str) -> None:
if glyphName not in self.glyphNameToIndex:
logger.debug(f"Can't delete unknown glyph '{glyphName}'")
return
del self.glyphMap[glyphName]
index = self.glyphNameToIndex[glyphName]
assert self.rawGlyphsData[index]["glyphname"] == glyphName
del self.rawGlyphsData[index]
del self.gsFont.glyphs[index]
self.parsedGlyphNames.discard(glyphName)
self._updateGlyphNameToIndex()
self._updateDeletedGlyph(glyphName)
self._cachedGlyphClassifications = None
async def getFontInfo(self) -> FontInfo:
infoDict = {}
for name in rootInfoNames:
value = getattr(self.gsFont, name, None)
if value is not None:
infoDict[name] = value
properties = {p.key: p.value for p in self.gsFont.properties}
for fontraName, glyphsName in infoNamesMapping:
value = properties.get(glyphsName)
if value is not None:
infoDict[fontraName] = value
return FontInfo(**infoDict)
async def putFontInfo(self, fontInfo: FontInfo):
raise NotImplementedError(
"GlyphsApp Backend: Editing FontInfo is not yet implemented."
)
async def getSources(self) -> dict[str, FontSource]:
return gsMastersToFontraFontSources(self.gsFont, self.locationByMasterID)
async def putSources(self, sources: dict[str, FontSource]) -> None:
raise NotImplementedError(
"GlyphsApp Backend: Editing FontSources is not yet implemented."
)
async def getAxes(self) -> Axes:
return Axes(axes=deepcopy(self.axes))
async def putAxes(self, axes: Axes) -> None:
raise NotImplementedError(
"GlyphsApp Backend: Editing Axes is not yet implemented."
)
async def getUnitsPerEm(self) -> int:
return self.gsFont.upm
async def putUnitsPerEm(self, value: int) -> None:
raise NotImplementedError(
"GlyphsApp Backend: Editing UnitsPerEm is not yet implemented."
)
@property
def _verticalKerningAttr(self):
return "vertKerning" if self.gsFont.format_version == 2 else "kerningVertical"
async def getKerning(self) -> dict[str, Kerning]:
kerningLTR = await self._gsKerningToFontraKerning("kerning", "left", "right")
kerningRTL = kernutils.flipKerningDirection(
await self._gsKerningToFontraKerning("kerningRTL", "right", "left")
)
kerningVertical = await self._gsKerningToFontraKerning(
self._verticalKerningAttr, "top", "bottom"
)
kerning = {}
hasLTRKerning = hasKerning(kerningLTR)
hasRTLKerning = hasKerning(kerningRTL)
if hasLTRKerning and hasRTLKerning:
kerning["kern"] = kernutils.mergeKerning(kerningLTR, kerningRTL)
elif hasLTRKerning:
kerning["kern"] = kerningLTR
elif hasRTLKerning:
kerning["kern"] = kerningRTL
if hasKerning(kerningVertical):
kerning["vkrn"] = kerningVertical
return kerning
async def putKerning(self, kerning: dict[str, Kerning]) -> None:
async with self._writeLock:
ltrGlyphs, rtlGlyphs = await self._getGlyphClassifications()
return await runInThread(self._putKerning, kerning, ltrGlyphs, rtlGlyphs)
def _putKerning(
self, kerning: dict[str, Kerning], ltrGlyph: set[str], rtlGlyphs: set[str]
) -> None:
unknownKerningTypes = set(kerning) - set(["kern", "vkrn"])
if unknownKerningTypes:
s = ", ".join(sorted(unknownKerningTypes))
raise GlyphsBackendError(
f"GlyphsApp Backend: '{s}' kern type(s) not supported."
)
ltrKerning = rtlKerning = None
hKerning = kerning.get("kern")
if hKerning is not None:
ltrKerning, rtlKerning = kernutils.splitKerningByDirection(
hKerning, ltrGlyph, rtlGlyphs
)
rtlKerning = kernutils.flipKerningDirection(rtlKerning)
for side, _ in GS_FORMAT_3_KERN_SIDES:
self.kerningGroups[side].clear()
self._fontraKerningToGSKerning(ltrKerning, "kerning", "left", "right")
self._fontraKerningToGSKerning(rtlKerning, "kerningRTL", "right", "left")
self._fontraKerningToGSKerning(
kerning.get("vkrn"), self._verticalKerningAttr, "top", "bottom"
)
changedGlyphs = self._updateKerningGroups()
self._writeFontData(changedGlyphs)
async def _gsKerningToFontraKerning(
self, kerningAttr: str, side1: str, side2: str
) -> Kerning:
gsPrefix1 = GS_KERN_GROUP_PREFIXES[side1]
gsPrefix2 = GS_KERN_GROUP_PREFIXES[side2]
groupsSide1 = deepcopy(dict(self.kerningGroups[side1]))
groupsSide2 = deepcopy(dict(self.kerningGroups[side2]))
if side1 in {"left", "right"}:
# Kerning is horizontal. To avoid group name conflicts we filter out
# groups that we know can't be relevant: for RTL kerning we filter
# out groups that are LTR, and vice versa.
ltrGlyphs, rtlGlyphs = await self._getGlyphClassifications()
if kerningAttr == "kerningRTL":
groupsSide1 = filterGroupsByDirection(groupsSide1, ltrGlyphs)
groupsSide2 = filterGroupsByDirection(groupsSide2, ltrGlyphs)
else:
groupsSide1 = filterGroupsByDirection(groupsSide1, rtlGlyphs)
groupsSide2 = filterGroupsByDirection(groupsSide2, rtlGlyphs)
sourceIdentifiers = []
valueDicts: dict[str, dict[str, dict]] = defaultdict(lambda: defaultdict(dict))
for gsMaster in self.gsFont.masters:
kernDict = getattr(self.gsFont, kerningAttr, {}).get(gsMaster.id, {})
sourceIdentifiers.append(gsMaster.id)
for name1, name2Dict in kernDict.items():
name1 = translateGroupName(name1, gsPrefix1, "@")
for name2, value in name2Dict.items():
name2 = translateGroupName(name2, gsPrefix2, "@")
valueDicts[name1][name2][gsMaster.id] = value
values = {
left: {
right: [valueDict.get(key) for key in sourceIdentifiers]
for right, valueDict in rightDict.items()
}
for left, rightDict in valueDicts.items()
}
return Kerning(
groupsSide1=groupsSide1,
groupsSide2=groupsSide2,
sourceIdentifiers=sourceIdentifiers,
values=values,
)
def _fontraKerningToGSKerning(
self, kerning: Kerning | None, kerningAttr: str, side1: str, side2: str
) -> None:
if kerning is None or not hasKerning(kerning):
setattr(self.gsFont, kerningAttr, {})
return
if kerningAttr == "vertKerning":
raise GlyphsBackendError(
"Writing vertical kerning is not supported for the Glyphs 2 format"
)
sourceIdentifiers = kerning.sourceIdentifiers
unknownSourceIdentifiers = set(sourceIdentifiers) - set(
gsMaster.id for gsMaster in self.gsFont.masters
)
if unknownSourceIdentifiers:
s = ", ".join(sorted(unknownSourceIdentifiers))
raise GlyphsBackendError(
f"Can't write kerning, found unknown source identifiers: {s}"
)
gsPrefix1 = GS_KERN_GROUP_PREFIXES[side1]
gsPrefix2 = GS_KERN_GROUP_PREFIXES[side2]
kerningPerSource: dict = defaultdict(lambda: defaultdict(dict))
for leftName, rightDict in kerning.values.items():
if leftName.startswith("@"):
leftName = gsPrefix1 + leftName[1:]
for rightName, values in rightDict.items():
if rightName.startswith("@"):
rightName = gsPrefix2 + rightName[1:]
for sourceIdentifier, value in zip(sourceIdentifiers, values):
if value is not None:
kerningPerSource[sourceIdentifier][leftName][rightName] = value
kerningPerSource = OrderedDict(
{
gsMaster.id: dict(kerningPerSource.get(gsMaster.id, {}))
for gsMaster in self.gsFont.masters
}
)
setattr(self.gsFont, kerningAttr, kerningPerSource)
self.kerningGroups[side1] |= deepcopy(kerning.groupsSide1)
self.kerningGroups[side2] |= deepcopy(kerning.groupsSide2)
async def _getGlyphClassifications(self) -> tuple[set[str], set[str]]:
if self._cachedGlyphClassifications is None:
features = await self.getFeatures()
axes = [axis for axis in self.axes if isinstance(axis, FontAxis)]
self._cachedGlyphClassifications = kernutils.classifyGlyphsByDirection(
self.glyphMap, features.text, axes
)
return self._cachedGlyphClassifications
async def getFeatures(self) -> OpenTypeFeatures:
if self._cachedFeatures is None:
self._cachedFeatures = await self._getFeatures()
return deepcopy(self._cachedFeatures)
async def _getFeatures(self) -> OpenTypeFeatures:
invalidFeatures = self.gsFont.userData.get(invalidFeaturesUserDataKey)
if invalidFeatures is not None:
return OpenTypeFeatures(text=invalidFeatures)
featureText = glyphsLib.builder.features._to_ufo_features(self.gsFont)
self._includedFeaturePaths = extractIncludedFeatureFiles(
featureText, self.path.parent
)
self._updatePathsToWatch()
if not canParseFeatures(featureText, self.glyphNameToIndex.keys()):
expandedFeatures = await runInSubProcess(expensiveGetFeatures, self.path)
if expandedFeatures:
featureText = expandedFeatures
return OpenTypeFeatures(text=featureText)
async def putFeatures(self, features: OpenTypeFeatures) -> None:
self._cachedFeatures = deepcopy(features)
async with self._writeLock:
return await runInThread(self._putFeatures, features)
def _putFeatures(self, features: OpenTypeFeatures) -> None:
if features.language != "fea":
raise NotImplementedError(
"GlyphsApp Backend: skip writing features in unsupported language: "
f"{features.language!r}"
)
# Delete existing features, prefixes and classes
# This is needed, because glyphsLib.builder.features._to_glyphs_features()
# will not overwrite existing features, prefixes and classes.
# '_to_glyphs_features' only adds new ones to self.gsFont.
self.gsFont.featurePrefixes = []
self.gsFont.features = []
self.gsFont.classes = []
# Convert feature.text into Glyphs featurePrefixes, features and classes
try:
glyphsLib.builder.features._to_glyphs_features(
self.gsFont, features.text, glyph_names=self.glyphNameToIndex.keys()
)
except FeatureLibError:
self.gsFont.userData[invalidFeaturesUserDataKey] = features.text
else:
if invalidFeaturesUserDataKey in self.gsFont.userData:
del self.gsFont.userData[invalidFeaturesUserDataKey]
self._writeFontData()
self._cachedGlyphClassifications = None
def _writeFontData(self, changedGlyphs=None):
# Set self.gsFont.glyphs to an empty list temporarily, so no time is wasted on these.
originalGlyphs = list(self.gsFont.glyphs.values())
self.gsFont.glyphs = []
try:
self.rawFontData = self._getRawData(self.gsFont)
self._writeRawFontData(changedGlyphs)
finally:
self.gsFont.glyphs = originalGlyphs
async def getBackgroundImage(self, imageIdentifier: str) -> ImageData | None:
return None
async def putBackgroundImage(self, imageIdentifier: str, data: ImageData) -> None:
raise NotImplementedError(
"GlyphsApp Backend: Editing BackgroundImage is not yet implemented."
)
async def getCustomData(self) -> dict[str, Any]:
return {}
async def putCustomData(self, lib):
raise NotImplementedError(
"GlyphsApp Backend: Editing CustomData is not yet implemented."
)
async def getGlyphInfos(self) -> dict[str, Any]:
return deepcopy(self.glyphInfos)
async def getGlyph(self, glyphName: str) -> VariableGlyph | None:
if glyphName not in self.glyphNameToIndex:
return None
self._ensureGlyphIsParsed(glyphName)
gsGlyph = self.gsFont.glyphs[glyphName]
assert gsGlyph is not None, glyphName
customData = {}
if gsGlyph.color is not None:
customData["com.glyphsapp.glyph-color"] = gsGlyph.color
localAxes = gsLocalAxesToFontraLocalAxes(gsGlyph)
localAxesByName = {axis.name: axis for axis in localAxes}
sources = []
layers = {}
seenMasterIDs: dict[str, None] = {}
gsLayers = []
for i, gsLayer in enumerate(gsGlyph.layers):
gsLayers.append((i, gsLayer))
assert gsLayer.associatedMasterId
# We use a dict as a set, because we need the insertion order
seenMasterIDs[gsLayer.associatedMasterId] = None
masterOrder = {masterID: i for i, masterID in enumerate(seenMasterIDs)}
gsLayers = sorted(
gsLayers, key=lambda i_gsLayer: masterOrder[i_gsLayer[1].associatedMasterId]
)
seenLocations = []
smartAxisNames: set[str] = set()
for i, gsLayer in gsLayers:
braceLocation = self._getBraceLayerLocation(gsLayer)
smartLocation = self._getSmartLocation(gsLayer, localAxesByName)
if smartLocation and not smartAxisNames:
smartAxisNames = set(smartLocation)
masterName = self.gsFont.masters[gsLayer.associatedMasterId].name
if "xyz.fontra.source-name" in gsLayer.userData:
sourceName = gsLayer.userData["xyz.fontra.source-name"]
elif braceLocation or smartLocation:
sourceName = f"{masterName} / {gsLayer.name}"
else:
sourceName = gsLayer.name or masterName
layerName = gsLayer.userData["xyz.fontra.layer-name"] or gsLayer.layerId
baseLocation = self.locationByMasterID[gsLayer.associatedMasterId]
extraLocation = braceLocation | smartLocation
location = baseLocation | extraLocation
needLocationBase = not (set(extraLocation) >= set(self.defaultLocation))
storeLayerId = True
if location in seenLocations:
bgLayerName = (
gsLayer.name if gsLayer.name else "empty-background-layer-name"
)
layerName = f"{gsLayer.associatedMasterId}^{bgLayerName}"
bgSeparator = "/"
else:
storeLayerId = layerName != gsLayer.layerId
seenLocations.append(location)
sources.append(
GlyphSource(
name=(
sourceName
if extraLocation or sourceName != masterName
else ""
),
location=extraLocation,
locationBase=(
gsLayer.associatedMasterId if needLocationBase else None
),
layerName=layerName,
)
)
bgSeparator = "^"
layers[layerName] = gsLayerToFontraLayer(
gsLayer,
self.axisNames,
gsLayer.width,
gsLayer.layerId if storeLayerId else None,
)
if gsLayer.hasBackground:
layers[layerName + bgSeparator + "background"] = gsLayerToFontraLayer(
gsLayer.background, self.axisNames, gsLayer.width, None
)
fixSmartComponentSourceLocationsFromGlyphs(
sources, smartAxisNames, self.defaultLocation
)
glyph = VariableGlyph(
name=glyphName,
axes=localAxes,
sources=sources,
layers=layers,
customData=customData,
)
return glyph
def _ensureGlyphIsParsed(self, glyphName: str) -> None:
if glyphName in self.parsedGlyphNames:
return
glyphIndex = self.glyphNameToIndex[glyphName]
rawGlyphData = self.rawGlyphsData[glyphIndex]
self.parsedGlyphNames.add(glyphName)
gsGlyph = glyphsLib.classes.GSGlyph()
p = glyphsLib.parser.Parser(
current_type=gsGlyph.__class__, format_version=self.gsFont.format_version
)
p.parse_into_object(gsGlyph, rawGlyphData)
assert glyphIndex < len(self.gsFont.glyphs), len(self.gsFont.glyphs)
self.gsFont.glyphs[glyphIndex] = gsGlyph
# Load all component dependencies
componentNames = set()
for layer in gsGlyph.layers:
for component in layer.components:
componentNames.add(component.name)
if layer.hasBackground:
for component in layer.background.components:
componentNames.add(component.name)
for compoName in sorted(componentNames):
if compoName not in self.glyphNameToIndex:
continue
self._ensureGlyphIsParsed(compoName)
def _getBraceLayerLocation(self, gsLayer):
if not gsLayer._is_brace_layer():
return {}
return dict(
(axis.name, value)
for axis, value in zip(self.axes, gsLayer._brace_coordinates())
)
def _getSmartLocation(self, gsLayer, localAxesByName):
location = {
name: (
localAxesByName[name].minValue
if poleValue == Pole.MIN
else localAxesByName[name].maxValue
)
for name, poleValue in gsLayer.smartComponentPoleMapping.items()
}
return {
disambiguateLocalAxisName(name, self.axisNames): value
for name, value in location.items()
if value != localAxesByName[name].defaultValue
}
def _getRawData(self, object):
# Serialize to text with glyphsLib.writer.Writer(), using io.StringIO
f = io.StringIO()
writer = glyphsLib.writer.Writer(f)
writer.format_version = self.gsFont.format_version
writer.write(object)
# Parse stream into "raw" object
return openstep_plist.loads(f.getvalue(), use_numbers=True)
async def putGlyph(
self, glyphName: str, glyph: VariableGlyph, codePoints: list[int]
) -> None:
async with self._writeLock:
return await runInThread(self._putGlyph, glyphName, glyph, codePoints)
def _putGlyph(
self, glyphName: str, glyph: VariableGlyph, codePoints: list[int]
) -> None:
assert isinstance(codePoints, list)
assert all(isinstance(cp, int) for cp in codePoints)
assert all(source.layerName in glyph.layers for source in glyph.sources)
if self.glyphMap.get(glyphName) != codePoints:
self.glyphMap[glyphName] = codePoints
self._cachedGlyphClassifications = None
isNewGlyph = glyphName not in self.gsFont.glyphs
# Glyph does not exist: create new one.
if isNewGlyph:
gsGlyph = glyphsLib.classes.GSGlyph(glyphName)
self.gsFont.glyphs.append(gsGlyph)
self.glyphNameToIndex[glyphName] = len(self.gsFont.glyphs) - 1
gsGlyph = deepcopy(self.gsFont.glyphs[glyphName])
self._variableGlyphToGSGlyph(glyph, gsGlyph)
# Update unicodes: need to be converted from decimal to hex strings
gsGlyph.unicodes = [f"{codePoint:04X}" for codePoint in codePoints]
rawGlyphData = self._getRawData(gsGlyph)
self._updateKerningSidesForGlyph(rawGlyphData)
# Replace original "raw" object with new "raw" object
glyphIndex = self.glyphNameToIndex[glyphName]
if isNewGlyph:
assert glyphIndex == len(self.rawGlyphsData)
self.rawGlyphsData.append(rawGlyphData)
self.rawGlyphsData.sort(
key=lambda glyphData: self.originalGlyphNameToIndex.get(
glyphData["glyphname"], 0xFFFFFFFF
)
)
self._updateGlyphNameToIndex()
else:
self.rawGlyphsData[glyphIndex] = rawGlyphData
self._writeRawGlyph(glyphName, isNewGlyph)
# Remove glyph from parsed glyph names, because we changed it.
# Next time it needs to be parsed again.
self.parsedGlyphNames.discard(glyphName)
def _variableGlyphToGSGlyph(self, variableGlyph, gsGlyph):
sourceLayers, sourceLayerNames = getSourceLayerNames(variableGlyph)
nonSourceLayerNames = set(variableGlyph.layers) - sourceLayerNames
if nonSourceLayerNames:
raise GlyphsBackendError(
"GlyphsApp Backend: Layer without glyph source is not supported."
)
defaultGlyphLocation = getDefaultLocation(variableGlyph.axes)
nonParticipatingMasterIDs = set()
if defaultGlyphLocation:
# This is a smart component part glyph. We clean the source locations
# for font axis overrides added by Fontra, and we record the relevant
# master IDs so we can ensure the expected layers exist.
# See https://github.com/fontra/fontra-glyphs/pull/133 for discussion.
sources, nonParticipatingMasterIDs = (
fixSmartComponentSourceLocationsToGlyps(
variableGlyph.sources, self.defaultLocation
)
)
variableGlyph = replace(variableGlyph, sources=sources)
gsGlyph.smartComponentAxes = setupSmartComponentAxes(variableGlyph)
layerIdsInUse = set()
for glyphSource in variableGlyph.sources:
sourceInfo = self._setupSourceInfo(
glyphSource, sourceLayers, variableGlyph, defaultGlyphLocation
)
sourceLayerNames = [glyphSource.layerName] + sorted(
sourceLayers[glyphSource.layerName]
)
for layerName in sourceLayerNames:
assert layerName in variableGlyph.layers
layerInfo = setupLayerInfo(
glyphSource,
sourceInfo,
layerName,
variableGlyph,
gsGlyph,
nonParticipatingMasterIDs,
)
gsLayer = getOrCreateGSLayer(gsGlyph, layerInfo.gsLayerId)
layerIdsInUse.add(layerInfo.gsLayerId)
targetLayer = updateGSLayer(
variableGlyph,
layerName,
glyphSource,
gsLayer,
sourceInfo,
layerInfo,
)
fontraLayerToGSLayer(variableGlyph.layers[layerName], targetLayer)
if sourceInfo.isBraceLayer:
gsLayer.attributes["coordinates"] = list(
sourceInfo.fontLocation.values()
)
for gsLayer in list(gsGlyph.layers):
if gsLayer.layerId not in layerIdsInUse:
del gsGlyph.layers[gsLayer.layerId]
def _setupSourceInfo(
self, glyphSource, sourceLayers, variableGlyph, defaultGlyphLocation
):
fontLocation, glyphLocation = self._getSourceLocations(
glyphSource, variableGlyph.axes, defaultGlyphLocation
)
masterId = self.masterIDByLocationTuple.get(locationToTuple(fontLocation))
masterName = (
self.gsFont.masters[masterId].name if masterId is not None else None
)
isBraceLayer = masterId is None
isSmartComponentLayer = glyphLocation != defaultGlyphLocation
if isBraceLayer and variableGlyph.axes:
raise NotImplementedError(
"GlyphsApp Backend: Brace layers "
"within smart glyphs are not yet implemented."
)
associatedMasterId = (
masterId
or glyphSource.customData.get("com.glyphsapp.layer.associatedMasterId")
or self._findNearestMasterId(fontLocation)
)
associatedMasterName = self.gsFont.masters[associatedMasterId].name
return SimpleNamespace(
fontLocation=fontLocation,
glyphLocation=glyphLocation,
masterId=masterId,
masterName=masterName,
isBraceLayer=isBraceLayer,
isSmartComponentLayer=isSmartComponentLayer,
associatedMasterId=associatedMasterId,
associatedMasterName=associatedMasterName,
)
def _getSourceLocations(self, glyphSource, glyphAxes, defaultGlyphLocation):
location = self._getSourceLocation(glyphSource)
fontLocation, glyphLocation = splitLocation(location, glyphAxes)
fontLocation = makeDenseLocation(fontLocation, self.defaultLocation)
glyphLocation = makeDenseLocation(glyphLocation, defaultGlyphLocation)
return fontLocation, glyphLocation
def _getSourceLocation(self, glyphSource):
baseLocation = (
{}
if glyphSource.locationBase is None
else self.locationByMasterID[glyphSource.locationBase]
)
return baseLocation | glyphSource.location
def _updateKerningSidesForGlyph(self, rawGlyphData):
glyphName = rawGlyphData["glyphname"]
for pairSide, glyphSideAttr in self._kerningSideAttrs:
if pairSide not in self.kerningGroups:
continue
for groupName, glyphNames in self.kerningGroups[pairSide].items():
if glyphName in glyphNames:
rawGlyphData[glyphSideAttr] = groupName
# sort dict by key for easier round-tripping
sortedData = {k: v for k, v in sorted(rawGlyphData.items())}
rawGlyphData.clear()
rawGlyphData.update(sortedData)
def _writeRawFontData(self, changedGlyphs=None):
# `changedGlyphs` is ignored, needed for glyphsPackage
rawFontData = dict(self.rawFontData)
rawFontData["glyphs"] = self.rawGlyphsData
rawFontData = convertMatchesToTuples(rawFontData, matchTreeFont)
out = openstepPlistDumps(rawFontData)
self.path.write_text(out)
self.fileWatcherIgnoreNextChange(self.path)
def _writeRawGlyph(self, glyphName, isNewGlyph):
# Write whole file with openstep_plist
# 'glyphName' and 'isNewGlyph' arguments not used, because we write the whole file,
# but is required for the glyphspackage backend
self._writeRawFontData()
def _updateDeletedGlyph(self, glyphName):
# `glyphName` is ignored, needed for glyphsPackage