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 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563
|
import logging
import os
from io import BytesIO
import pytest
from fontTools.colorLib.unbuilder import unbuildColrV1
from fontTools.cu2qu.ufo import font_to_quadratic
from fontTools.misc.arrayTools import quantizeRect
from fontTools.ttLib import TTFont
from fontTools.ttLib.tables._g_l_y_f import USE_MY_METRICS
from ufo2ft import (
compileInterpolatableOTFsFromDS,
compileInterpolatableTTFs,
compileInterpolatableTTFsFromDS,
compileOTF,
compileTTF,
)
from ufo2ft.constants import (
GLYPHS_DONT_USE_PRODUCTION_NAMES,
GLYPHS_MATH_CONSTANTS_KEY,
GLYPHS_MATH_EXTENDED_SHAPE_KEY,
GLYPHS_MATH_VARIANTS_KEY,
OPENTYPE_POST_UNDERLINE_POSITION_KEY,
SPARSE_OTF_MASTER_TABLES,
SPARSE_TTF_MASTER_TABLES,
USE_PRODUCTION_NAMES,
)
from ufo2ft.errors import InvalidFontData
from ufo2ft.filters import DecomposeTransformedComponentsFilter
from ufo2ft.fontInfoData import intListToNum
from ufo2ft.outlineCompiler import OutlineOTFCompiler, OutlineTTFCompiler
def getpath(filename):
dirname = os.path.dirname(__file__)
return os.path.join(dirname, "data", filename)
@pytest.fixture
def testufo(FontClass):
font = FontClass(getpath("TestFont.ufo"))
del font.lib["public.postscriptNames"]
return font
@pytest.fixture
def quadufo(FontClass):
font = FontClass(getpath("TestFont.ufo"))
font_to_quadratic(font)
return font
@pytest.fixture
def nestedcomponentsufo(FontClass):
font = FontClass(getpath("NestedComponents-Regular.ufo"))
return font
@pytest.fixture
def use_my_metrics_ufo(FontClass):
return FontClass(getpath("UseMyMetrics.ufo"))
@pytest.fixture
def emptyufo(FontClass):
font = FontClass()
font.info.unitsPerEm = 1000
font.info.familyName = "Test Font"
font.info.styleName = "Regular"
font.info.ascender = 750
font.info.descender = -250
font.info.xHeight = 500
font.info.capHeight = 750
return font
class OutlineTTFCompilerTest:
def test_compile_with_gasp(self, quadufo):
compiler = OutlineTTFCompiler(quadufo)
compiler.compile()
assert "gasp" in compiler.otf
assert compiler.otf["gasp"].gaspRange == {7: 10, 65535: 15}
def test_compile_without_gasp(self, quadufo):
quadufo.info.openTypeGaspRangeRecords = None
compiler = OutlineTTFCompiler(quadufo)
compiler.compile()
assert "gasp" not in compiler.otf
def test_compile_empty_gasp(self, quadufo):
# ignore empty gasp
quadufo.info.openTypeGaspRangeRecords = []
compiler = OutlineTTFCompiler(quadufo)
compiler.compile()
assert "gasp" not in compiler.otf
def test_makeGlyphsBoundingBoxes(self, quadufo):
compiler = OutlineTTFCompiler(quadufo)
assert compiler.glyphBoundingBoxes[".notdef"] == (50, 0, 450, 750)
# no outline data
assert compiler.glyphBoundingBoxes["space"] is None
# float coordinates are rounded, so is the bbox
assert compiler.glyphBoundingBoxes["d"] == (90, 77, 211, 197)
def test_getMaxComponentDepths(self, nestedcomponentsufo):
compiler = OutlineTTFCompiler(nestedcomponentsufo)
assert "a" not in compiler.getMaxComponentDepths()
assert "b" not in compiler.getMaxComponentDepths()
assert compiler.getMaxComponentDepths()["c"] == 1
assert compiler.getMaxComponentDepths()["d"] == 1
assert compiler.getMaxComponentDepths()["e"] == 2
def test_autoUseMyMetrics(self, use_my_metrics_ufo):
compiler = OutlineTTFCompiler(use_my_metrics_ufo)
ttf = compiler.compile()
# the first component in the 'Iacute' composite glyph ('acute')
# does _not_ have the USE_MY_METRICS flag
assert not (ttf["glyf"]["Iacute"].components[0].flags & USE_MY_METRICS)
# the second component in the 'Iacute' composite glyph ('I')
# has the USE_MY_METRICS flag set
assert ttf["glyf"]["Iacute"].components[1].flags & USE_MY_METRICS
# none of the 'I' components of the 'romanthree' glyph has
# the USE_MY_METRICS flag set, because the composite glyph has a
# different width
for component in ttf["glyf"]["romanthree"].components:
assert not (component.flags & USE_MY_METRICS)
def test_autoUseMyMetrics_False(self, use_my_metrics_ufo):
compiler = OutlineTTFCompiler(use_my_metrics_ufo, autoUseMyMetrics=False)
ttf = compiler.compile()
assert not (ttf["glyf"]["Iacute"].components[1].flags & USE_MY_METRICS)
def test_autoUseMyMetrics_None(self, use_my_metrics_ufo):
compiler = OutlineTTFCompiler(use_my_metrics_ufo)
# setting 'autoUseMyMetrics' attribute to None disables the feature
compiler.autoUseMyMetrics = None
ttf = compiler.compile()
assert not (ttf["glyf"]["Iacute"].components[1].flags & USE_MY_METRICS)
def test_importTTX(self, testufo):
compiler = OutlineTTFCompiler(testufo)
otf = compiler.otf = TTFont()
compiler.importTTX()
assert "CUST" in otf
assert otf["CUST"].data == b"\x00\x01\xbe\xef"
assert otf.sfntVersion == "\x00\x01\x00\x00"
def test_no_contour_glyphs(self, testufo):
for glyph in testufo:
glyph.clearContours()
compiler = OutlineTTFCompiler(testufo)
compiler.compile()
assert compiler.otf["hhea"].advanceWidthMax == 600
assert compiler.otf["hhea"].minLeftSideBearing == 0
assert compiler.otf["hhea"].minRightSideBearing == 0
assert compiler.otf["hhea"].xMaxExtent == 0
def test_os2_no_widths(self, quadufo):
for glyph in quadufo:
glyph.width = 0
compiler = OutlineTTFCompiler(quadufo)
compiler.compile()
assert compiler.otf["OS/2"].xAvgCharWidth == 0
def test_missing_component(self, emptyufo):
ufo = emptyufo
a = ufo.newGlyph("a")
pen = a.getPen()
pen.moveTo((0, 0))
pen.lineTo((100, 0))
pen.lineTo((100, 100))
pen.lineTo((0, 100))
pen.closePath()
# a mixed contour/component glyph, which is decomposed by the
# TTGlyphPen; one of the components does not exist thus should
# be dropped
b = ufo.newGlyph("b")
pen = b.getPen()
pen.moveTo((0, 200))
pen.lineTo((100, 200))
pen.lineTo((50, 300))
pen.closePath()
pen.addComponent("a", (1, 0, 0, 1, 0, 0))
pen.addComponent("c", (1, 0, 0, 1, 0, 0)) # missing
d = ufo.newGlyph("d")
pen = d.getPen()
pen.addComponent("c", (1, 0, 0, 1, 0, 0)) # missing
e = ufo.newGlyph("e")
pen = e.getPen()
pen.addComponent("a", (1, 0, 0, 1, 0, 0))
pen.addComponent("c", (1, 0, 0, 1, 0, 0)) # missing
compiler = OutlineTTFCompiler(ufo)
ttFont = compiler.compile()
glyf = ttFont["glyf"]
assert glyf["a"].numberOfContours == 1
assert glyf["b"].numberOfContours == 2
assert glyf["d"].numberOfContours == 0
assert glyf["e"].numberOfContours == -1 # composite glyph
assert len(glyf["e"].components) == 1
def test_contour_starts_with_offcurve_point(self, emptyufo):
ufo = emptyufo
a = ufo.newGlyph("a")
pen = a.getPointPen()
pen.beginPath()
pen.addPoint((0, 0), None)
pen.addPoint((0, 10), None)
pen.addPoint((10, 10), None)
pen.addPoint((10, 0), None)
pen.addPoint((5, 0), "qcurve")
pen.endPath()
compiler = OutlineTTFCompiler(ufo)
ttFont = compiler.compile()
glyf = ttFont["glyf"]
assert glyf["a"].numberOfContours == 1
coords, endPts, flags = glyf["a"].getCoordinates(glyf)
assert list(coords) == [(0, 0), (0, 10), (10, 10), (10, 0), (5, 0)]
assert endPts == [4]
assert list(flags) == [0, 0, 0, 0, 1]
def test_compileTTF_decomposes_flipped_component_with_oncurve_first(self, emptyufo):
# https://github.com/googlefonts/fontc/issues/1633
ufo = emptyufo
base = ufo.newGlyph("base")
pen = base.getPointPen()
pen.beginPath()
# the first point is off-curve in the original base glyph
pen.addPoint((50, 0), None)
pen.addPoint((100, 0), "curve")
pen.addPoint((150, 0), None)
pen.addPoint((200, 50), None)
pen.addPoint((200, 100), "curve")
pen.addPoint((200, 150), None)
pen.addPoint((150, 200), None)
pen.addPoint((100, 200), "curve")
pen.addPoint((50, 200), None)
pen.addPoint((0, 150), None)
pen.addPoint((0, 100), "curve")
pen.addPoint((0, 50), None)
pen.endPath()
comp = ufo.newGlyph("comp")
pen = comp.getPen()
# Apply a horizontal flip to the component (negative determinant).
pen.addComponent("base", (-1, 0, 0, 1, 0, 0))
ttFont = compileTTF(ufo, filters=[DecomposeTransformedComponentsFilter()])
glyf = ttFont["glyf"]
compGlyph = glyf["comp"]
# Flipped component gets decomposed to a single contour
assert compGlyph.numberOfContours == 1
coords, endPts, flags = compGlyph.getCoordinates(glyf)
assert endPts == [len(coords) - 1]
# The contour point list is rotated such that it starts with an on-curve point,
# which corresponds to the original base glyph's first on-curve point, flipped.
assert flags[0] == 1
assert coords[0] == (-100, 0)
# Its contour direction is reversed from counter-clockwise to clockwise
oncurve_points = [p for p, f in zip(coords, flags) if f & 1]
assert oncurve_points == [(-100, 0), (-200, 100), (-100, 200), (0, 100)]
def test_setupTable_meta(self, quadufo):
quadufo.lib["public.openTypeMeta"] = {
"appl": b"BEEF",
"bild": b"AAAA",
"dlng": ["en-Latn", "nl-Latn"],
"slng": ["Latn"],
"PRIB": b"Some private bytes",
"PRIA": "Some private ascii string",
"PRIU": "Some private unicode string…",
}
compiler = OutlineTTFCompiler(quadufo)
ttFont = compiler.compile()
meta = ttFont["meta"]
assert meta.data["appl"] == b"BEEF"
assert meta.data["bild"] == b"AAAA"
assert meta.data["dlng"] == "en-Latn,nl-Latn"
assert meta.data["slng"] == "Latn"
assert meta.data["PRIB"] == b"Some private bytes"
assert meta.data["PRIA"] == b"Some private ascii string"
assert meta.data["PRIU"] == "Some private unicode string…".encode("utf-8")
def test_setupTable_name(self, quadufo):
compiler = OutlineTTFCompiler(quadufo)
compiler.compile()
actual = compiler.otf["name"].getName(1, 3, 1, 1033).string
assert actual == "Some Font Regular (Style Map Family Name)"
quadufo.info.openTypeNameRecords.append(
{
"nameID": 1,
"platformID": 3,
"encodingID": 1,
"languageID": 1033,
"string": "Custom Name for Windows",
}
)
compiler = OutlineTTFCompiler(quadufo)
compiler.compile()
actual = compiler.otf["name"].getName(1, 3, 1, 1033).string
assert actual == "Custom Name for Windows"
def test_post_underline_without_public_key(self, quadufo):
compiler = OutlineTTFCompiler(quadufo)
compiler.compile()
actual = compiler.otf["post"].underlinePosition
assert actual == -200
def test_post_underline_with_public_key(self, quadufo):
quadufo.lib[OPENTYPE_POST_UNDERLINE_POSITION_KEY] = -485
compiler = OutlineTTFCompiler(quadufo)
compiler.compile()
actual = compiler.otf["post"].underlinePosition
assert actual == -485
class OutlineOTFCompilerTest:
def test_setupTable_CFF_all_blues_defined(self, testufo):
testufo.info.postscriptBlueFuzz = 2
testufo.info.postscriptBlueShift = 8
testufo.info.postscriptBlueScale = 0.049736
testufo.info.postscriptForceBold = False
testufo.info.postscriptBlueValues = [-12, 0, 486, 498, 712, 724]
testufo.info.postscriptOtherBlues = [-217, -205]
testufo.info.postscriptFamilyBlues = [-12, 0, 486, 498, 712, 724]
testufo.info.postscriptFamilyOtherBlues = [-217, -205]
compiler = OutlineOTFCompiler(testufo)
compiler.otf = TTFont(sfntVersion="OTTO")
compiler.setupTable_CFF()
cff = compiler.otf["CFF "].cff
private = cff[list(cff.keys())[0]].Private
assert private.BlueFuzz == 2
assert private.BlueShift == 8
assert private.BlueScale == 0.049736
assert private.ForceBold == 0
assert private.BlueValues == [-12, 0, 486, 498, 712, 724]
assert private.OtherBlues == [-217, -205]
assert private.FamilyBlues == [-12, 0, 486, 498, 712, 724]
assert private.FamilyOtherBlues == [-217, -205]
def test_setupTable_CFF_no_blues_defined(self, testufo):
# no blue values defined
testufo.info.postscriptBlueValues = []
testufo.info.postscriptOtherBlues = []
testufo.info.postscriptFamilyBlues = []
testufo.info.postscriptFamilyOtherBlues = []
# the following attributes have no effect
testufo.info.postscriptBlueFuzz = 2
testufo.info.postscriptBlueShift = 8
testufo.info.postscriptBlueScale = 0.049736
testufo.info.postscriptForceBold = False
compiler = OutlineOTFCompiler(testufo)
compiler.otf = TTFont(sfntVersion="OTTO")
compiler.setupTable_CFF()
cff = compiler.otf["CFF "].cff
private = cff[list(cff.keys())[0]].Private
# expect default values as defined in fontTools' cffLib.py
assert private.BlueFuzz == 1
assert private.BlueShift == 7
assert private.BlueScale == 0.039625
assert private.ForceBold == 0
# CFF PrivateDict has no blues attributes
assert not hasattr(private, "BlueValues")
assert not hasattr(private, "OtherBlues")
assert not hasattr(private, "FamilyBlues")
assert not hasattr(private, "FamilyOtherBlues")
def test_setupTable_CFF_some_blues_defined(self, testufo):
testufo.info.postscriptBlueFuzz = 2
testufo.info.postscriptForceBold = True
testufo.info.postscriptBlueValues = []
testufo.info.postscriptOtherBlues = [-217, -205]
testufo.info.postscriptFamilyBlues = []
testufo.info.postscriptFamilyOtherBlues = []
compiler = OutlineOTFCompiler(testufo)
compiler.otf = TTFont(sfntVersion="OTTO")
compiler.setupTable_CFF()
cff = compiler.otf["CFF "].cff
private = cff[list(cff.keys())[0]].Private
assert private.BlueFuzz == 2
assert private.BlueShift == 7 # default
assert private.BlueScale == 0.039625 # default
assert private.ForceBold is True
assert not hasattr(private, "BlueValues")
assert private.OtherBlues == [-217, -205]
assert not hasattr(private, "FamilyBlues")
assert not hasattr(private, "FamilyOtherBlues")
@staticmethod
def get_charstring_program(ttFont, glyphName):
cff = ttFont["CFF "].cff
charstrings = cff[list(cff.keys())[0]].CharStrings
c, _ = charstrings.getItemAndSelector(glyphName)
c.decompile()
return c.program
def assertProgramEqual(self, expected, actual):
assert len(expected) == len(actual)
for exp_token, act_token in zip(expected, actual):
if isinstance(exp_token, str):
assert exp_token == act_token
else:
assert not isinstance(act_token, str)
assert exp_token == pytest.approx(act_token)
def test_setupTable_CFF_round_all(self, testufo):
# by default all floats are rounded to integer
compiler = OutlineOTFCompiler(testufo)
otf = compiler.otf = TTFont(sfntVersion="OTTO")
compiler.setupTable_CFF()
# glyph 'd' in TestFont.ufo contains float coordinates
program = self.get_charstring_program(otf, "d")
self.assertProgramEqual(
program,
[
-26,
151,
197,
"rmoveto",
-34,
-27,
-27,
-33,
-33,
27,
-27,
34,
33,
27,
27,
33,
33,
-27,
27,
-33,
"hvcurveto",
"endchar",
],
)
def test_setupTable_CFF_round_none(self, testufo):
# roundTolerance=0 means 'don't round, keep all floats'
compiler = OutlineOTFCompiler(testufo, roundTolerance=0)
otf = compiler.otf = TTFont(sfntVersion="OTTO")
compiler.setupTable_CFF()
program = self.get_charstring_program(otf, "d")
self.assertProgramEqual(
program,
[
-26,
150.66,
197.32,
"rmoveto",
-33.66,
-26.67,
-26.99,
-33.33,
-33.33,
26.67,
-26.66,
33.66,
33.33,
26.66,
26.66,
33.33,
33.33,
-26.66,
26.99,
-33.33,
"hvcurveto",
"endchar",
],
)
def test_setupTable_CFF_round_some(self, testufo):
# only floats 'close enough' are rounded to integer
compiler = OutlineOTFCompiler(testufo, roundTolerance=0.34)
otf = compiler.otf = TTFont(sfntVersion="OTTO")
compiler.setupTable_CFF()
program = self.get_charstring_program(otf, "d")
self.assertProgramEqual(
program,
[
-26,
150.66,
197,
"rmoveto",
-33.66,
-27,
-27,
-33,
-33,
27,
-27,
33.66,
33.34,
26.65,
27,
33,
33,
-26.65,
27,
-33.34,
"hvcurveto",
"endchar",
],
)
def test_setupTable_CFF_optimize(self, testufo):
compiler = OutlineOTFCompiler(testufo, optimizeCFF=True)
otf = compiler.otf = TTFont(sfntVersion="OTTO")
compiler.setupTable_CFF()
program = self.get_charstring_program(otf, "a")
self.assertProgramEqual(
program,
[-12, 66, "hmoveto", 256, "hlineto", -128, 510, "rlineto", "endchar"],
)
def test_setupTable_CFF_no_optimize(self, testufo):
compiler = OutlineOTFCompiler(testufo, optimizeCFF=False)
otf = compiler.otf = TTFont(sfntVersion="OTTO")
compiler.setupTable_CFF()
program = self.get_charstring_program(otf, "a")
self.assertProgramEqual(
program,
[-12, 66, 0, "rmoveto", 256, 0, "rlineto", -128, 510, "rlineto", "endchar"],
)
def test_makeGlyphsBoundingBoxes(self, testufo):
compiler = OutlineOTFCompiler(testufo)
# with default roundTolerance, all coordinates and hence the bounding
# box values are rounded with otRound()
assert compiler.glyphBoundingBoxes["d"] == (90, 77, 211, 197)
def test_makeGlyphsBoundingBoxes_floats(self, testufo):
# specifying a custom roundTolerance affects which coordinates are
# rounded; in this case, the top-most Y coordinate stays a float
# (197.32), hence the bbox.yMax (198) is rounded using math.ceiling()
compiler = OutlineOTFCompiler(testufo, roundTolerance=0.1)
assert compiler.glyphBoundingBoxes["d"] == (90, 77, 211, 198)
def test_importTTX(self, testufo):
compiler = OutlineOTFCompiler(testufo)
otf = compiler.otf = TTFont(sfntVersion="OTTO")
compiler.importTTX()
assert "CUST" in otf
assert otf["CUST"].data == b"\x00\x01\xbe\xef"
assert otf.sfntVersion == "OTTO"
def test_no_contour_glyphs(self, testufo):
for glyph in testufo:
glyph.clearContours()
compiler = OutlineOTFCompiler(testufo)
compiler.compile()
assert compiler.otf["hhea"].advanceWidthMax == 600
assert compiler.otf["hhea"].minLeftSideBearing == 0
assert compiler.otf["hhea"].minRightSideBearing == 0
assert compiler.otf["hhea"].xMaxExtent == 0
def test_optimized_default_and_nominal_widths(self, FontClass):
ufo = FontClass()
ufo.info.unitsPerEm = 1000
for glyphName, width in (
(".notdef", 500),
("space", 250),
("a", 388),
("b", 410),
("c", 374),
("d", 374),
("e", 388),
("f", 410),
("g", 388),
("h", 410),
("i", 600),
("j", 600),
("k", 600),
("l", 600),
):
glyph = ufo.newGlyph(glyphName)
glyph.width = width
compiler = OutlineOTFCompiler(ufo)
compiler.otf = TTFont(sfntVersion="OTTO")
compiler.setupTable_hmtx()
compiler.setupTable_CFF()
cff = compiler.otf["CFF "].cff
topDict = cff[list(cff.keys())[0]]
private = topDict.Private
assert private.defaultWidthX == 600
assert private.nominalWidthX == 303
charStrings = topDict.CharStrings
# the following have width == defaultWidthX, so it's omitted
for g in ("i", "j", "k", "l"):
assert charStrings.getItemAndSelector(g)[0].program == ["endchar"]
# 'space' has width 250, so the width encoded in its charstring is:
# 250 - nominalWidthX
assert charStrings.getItemAndSelector("space")[0].program == [-53, "endchar"]
def test_optimized_default_but_no_nominal_widths(self, FontClass):
ufo = FontClass()
ufo.info.familyName = "Test"
ufo.info.styleName = "R"
ufo.info.ascender = 1
ufo.info.descender = 1
ufo.info.capHeight = 1
ufo.info.xHeight = 1
ufo.info.unitsPerEm = 1000
ufo.info.postscriptDefaultWidthX = 500
for glyphName, width in (
(".notdef", 500),
("space", 500),
("a", 500),
):
glyph = ufo.newGlyph(glyphName)
glyph.width = width
font = compileOTF(ufo)
cff = font["CFF "].cff
private = cff[list(cff.keys())[0]].Private
assert private.defaultWidthX == 500
assert private.nominalWidthX == 0
def test_underline_without_public_key(self, testufo):
# Test with no lib key
compiler = OutlineOTFCompiler(testufo)
compiler.compile()
post = compiler.otf["post"].underlinePosition
cff = compiler.otf["CFF "].cff
cff_underline = cff[list(cff.keys())[0]].UnderlinePosition
assert post == -200
assert cff_underline == -200
def test_underline_with_public_key(self, testufo):
# Test with a lib key and postscriptUnderlinePosition
testufo.lib[OPENTYPE_POST_UNDERLINE_POSITION_KEY] = -485
testufo.info.postscriptUnderlinePosition = -42
compiler = OutlineOTFCompiler(testufo)
compiler.compile()
post = compiler.otf["post"].underlinePosition
cff = compiler.otf["CFF "].cff
cff_underline = cff[list(cff.keys())[0]].UnderlinePosition
assert post == -485
assert cff_underline == -42
def test_underline_with_public_key_and_no_psPosition(self, testufo):
# Test with a lib key and no postscriptUnderlinePosition
testufo.lib[OPENTYPE_POST_UNDERLINE_POSITION_KEY] = -485
testufo.info.postscriptUnderlinePosition = None
testufo.info.postscriptUnderlineThickness = 100
compiler = OutlineOTFCompiler(testufo)
compiler.compile()
post = compiler.otf["post"].underlinePosition
cff = compiler.otf["CFF "].cff
cff_underline = cff[list(cff.keys())[0]].UnderlinePosition
assert post == -485
assert cff_underline == -535
def test_underline_with_no_public_key_and_no_psPosition(self, testufo):
compiler = OutlineOTFCompiler(testufo)
compiler.compile()
post = compiler.otf["post"].underlinePosition
cff = compiler.otf["CFF "].cff
cff_underline = cff[list(cff.keys())[0]].UnderlinePosition
# Note: This is actually incorrect according to the post/cff
# spec, but it is how UFO3 has things defined, and is expected
# current behavior.
assert post == -200
assert cff_underline == -200
def test_underline_ps_rounding(self, testufo):
# Test rounding
testufo.lib[OPENTYPE_POST_UNDERLINE_POSITION_KEY] = -485
testufo.info.postscriptUnderlinePosition = None
testufo.info.postscriptUnderlineThickness = 43
compiler = OutlineOTFCompiler(testufo)
compiler.compile()
post = compiler.otf["post"].underlinePosition
cff = compiler.otf["CFF "].cff
cff_underline = cff[list(cff.keys())[0]].UnderlinePosition
assert post == -485
assert cff_underline == -506
class GlyphOrderTest:
def test_compile_original_glyph_order(self, quadufo):
DEFAULT_ORDER = [
".notdef",
"space",
"a",
"b",
"c",
"d",
"e",
"f",
"g",
"h",
"i",
"j",
"k",
"l",
]
compiler = OutlineTTFCompiler(quadufo)
compiler.compile()
assert compiler.otf.getGlyphOrder() == DEFAULT_ORDER
def test_compile_tweaked_glyph_order(self, quadufo):
NEW_ORDER = [
".notdef",
"space",
"b",
"a",
"c",
"d",
"e",
"f",
"g",
"h",
"i",
"j",
"k",
"l",
]
quadufo.lib["public.glyphOrder"] = NEW_ORDER
compiler = OutlineTTFCompiler(quadufo)
compiler.compile()
assert compiler.otf.getGlyphOrder() == NEW_ORDER
def test_compile_strange_glyph_order(self, quadufo):
"""Move space and .notdef to end of glyph ids
ufo2ft always puts .notdef first.
"""
NEW_ORDER = ["b", "a", "c", "d", "space", ".notdef"]
EXPECTED_ORDER = [
".notdef",
"b",
"a",
"c",
"d",
"space",
"e",
"f",
"g",
"h",
"i",
"j",
"k",
"l",
]
quadufo.lib["public.glyphOrder"] = NEW_ORDER
compiler = OutlineTTFCompiler(quadufo)
compiler.compile()
assert compiler.otf.getGlyphOrder() == EXPECTED_ORDER
class NamesTest:
@pytest.mark.parametrize(
"prod_names_key, prod_names_value",
[(USE_PRODUCTION_NAMES, False), (GLYPHS_DONT_USE_PRODUCTION_NAMES, True)],
ids=["useProductionNames", "Don't use Production Names"],
)
def test_compile_without_production_names(
self, testufo, prod_names_key, prod_names_value
):
expected = [
".notdef",
"space",
"a",
"b",
"c",
"d",
"e",
"f",
"g",
"h",
"i",
"j",
"k",
"l",
]
result = compileTTF(testufo, useProductionNames=False)
assert result.getGlyphOrder() == expected
testufo.lib[prod_names_key] = prod_names_value
result = compileTTF(testufo)
assert result.getGlyphOrder() == expected
def test_compile_with_production_names(self, testufo):
original = [
".notdef",
"space",
"a",
"b",
"c",
"d",
"e",
"f",
"g",
"h",
"i",
"j",
"k",
"l",
]
modified = [
".notdef",
"uni0020",
"uni0061",
"uni0062",
"uni0063",
"uni0064",
"uni0065",
"uni0066",
"uni0067",
"uni0068",
"uni0069",
"uni006A",
"uni006B",
"uni006C",
]
result = compileTTF(testufo)
assert result.getGlyphOrder() == original
result = compileTTF(testufo, useProductionNames=True)
assert result.getGlyphOrder() == modified
testufo.lib[USE_PRODUCTION_NAMES] = True
result = compileTTF(testufo)
assert result.getGlyphOrder() == modified
def test_postprocess_production_names_no_notdef(self, testufo):
import ufo2ft
del testufo[".notdef"]
assert ".notdef" not in testufo
result = compileTTF(testufo, useProductionNames=False)
assert ".notdef" in result.getGlyphOrder()
pp = ufo2ft.postProcessor.PostProcessor(result, testufo, glyphSet=None)
try:
f = pp.process(useProductionNames=True)
except Exception as e:
pytest.xfail("Unexpected exception: " + str(e))
assert ".notdef" in f.getGlyphOrder()
CUSTOM_POSTSCRIPT_NAMES = {
".notdef": ".notdef",
"space": "foo",
"a": "bar",
"b": "baz",
"c": "meh",
"d": "doh",
"e": "bim",
"f": "bum",
"g": "bam",
"h": "bib",
"i": "bob",
"j": "bub",
"k": "kkk",
"l": "lll",
}
@pytest.mark.parametrize("use_production_names", [None, True])
def test_compile_with_custom_postscript_names(self, testufo, use_production_names):
testufo.lib["public.postscriptNames"] = self.CUSTOM_POSTSCRIPT_NAMES
result = compileTTF(testufo, useProductionNames=use_production_names)
assert sorted(result.getGlyphOrder()) == sorted(
self.CUSTOM_POSTSCRIPT_NAMES.values()
)
@pytest.mark.parametrize("use_production_names", [None, True])
def test_compile_with_custom_postscript_names_notdef_preserved(
self, testufo, use_production_names
):
custom_names = dict(self.CUSTOM_POSTSCRIPT_NAMES)
del custom_names[".notdef"]
testufo.lib["public.postscriptNames"] = custom_names
result = compileTTF(testufo, useProductionNames=use_production_names)
assert result.getGlyphOrder() == [
".notdef",
"foo",
"bar",
"baz",
"meh",
"doh",
"bim",
"bum",
"bam",
"bib",
"bob",
"bub",
"kkk",
"lll",
]
def test_warn_name_exceeds_max_length(self, testufo, caplog):
long_name = 64 * "a"
testufo.newGlyph(long_name)
with caplog.at_level(logging.WARNING, logger="ufo2ft.postProcessor"):
result = compileTTF(testufo, useProductionNames=True)
assert "length exceeds 63 characters" in caplog.text
assert long_name in result.getGlyphOrder()
def test_duplicate_glyph_names(self, testufo):
order = ["ab", "ab.1", "a-b", "a/b", "ba"]
testufo.lib["public.glyphOrder"] = order
testufo.lib["public.postscriptNames"] = {"ba": "ab"}
for name in order:
if name not in testufo:
testufo.newGlyph(name)
result = compileTTF(testufo, useProductionNames=True).getGlyphOrder()
assert result[1] == "ab"
assert result[2] == "ab.1"
assert result[3] == "ab.2"
assert result[4] == "ab.3"
assert result[5] == "ab.4"
def test_too_long_production_name(self, testufo):
name = "_".join(("a",) * 16)
testufo.newGlyph(name)
result = compileTTF(testufo, useProductionNames=True).getGlyphOrder()
# the production name uniXXXX would exceed the max length so the
# original name is used
assert name in result
class ColrCpalTest:
def test_colr_cpal(self, FontClass):
testufo = FontClass(getpath("ColorTest.ufo"))
assert "com.github.googlei18n.ufo2ft.colorLayerMapping" in testufo.lib
assert "com.github.googlei18n.ufo2ft.colorPalettes" in testufo.lib
result = compileTTF(testufo)
assert "COLR" in result
assert "CPAL" in result
layers = {
gn: [(layer.name, layer.colorID) for layer in layers]
for gn, layers in result["COLR"].ColorLayers.items()
}
assert layers == {
"a": [("a.color1", 0), ("a.color2", 1)],
"b": [("b.color1", 1), ("b.color2", 0)],
"c": [("c.color2", 1), ("c.color1", 0)],
}
def test_colr_cpal_raw(self, FontClass):
testufo = FontClass(getpath("ColorTestRaw.ufo"))
assert "com.github.googlei18n.ufo2ft.colorLayers" in testufo.lib
assert "com.github.googlei18n.ufo2ft.colorPalettes" in testufo.lib
result = compileTTF(testufo)
palettes = [
[(c.red, c.green, c.blue, c.alpha) for c in p]
for p in result["CPAL"].palettes
]
assert palettes == [[(255, 76, 26, 255), (0, 102, 204, 255)]]
layers = {
gn: [(layer.name, layer.colorID) for layer in layers]
for gn, layers in result["COLR"].ColorLayers.items()
}
assert layers == {"a": [("a.color1", 0), ("a.color2", 1)]}
def test_colr_cpal_otf(self, FontClass):
testufo = FontClass(getpath("ColorTest.ufo"))
assert "com.github.googlei18n.ufo2ft.colorLayerMapping" in testufo.lib
assert "com.github.googlei18n.ufo2ft.colorPalettes" in testufo.lib
result = compileOTF(testufo)
assert "COLR" in result
assert "CPAL" in result
layers = {
gn: [(layer.name, layer.colorID) for layer in layers]
for gn, layers in result["COLR"].ColorLayers.items()
}
assert layers == {
"a": [("a.color1", 0), ("a.color2", 1)],
"b": [("b.color1", 1), ("b.color2", 0)],
"c": [("c.color2", 1), ("c.color1", 0)],
}
def test_colr_cpal_interpolatable_ttf(self, FontClass):
testufo = FontClass(getpath("ColorTest.ufo"))
assert "com.github.googlei18n.ufo2ft.colorLayerMapping" in testufo.lib
assert "com.github.googlei18n.ufo2ft.colorPalettes" in testufo.lib
result = list(compileInterpolatableTTFs([testufo]))[0]
assert "COLR" in result
assert "CPAL" in result
layers = {
gn: [(layer.name, layer.colorID) for layer in layers]
for gn, layers in result["COLR"].ColorLayers.items()
}
assert layers == {
"a": [("a.color1", 0), ("a.color2", 1)],
"b": [("b.color1", 1), ("b.color2", 0)],
"c": [("c.color2", 1), ("c.color1", 0)],
}
def test_colr_cpal_gid1_not_blank(self, FontClass, caplog):
# https://github.com/MicrosoftDocs/typography-issues/issues/346
testufo = FontClass(getpath("ColorTest.ufo"))
del testufo["space"]
with caplog.at_level(logging.WARNING, logger="ufo2ft.outlineCompiler"):
ttf = compileTTF(testufo)
assert ttf["COLR"].version == 0
assert ttf.getGlyphOrder()[1] == "a"
assert (
"COLRv0 might not render correctly on Windows because "
"the glyph at index 1 is not empty ('a')."
) in caplog.text
@pytest.mark.parametrize("compileFunc", [compileTTF, compileOTF])
@pytest.mark.parametrize("manualClipBoxes", [True, False])
@pytest.mark.parametrize(
"autoClipBoxes, quantization",
[
(True, 1),
(True, 32),
(True, 100),
(False, None),
],
)
def test_colrv1_computeClipBoxes(
self,
FontClass,
compileFunc,
manualClipBoxes,
autoClipBoxes,
quantization,
):
testufo = FontClass(getpath("COLRv1Test.ufo"))
assert "com.github.googlei18n.ufo2ft.colorLayers" in testufo.lib
assert "com.github.googlei18n.ufo2ft.colorPalettes" in testufo.lib
assert "com.github.googlei18n.ufo2ft.colrClipBoxes" not in testufo.lib
if manualClipBoxes:
testufo.lib["com.github.googlei18n.ufo2ft.colrClipBoxes"] = [
("a", (0, 0, 1000, 1000))
]
result = compileFunc(
testufo,
colrAutoClipBoxes=autoClipBoxes,
colrClipBoxQuantization=lambda _ufo: quantization,
)
palettes = [
[(c.red, c.green, c.blue, c.alpha) for c in p]
for p in result["CPAL"].palettes
]
assert palettes == [[(255, 76, 26, 255), (0, 102, 204, 255)]]
colr = result["COLR"].table
layers = unbuildColrV1(colr.LayerList, colr.BaseGlyphList)
assert layers == {
"a": {
"Format": 1,
"Layers": [
{
"Format": 10,
"Paint": {"Format": 2, "PaletteIndex": 0, "Alpha": 1.0},
"Glyph": "a.color1",
},
{
"Format": 10,
"Paint": {"Format": 2, "PaletteIndex": 1, "Alpha": 1.0},
"Glyph": "a.color2",
},
],
}
}
if manualClipBoxes or autoClipBoxes:
assert colr.ClipList is not None
clipBoxes = {g: clip.as_tuple() for g, clip in colr.ClipList.clips.items()}
if manualClipBoxes:
# the one that was set manually always prevails
assert clipBoxes == {"a": (0, 0, 1000, 1000)}
elif autoClipBoxes:
# the clipBox that was computed automatically
assert clipBoxes == {
"a": quantizeRect((111, 82, 485, 626), quantization)
}
else:
# no clipboxes, neither manual nor automatic
assert colr.ClipList is None
@pytest.mark.parametrize("compileFunc", [compileTTF, compileOTF])
def test_strip_color_codepoints(self, FontClass, compileFunc):
"""Test that glyphs in the color layer do not become accessible by
codepoint in the final font, given that they are copied into the default
layer as alternates.
See: https://github.com/googlefonts/ufo2ft/pull/739#issuecomment-1516075892"""
# Load a test UFO with color layers, and give a codepoint to one of the
# glyphs in those layers.
ufo = FontClass(getpath("ColorTest.ufo"))
color_glyph = ufo.layers["color1"]["a"]
color_glyph.unicode = 0x3020
# Build the UFO into a TTF or OTF.
built = compileFunc(ufo)
# Confirm that it has no entry for the codepoint above.
cmap = built.getBestCmap()
assert 0x3020 not in cmap
class CmapTest:
def test_cmap_BMP(self, testufo):
compiler = OutlineOTFCompiler(testufo)
otf = compiler.otf = TTFont(sfntVersion="OTTO")
compiler.setupTable_cmap()
assert "cmap" in otf
cmap = otf["cmap"]
assert len(cmap.tables) == 2
cmap4_0_3 = cmap.tables[0]
cmap4_3_1 = cmap.tables[1]
assert (cmap4_0_3.platformID, cmap4_0_3.platEncID) == (0, 3)
assert (cmap4_3_1.platformID, cmap4_3_1.platEncID) == (3, 1)
assert cmap4_0_3.language == cmap4_3_1.language
assert cmap4_0_3.language == 0
mapping = {c: chr(c) for c in range(0x61, 0x6D)}
mapping[0x20] = "space"
assert cmap4_0_3.cmap == cmap4_3_1.cmap
assert cmap4_0_3.cmap == mapping
def test_cmap_nonBMP_with_UVS(self, testufo):
u1F170 = testufo.newGlyph("u1F170")
u1F170.unicode = 0x1F170
testufo.newGlyph("u1F170.text")
testufo.lib["public.unicodeVariationSequences"] = {
"FE0E": {
"1F170": "u1F170.text",
},
"FE0F": {
"1F170": "u1F170",
},
}
compiler = OutlineOTFCompiler(testufo)
otf = compiler.compile()
assert "cmap" in otf
cmap = otf["cmap"]
cmap.compile(otf)
assert len(cmap.tables) == 5
cmap4_0_3 = cmap.tables[0]
cmap12_0_4 = cmap.tables[1]
cmap14_0_5 = cmap.tables[2]
cmap4_3_1 = cmap.tables[3]
cmap12_3_10 = cmap.tables[4]
assert (cmap4_0_3.platformID, cmap4_0_3.platEncID) == (0, 3)
assert (cmap4_3_1.platformID, cmap4_3_1.platEncID) == (3, 1)
assert cmap4_0_3.language == cmap4_3_1.language
assert cmap4_0_3.language == 0
mapping = {c: chr(c) for c in range(0x61, 0x6D)}
mapping[0x20] = "space"
assert cmap4_0_3.cmap == cmap4_3_1.cmap
assert cmap4_0_3.cmap == mapping
assert (cmap12_0_4.platformID, cmap12_0_4.platEncID) == (0, 4)
assert (cmap12_3_10.platformID, cmap12_3_10.platEncID) == (3, 10)
assert cmap12_0_4.language == cmap12_3_10.language
assert cmap12_0_4.language == 0
mapping[0x1F170] = "u1F170"
assert cmap12_0_4.cmap == cmap12_3_10.cmap
assert cmap12_0_4.cmap == mapping
assert (cmap14_0_5.platformID, cmap14_0_5.platEncID) == (0, 5)
assert cmap14_0_5.language == 0
assert cmap14_0_5.uvsDict == {
0xFE0E: [(0x1F170, "u1F170.text")],
0xFE0F: [(0x1F170, None)],
}
ASCII = [chr(c) for c in range(0x20, 0x7E)]
@pytest.mark.parametrize(
"unicodes, expected",
[
[ASCII + ["Þ"], {0}], # Latin 1
[ASCII + ["Ľ"], {1}], # Latin 2: Eastern Europe
[ASCII + ["Ľ", "┤"], {1, 58}], # Latin 2
[["Б"], {2}], # Cyrillic
[["Б", "Ѕ", "┤"], {2, 57}], # IBM Cyrillic
[["Б", "╜", "┤"], {2, 49}], # MS-DOS Russian
[["Ά"], {3}], # Greek
[["Ά", "½", "┤"], {3, 48}], # IBM Greek
[["Ά", "√", "┤"], {3, 60}], # Greek, former 437 G
[ASCII + ["İ"], {4}], # Turkish
[ASCII + ["İ", "┤"], {4, 56}], # IBM turkish
[["א"], {5}], # Hebrew
[["א", "√", "┤"], {5, 53}], # Hebrew
[["ر"], {6}], # Arabic
[["ر", "√"], {6, 51}], # Arabic
[["ر", "√", "┤"], {6, 51, 61}], # Arabic; ASMO 708
[ASCII + ["ŗ"], {7}], # Windows Baltic
[ASCII + ["ŗ", "┤"], {7, 59}], # MS-DOS Baltic
[ASCII + ["₫"], {8}], # Vietnamese
[["ๅ"], {16}], # Thai
[["エ"], {17}], # JIS/Japan
[["ㄅ"], {18}], # Chinese: Simplified chars
[["ㄱ"], {19}], # Korean wansung
[["央"], {20}], # Chinese: Traditional chars
[["곴"], {21}], # Korean Johab
[ASCII + ["♥"], {30}], # OEM Character Set
[ASCII + ["þ", "┤"], {54}], # MS-DOS Icelandic
[ASCII + ["╚"], {62, 63}], # WE/Latin 1
[ASCII + ["┤", "√", "Å"], {50}], # MS-DOS Nordic
[ASCII + ["┤", "√", "é"], {52}], # MS-DOS Canadian French
[ASCII + ["┤", "√", "õ"], {55}], # MS-DOS Portuguese
[ASCII + ["‰", "∑"], {29}], # Macintosh Character Set (US Roman)
[[" ", "0", "1", "2", "අ"], {0}], # always fallback to Latin 1
],
)
def test_calcCodePageRanges(emptyufo, unicodes, expected):
font = emptyufo
for i, c in enumerate(unicodes):
font.newGlyph("glyph%d" % i).unicode = ord(c)
compiler = OutlineOTFCompiler(font)
compiler.compile()
assert compiler.otf["OS/2"].ulCodePageRange1 == intListToNum(
expected, start=0, length=32
)
assert compiler.otf["OS/2"].ulCodePageRange2 == intListToNum(
expected, start=32, length=32
)
def test_custom_layer_compilation(layertestrgufo):
ufo = layertestrgufo
font_otf = compileOTF(ufo, layerName="Medium")
assert font_otf.getGlyphOrder() == [".notdef", "e"]
font_ttf = compileTTF(ufo, layerName="Medium")
assert font_ttf.getGlyphOrder() == [".notdef", "e"]
def test_custom_layer_compilation_interpolatable(layertestrgufo, layertestbdufo):
ufo1 = layertestrgufo
ufo2 = layertestbdufo
master_ttfs = list(
compileInterpolatableTTFs([ufo1, ufo1, ufo2], layerNames=[None, "Medium", None])
)
assert master_ttfs[0].getGlyphOrder() == [
".notdef",
"a",
"e",
"s",
"dotabovecomb",
"edotabove",
]
assert master_ttfs[1].getGlyphOrder() == [".notdef", "e"]
assert master_ttfs[2].getGlyphOrder() == [
".notdef",
"a",
"e",
"s",
"dotabovecomb",
"edotabove",
]
sparse_tables = [tag for tag in master_ttfs[1].keys() if tag != "GlyphOrder"]
assert SPARSE_TTF_MASTER_TABLES.issuperset(sparse_tables)
@pytest.mark.parametrize("inplace", [False, True], ids=["not inplace", "inplace"])
def test_custom_layer_compilation_interpolatable_from_ds(designspace, inplace):
result = compileInterpolatableTTFsFromDS(designspace, inplace=inplace)
assert (designspace is result) == inplace
master_ttfs = [s.font for s in result.sources]
assert master_ttfs[0].getGlyphOrder() == [
".notdef",
"a",
"e",
"s",
"dotabovecomb",
"edotabove",
]
assert master_ttfs[1].getGlyphOrder() == [".notdef", "e"]
assert master_ttfs[2].getGlyphOrder() == [
".notdef",
"a",
"e",
"s",
"dotabovecomb",
"edotabove",
]
sparse_tables = [tag for tag in master_ttfs[1].keys() if tag != "GlyphOrder"]
assert SPARSE_TTF_MASTER_TABLES.issuperset(sparse_tables)
# sentinel value used by varLib to ignore the post table for this sparse
# master when building the MVAR table
assert master_ttfs[1]["post"].underlinePosition == -0x8000
assert master_ttfs[1]["post"].underlineThickness == -0x8000
@pytest.mark.parametrize("inplace", [False, True], ids=["not inplace", "inplace"])
def test_custom_layer_compilation_interpolatable_otf_from_ds(designspace, inplace):
result = compileInterpolatableOTFsFromDS(designspace, inplace=inplace)
assert (designspace is result) == inplace
master_otfs = [s.font for s in result.sources]
assert master_otfs[0].getGlyphOrder() == [
".notdef",
"a",
"e",
"s",
"dotabovecomb",
"edotabove",
]
# 'edotabove' composite glyph needed to be decomposed because these are CFF fonts;
# and because one of its components 'e' has an additional intermediate master, the
# latter 'bubbled up' to the parent glyph when this got decomposed; hence why
# we see 'edotabove' in master_otfs[1] below, but we do not in the previous test
# with interpolatalbe TTFs where 'edotabove' stays a composite glyph.
assert master_otfs[1].getGlyphOrder() == [".notdef", "e", "edotabove"]
assert master_otfs[2].getGlyphOrder() == [
".notdef",
"a",
"e",
"s",
"dotabovecomb",
"edotabove",
]
sparse_tables = [tag for tag in master_otfs[1].keys() if tag != "GlyphOrder"]
assert SPARSE_OTF_MASTER_TABLES.issuperset(sparse_tables)
def test_compilation_from_ds_missing_source_font(designspace):
designspace.sources[0].font = None
with pytest.raises(AttributeError, match="missing required 'font'"):
compileInterpolatableTTFsFromDS(designspace)
def test_compile_empty_ufo(FontClass):
ufo = FontClass()
font = compileTTF(ufo)
assert font["name"].getName(1, 3, 1).toUnicode() == "New Font"
assert font["name"].getName(2, 3, 1).toUnicode() == "Regular"
assert font["name"].getName(4, 3, 1).toUnicode() == "New Font Regular"
assert font["head"].unitsPerEm == 1000
assert font["OS/2"].sTypoAscender == 800
assert font["OS/2"].sCapHeight == 700
assert font["OS/2"].sxHeight == 500
assert font["OS/2"].sTypoDescender == -200
def test_pass_on_conversion_error(FontClass):
ufo = FontClass()
ufo.info.unitsPerEm = 2000
# Draw quarter circle
glyph = ufo.newGlyph("test")
pen = glyph.getPointPen()
pen.beginPath()
pen.addPoint((0, 43), segmentType="line")
pen.addPoint((25, 43))
pen.addPoint((43, 25))
pen.addPoint((43, 0), segmentType="curve")
pen.addPoint((0, 0), segmentType="line")
pen.endPath()
font1 = compileTTF(ufo) # Default error: 0.001
font2 = compileTTF(ufo, cubicConversionError=0.0005)
# One off-curve:
font1_coords = list(font1["glyf"]["test"].coordinates)
assert font1_coords == [(0, 43), (0, 0), (43, 0), (43, 43)]
# Two off-curves:
font2_coords = list(font2["glyf"]["test"].coordinates)
assert font2_coords == [(0, 43), (0, 0), (43, 0), (43, 19), (19, 43)]
@pytest.mark.parametrize("CompilerClass", [OutlineOTFCompiler, OutlineTTFCompiler])
@pytest.mark.parametrize(
"vendorID, expected",
[
("A", "A "),
("AA", "AA "),
("AAA", "AAA "),
("AAAA", "AAAA"),
],
)
def test_achVendId_space_padded_if_less_than_4_chars(
FontClass, CompilerClass, vendorID, expected
):
ufo = FontClass()
ufo.info.openTypeOS2VendorID = vendorID
font = CompilerClass(ufo).compile()
tmp = BytesIO()
font.save(tmp)
font = TTFont(tmp)
assert font["OS/2"].achVendID == expected
@pytest.mark.parametrize("compile", [compileTTF, compileOTF])
def test_MATH_table(FontClass, compile):
ufo = FontClass(getpath("TestMathFont-Regular.ufo"))
result = compile(ufo)
assert "MATH" in result
math = result["MATH"].table
for key, value in ufo.lib[GLYPHS_MATH_CONSTANTS_KEY].items():
attr = getattr(math.MathConstants, key)
if isinstance(attr, int):
assert attr == value
else:
assert attr.Value == value
extendedShapes = set(ufo.lib[GLYPHS_MATH_EXTENDED_SHAPE_KEY])
for glyph in ufo.lib[GLYPHS_MATH_EXTENDED_SHAPE_KEY]:
if variants := ufo[glyph].lib.get(GLYPHS_MATH_VARIANTS_KEY):
extendedShapes.update(variants.get("vVariants", []))
assert set(math.MathGlyphInfo.ExtendedShapeCoverage.glyphs) == extendedShapes
assert set(math.MathVariants.VertGlyphCoverage.glyphs) == {
"parenright",
"parenleft",
}
assert math.MathVariants.VertGlyphConstruction
assert len(math.MathVariants.VertGlyphConstruction) == 2
assert (
math.MathVariants.VertGlyphConstruction[0].GlyphAssembly.ItalicsCorrection.Value
== 0
)
assert (
len(math.MathVariants.VertGlyphConstruction[0].GlyphAssembly.PartRecords) == 3
)
assert not math.MathVariants.HorizGlyphCoverage
assert not math.MathVariants.HorizGlyphConstruction
@pytest.mark.parametrize("compile", [compileTTF, compileOTF])
@pytest.mark.parametrize(
"attribute",
[
"vAssembly",
"hAssembly",
"vVariants",
"hVariants",
],
)
def test_MATH_table_ignore_empty(FontClass, compile, attribute):
# Should not raise becaise of empty assembly/variants
ufo = FontClass(getpath("TestMathFont-Regular.ufo"))
ufo["parenright"].lib[GLYPHS_MATH_VARIANTS_KEY][attribute] = []
compile(ufo)
@pytest.mark.parametrize("compile", [compileTTF, compileOTF])
@pytest.mark.parametrize("attribute", ["vAssembly", "hAssembly"])
def test_MATH_table_invalid(FontClass, compile, attribute):
ufo = FontClass(getpath("TestMathFont-Regular.ufo"))
ufo["parenright"].lib[GLYPHS_MATH_VARIANTS_KEY][attribute] = [
["parenright.top", 0, 0],
["parenright.ext", 1, 100, 100],
["parenright.bot", 0, 100, 0],
]
with pytest.raises(InvalidFontData, match="Invalid assembly"):
compile(ufo)
@pytest.mark.parametrize("compile", [compileTTF, compileOTF])
def test_CMAP_format_14_table_no_cmap_entry(FontClass, compile):
#
# https://github.com/googlefonts/ufo2ft/issues/908
#
# Typically, code points listed in the uvsMappings array will have corresponding
# entries in a Unicode 'cmap' subtable. This is not required, however.
# In Bug908.ufo, the font maps U+20122 U+FE00 to U+2F803, but U+20122
# is not in the 'cmap' subtable.
ufo = FontClass(getpath("Bug908.ufo"))
result = compile(ufo)
cmap = result.getBestCmap()
assert 0x20122 not in cmap
if __name__ == "__main__":
import sys
sys.exit(pytest.main(sys.argv))
|