-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathtest_backend.py
More file actions
1852 lines (1504 loc) · 58.3 KB
/
Copy pathtest_backend.py
File metadata and controls
1852 lines (1504 loc) · 58.3 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 os
import pathlib
import re
import shutil
import uuid
from contextlib import aclosing
from copy import deepcopy
import glyphsLib
import openstep_plist
import pytest
from fontra.backends import getFileSystemBackend
from fontra.core.classes import (
Anchor,
Axes,
FontInfo,
GlyphAxis,
GlyphSource,
Guideline,
Kerning,
Layer,
OpenTypeFeatures,
StaticGlyph,
VariableGlyph,
structure,
)
from fontra.core.fonthandler import FontHandler
from fontra.filesystem.projectmanager import FileSystemProjectManager
from fontTools.ufoLib.filenames import userNameToFileName
from fontra_glyphs.backend import GlyphsBackendError
dataDir = pathlib.Path(__file__).resolve().parent / "data"
glyphs2Path = dataDir / "GlyphsUnitTestSans.glyphs"
glyphs3Path = dataDir / "GlyphsUnitTestSans3.glyphs"
glyphsPackagePath = dataDir / "GlyphsUnitTestSans3.glyphspackage"
expansionFontPath = dataDir / "FeatureExpansionTest.glyphs"
externalFeaturesFilePath = dataDir / "ExternalFeatureFile.glyphs"
referenceFontPath = dataDir / "GlyphsUnitTestSans3.fontra"
rtlFontPath = dataDir / "right-to-left-kerning.glyphs"
propagateAnchorsFontPath = dataDir / "PropagateAnchorsTest.glyphs"
fileFormatFontPath = dataDir / "GlyphsFileFormatv3.glyphs"
smartComponentsFontPath = dataDir / "GlyphsSmartComponents.glyphspackage"
smartComponentsReferenceFontPath = dataDir / "GlyphsSmartComponents.fontra"
def sourceNameMappingFromSources(fontSources):
return {
source.name: sourceIdentifier
for sourceIdentifier, source in fontSources.items()
}
def _getCopiedBackend(srcPath, tmpdir, copyFeaFiles=False):
dstPath = tmpdir / os.path.basename(srcPath)
if os.path.isdir(srcPath):
shutil.copytree(srcPath, dstPath)
else:
shutil.copy(srcPath, dstPath)
if copyFeaFiles:
for feaPath in srcPath.parent.glob("*.fea"):
shutil.copy(feaPath, tmpdir / feaPath.name)
return getFileSystemBackend(dstPath)
@pytest.fixture(scope="module", params=[glyphs2Path, glyphs3Path, glyphsPackagePath])
def testFont(request):
return getFileSystemBackend(request.param)
@pytest.fixture
def externalFeaturesFileFont(tmpdir):
return _getCopiedBackend(externalFeaturesFilePath, tmpdir, True)
@pytest.fixture(scope="module")
def referenceFont(request):
return getFileSystemBackend(referenceFontPath)
@pytest.fixture(params=[glyphs2Path, glyphs3Path, glyphsPackagePath])
def writableTestFont(tmpdir, request):
return _getCopiedBackend(request.param, tmpdir)
@pytest.fixture
def rtlTestFont(tmpdir):
return _getCopiedBackend(rtlFontPath, tmpdir)
@pytest.fixture
def fileFormatTestFont(tmpdir):
return _getCopiedBackend(fileFormatFontPath, tmpdir)
@pytest.fixture
def propagateAnchorsTestFont(tmpdir):
return _getCopiedBackend(propagateAnchorsFontPath, tmpdir)
@pytest.fixture
def writableRTLTestFont(tmpdir):
return _getCopiedBackend(rtlFontPath, tmpdir)
@pytest.fixture
def smartComponentsFont(tmpdir):
return _getCopiedBackend(smartComponentsFontPath, tmpdir)
@pytest.fixture
def smartComponentsReferenceFont():
return getFileSystemBackend(smartComponentsReferenceFontPath)
expectedAxes = structure(
{
"axes": [
{
"defaultValue": 400,
"hidden": False,
"label": "Weight",
"mapping": [
[100, 17],
[200, 30],
[300, 55],
[357, 75],
[400, 90],
[500, 133],
[700, 179],
[900, 220],
],
"maxValue": 900,
"minValue": 100,
"name": "Weight",
"tag": "wght",
},
]
},
Axes,
)
@pytest.mark.asyncio
async def test_getAxes(testFont):
axes = await testFont.getAxes()
assert expectedAxes == axes
expectedGlyphMap = {
"A": [65],
"Adieresis": [196],
"_part.shoulder": [],
"_part.stem": [],
"a": [97],
"a.sc": [],
"adieresis": [228],
"dieresis": [168],
"h": [104],
"m": [109],
"n": [110],
"V": [86],
"A-cy": [1040],
}
@pytest.mark.asyncio
async def test_getGlyphMap(testFont):
glyphMap = await testFont.getGlyphMap()
assert expectedGlyphMap == glyphMap
expectedFontInfo = FontInfo(
familyName="Glyphs Unit Test Sans",
versionMajor=1,
versionMinor=0,
copyright=None,
trademark=None,
description=None,
sampleText=None,
designer=None,
designerURL=None,
manufacturer=None,
manufacturerURL=None,
licenseDescription=None,
licenseInfoURL=None,
vendorID=None,
customData={},
)
@pytest.mark.asyncio
async def test_getFontInfo(testFont):
fontInfo = await testFont.getFontInfo()
assert expectedFontInfo == fontInfo
@pytest.mark.asyncio
@pytest.mark.parametrize("glyphName", list(expectedGlyphMap))
async def test_getGlyph(testFont, referenceFont, glyphName):
glyph = await testFont.getGlyph(glyphName)
if glyphName == "A" and "com.glyphsapp.glyph-color" not in glyph.customData:
# glyphsLib doesn't read the color attr from Glyphs-2 files,
# so let's monkeypatch the data
glyph.customData["com.glyphsapp.glyph-color"] = [120, 220, 20, 4]
if (
glyphName in ["h", "m", "n"]
and "com.glyphsapp.glyph-color" not in glyph.customData
):
# glyphsLib doesn't read the component alignment from Glyphs-2 files,
# so let's monkeypatch the data
for layerName in glyph.layers:
for component in glyph.layers[layerName].glyph.components:
if "com.glyphsapp.component.alignment" not in component.customData:
component.customData["com.glyphsapp.component.alignment"] = -1
referenceGlyph = await referenceFont.getGlyph(glyphName)
assert referenceGlyph == glyph
@pytest.mark.asyncio
@pytest.mark.parametrize("glyphName", list(expectedGlyphMap))
async def test_putGlyph(writableTestFont, glyphName):
glyphMap = await writableTestFont.getGlyphMap()
glyph = await writableTestFont.getGlyph(glyphName)
# for testing change every coordinate by 10 units
for layerName, layer in iter(glyph.layers.items()):
layer.glyph.xAdvance = 500 # for testing change xAdvance
for i, coordinate in enumerate(layer.glyph.path.coordinates):
layer.glyph.path.coordinates[i] = coordinate + 10
glyphCopy = deepcopy(glyph)
await writableTestFont.putGlyph(glyphName, glyph, glyphMap[glyphName])
assert glyphCopy == glyph # putGlyph may not mutate
savedGlyph = await writableTestFont.getGlyph(glyphName)
assert glyph == savedGlyph
reopened = getFileSystemBackend(writableTestFont.path)
reopenedGlyph = await reopened.getGlyph(glyphName)
assert glyph == reopenedGlyph
@pytest.mark.asyncio
@pytest.mark.parametrize("gName", ["a", "A"])
async def test_duplicateGlyph(writableTestFont, gName):
glyphName = f"{gName}.ss01"
glyph = deepcopy(await writableTestFont.getGlyph(gName))
glyph.name = glyphName
await writableTestFont.putGlyph(glyphName, glyph, [])
savedGlyph = await writableTestFont.getGlyph(glyphName)
# glyphsLib doesn't read the color attr from Glyphs-2 files,
# so let's monkeypatch the data
glyph.customData["com.glyphsapp.glyph-color"] = [120, 220, 20, 4]
savedGlyph.customData["com.glyphsapp.glyph-color"] = [120, 220, 20, 4]
assert glyph == savedGlyph
if os.path.isdir(writableTestFont.path):
# This is a glyphspackage:
# check if the order.plist has been updated as well.
packagePath = pathlib.Path(writableTestFont.path)
orderPath = packagePath / "order.plist"
with open(orderPath, "r", encoding="utf-8") as fp:
glyphOrder = openstep_plist.load(fp, use_numbers=True)
assert glyphName == glyphOrder[-1]
async def test_updateGlyphCodePoints(writableTestFont):
# Use case: all uppercase font via double encodeding
# for example: A -> A, a [0x0041, 0x0061]
glyphName = "A"
glyph = await writableTestFont.getGlyph(glyphName)
codePoints = [0x0041, 0x0061]
await writableTestFont.putGlyph(glyphName, glyph, codePoints)
reopened = getFileSystemBackend(writableTestFont.path)
reopenedGlyphMap = await reopened.getGlyphMap()
assert reopenedGlyphMap["A"] == [0x0041, 0x0061]
async def test_updateSourceName(writableTestFont):
glyphName = "a"
glyph = await writableTestFont.getGlyph(glyphName)
for i, source in enumerate(glyph.sources):
source.name = f"source#{i}"
await writableTestFont.putGlyph(glyphName, glyph, [ord("a")])
savedGlyph = await writableTestFont.getGlyph(glyphName)
assert glyph == savedGlyph
async def test_createNewGlyph(writableTestFont):
fontSources = await writableTestFont.getSources()
sourceNameMappingToIDs = sourceNameMappingFromSources(fontSources)
glyphName = "a.ss02"
glyph = VariableGlyph(name=glyphName)
layerName = masterId = sourceNameMappingToIDs["Regular"]
glyph.sources.append(
GlyphSource(
name="Default", location={}, locationBase=masterId, layerName=layerName
)
)
glyph.layers[layerName] = Layer(glyph=StaticGlyph(xAdvance=333))
await writableTestFont.putGlyph(glyphName, glyph, [])
savedGlyph = await writableTestFont.getGlyph(glyphName)
assert glyph == savedGlyph
async def test_createNewSmartGlyph(writableTestFont):
fontSources = await writableTestFont.getSources()
sourceNameMappingToIDs = sourceNameMappingFromSources(fontSources)
glyphName = "a.smart"
glyphAxis = GlyphAxis(name="Height", minValue=0, maxValue=100, defaultValue=0)
glyph = VariableGlyph(name=glyphName, axes=[glyphAxis])
sourceInfo = [
("Light", {}, "Light"),
("Light-Height", {"Height": 100}, "Light"),
("Regular", {}, "Regular"),
("Regular-Height", {"Height": 100}, "Regular"),
("Bold", {}, "Bold"),
("Bold-Height", {"Height": 100}, "Bold"),
]
# create a glyph with glyph axis
for sourceName, location, associatedSourceName in sourceInfo:
locationBase = sourceNameMappingToIDs[associatedSourceName]
layerName = sourceNameMappingToIDs.get(sourceName) or str(uuid.uuid4()).upper()
glyph.sources.append(
GlyphSource(
name=sourceName if location else "",
location=location,
locationBase=locationBase,
layerName=layerName,
)
)
glyph.layers[layerName] = Layer(glyph=StaticGlyph(xAdvance=100))
await writableTestFont.putGlyph(glyphName, glyph, [])
savedGlyph = await writableTestFont.getGlyph(glyphName)
assert glyph == savedGlyph
async def test_extendSmartGlyphWithIntermediateLayerOnFontAxis(writableTestFont):
# This should fail, because not yet implemented.
glyphName = "_part.shoulder"
glyph = await writableTestFont.getGlyph(glyphName)
layerName = str(uuid.uuid4()).upper()
glyph.sources.append(
GlyphSource(
name="Intermediate Layer", location={"Weight": 99}, layerName=layerName
)
)
glyph.layers[layerName] = Layer(glyph=StaticGlyph(xAdvance=100))
with pytest.raises(
NotImplementedError,
match="Brace layers within smart glyphs are not yet implemented",
):
await writableTestFont.putGlyph(glyphName, glyph, [])
async def test_extendSmartGlyphWithIntermediateLayerOnGlyphAxis(writableTestFont):
# This should fail, because not yet implemented.
glyphName = "_part.shoulder"
glyph = await writableTestFont.getGlyph(glyphName)
layerName = str(uuid.uuid4()).upper()
glyph.sources.append(
GlyphSource(
name="Intermediate Layer",
location={"shoulderWidth": 50},
layerName=layerName,
)
)
glyph.layers[layerName] = Layer(glyph=StaticGlyph(xAdvance=100))
with pytest.raises(
NotImplementedError,
match="Intermediate layers within smart glyphs are not yet implemented",
):
await writableTestFont.putGlyph(glyphName, glyph, [])
async def test_smartGlyphAddGlyphAxisWithDefaultNotMinOrMax(writableTestFont):
# This should fail, because not yet implemented.
glyphName = "_part.shoulder"
glyph = await writableTestFont.getGlyph(glyphName)
glyphAxis = GlyphAxis(name="Height", minValue=0, maxValue=100, defaultValue=50)
glyph.axes.append(glyphAxis)
with pytest.raises(
GlyphsBackendError,
match="Glyph axis 'Height' defaultValue must be at MIN or MAX.",
):
await writableTestFont.putGlyph(glyphName, glyph, [])
async def test_smartGlyphUpdateGlyphAxisWithDefaultNotMinOrMax(writableTestFont):
# This should fail, because not yet implemented.
glyphName = "_part.shoulder"
glyph = await writableTestFont.getGlyph(glyphName)
glyphAxis = glyph.axes[0]
glyphAxis.defaultValue = 50
with pytest.raises(
GlyphsBackendError,
match="defaultValue must be at MIN or MAX.",
):
await writableTestFont.putGlyph(glyphName, glyph, [])
async def test_smartGlyphAddGlyphAxisWithDefaultAtMinOrMax(writableTestFont):
glyphName = "_part.shoulder"
glyph = await writableTestFont.getGlyph(glyphName)
glyphAxis = GlyphAxis(name="Height", minValue=0, maxValue=100, defaultValue=100)
glyph.axes.append(glyphAxis)
await writableTestFont.putGlyph(glyphName, glyph, [])
savedGlyph = await writableTestFont.getGlyph(glyphName)
assert glyph == savedGlyph
async def test_smartGlyphRemoveGlyphAxis(writableTestFont):
glyphName = "_part.shoulder"
glyph = await writableTestFont.getGlyph(glyphName)
del glyph.axes[0]
# We expect we cannot roundtrip a glyph when removing a glyph axis,
# because then some layers locations are not unique anymore.
for i in [8, 5, 2]:
del glyph.layers[glyph.sources[i].layerName]
del glyph.sources[i]
await writableTestFont.putGlyph(glyphName, glyph, [])
savedGlyph = await writableTestFont.getGlyph(glyphName)
assert glyph == savedGlyph
async def test_smartGlyphChangeGlyphAxisValue(writableTestFont):
glyphName = "_part.shoulder"
glyph = await writableTestFont.getGlyph(glyphName)
glyph.axes[1].maxValue = 200
# We expect we cannot roundtrip a glyph when changing a glyph axis min or
# max value without changing the default, because in GlyphsApp there is
# no defaultValue-concept. Therefore we need to change the defaultValue as well.
glyph.axes[1].defaultValue = 200
await writableTestFont.putGlyph(glyphName, glyph, [])
savedGlyph = await writableTestFont.getGlyph(glyphName)
assert glyph == savedGlyph
async def test_deleteLayer(writableTestFont):
glyphName = "a"
glyphMap = await writableTestFont.getGlyphMap()
glyph = await writableTestFont.getGlyph(glyphName)
numGlyphLayers = len(glyph.layers)
# delete intermediate layer
sourceIndex = 1
del glyph.layers[glyph.sources[sourceIndex].layerName + "^background"]
del glyph.layers[glyph.sources[sourceIndex].layerName]
del glyph.sources[sourceIndex]
await writableTestFont.putGlyph(glyphName, glyph, glyphMap[glyphName])
savedGlyph = await writableTestFont.getGlyph(glyphName)
assert len(savedGlyph.layers) < numGlyphLayers
async def test_addLayer(writableTestFont):
fontSources = await writableTestFont.getSources()
sourceNameMappingToIDs = sourceNameMappingFromSources(fontSources)
glyphName = "a"
glyphMap = await writableTestFont.getGlyphMap()
glyph = await writableTestFont.getGlyph(glyphName)
layerName = str(uuid.uuid4()).upper()
glyph.sources.append(
GlyphSource(name="SemiBold", location={"Weight": 166}, layerName=layerName)
)
# Copy StaticGlyph from Bold:
glyph.layers[layerName] = Layer(
glyph=deepcopy(glyph.layers[sourceNameMappingToIDs["Bold"]].glyph)
)
await writableTestFont.putGlyph(glyphName, glyph, glyphMap[glyphName])
savedGlyph = await writableTestFont.getGlyph(glyphName)
assert glyph == savedGlyph
async def test_addBackgroundLayer(writableTestFont):
fontSources = await writableTestFont.getSources()
sourceNameMappingToIDs = sourceNameMappingFromSources(fontSources)
glyphName = "a"
glyphMap = await writableTestFont.getGlyphMap()
glyph = await writableTestFont.getGlyph(glyphName)
# add background layer:
glyph.layers[sourceNameMappingToIDs.get("Regular") + "^background"] = Layer(
glyph=deepcopy(glyph.layers[sourceNameMappingToIDs.get("Regular")].glyph)
)
await writableTestFont.putGlyph(glyphName, glyph, glyphMap[glyphName])
savedGlyph = await writableTestFont.getGlyph(glyphName)
assert glyph == savedGlyph
async def test_addBackgroundLayerToLayer(writableTestFont):
# This is a nested behaviour.
fontSources = await writableTestFont.getSources()
sourceNameMappingToIDs = sourceNameMappingFromSources(fontSources)
glyphName = "A"
glyphMap = await writableTestFont.getGlyphMap()
glyph = await writableTestFont.getGlyph(glyphName)
# add layout layer:
glyph.layers[sourceNameMappingToIDs.get("Regular") + "^Testing"] = Layer(
glyph=deepcopy(glyph.layers[sourceNameMappingToIDs.get("Regular")].glyph),
# Add explicit layerId for perfect round tripping
customData={"com.glyphsapp.layer.layerId": str(uuid.uuid4()).upper()},
)
# add background to layout layer:
glyph.layers[sourceNameMappingToIDs.get("Regular") + "^Testing/background"] = Layer(
glyph=deepcopy(glyph.layers[sourceNameMappingToIDs.get("Regular")].glyph)
)
await writableTestFont.putGlyph(glyphName, glyph, glyphMap[glyphName])
savedGlyph = await writableTestFont.getGlyph(glyphName)
assert glyph == savedGlyph
async def test_addLayoutLayer(writableTestFont):
fontSources = await writableTestFont.getSources()
sourceNameMappingToIDs = sourceNameMappingFromSources(fontSources)
glyphName = "A"
glyphMap = await writableTestFont.getGlyphMap()
glyph = await writableTestFont.getGlyph(glyphName)
# add layout layer:
glyph.layers[sourceNameMappingToIDs.get("Regular") + "^Layout Layer"] = Layer(
glyph=deepcopy(glyph.layers[sourceNameMappingToIDs["Bold"]].glyph),
# Add explicit layerId for perfect round tripping
customData={"com.glyphsapp.layer.layerId": str(uuid.uuid4()).upper()},
)
await writableTestFont.putGlyph(glyphName, glyph, glyphMap[glyphName])
savedGlyph = await writableTestFont.getGlyph(glyphName)
assert glyph == savedGlyph
async def test_readBackgroundLayer(writableTestFont):
glyphName = "a"
glyph = await writableTestFont.getGlyph(glyphName)
# every master layer of /a should have a background layer.
for glyphSource in glyph.sources:
assert f"{glyphSource.layerName}^background" in glyph.layers
async def test_addLayerWithoutSource(writableTestFont):
fontSources = await writableTestFont.getSources()
sourceNameMappingToIDs = sourceNameMappingFromSources(fontSources)
glyphName = "a"
glyphMap = await writableTestFont.getGlyphMap()
glyph = await writableTestFont.getGlyph(glyphName)
layerName = str(uuid.uuid4()).upper()
# Copy StaticGlyph from Bold:
glyph.layers[layerName] = Layer(
glyph=deepcopy(glyph.layers[sourceNameMappingToIDs["Bold"]].glyph)
)
with pytest.raises(
GlyphsBackendError, match="Layer without glyph source is not supported"
):
await writableTestFont.putGlyph(glyphName, glyph, glyphMap[glyphName])
async def test_addLayerWithComponent(writableTestFont):
fontSources = await writableTestFont.getSources()
sourceNameMappingToIDs = sourceNameMappingFromSources(fontSources)
glyphName = "n" # n is made from components
glyphMap = await writableTestFont.getGlyphMap()
glyph = await writableTestFont.getGlyph(glyphName)
layerName = str(uuid.uuid4()).upper()
glyph.sources.append(
GlyphSource(name="SemiBold", location={"Weight": 166}, layerName=layerName)
)
# Copy StaticGlyph of Bold:
glyph.layers[layerName] = Layer(
glyph=deepcopy(glyph.layers[sourceNameMappingToIDs["Bold"]].glyph)
)
# add background layer
glyph.layers[layerName + "^background"] = Layer(
glyph=deepcopy(glyph.layers[sourceNameMappingToIDs["Bold"]].glyph)
)
await writableTestFont.putGlyph(glyphName, glyph, glyphMap[glyphName])
savedGlyph = await writableTestFont.getGlyph(glyphName)
assert glyph == savedGlyph
async def test_addLayoutLayerToBraceLayer(writableTestFont):
# This is a fundamental difference between Fontra and Glyphs. Therefore raise error.
fontSources = await writableTestFont.getSources()
sourceNameMappingToIDs = sourceNameMappingFromSources(fontSources)
glyphName = "n"
glyphMap = await writableTestFont.getGlyphMap()
glyph = await writableTestFont.getGlyph(glyphName)
layerName = str(uuid.uuid4()).upper()
glyph.sources.append(
GlyphSource(name="SemiBold", location={"Weight": 166}, layerName=layerName)
)
# brace layer
glyph.layers[layerName] = Layer(
glyph=deepcopy(glyph.layers[sourceNameMappingToIDs["Light"]].glyph)
)
# secondary layer for brace layer
glyph.layers[layerName + "^Layout Layer"] = Layer(
glyph=deepcopy(glyph.layers[sourceNameMappingToIDs["Bold"]].glyph)
)
with pytest.raises(
GlyphsBackendError,
match="A brace layer can only have an additional source layer named 'background'",
):
await writableTestFont.putGlyph(glyphName, glyph, glyphMap[glyphName])
expectedSkewErrors = [
# skewValue, expectedErrorMatch
[20, "Does not support skewing of components"],
[-0.001, "Does not support skewing of components"],
]
@pytest.mark.parametrize("skewValue,expectedErrorMatch", expectedSkewErrors)
async def test_skewComponent(writableTestFont, skewValue, expectedErrorMatch):
fontSources = await writableTestFont.getSources()
sourceNameMappingToIDs = sourceNameMappingFromSources(fontSources)
glyphName = "Adieresis" # Adieresis is made from components
glyphMap = await writableTestFont.getGlyphMap()
glyph = await writableTestFont.getGlyph(glyphName)
glyph.layers[sourceNameMappingToIDs.get("Light")].glyph.components[
0
].transformation.skewX = skewValue
with pytest.raises(TypeError, match=expectedErrorMatch):
await writableTestFont.putGlyph(glyphName, glyph, glyphMap[glyphName])
async def test_addAnchor(writableTestFont):
glyphName = "a"
glyphMap = await writableTestFont.getGlyphMap()
glyph = await writableTestFont.getGlyph(glyphName)
layerName = str(uuid.uuid4()).upper()
glyph.sources.append(
GlyphSource(name="SemiBold", location={"Weight": 166}, layerName=layerName)
)
glyph.layers[layerName] = Layer(glyph=StaticGlyph(xAdvance=0))
glyph.layers[layerName].glyph.anchors.append(Anchor(name="top", x=207, y=746))
await writableTestFont.putGlyph(glyphName, glyph, glyphMap[glyphName])
savedGlyph = await writableTestFont.getGlyph(glyphName)
assert (
glyph.layers[layerName].glyph.anchors
== savedGlyph.layers[layerName].glyph.anchors
)
async def test_addGuideline(writableTestFont):
glyphName = "a"
glyphMap = await writableTestFont.getGlyphMap()
glyph = await writableTestFont.getGlyph(glyphName)
layerName = str(uuid.uuid4()).upper()
glyph.sources.append(
GlyphSource(name="SemiBold", location={"Weight": 166}, layerName=layerName)
)
glyph.layers[layerName] = Layer(glyph=StaticGlyph(xAdvance=0))
glyph.layers[layerName].glyph.guidelines.append(Guideline(name="top", x=207, y=746))
glyph.layers[layerName].glyph.guidelines.append(
Guideline(name="bottom", x=207, y=0, locked=True)
)
await writableTestFont.putGlyph(glyphName, glyph, glyphMap[glyphName])
savedGlyph = await writableTestFont.getGlyph(glyphName)
savedGuidelines = savedGlyph.layers[layerName].glyph.guidelines
assert glyph.layers[layerName].glyph.guidelines == savedGuidelines
assert savedGuidelines[0].locked is False
assert savedGuidelines[1].locked is True
async def test_getKerning(testFont, referenceFont):
assert await testFont.getKerning() == await referenceFont.getKerning()
def modifyKerningPair(kerning):
kerning["kern"].values["@A"]["@J"][0] = -40
return kerning
def deleteKerningPair(kerning):
del kerning["kern"].values["@A"]["@J"]
return kerning
def modifyKerningGroups(kerning):
kerning["kern"].groupsSide1["A"].append("Adieresis")
kerning["kern"].groupsSide2["A"].append("Adieresis")
return kerning
def deleteAllKerning(kerning):
return {}
def addUnknownSourceKerning(kerning):
return {
"kern": Kerning(
groupsSide1={"A": ["A"]}, groupsSide2={}, sourceIdentifiers=["X"], values={}
)
}
putKerningTestData = [
(modifyKerningPair, None),
(deleteKerningPair, None),
(modifyKerningGroups, None),
(deleteAllKerning, None),
(addUnknownSourceKerning, GlyphsBackendError),
]
@pytest.mark.parametrize("modifierFunction, expectedException", putKerningTestData)
async def test_putKerning(writableTestFont, modifierFunction, expectedException):
kerning = await writableTestFont.getKerning()
if writableTestFont.gsFont.format_version == 2:
kerning.pop(
"vkrn", None
) # glyphsLib does not support writing of vertical kerning
kerning = modifierFunction(kerning)
if expectedException:
with pytest.raises(GlyphsBackendError):
async with aclosing(writableTestFont):
await writableTestFont.putKerning(kerning)
else:
async with aclosing(writableTestFont):
await writableTestFont.putKerning(kerning)
reopened = getFileSystemBackend(writableTestFont.path)
reopenedKerning = await reopened.getKerning()
assert reopenedKerning == kerning
async def test_putKerning_master_order(tmpdir):
tmpdir = pathlib.Path(tmpdir)
srcPath = pathlib.Path(glyphs3Path)
dstPath = tmpdir / srcPath.name
shutil.copy(srcPath, dstPath)
testFont = getFileSystemBackend(dstPath)
async with aclosing(testFont):
await testFont.putKerning(await testFont.getKerning())
assert srcPath.read_text() == dstPath.read_text()
async def test_getFeatures(testFont, referenceFont):
assert await testFont.getFeatures() == await referenceFont.getFeatures()
expectedExternalFeatureFileFragment = """feature c2sc {
sub A by A.sc;
sub V by V.sc;
} c2sc;"""
async def test_getFeatures_externalFeatureFile(externalFeaturesFileFont):
features = await externalFeaturesFileFont.getFeatures()
assert expectedExternalFeatureFileFragment in features.text
async def test_getFeatures_with_expansion():
expansionFontPath = dataDir / "FeatureExpansionTest.glyphs"
testFont = getFileSystemBackend(expansionFontPath)
features = await testFont.getFeatures()
assert "WARNING" in features.text
assert "@TOKEN_TESTING_CLASS = [A Adieresis A-cy];" in features.text
assert "lookup testing_lookup {" in features.text
glyphsSource = expansionFontPath.read_text(encoding="utf-8")
assert "WARNING" not in glyphsSource
assert "@TOKEN_TESTING_CLASS = [A Adieresis A-cy];" not in glyphsSource
assert "lookup testing_lookup {" not in glyphsSource
putFeaturesTestData = [
"# dummy feature data\n",
"""@c2sc_source = [ A
];
@c2sc_target = [ a.sc
];
# Prefix: Languagesystems
# Demo feature code for testing
languagesystem DFLT dflt; # Default, Default
languagesystem latn dflt; # Latin, Default
feature c2sc {
sub @c2sc_source by @c2sc_target;
} c2sc;
""",
"syntax error",
]
@pytest.mark.parametrize("featureText", putFeaturesTestData)
async def test_putFeatures(writableTestFont, featureText):
async with aclosing(writableTestFont):
await writableTestFont.putFeatures(OpenTypeFeatures(text=featureText))
# Test reading a glyph, to test we didn't mess up the internals
# https://github.com/fontra/fontra-glyphs/pull/125
glyph = await writableTestFont.getGlyph("A")
assert glyph is not None
reopened = getFileSystemBackend(writableTestFont.path)
features = await reopened.getFeatures()
assert features.text == featureText
async def test_locationBaseWrite(writableTestFont):
glyphName = "q" # Any glyph that doesn't exist yet
fontSources = await writableTestFont.getSources()
glyph = VariableGlyph(name=glyphName)
for sourceIdentifier in fontSources.keys():
glyph.sources.append(
GlyphSource(
name="", locationBase=sourceIdentifier, layerName=sourceIdentifier
)
)
glyph.layers[sourceIdentifier] = Layer(glyph=StaticGlyph(xAdvance=333))
await writableTestFont.putGlyph(glyphName, glyph, [])
savedGlyph = await writableTestFont.getGlyph(glyphName)
for (sourceIdentifier, fontSource), glyphSource in zip(
fontSources.items(), savedGlyph.sources, strict=True
):
assert glyphSource.name == ""
glyphSource.location == {}
assert glyph.layers == savedGlyph.layers
async def test_deleteGlyph(writableTestFont):
glyphName = "A"
async with aclosing(writableTestFont):
await writableTestFont.deleteGlyph(glyphName)
reopened = getFileSystemBackend(writableTestFont.path)
glyphMap = await reopened.getGlyphMap()
assert glyphName not in glyphMap
glyph = await reopened.getGlyph(glyphName)
assert glyph is None
async def test_deleteGlyph_addGlyph(writableTestFont):
# This test (ab)uses the fact that the glyphMap order reveals the
# glyph order in the .glyphs or .glyphspackage file.
glyphName = "A"
glyphMap = await writableTestFont.getGlyphMap()
beforeKerning = await writableTestFont.getKerning()
beforeGlyphOrder = list(glyphMap)
glyph = await writableTestFont.getGlyph(glyphName)
async with aclosing(writableTestFont):
await writableTestFont.deleteGlyph(glyphName)
await writableTestFont.putGlyph(glyphName, glyph, glyphMap[glyphName])
reopened = getFileSystemBackend(writableTestFont.path)
glyphMap = await reopened.getGlyphMap()
assert glyphName in glyphMap
afterKerning = await reopened.getKerning()
glyph = await reopened.getGlyph(glyphName)
assert glyph is not None
afterGlyphOrder = list(glyphMap)
assert beforeGlyphOrder == afterGlyphOrder
assert beforeKerning == afterKerning
async def test_writeFontData_glyphspackage_empty_glyphs_list(tmpdir):
tmpdir = pathlib.Path(tmpdir)
srcPath = pathlib.Path(glyphsPackagePath)
dstPath = tmpdir / srcPath.name
fontInfoPath = dstPath / "fontinfo.plist"
shutil.copytree(srcPath, dstPath)
fontInfoBefore = fontInfoPath.read_text()
testFont = getFileSystemBackend(dstPath)
async with aclosing(testFont):
await testFont.putKerning(await testFont.getKerning())
fontInfoAfter = fontInfoPath.read_text()
assert fontInfoAfter == fontInfoBefore
@pytest.mark.parametrize(
"glyphName, expectedUsedBy",
[
("A", ["A-cy", "Adieresis"]),
("a", ["adieresis"]),
("_part.shoulder", ["h", "m", "n"]),
("dieresis", ["Adieresis", "adieresis"]),
("V", []),
("V.undefined", []),
],
)
async def test_findGlyphsThatUseGlyph(testFont, glyphName, expectedUsedBy):
usedBy = await testFont.findGlyphsThatUseGlyph(glyphName)
assert usedBy == expectedUsedBy
async def setupFontHandler(backend):
fh = FontHandler(
backend=backend,
projectIdentifier="test",
metaInfoProvider=FileSystemProjectManager(),
)
await fh.startTasks()
return fh
@pytest.mark.parametrize("changeUnicodes", [False, True])
async def test_externalChanges_putGlyph(writableTestFont, changeUnicodes):
listenerFont = getFileSystemBackend(writableTestFont.path)
listenerHandler = await setupFontHandler(listenerFont)
glyphName = "A"
async with aclosing(listenerHandler):
listenerGlyphMap = await listenerHandler.getGlyphMap() # load in cache
listenerGlyph = await listenerHandler.getGlyph(glyphName) # load in cache