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 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413
|
# -*- coding: utf-8 -*-
# -----------------------------------------------------------------------------
#
# FreeType high-level python API - Copyright 2011-2015 Nicolas P. Rougier
# Distributed under the terms of the new BSD license.
#
# -----------------------------------------------------------------------------
'''
FreeType high-level python API
This the bindings for the high-level API of FreeType (that must be installed
somewhere on your system).
Note: C Library will be searched using the ctypes.util.find_library. However,
this search might fail. In such a case (or for other reasons), you may
have to specify an explicit path below.
'''
import io
import sys
from ctypes import *
import ctypes.util
import struct
from freetype.raw import *
# Hack to get unicode class in python3
PY3 = sys.version_info[0] == 3
if PY3: unicode = str
def unmake_tag(i):
# roughly opposite of FT_MAKE_TAG, converts 32-bit int to Python string
# could do with .to_bytes if limited to Python 3.2 or higher...
b = struct.pack('>I', i)
return b.decode('ascii', errors='replace')
_handle = None
FT_Library_filename = filename
class _FT_Library_Wrapper(FT_Library):
'''Subclass of FT_Library to help with calling FT_Done_FreeType'''
# for some reason this doesn't get carried over and ctypes complains
_type_ = FT_Library._type_
# Store ref to FT_Done_FreeType otherwise it will be deleted before needed.
_ft_done_freetype = FT_Done_FreeType
def __del__(self):
# call FT_Done_FreeType
# This does not work properly (seg fault on sime system (OSX))
# self._ft_done_freetype(self)
pass
def _init_freetype():
global _handle
_handle = _FT_Library_Wrapper()
error = FT_Init_FreeType( byref(_handle) )
if error: raise FT_Exception(error)
try:
set_lcd_filter( FT_LCD_FILTER_DEFAULT )
except:
pass
# -----------------------------------------------------------------------------
# High-level API of FreeType 2
# -----------------------------------------------------------------------------
def get_handle():
'''
Get unique FT_Library handle
'''
if not _handle:
_init_freetype()
return _handle
def version():
'''
Return the version of the FreeType library being used as a tuple of
( major version number, minor version number, patch version number )
'''
amajor = FT_Int()
aminor = FT_Int()
apatch = FT_Int()
library = get_handle()
FT_Library_Version(library, byref(amajor), byref(aminor), byref(apatch))
return (amajor.value, aminor.value, apatch.value)
# -----------------------------------------------------------------------------
# Stand alone functions
# -----------------------------------------------------------------------------
def set_lcd_filter(filt):
'''
This function is used to apply color filtering to LCD decimated bitmaps,
like the ones used when calling FT_Render_Glyph with FT_RENDER_MODE_LCD or
FT_RENDER_MODE_LCD_V.
**Note**
This feature is always disabled by default. Clients must make an explicit
call to this function with a 'filter' value other than FT_LCD_FILTER_NONE
in order to enable it.
Due to PATENTS covering subpixel rendering, this function doesn't do
anything except returning 'FT_Err_Unimplemented_Feature' if the
configuration macro FT_CONFIG_OPTION_SUBPIXEL_RENDERING is not defined in
your build of the library, which should correspond to all default builds of
FreeType.
The filter affects glyph bitmaps rendered through FT_Render_Glyph,
FT_Outline_Get_Bitmap, FT_Load_Glyph, and FT_Load_Char.
It does not affect the output of FT_Outline_Render and
FT_Outline_Get_Bitmap.
If this feature is activated, the dimensions of LCD glyph bitmaps are
either larger or taller than the dimensions of the corresponding outline
with regards to the pixel grid. For example, for FT_RENDER_MODE_LCD, the
filter adds up to 3 pixels to the left, and up to 3 pixels to the right.
The bitmap offset values are adjusted correctly, so clients shouldn't need
to modify their layout and glyph positioning code when enabling the filter.
'''
library = get_handle()
error = FT_Library_SetLcdFilter(library, filt)
if error: raise FT_Exception(error)
def set_lcd_filter_weights(a,b,c,d,e):
'''
Use this function to override the filter weights selected by
FT_Library_SetLcdFilter. By default, FreeType uses the quintuple (0x00,
0x55, 0x56, 0x55, 0x00) for FT_LCD_FILTER_LIGHT, and (0x10, 0x40, 0x70,
0x40, 0x10) for FT_LCD_FILTER_DEFAULT and FT_LCD_FILTER_LEGACY.
**Note**
Only available if version > 2.4.0
'''
if version()>=(2,4,0):
library = get_handle()
weights = FT_Char(5)(a,b,c,d,e)
error = FT_Library_SetLcdFilterWeights(library, weights)
if error: raise FT_Exception(error)
else:
raise RuntimeError(
'set_lcd_filter_weights require freetype > 2.4.0')
def _encode_filename(filename):
encoded = filename.encode(sys.getfilesystemencoding())
if "?" not in filename and b"?" in encoded:
# A bug, decoding mbcs always ignore exception, still isn't fixed in Python 2,
# view http://bugs.python.org/issue850997 for detail
raise UnicodeError()
return encoded
# -----------------------------------------------------------------------------
# Direct wrapper (simple renaming)
# -----------------------------------------------------------------------------
Vector = FT_Vector
Matrix = FT_Matrix
# -----------------------------------------------------------------------------
# Handling for FT_Done_MM_Var, which was added in FreeType 2.9. Prior to that,
# we need to import libc and use libc free on the memory allocated for the
# FT_MM_Var data structure. See Face.get_variation_info().
# -----------------------------------------------------------------------------
if version() < (2,9,1):
if platform.system() == "Windows":
libcpath = ctypes.util.find_library("msvcrt")
else:
libcpath = ctypes.util.find_library("c")
libc = CDLL(libcpath)
libc.free.argtypes = [c_void_p]
libc.free.restype = None
def FT_Done_MM_Var_func(p):
libc.free(p)
else:
def FT_Done_MM_Var_func(p):
error = FT_Done_MM_Var(get_handle(), p)
if error:
raise FT_Exception("Failure calling FT_Done_MM_Var")
# -----------------------------------------------------------------------------
class BBox( object ):
'''
FT_BBox wrapper.
A structure used to hold an outline's bounding box, i.e., the coordinates
of its extrema in the horizontal and vertical directions.
**Note**
The bounding box is specified with the coordinates of the lower left and
the upper right corner. In PostScript, those values are often called
(llx,lly) and (urx,ury), respectively.
If 'yMin' is negative, this value gives the glyph's descender. Otherwise,
the glyph doesn't descend below the baseline. Similarly, if 'ymax' is
positive, this value gives the glyph's ascender.
'xMin' gives the horizontal distance from the glyph's origin to the left
edge of the glyph's bounding box. If 'xMin' is negative, the glyph
extends to the left of the origin.
'''
def __init__(self, bbox):
'''
Create a new BBox object.
:param bbox: a FT_BBox or a tuple of 4 values
'''
if type(bbox) is FT_BBox:
self._FT_BBox = bbox
else:
self._FT_BBox = FT_BBox(*bbox)
xMin = property(lambda self: self._FT_BBox.xMin,
doc = 'The horizontal minimum (left-most).')
yMin = property(lambda self: self._FT_BBox.yMin,
doc = 'The vertical minimum (bottom-most).')
xMax = property(lambda self: self._FT_BBox.xMax,
doc = 'The horizontal maximum (right-most).')
yMax = property(lambda self: self._FT_BBox.yMax,
doc = 'The vertical maximum (top-most).')
# -----------------------------------------------------------------------------
class GlyphMetrics( object ):
'''
A structure used to model the metrics of a single glyph. The values are
expressed in 26.6 fractional pixel format; if the flag FT_LOAD_NO_SCALE has
been used while loading the glyph, values are expressed in font units
instead.
**Note**
If not disabled with FT_LOAD_NO_HINTING, the values represent dimensions of
the hinted glyph (in case hinting is applicable).
Stroking a glyph with an outside border does not increase ‘horiAdvance’ or
‘vertAdvance’; you have to manually adjust these values to account for the
added width and height.
'''
def __init__(self, metrics ):
'''
Create a new GlyphMetrics object.
:param metrics: a FT_Glyph_Metrics
'''
self._FT_Glyph_Metrics = metrics
width = property( lambda self: self._FT_Glyph_Metrics.width,
doc = '''The glyph's width.''' )
height = property( lambda self: self._FT_Glyph_Metrics.height,
doc = '''The glyph's height.''' )
horiBearingX = property( lambda self: self._FT_Glyph_Metrics.horiBearingX,
doc = '''Left side bearing for horizontal layout.''' )
horiBearingY = property( lambda self: self._FT_Glyph_Metrics.horiBearingY,
doc = '''Top side bearing for horizontal layout.''' )
horiAdvance = property( lambda self: self._FT_Glyph_Metrics.horiAdvance,
doc = '''Advance width for horizontal layout.''' )
vertBearingX = property( lambda self: self._FT_Glyph_Metrics.vertBearingX,
doc = '''Left side bearing for vertical layout.''' )
vertBearingY = property( lambda self: self._FT_Glyph_Metrics.vertBearingY,
doc = '''Top side bearing for vertical layout. Larger positive values
mean further below the vertical glyph origin.''' )
vertAdvance = property( lambda self: self._FT_Glyph_Metrics.vertAdvance,
doc = '''Advance height for vertical layout. Positive values mean the
glyph has a positive advance downward.''' )
# -----------------------------------------------------------------------------
class SizeMetrics( object ):
'''
The size metrics structure gives the metrics of a size object.
**Note**
The scaling values, if relevant, are determined first during a size
changing operation. The remaining fields are then set by the driver. For
scalable formats, they are usually set to scaled values of the
corresponding fields in Face.
Note that due to glyph hinting, these values might not be exact for certain
fonts. Thus they must be treated as unreliable with an error margin of at
least one pixel!
Indeed, the only way to get the exact metrics is to render all glyphs. As
this would be a definite performance hit, it is up to client applications
to perform such computations.
The SizeMetrics structure is valid for bitmap fonts also.
'''
def __init__(self, metrics ):
'''
Create a new SizeMetrics object.
:param metrics: a FT_SizeMetrics
'''
self._FT_Size_Metrics = metrics
x_ppem = property( lambda self: self._FT_Size_Metrics.x_ppem,
doc = '''The width of the scaled EM square in pixels, hence the term
'ppem' (pixels per EM). It is also referred to as 'nominal
width'.''' )
y_ppem = property( lambda self: self._FT_Size_Metrics.y_ppem,
doc = '''The height of the scaled EM square in pixels, hence the term
'ppem' (pixels per EM). It is also referred to as 'nominal
height'.''' )
x_scale = property( lambda self: self._FT_Size_Metrics.x_scale,
doc = '''A 16.16 fractional scaling value used to convert horizontal
metrics from font units to 26.6 fractional pixels. Only
relevant for scalable font formats.''' )
y_scale = property( lambda self: self._FT_Size_Metrics.y_scale,
doc = '''A 16.16 fractional scaling value used to convert vertical
metrics from font units to 26.6 fractional pixels. Only
relevant for scalable font formats.''' )
ascender = property( lambda self: self._FT_Size_Metrics.ascender,
doc = '''The ascender in 26.6 fractional pixels. See Face for the
details.''' )
descender = property( lambda self: self._FT_Size_Metrics.descender,
doc = '''The descender in 26.6 fractional pixels. See Face for the
details.''' )
height = property( lambda self: self._FT_Size_Metrics.height,
doc = '''The height in 26.6 fractional pixels. See Face for the details.''' )
max_advance = property(lambda self: self._FT_Size_Metrics.max_advance,
doc = '''The maximal advance width in 26.6 fractional pixels. See
Face for the details.''' )
# -----------------------------------------------------------------------------
class BitmapSize( object ):
'''
FT_Bitmap_Size wrapper
This structure models the metrics of a bitmap strike (i.e., a set of glyphs
for a given point size and resolution) in a bitmap font. It is used for the
'available_sizes' field of Face.
**Note**
Windows FNT: The nominal size given in a FNT font is not reliable. Thus
when the driver finds it incorrect, it sets 'size' to some calculated
values and sets 'x_ppem' and 'y_ppem' to the pixel width and height given
in the font, respectively.
TrueType embedded bitmaps: 'size', 'width', and 'height' values are not
contained in the bitmap strike itself. They are computed from the global
font parameters.
'''
def __init__(self, size ):
'''
Create a new SizeMetrics object.
:param size: a FT_Bitmap_Size
'''
self._FT_Bitmap_Size = size
height = property( lambda self: self._FT_Bitmap_Size.height,
doc = '''The vertical distance, in pixels, between two consecutive
baselines. It is always positive.''')
width = property( lambda self: self._FT_Bitmap_Size.width,
doc = '''The average width, in pixels, of all glyphs in the strike.''')
size = property( lambda self: self._FT_Bitmap_Size.size,
doc = '''The nominal size of the strike in 26.6 fractional points. This
field is not very useful.''')
x_ppem = property( lambda self: self._FT_Bitmap_Size.x_ppem,
doc = '''The horizontal ppem (nominal width) in 26.6 fractional
pixels.''')
y_ppem = property( lambda self: self._FT_Bitmap_Size.y_ppem,
doc = '''The vertical ppem (nominal width) in 26.6 fractional
pixels.''')
# -----------------------------------------------------------------------------
class Bitmap(object):
'''
FT_Bitmap wrapper
A structure used to describe a bitmap or pixmap to the raster. Note that we
now manage pixmaps of various depths through the 'pixel_mode' field.
*Note*:
For now, the only pixel modes supported by FreeType are mono and
grays. However, drivers might be added in the future to support more
'colorful' options.
'''
def __init__(self, bitmap):
'''
Create a new Bitmap object.
:param bitmap: a FT_Bitmap
'''
self._FT_Bitmap = bitmap
rows = property(lambda self: self._FT_Bitmap.rows,
doc = '''The number of bitmap rows.''')
width = property(lambda self: self._FT_Bitmap.width,
doc = '''The number of pixels in bitmap row.''')
pitch = property(lambda self: self._FT_Bitmap.pitch,
doc = '''The pitch's absolute value is the number of bytes taken by one
bitmap row, including padding. However, the pitch is positive
when the bitmap has a 'down' flow, and negative when it has an
'up' flow. In all cases, the pitch is an offset to add to a
bitmap pointer in order to go down one row.
Note that 'padding' means the alignment of a bitmap to a byte
border, and FreeType functions normally align to the smallest
possible integer value.
For the B/W rasterizer, 'pitch' is always an even number.
To change the pitch of a bitmap (say, to make it a multiple of
4), use FT_Bitmap_Convert. Alternatively, you might use callback
functions to directly render to the application's surface; see
the file 'example2.py' in the tutorial for a demonstration.''')
def _get_buffer(self):
data = [self._FT_Bitmap.buffer[i] for i in range(self.rows*self.pitch)]
return data
buffer = property(_get_buffer,
doc = '''A typeless pointer to the bitmap buffer. This value should be
aligned on 32-bit boundaries in most cases.''')
num_grays = property(lambda self: self._FT_Bitmap.num_grays,
doc = '''This field is only used with FT_PIXEL_MODE_GRAY; it gives
the number of gray levels used in the bitmap.''')
pixel_mode = property(lambda self: self._FT_Bitmap.pixel_mode,
doc = '''The pixel mode, i.e., how pixel bits are stored. See
FT_Pixel_Mode for possible values.''')
palette_mode = property(lambda self: self._FT_Bitmap.palette_mode,
doc ='''This field is intended for paletted pixel modes; it
indicates how the palette is stored. Not used currently.''')
palette = property(lambda self: self._FT_Bitmap.palette,
doc = '''A typeless pointer to the bitmap palette; this field is
intended for paletted pixel modes. Not used currently.''')
# -----------------------------------------------------------------------------
class Charmap( object ):
'''
FT_Charmap wrapper.
A handle to a given character map. A charmap is used to translate character
codes in a given encoding into glyph indexes for its parent's face. Some
font formats may provide several charmaps per font.
Each face object owns zero or more charmaps, but only one of them can be
'active' and used by FT_Get_Char_Index or FT_Load_Char.
The list of available charmaps in a face is available through the
'face.num_charmaps' and 'face.charmaps' fields of FT_FaceRec.
The currently active charmap is available as 'face.charmap'. You should
call FT_Set_Charmap to change it.
**Note**:
When a new face is created (either through FT_New_Face or FT_Open_Face),
the library looks for a Unicode charmap within the list and automatically
activates it.
**See also**:
See FT_CharMapRec for the publicly accessible fields of a given character
map.
'''
def __init__( self, charmap ):
'''
Create a new Charmap object.
Parameters:
-----------
charmap : a FT_Charmap
'''
self._FT_Charmap = charmap
encoding = property( lambda self: self._FT_Charmap.contents.encoding,
doc = '''An FT_Encoding tag identifying the charmap. Use this with
FT_Select_Charmap.''')
platform_id = property( lambda self: self._FT_Charmap.contents.platform_id,
doc = '''An ID number describing the platform for the following
encoding ID. This comes directly from the TrueType
specification and should be emulated for other
formats.''')
encoding_id = property( lambda self: self._FT_Charmap.contents.encoding_id,
doc = '''A platform specific encoding number. This also comes from
the TrueType specification and should be emulated
similarly.''')
def _get_encoding_name(self):
encoding = self.encoding
for key,value in FT_ENCODINGS.items():
if encoding == value:
return key
return 'Unknown encoding'
encoding_name = property( _get_encoding_name,
doc = '''A platform specific encoding name. This also comes from
the TrueType specification and should be emulated
similarly.''')
def _get_index( self ):
return FT_Get_Charmap_Index( self._FT_Charmap )
index = property( _get_index,
doc = '''The index into the array of character maps within the face to
which 'charmap' belongs. If an error occurs, -1 is returned.''')
def _get_cmap_language_id( self ):
return FT_Get_CMap_Language_ID( self._FT_Charmap )
cmap_language_id = property( _get_cmap_language_id,
doc = '''The language ID of 'charmap'. If 'charmap' doesn't
belong to a TrueType/sfnt face, just return 0 as the
default value.''')
def _get_cmap_format( self ):
return FT_Get_CMap_Format( self._FT_Charmap )
cmap_format = property( _get_cmap_format,
doc = '''The format of 'charmap'. If 'charmap' doesn't belong to a
TrueType/sfnt face, return -1.''')
# -----------------------------------------------------------------------------
class Outline( object ):
'''
FT_Outline wrapper.
This structure is used to describe an outline to the scan-line converter.
'''
def __init__( self, outline ):
'''
Create a new Outline object.
:param charmap: a FT_Outline
'''
self._FT_Outline = outline
n_contours = property(lambda self: self._FT_Outline.n_contours)
def _get_contours(self):
n = self._FT_Outline.n_contours
data = [self._FT_Outline.contours[i] for i in range(n)]
return data
contours = property(_get_contours,
doc = '''The number of contours in the outline.''')
n_points = property(lambda self: self._FT_Outline.n_points)
def _get_points(self):
n = self._FT_Outline.n_points
data = []
for i in range(n):
v = self._FT_Outline.points[i]
data.append( (v.x,v.y) )
return data
points = property( _get_points,
doc = '''The number of points in the outline.''')
def _get_tags(self):
n = self._FT_Outline.n_points
data = [self._FT_Outline.tags[i] for i in range(n)]
return data
tags = property(_get_tags,
doc = '''A list of 'n_points' chars, giving each outline point's type.
If bit 0 is unset, the point is 'off' the curve, i.e., a Bezier
control point, while it is 'on' if set.
Bit 1 is meaningful for 'off' points only. If set, it indicates a
third-order Bezier arc control point; and a second-order control
point if unset.
If bit 2 is set, bits 5-7 contain the drop-out mode (as defined
in the OpenType specification; the value is the same as the
argument to the SCANMODE instruction).
Bits 3 and 4 are reserved for internal purposes.''')
flags = property(lambda self: self._FT_Outline.flags,
doc = '''A set of bit flags used to characterize the outline and give
hints to the scan-converter and hinter on how to
convert/grid-fit it. See FT_OUTLINE_FLAGS.''')
def get_inside_border( self ):
'''
Retrieve the FT_StrokerBorder value corresponding to the 'inside'
borders of a given outline.
:return: The border index. FT_STROKER_BORDER_RIGHT for empty or invalid
outlines.
'''
return FT_Outline_GetInsideBorder( byref(self._FT_Outline) )
def get_outside_border( self ):
'''
Retrieve the FT_StrokerBorder value corresponding to the 'outside'
borders of a given outline.
:return: The border index. FT_STROKER_BORDER_RIGHT for empty or invalid
outlines.
'''
return FT_Outline_GetOutsideBorder( byref(self._FT_Outline) )
def get_bbox(self):
'''
Compute the exact bounding box of an outline. This is slower than
computing the control box. However, it uses an advanced algorithm which
returns very quickly when the two boxes coincide. Otherwise, the
outline Bezier arcs are traversed to extract their extrema.
'''
bbox = FT_BBox()
error = FT_Outline_Get_BBox(byref(self._FT_Outline), byref(bbox))
if error: raise FT_Exception(error)
return BBox(bbox)
def get_cbox(self):
'''
Return an outline's 'control box'. The control box encloses all the
outline's points, including Bezier control points. Though it coincides
with the exact bounding box for most glyphs, it can be slightly larger
in some situations (like when rotating an outline which contains Bezier
outside arcs).
Computing the control box is very fast, while getting the bounding box
can take much more time as it needs to walk over all segments and arcs
in the outline. To get the latter, you can use the 'ftbbox' component
which is dedicated to this single task.
'''
bbox = FT_BBox()
FT_Outline_Get_CBox(byref(self._FT_Outline), byref(bbox))
return BBox(bbox)
_od_move_to_noop = FT_Outline_MoveToFunc(lambda a, b: 0)
def _od_move_to_builder(self, cb):
if cb is None:
return self._od_move_to_noop
def move_to(a, b):
return cb(a[0], b) or 0
return FT_Outline_MoveToFunc(move_to)
_od_line_to_noop = FT_Outline_LineToFunc(lambda a, b: 0)
def _od_line_to_builder(self, cb):
if cb is None:
return self._od_line_to_noop
def line_to(a, b):
return cb(a[0], b) or 0
return FT_Outline_LineToFunc(line_to)
_od_conic_to_noop = FT_Outline_ConicToFunc(lambda a, b, c: 0)
def _od_conic_to_builder(self, cb):
if cb is None:
return self._od_conic_to_noop
def conic_to(a, b, c):
return cb(a[0], b[0], c) or 0
return FT_Outline_ConicToFunc(conic_to)
_od_cubic_to_noop = FT_Outline_CubicToFunc(lambda a, b, c, d: 0)
def _od_cubic_to_builder(self, cb):
if cb is None:
return self._od_cubic_to_noop
def cubic_to(a, b, c, d):
return cb(a[0], b[0], c[0], d) or 0
return FT_Outline_CubicToFunc(cubic_to)
def decompose(self, context=None, move_to=None, line_to=None, conic_to=None, cubic_to=None, shift=0, delta=0):
'''
Decompose the outline into a sequence of move, line, conic, and
cubic segments.
:param context: Arbitrary contextual object which will be passed as
the last parameter of all callbacks. Typically an
object to be drawn to, but can be anything.
:param move_to: Callback which will be passed an `FT_Vector`
control point and the context. Called when outline
needs to jump to a new path component.
:param line_to: Callback which will be passed an `FT_Vector`
control point and the context. Called to draw a
straight line from the current position to the
control point.
:param conic_to: Callback which will be passed two `FT_Vector`
control points and the context. Called to draw a
second-order Bézier curve from the current
position using the passed control points.
:param curve_to: Callback which will be passed three `FT_Vector`
control points and the context. Called to draw a
third-order Bézier curve from the current position
using the passed control points.
:param shift: Passed to FreeType which will transform vectors via
`x = (x << shift) - delta` and `y = (y << shift) - delta`
:param delta: Passed to FreeType which will transform vectors via
`x = (x << shift) - delta` and `y = (y << shift) - delta`
:since: 1.3
'''
func = FT_Outline_Funcs(
move_to = self._od_move_to_builder(move_to),
line_to = self._od_line_to_builder(line_to),
conic_to = self._od_conic_to_builder(conic_to),
cubic_to = self._od_cubic_to_builder(cubic_to),
shift = shift,
delta = FT_Pos(delta),
)
error = FT_Outline_Decompose( byref(self._FT_Outline), byref(func), py_object(context) )
if error: raise FT_Exception( error )
# -----------------------------------------------------------------------------
class Glyph( object ):
'''
FT_Glyph wrapper.
The root glyph structure contains a given glyph image plus its advance
width in 16.16 fixed float format.
'''
def __init__( self, glyph ):
'''
Create Glyph object from an FT glyph.
:param glyph: valid FT_Glyph object
'''
self._FT_Glyph = glyph
def __del__( self ):
'''
Destroy glyph.
'''
FT_Done_Glyph( self._FT_Glyph )
def _get_format( self ):
return self._FT_Glyph.contents.format
format = property( _get_format,
doc = '''The format of the glyph's image.''')
def stroke( self, stroker, destroy=False ):
'''
Stroke a given outline glyph object with a given stroker.
:param stroker: A stroker handle.
:param destroy: A Boolean. If 1, the source glyph object is destroyed on
success.
**Note**:
The source glyph is untouched in case of error.
'''
error = FT_Glyph_Stroke( byref(self._FT_Glyph),
stroker._FT_Stroker, destroy )
if error: raise FT_Exception( error )
def to_bitmap( self, mode, origin, destroy=False ):
'''
Convert a given glyph object to a bitmap glyph object.
:param mode: An enumeration that describes how the data is rendered.
:param origin: A pointer to a vector used to translate the glyph image
before rendering. Can be 0 (if no translation). The origin is
expressed in 26.6 pixels.
We also detect a plain vector and make a pointer out of it,
if that's the case.
:param destroy: A boolean that indicates that the original glyph image
should be destroyed by this function. It is never destroyed
in case of error.
**Note**:
This function does nothing if the glyph format isn't scalable.
The glyph image is translated with the 'origin' vector before
rendering.
The first parameter is a pointer to an FT_Glyph handle, that will be
replaced by this function (with newly allocated data). Typically, you
would use (omitting error handling):
'''
if ( type(origin) == FT_Vector ):
error = FT_Glyph_To_Bitmap( byref(self._FT_Glyph),
mode, byref(origin), destroy )
else:
error = FT_Glyph_To_Bitmap( byref(self._FT_Glyph),
mode, origin, destroy )
if error: raise FT_Exception( error )
return BitmapGlyph( self._FT_Glyph )
def get_cbox(self, bbox_mode):
'''
Return an outline's 'control box'. The control box encloses all the
outline's points, including Bezier control points. Though it coincides
with the exact bounding box for most glyphs, it can be slightly larger
in some situations (like when rotating an outline which contains Bezier
outside arcs).
Computing the control box is very fast, while getting the bounding box
can take much more time as it needs to walk over all segments and arcs
in the outline. To get the latter, you can use the 'ftbbox' component
which is dedicated to this single task.
:param mode: The mode which indicates how to interpret the returned
bounding box values.
**Note**:
Coordinates are relative to the glyph origin, using the y upwards
convention.
If the glyph has been loaded with FT_LOAD_NO_SCALE, 'bbox_mode' must be
set to FT_GLYPH_BBOX_UNSCALED to get unscaled font units in 26.6 pixel
format. The value FT_GLYPH_BBOX_SUBPIXELS is another name for this
constant.
Note that the maximum coordinates are exclusive, which means that one
can compute the width and height of the glyph image (be it in integer
or 26.6 pixels) as:
width = bbox.xMax - bbox.xMin;
height = bbox.yMax - bbox.yMin;
Note also that for 26.6 coordinates, if 'bbox_mode' is set to
FT_GLYPH_BBOX_GRIDFIT, the coordinates will also be grid-fitted, which
corresponds to:
bbox.xMin = FLOOR(bbox.xMin);
bbox.yMin = FLOOR(bbox.yMin);
bbox.xMax = CEILING(bbox.xMax);
bbox.yMax = CEILING(bbox.yMax);
To get the bbox in pixel coordinates, set 'bbox_mode' to
FT_GLYPH_BBOX_TRUNCATE.
To get the bbox in grid-fitted pixel coordinates, set 'bbox_mode' to
FT_GLYPH_BBOX_PIXELS.
'''
bbox = FT_BBox()
FT_Glyph_Get_CBox(byref(self._FT_Glyph.contents), bbox_mode, byref(bbox))
return BBox(bbox)
# -----------------------------------------------------------------------------
class BitmapGlyph( object ):
'''
FT_BitmapGlyph wrapper.
A structure used for bitmap glyph images. This really is a 'sub-class' of
FT_GlyphRec.
'''
def __init__( self, glyph ):
'''
Create Glyph object from an FT glyph.
Parameters:
-----------
glyph: valid FT_Glyph object
'''
self._FT_BitmapGlyph = cast(glyph, FT_BitmapGlyph)
# def __del__( self ):
# '''
# Destroy glyph.
# '''
# FT_Done_Glyph( cast(self._FT_BitmapGlyph, FT_Glyph) )
def _get_format( self ):
return self._FT_BitmapGlyph.contents.format
format = property( _get_format,
doc = '''The format of the glyph's image.''')
def _get_bitmap( self ):
return Bitmap( self._FT_BitmapGlyph.contents.bitmap )
bitmap = property( _get_bitmap,
doc = '''A descriptor for the bitmap.''')
def _get_left( self ):
return self._FT_BitmapGlyph.contents.left
left = property( _get_left,
doc = '''The left-side bearing, i.e., the horizontal distance from the
current pen position to the left border of the glyph bitmap.''')
def _get_top( self ):
return self._FT_BitmapGlyph.contents.top
top = property( _get_top,
doc = '''The top-side bearing, i.e., the vertical distance from the
current pen position to the top border of the glyph bitmap.
This distance is positive for upwards y!''')
# -----------------------------------------------------------------------------
class GlyphSlot( object ):
'''
FT_GlyphSlot wrapper.
FreeType root glyph slot class structure. A glyph slot is a container where
individual glyphs can be loaded, be they in outline or bitmap format.
'''
def __init__( self, slot ):
'''
Create GlyphSlot object from an FT glyph slot.
Parameters:
-----------
glyph: valid FT_GlyphSlot object
'''
self._FT_GlyphSlot = slot
def render( self, render_mode ):
'''
Convert a given glyph image to a bitmap. It does so by inspecting the
glyph image format, finding the relevant renderer, and invoking it.
:param render_mode: The render mode used to render the glyph image into
a bitmap. See FT_Render_Mode for a list of possible
values.
If FT_RENDER_MODE_NORMAL is used, a previous call
of FT_Load_Glyph with flag FT_LOAD_COLOR makes
FT_Render_Glyph provide a default blending of
colored glyph layers associated with the current
glyph slot (provided the font contains such layers)
instead of rendering the glyph slot's outline.
This is an experimental feature; see FT_LOAD_COLOR
for more information.
**Note**:
To get meaningful results, font scaling values must be set with
functions like FT_Set_Char_Size before calling FT_Render_Glyph.
When FreeType outputs a bitmap of a glyph, it really outputs an alpha
coverage map. If a pixel is completely covered by a filled-in
outline, the bitmap contains 0xFF at that pixel, meaning that
0xFF/0xFF fraction of that pixel is covered, meaning the pixel is
100% black (or 0% bright). If a pixel is only 50% covered
(value 0x80), the pixel is made 50% black (50% bright or a middle
shade of grey). 0% covered means 0% black (100% bright or white).
On high-DPI screens like on smartphones and tablets, the pixels are
so small that their chance of being completely covered and therefore
completely black are fairly good. On the low-DPI screens, however,
the situation is different. The pixels are too large for most of the
details of a glyph and shades of gray are the norm rather than the
exception.
This is relevant because all our screens have a second problem: they
are not linear. 1 + 1 is not 2. Twice the value does not result in
twice the brightness. When a pixel is only 50% covered, the coverage
map says 50% black, and this translates to a pixel value of 128 when
you use 8 bits per channel (0-255). However, this does not translate
to 50% brightness for that pixel on our sRGB and gamma 2.2 screens.
Due to their non-linearity, they dwell longer in the darks and only a
pixel value of about 186 results in 50% brightness – 128 ends up too
dark on both bright and dark backgrounds. The net result is that dark
text looks burnt-out, pixely and blotchy on bright background, bright
text too frail on dark backgrounds, and colored text on colored
background (for example, red on green) seems to have dark halos or
‘dirt’ around it. The situation is especially ugly for diagonal stems
like in ‘w’ glyph shapes where the quality of FreeType's
anti-aliasing depends on the correct display of grays. On high-DPI
screens where smaller, fully black pixels reign supreme, this doesn't
matter, but on our low-DPI screens with all the gray shades, it does.
0% and 100% brightness are the same things in linear and non-linear
space, just all the shades in-between aren't.
The blending function for placing text over a background is
dst = alpha * src + (1 - alpha) * dst
which is known as the OVER operator.
To correctly composite an anti-aliased pixel of a glyph onto a
surface, take the foreground and background colors (e.g., in sRGB
space) and apply gamma to get them in a linear space, use OVER to
blend the two linear colors using the glyph pixel as the alpha value
(remember, the glyph bitmap is an alpha coverage bitmap), and apply
inverse gamma to the blended pixel and write it back to the image.
Internal testing at Adobe found that a target inverse gamma of 1.8
for step 3 gives good results across a wide range of displays with
an sRGB gamma curve or a similar one.
This process can cost performance. There is an approximation that
does not need to know about the background color; see
https://bel.fi/alankila/lcd/ and
https://bel.fi/alankila/lcd/alpcor.html for details.
**ATTENTION:** Linear blending is even more important when dealing
with subpixel-rendered glyphs to prevent color-fringing! A
subpixel-rendered glyph must first be filtered with a filter that
gives equal weight to the three color primaries and does not exceed a
sum of 0x100, see section ‘Subpixel Rendering’. Then the only
difference to gray linear blending is that subpixel-rendered linear
blending is done 3 times per pixel: red foreground subpixel to red
background subpixel and so on for green and blue.
'''
error = FT_Render_Glyph( self._FT_GlyphSlot, render_mode )
if error: raise FT_Exception( error )
def get_glyph( self ):
'''
A function used to extract a glyph image from a slot. Note that the
created FT_Glyph object must be released with FT_Done_Glyph.
'''
aglyph = FT_Glyph()
error = FT_Get_Glyph( self._FT_GlyphSlot, byref(aglyph) )
if error: raise FT_Exception( error )
return Glyph( aglyph )
def _get_bitmap( self ):
return Bitmap( self._FT_GlyphSlot.contents.bitmap )
bitmap = property( _get_bitmap,
doc = '''This field is used as a bitmap descriptor when the slot format
is FT_GLYPH_FORMAT_BITMAP. Note that the address and content of
the bitmap buffer can change between calls of FT_Load_Glyph and
a few other functions.''')
def _get_metrics( self ):
return GlyphMetrics( self._FT_GlyphSlot.contents.metrics )
metrics = property( _get_metrics,
doc = '''The metrics of the last loaded glyph in the slot. The returned
values depend on the last load flags (see the FT_Load_Glyph API
function) and can be expressed either in 26.6 fractional pixels or font
units. Note that even when the glyph image is transformed, the metrics
are not.''')
def _get_next( self ):
return GlyphSlot( self._FT_GlyphSlot.contents.next )
next = property( _get_next,
doc = '''In some cases (like some font tools), several glyph slots per
face object can be a good thing. As this is rare, the glyph slots
are listed through a direct, single-linked list using its 'next'
field.''')
advance = property( lambda self: self._FT_GlyphSlot.contents.advance,
doc = '''This shorthand is, depending on FT_LOAD_IGNORE_TRANSFORM, the
transformed advance width for the glyph (in 26.6 fractional
pixel format). As specified with FT_LOAD_VERTICAL_LAYOUT, it
uses either the 'horiAdvance' or the 'vertAdvance' value of
'metrics' field.''')
def _get_outline( self ):
return Outline( self._FT_GlyphSlot.contents.outline )
outline = property( _get_outline,
doc = '''The outline descriptor for the current glyph image if its
format is FT_GLYPH_FORMAT_OUTLINE. Once a glyph is loaded,
'outline' can be transformed, distorted, embolded,
etc. However, it must not be freed.''')
format = property( lambda self: self._FT_GlyphSlot.contents.format,
doc = '''This field indicates the format of the image contained in the
glyph slot. Typically FT_GLYPH_FORMAT_BITMAP,
FT_GLYPH_FORMAT_OUTLINE, or FT_GLYPH_FORMAT_COMPOSITE, but
others are possible.''')
bitmap_top = property( lambda self:
self._FT_GlyphSlot.contents.bitmap_top,
doc = '''This is the bitmap's top bearing expressed in integer
pixels. Remember that this is the distance from the
baseline to the top-most glyph scanline, upwards y
coordinates being positive.''')
bitmap_left = property( lambda self:
self._FT_GlyphSlot.contents.bitmap_left,
doc = '''This is the bitmap's left bearing expressed in integer
pixels. Of course, this is only valid if the format is
FT_GLYPH_FORMAT_BITMAP.''')
linearHoriAdvance = property( lambda self:
self._FT_GlyphSlot.contents.linearHoriAdvance,
doc = '''The advance width of the unhinted glyph. Its value
is expressed in 16.16 fractional pixels, unless
FT_LOAD_LINEAR_DESIGN is set when loading the glyph.
This field can be important to perform correct
WYSIWYG layout. Only relevant for outline glyphs.''')
linearVertAdvance = property( lambda self:
self._FT_GlyphSlot.contents.linearVertAdvance,
doc = '''The advance height of the unhinted glyph. Its value
is expressed in 16.16 fractional pixels, unless
FT_LOAD_LINEAR_DESIGN is set when loading the glyph.
This field can be important to perform correct
WYSIWYG layout. Only relevant for outline glyphs.''')
# -----------------------------------------------------------------------------
# Face wrapper
# -----------------------------------------------------------------------------
class Face( object ):
'''
FT_Face wrapper
FreeType root face class structure. A face object models a typeface in a
font file.
'''
def __init__( self, path_or_stream, index = 0 ):
'''
Build a new Face
:param Union[str, typing.BinaryIO] path_or_stream:
A path to the font file or an io.BytesIO stream.
:param int index:
The index of the face within the font.
The first face has index 0.
'''
library = get_handle( )
face = FT_Face( )
self._FT_Face = None
#error = FT_New_Face( library, path_or_stream, 0, byref(face) )
self._filebodys = []
if hasattr(path_or_stream, "read"):
error = self._init_from_memory(library, face, index, path_or_stream.read())
else:
try:
error = self._init_from_file(library, face, index, path_or_stream)
except UnicodeError:
with open(path_or_stream, mode="rb") as f:
filebody = f.read()
error = self._init_from_memory(library, face, index, filebody)
if error:
raise FT_Exception(error)
self._index = index
self._FT_Face = face
self._name_strings = dict()
def _init_from_file(self, library, face, index, path):
u_filename = c_char_p(_encode_filename(path))
error = FT_New_Face(library, u_filename, index, byref(face))
return error
def _init_from_memory(self, library, face, index, byte_stream):
error = FT_New_Memory_Face(
library, byte_stream, len(byte_stream), index, byref(face)
)
self._filebodys.append(byte_stream) # prevent gc
return error
def _init_name_string_map(self):
# build map of (nID, pID, eID, lID) keys to name string bytes
self._name_strings = dict()
for nidx in range(self._get_sfnt_name_count()):
namerec = self.get_sfnt_name(nidx)
nk = (namerec.name_id,
namerec.platform_id,
namerec.encoding_id,
namerec.language_id)
self._name_strings[nk] = namerec.string
@classmethod
def from_bytes(cls, bytes_, index=0):
return cls(io.BytesIO(bytes_), index)
def __del__( self ):
'''
Discard face object, as well as all of its child slots and sizes.
'''
# We check FT_Done_Face because by the time we're called it
# may already be gone (see #44 and discussion in #169)
if FT_Done_Face is not None and self._FT_Face is not None:
FT_Done_Face( self._FT_Face )
def attach_file( self, filename ):
'''
Attach data to a face object. Normally, this is used to read
additional information for the face object. For example, you can attach
an AFM file that comes with a Type 1 font to get the kerning values and
other metrics.
:param filename: Filename to attach
**Note**
The meaning of the 'attach' (i.e., what really happens when the new
file is read) is not fixed by FreeType itself. It really depends on the
font format (and thus the font driver).
Client applications are expected to know what they are doing when
invoking this function. Most drivers simply do not implement file
attachments.
'''
try:
u_filename = c_char_p(_encode_filename(filename))
error = FT_Attach_File( self._FT_Face, u_filename )
except UnicodeError:
with open(filename, mode='rb') as f:
filebody = f.read()
parameters = FT_Open_Args()
parameters.flags = FT_OPEN_MEMORY
parameters.memory_base = filebody
parameters.memory_size = len(filebody)
parameters.stream = None
error = FT_Attach_Stream( self._FT_Face, parameters )
self._filebodys.append(filebody) # prevent gc
if error: raise FT_Exception( error)
def set_char_size( self, width=0, height=0, hres=72, vres=72 ):
'''
This function calls FT_Request_Size to request the nominal size (in
points).
:param float width: The nominal width, in 26.6 fractional points.
:param float height: The nominal height, in 26.6 fractional points.
:param float hres: The horizontal resolution in dpi.
:param float vres: The vertical resolution in dpi.
**Note**
If either the character width or height is zero, it is set equal to the
other value.
If either the horizontal or vertical resolution is zero, it is set
equal to the other value.
A character width or height smaller than 1pt is set to 1pt; if both
resolution values are zero, they are set to 72dpi.
Don't use this function if you are using the FreeType cache API.
'''
error = FT_Set_Char_Size( self._FT_Face, width, height, hres, vres )
if error: raise FT_Exception( error)
def set_pixel_sizes( self, width, height ):
'''
This function calls FT_Request_Size to request the nominal size (in
pixels).
:param width: The nominal width, in pixels.
:param height: The nominal height, in pixels.
'''
error = FT_Set_Pixel_Sizes( self._FT_Face, width, height )
if error: raise FT_Exception(error)
def select_charmap( self, encoding ):
'''
Select a given charmap by its encoding tag (as listed in 'freetype.h').
**Note**:
This function returns an error if no charmap in the face corresponds to
the encoding queried here.
Because many fonts contain more than a single cmap for Unicode
encoding, this function has some special code to select the one which
covers Unicode best ('best' in the sense that a UCS-4 cmap is preferred
to a UCS-2 cmap). It is thus preferable to FT_Set_Charmap in this case.
'''
error = FT_Select_Charmap( self._FT_Face, encoding )
if error: raise FT_Exception(error)
def set_charmap( self, charmap ):
'''
Select a given charmap for character code to glyph index mapping.
:param charmap: A handle to the selected charmap, or an index to face->charmaps[]
'''
if ( type(charmap) == Charmap ):
error = FT_Set_Charmap( self._FT_Face, charmap._FT_Charmap )
# Type 14 is allowed to fail, to match ft2demo's behavior.
if ( charmap.cmap_format == 14 ):
error = 0
else:
# Treat "charmap" as plain number
error = FT_Set_Charmap( self._FT_Face, self._FT_Face.contents.charmaps[charmap] )
if error : raise FT_Exception(error)
def get_char_index( self, charcode ):
'''
Return the glyph index of a given character code. This function uses a
charmap object to do the mapping.
:param charcode: The character code.
**Note**:
If you use FreeType to manipulate the contents of font files directly,
be aware that the glyph index returned by this function doesn't always
correspond to the internal indices used within the file. This is done
to ensure that value 0 always corresponds to the 'missing glyph'.
'''
if isinstance(charcode, (str,unicode)):
charcode = ord(charcode)
return FT_Get_Char_Index( self._FT_Face, charcode )
def get_glyph_name(self, agindex, buffer_max=64):
'''
This function is used to return the glyph name for the given charcode.
:param agindex: The glyph index.
:param buffer_max: The maximum number of bytes to use to store the
glyph name.
:param glyph_name: The glyph name, possibly truncated.
'''
buff = create_string_buffer(buffer_max)
error = FT_Get_Glyph_Name(self._FT_Face, FT_UInt(agindex), byref(buff),
FT_UInt(buffer_max))
if error: raise FT_Exception(error)
return buff.value
def get_chars( self ):
'''
This generator function is used to return all unicode character
codes in the current charmap of a given face. For each character it
also returns the corresponding glyph index.
:return: character code, glyph index
**Note**:
Note that 'agindex' is set to 0 if the charmap is empty. The
character code itself can be 0 in two cases: if the charmap is empty
or if the value 0 is the first valid character code.
'''
charcode, agindex = self.get_first_char()
yield charcode, agindex
while agindex != 0:
charcode, agindex = self.get_next_char(charcode, 0)
yield charcode, agindex
def get_first_char( self ):
'''
This function is used to return the first character code in the current
charmap of a given face. It also returns the corresponding glyph index.
:return: Glyph index of first character code. 0 if charmap is empty.
**Note**:
You should use this function with get_next_char to be able to parse
all character codes available in a given charmap. The code should look
like this:
Note that 'agindex' is set to 0 if the charmap is empty. The result
itself can be 0 in two cases: if the charmap is empty or if the value 0
is the first valid character code.
'''
agindex = FT_UInt()
charcode = FT_Get_First_Char( self._FT_Face, byref(agindex) )
return charcode, agindex.value
def get_next_char( self, charcode, agindex ):
'''
This function is used to return the next character code in the current
charmap of a given face following the value 'charcode', as well as the
corresponding glyph index.
:param charcode: The starting character code.
:param agindex: Glyph index of next character code. 0 if charmap is empty.
**Note**:
You should use this function with FT_Get_First_Char to walk over all
character codes available in a given charmap. See the note for this
function for a simple code example.
Note that 'agindex' is set to 0 when there are no more codes in the
charmap.
'''
agindex = FT_UInt( 0 ) #agindex )
charcode = FT_Get_Next_Char( self._FT_Face, charcode, byref(agindex) )
return charcode, agindex.value
def get_name_index( self, name ):
'''
Return the glyph index of a given glyph name. This function uses driver
specific objects to do the translation.
:param name: The glyph name.
'''
if not isinstance(name, bytes):
raise FT_Exception(0x06, "FT_Get_Name_Index() expects a binary "
"string for the name parameter.")
return FT_Get_Name_Index( self._FT_Face, name )
def set_transform( self, matrix, delta ):
'''
A function used to set the transformation that is applied to glyph
images when they are loaded into a glyph slot through FT_Load_Glyph.
:param matrix: A pointer to the transformation's 2x2 matrix.
Use 0 for the identity matrix.
:parm delta: A pointer to the translation vector.
Use 0 for the null vector.
**Note**:
The transformation is only applied to scalable image formats after the
glyph has been loaded. It means that hinting is unaltered by the
transformation and is performed on the character size given in the last
call to FT_Set_Char_Size or FT_Set_Pixel_Sizes.
Note that this also transforms the 'face.glyph.advance' field, but
not the values in 'face.glyph.metrics'.
'''
FT_Set_Transform( self._FT_Face,
byref(matrix), byref(delta) )
def select_size( self, strike_index ):
'''
Select a bitmap strike.
:param strike_index: The index of the bitmap strike in the
'available_sizes' field of Face object.
'''
error = FT_Select_Size( self._FT_Face, strike_index )
if error: raise FT_Exception( error )
def load_glyph( self, index, flags = FT_LOAD_RENDER ):
'''
A function used to load a single glyph into the glyph slot of a face
object.
:param index: The index of the glyph in the font file. For CID-keyed
fonts (either in PS or in CFF format) this argument
specifies the CID value.
:param flags: A flag indicating what to load for this glyph. The FT_LOAD_XXX
constants can be used to control the glyph loading process
(e.g., whether the outline should be scaled, whether to load
bitmaps or not, whether to hint the outline, etc).
**Note**:
The loaded glyph may be transformed. See FT_Set_Transform for the
details.
For subsetted CID-keyed fonts, 'FT_Err_Invalid_Argument' is returned
for invalid CID values (this is, for CID values which don't have a
corresponding glyph in the font). See the discussion of the
FT_FACE_FLAG_CID_KEYED flag for more details.
'''
error = FT_Load_Glyph( self._FT_Face, index, flags )
if error: raise FT_Exception( error )
def load_char( self, char, flags = FT_LOAD_RENDER ):
'''
A function used to load a single glyph into the glyph slot of a face
object, according to its character code.
:param char: The glyph's character code, according to the current
charmap used in the face.
:param flags: A flag indicating what to load for this glyph. The
FT_LOAD_XXX constants can be used to control the glyph
loading process (e.g., whether the outline should be
scaled, whether to load bitmaps or not, whether to hint
the outline, etc).
**Note**:
This function simply calls FT_Get_Char_Index and FT_Load_Glyph.
'''
# python 2 with ascii input
if ( isinstance(char, str) and ( len(char) == 1 ) ):
char = ord(char)
# python 2 with utf8 string input
if ( isinstance(char, str) and ( len(char) != 1 ) ):
char = ord(char.decode('utf8'))
# python 3 or python 2 with __future__.unicode_literals
if ( isinstance(char, unicode) and ( len(char) == 1 ) ):
char = ord(char)
# allow bare integer to pass through
error = FT_Load_Char( self._FT_Face, char, flags )
if error: raise FT_Exception( error )
def get_advance( self, gindex, flags ):
'''
Retrieve the advance value of a given glyph outline in an FT_Face. By
default, the unhinted advance is returned in font units.
:param gindex: The glyph index.
:param flags: A set of bit flags similar to those used when calling
FT_Load_Glyph, used to determine what kind of advances
you need.
:return: The advance value, in either font units or 16.16 format.
If FT_LOAD_VERTICAL_LAYOUT is set, this is the vertical
advance corresponding to a vertical layout. Otherwise, it is
the horizontal advance in a horizontal layout.
'''
padvance = FT_Fixed(0)
error = FT_Get_Advance( self._FT_Face, gindex, flags, byref(padvance) )
if error: raise FT_Exception( error )
return padvance.value
def get_kerning( self, left, right, mode = FT_KERNING_DEFAULT ):
'''
Return the kerning vector between two glyphs of a same face.
:param left: The index of the left glyph in the kern pair.
:param right: The index of the right glyph in the kern pair.
:param mode: See FT_Kerning_Mode for more information. Determines the scale
and dimension of the returned kerning vector.
**Note**:
Only horizontal layouts (left-to-right & right-to-left) are supported
by this method. Other layouts, or more sophisticated kernings, are out
of the scope of this API function -- they can be implemented through
format-specific interfaces.
'''
left_glyph = self.get_char_index( left )
right_glyph = self.get_char_index( right )
kerning = FT_Vector(0,0)
error = FT_Get_Kerning( self._FT_Face,
left_glyph, right_glyph, mode, byref(kerning) )
if error: raise FT_Exception( error )
return kerning
def get_format(self):
'''
Return a string describing the format of a given face, using values
which can be used as an X11 FONT_PROPERTY. Possible values are
'TrueType', 'Type 1', 'BDF', ‘PCF', ‘Type 42', ‘CID Type 1', ‘CFF',
'PFR', and ‘Windows FNT'.
'''
return FT_Get_X11_Font_Format( self._FT_Face )
def get_fstype(self):
'''
Return the fsType flags for a font (embedding permissions).
The return value is a tuple containing the freetype enum name
as a string and the actual flag as an int
'''
flag = FT_Get_FSType_Flags( self._FT_Face )
for k, v in FT_FSTYPES.items():
if v == flag:
return k, v
def _get_sfnt_name_count(self):
return FT_Get_Sfnt_Name_Count( self._FT_Face )
sfnt_name_count = property(_get_sfnt_name_count,
doc = '''Number of name strings in the SFNT 'name' table.''')
def get_sfnt_name( self, index ):
'''
Retrieve a string of the SFNT 'name' table for a given index
:param index: The index of the 'name' string.
**Note**:
The 'string' array returned in the 'aname' structure is not
null-terminated. The application should deallocate it if it is no
longer in use.
Use FT_Get_Sfnt_Name_Count to get the total number of available
'name' table entries, then do a loop until you get the right
platform, encoding, and name ID.
'''
name = FT_SfntName( )
error = FT_Get_Sfnt_Name( self._FT_Face, index, byref(name) )
if error: raise FT_Exception( error )
return SfntName( name )
def get_best_name_string(self, nameID, default_string='', preferred_order=None):
'''
Retrieve a name string given nameID. Searches available font names
matching nameID and returns the decoded bytes of the best match.
"Best" is defined as a preferred list of platform/encoding/languageIDs
which can be overridden by supplying a preferred_order matching the
scheme of 'sort_order' (see below).
The routine will attempt to decode the string's bytes to a Python str, when the
platform/encoding[/langID] are known (Windows, Mac, or Unicode platforms).
If you prefer more control over name string selection and decoding than
this routine provides:
- call self._init_name_string_map()
- use (nameID, platformID, encodingID, languageID) as a key into
the self._name_strings dict
'''
if not(self._name_strings):
self._init_name_string_map()
sort_order = preferred_order or (
(3, 1, 1033), # Microsoft/Windows/US English
(1, 0, 0), # Mac/Roman/English
(0, 6, 0), # Unicode/SMP/*
(0, 4, 0), # Unicode/SMP/*
(0, 3, 0), # Unicode/BMP/*
(0, 2, 0), # Unicode/10646-BMP/*
(0, 1, 0), # Unicode/1.1/*
)
# get all keys matching nameID
keys_present = [k for k in self._name_strings.keys() if k[0] == nameID]
if keys_present:
# sort found keys by sort_order
key_order = {k: v for v, k in enumerate(sort_order)}
keys_present.sort(key=lambda x: key_order.get(x[1:4]))
best_key = keys_present[0]
nsbytes = self._name_strings[best_key]
if best_key[1:3] == (3, 1) or best_key[1] == 0:
enc = "utf-16-be"
elif best_key[1:4] == (1, 0, 0):
enc = "mac-roman"
else:
enc = "unicode_escape"
ns = nsbytes.decode(enc)
else:
ns = default_string
return ns
def get_variation_info(self):
'''
Retrieves variation space information for the current face.
'''
if version() < (2, 8, 1):
raise NotImplementedError("freetype-py VF support requires FreeType 2.8.1 or later")
p_amaster = pointer(FT_MM_Var())
error = FT_Get_MM_Var(self._FT_Face, byref(p_amaster))
if error:
raise FT_Exception(error)
vsi = VariationSpaceInfo(self, p_amaster)
FT_Done_MM_Var_func(p_amaster)
return vsi
def get_var_blend_coords(self):
'''
Get the current blend coordinates (-1.0..+1.0)
'''
vsi = self.get_variation_info()
num_coords = len(vsi.axes)
ft_coords = (FT_Fixed * num_coords)()
error = FT_Get_Var_Blend_Coordinates(self._FT_Face, num_coords, byref(ft_coords))
if error:
raise FT_Exception(error)
coords = tuple([ft_coords[ai]/65536.0 for ai in range(num_coords)])
return coords
def set_var_blend_coords(self, coords, reset=False):
'''
Set blend coords. Using reset=True will set all axes to
their default coordinates.
'''
if reset:
error = FT_Set_Var_Blend_Coordinates(self._FT_Face, 0, 0)
else:
num_coords = len(coords)
ft_coords = [int(round(c * 65536.0)) for c in coords]
coords_array = (FT_Fixed * num_coords)(*ft_coords)
error = FT_Set_Var_Blend_Coordinates(self._FT_Face, num_coords, byref(coords_array))
if error:
raise FT_Exception(error)
def get_var_design_coords(self):
'''
Get the current design coordinates
'''
vsi = self.get_variation_info()
num_coords = len(vsi.axes)
ft_coords = (FT_Fixed * num_coords)()
error = FT_Get_Var_Design_Coordinates(self._FT_Face, num_coords, byref(ft_coords))
if error:
raise FT_Exception(error)
coords = tuple([ft_coords[ai]/65536.0 for ai in range(num_coords)])
return coords
def set_var_design_coords(self, coords, reset=False):
'''
Set design coords. Using reset=True will set all axes to
their default coordinates.
'''
if reset:
error = FT_Set_Var_Design_Coordinates(self._FT_Face, 0, 0)
else:
num_coords = len(coords)
ft_coords = [int(round(c * 65536.0)) for c in coords]
coords_array = (FT_Fixed * num_coords)(*ft_coords)
error = FT_Set_Var_Design_Coordinates(self._FT_Face, num_coords, byref(coords_array))
if error:
raise FT_Exception(error)
def set_var_named_instance(self, instance_name):
'''
Set instance by name. This will work with any FreeType with variable support
(for our purposes: v2.8.1 or later). If the actual FT_Set_Named_Instance()
function is available (v2.9.1 or later), we use it (which, despite what you might
expect from its name, sets instances by *index*). Otherwise we just use the coords
of the named instance (if found) and call self.set_var_design_coords.
'''
have_func = freetype.version() >= (2, 9, 1)
vsi = self.get_variation_info()
for inst_idx, inst in enumerate(vsi.instances, start=1):
if inst.name == instance_name:
if have_func:
error = FT_Set_Named_Instance(self._FT_Face, inst_idx)
else:
error = self.set_var_design_coords(inst.coords)
if error:
raise FT_Exception(error)
break
# named instance not found; do nothing
def _get_postscript_name( self ):
return FT_Get_Postscript_Name( self._FT_Face )
postscript_name = property( _get_postscript_name,
doc = '''ASCII PostScript name of face, if available. This only
works with PostScript and TrueType fonts.''')
def _has_horizontal( self ):
return bool( self.face_flags & FT_FACE_FLAG_HORIZONTAL )
has_horizontal = property( _has_horizontal,
doc = '''True whenever a face object contains horizontal metrics
(this is true for all font formats though).''')
def _has_vertical( self ):
return bool( self.face_flags & FT_FACE_FLAG_VERTICAL )
has_vertical = property( _has_vertical,
doc = '''True whenever a face object contains vertical metrics.''')
def _has_kerning( self ):
return bool( self.face_flags & FT_FACE_FLAG_KERNING )
has_kerning = property( _has_kerning,
doc = '''True whenever a face object contains kerning data that can
be accessed with FT_Get_Kerning.''')
def _is_scalable( self ):
return bool( self.face_flags & FT_FACE_FLAG_SCALABLE )
is_scalable = property( _is_scalable,
doc = '''true whenever a face object contains a scalable font face
(true for TrueType, Type 1, Type 42, CID, OpenType/CFF,
and PFR font formats.''')
def _is_sfnt( self ):
return bool( self.face_flags & FT_FACE_FLAG_SFNT )
is_sfnt = property( _is_sfnt,
doc = '''true whenever a face object contains a font whose format is
based on the SFNT storage scheme. This usually means: TrueType
fonts, OpenType fonts, as well as SFNT-based embedded bitmap
fonts.
If this macro is true, all functions defined in
FT_SFNT_NAMES_H and FT_TRUETYPE_TABLES_H are available.''')
def _is_fixed_width( self ):
return bool( self.face_flags & FT_FACE_FLAG_FIXED_WIDTH )
is_fixed_width = property( _is_fixed_width,
doc = '''True whenever a face object contains a font face that
contains fixed-width (or 'monospace', 'fixed-pitch',
etc.) glyphs.''')
def _has_fixed_sizes( self ):
return bool( self.face_flags & FT_FACE_FLAG_FIXED_SIZES )
has_fixed_sizes = property( _has_fixed_sizes,
doc = '''True whenever a face object contains some embedded
bitmaps. See the 'available_sizes' field of the FT_FaceRec
structure.''')
def _has_glyph_names( self ):
return bool( self.face_flags & FT_FACE_FLAG_GLYPH_NAMES )
has_glyph_names = property( _has_glyph_names,
doc = '''True whenever a face object contains some glyph names
that can be accessed through FT_Get_Glyph_Name.''')
def _has_multiple_masters( self ):
return bool( self.face_flags & FT_FACE_FLAG_MULTIPLE_MASTERS )
has_multiple_masters = property( _has_multiple_masters,
doc = '''True whenever a face object contains some
multiple masters. The functions provided by
FT_MULTIPLE_MASTERS_H are then available to
choose the exact design you want.''')
def _is_cid_keyed( self ):
return bool( self.face_flags & FT_FACE_FLAG_CID_KEYED )
is_cid_keyed = property( _is_cid_keyed,
doc = '''True whenever a face object contains a CID-keyed
font. See the discussion of FT_FACE_FLAG_CID_KEYED for
more details.
If this macro is true, all functions defined in FT_CID_H
are available.''')
def _is_tricky( self ):
return bool( self.face_flags & FT_FACE_FLAG_TRICKY )
is_tricky = property( _is_tricky,
doc = '''True whenever a face represents a 'tricky' font. See the
discussion of FT_FACE_FLAG_TRICKY for more details.''')
num_faces = property(lambda self: self._FT_Face.contents.num_faces,
doc = '''The number of faces in the font file. Some font formats can
have multiple faces in a font file.''')
face_index = property(lambda self: self._FT_Face.contents.face_index,
doc = '''The index of the face in the font file. It is set to 0 if
there is only one face in the font file.''')
face_flags = property(lambda self: self._FT_Face.contents.face_flags,
doc = '''A set of bit flags that give important information about
the face; see FT_FACE_FLAG_XXX for the details.''')
style_flags = property(lambda self: self._FT_Face.contents.style_flags,
doc = '''A set of bit flags indicating the style of the face; see
FT_STYLE_FLAG_XXX for the details.''')
num_glyphs = property(lambda self: self._FT_Face.contents.num_glyphs,
doc = '''The number of glyphs in the face. If the face is scalable
and has sbits (see 'num_fixed_sizes'), it is set to the number of
outline glyphs.
For CID-keyed fonts, this value gives the highest CID used in the
font.''')
family_name = property(lambda self: self._FT_Face.contents.family_name,
doc = '''The face's family name. This is an ASCII string, usually
in English, which describes the typeface's family (like
'Times New Roman', 'Bodoni', 'Garamond', etc). This is a
least common denominator used to list fonts. Some formats
(TrueType & OpenType) provide localized and Unicode
versions of this string. Applications should use the
format specific interface to access them. Can be NULL
(e.g., in fonts embedded in a PDF file).''')
style_name = property(lambda self: self._FT_Face.contents.style_name,
doc = '''The face's style name. This is an ASCII string, usually in
English, which describes the typeface's style (like
'Italic', 'Bold', 'Condensed', etc). Not all font formats
provide a style name, so this field is optional, and can be
set to NULL. As for 'family_name', some formats provide
localized and Unicode versions of this string. Applications
should use the format specific interface to access them.''')
num_fixed_sizes = property(lambda self: self._FT_Face.contents.num_fixed_sizes,
doc = '''The number of bitmap strikes in the face. Even if the
face is scalable, there might still be bitmap strikes,
which are called 'sbits' in that case.''')
def _get_available_sizes( self ):
sizes = []
n = self.num_fixed_sizes
FT_sizes = self._FT_Face.contents.available_sizes
for i in range(n):
sizes.append( BitmapSize(FT_sizes[i]) )
return sizes
available_sizes = property(_get_available_sizes,
doc = '''A list of FT_Bitmap_Size for all bitmap strikes in the
face. It is set to NULL if there is no bitmap strike.''')
num_charmaps = property(lambda self: self._FT_Face.contents.num_charmaps)
def _get_charmaps( self ):
charmaps = []
n = self._FT_Face.contents.num_charmaps
FT_charmaps = self._FT_Face.contents.charmaps
for i in range(n):
charmaps.append( Charmap(FT_charmaps[i]) )
return charmaps
charmaps = property(_get_charmaps,
doc = '''A list of the charmaps of the face.''')
# ('generic', FT_Generic),
def _get_bbox( self ):
return BBox( self._FT_Face.contents.bbox )
bbox = property( _get_bbox,
doc = '''The font bounding box. Coordinates are expressed in font units
(see 'units_per_EM'). The box is large enough to contain any
glyph from the font. Thus, 'bbox.yMax' can be seen as the
'maximal ascender', and 'bbox.yMin' as the 'minimal
descender'. Only relevant for scalable formats.
Note that the bounding box might be off by (at least) one pixel
for hinted fonts. See FT_Size_Metrics for further discussion.''')
units_per_EM = property(lambda self: self._FT_Face.contents.units_per_EM,
doc = '''The number of font units per EM square for this
face. This is typically 2048 for TrueType fonts, and 1000
for Type 1 fonts. Only relevant for scalable formats.''')
ascender = property(lambda self: self._FT_Face.contents.ascender,
doc = '''The typographic ascender of the face, expressed in font
units. For font formats not having this information, it is
set to 'bbox.yMax'. Only relevant for scalable formats.''')
descender = property(lambda self: self._FT_Face.contents.descender,
doc = '''The typographic descender of the face, expressed in font
units. For font formats not having this information, it is
set to 'bbox.yMin'. Note that this field is usually
negative. Only relevant for scalable formats.''')
height = property(lambda self: self._FT_Face.contents.height,
doc = '''The height is the vertical distance between two consecutive
baselines, expressed in font units. It is always positive. Only
relevant for scalable formats.''')
max_advance_width = property(lambda self: self._FT_Face.contents.max_advance_width,
doc = '''The maximal advance width, in font units, for all
glyphs in this face. This can be used to make word
wrapping computations faster. Only relevant for
scalable formats.''')
max_advance_height = property(lambda self: self._FT_Face.contents.max_advance_height,
doc = '''The maximal advance height, in font units, for all
glyphs in this face. This is only relevant for
vertical layouts, and is set to 'height' for fonts
that do not provide vertical metrics. Only relevant
for scalable formats.''')
underline_position = property(lambda self: self._FT_Face.contents.underline_position,
doc = '''The position, in font units, of the underline line
for this face. It is the center of the underlining
stem. Only relevant for scalable formats.''')
underline_thickness = property(lambda self: self._FT_Face.contents.underline_thickness,
doc = '''The thickness, in font units, of the underline for
this face. Only relevant for scalable formats.''')
def _get_glyph( self ):
return GlyphSlot( self._FT_Face.contents.glyph )
glyph = property( _get_glyph,
doc = '''The face's associated glyph slot(s).''')
def _get_size( self ):
size = self._FT_Face.contents.size
metrics = size.contents.metrics
return SizeMetrics(metrics)
size = property( _get_size,
doc = '''The current active size for this face.''')
def _get_charmap( self ):
return Charmap( self._FT_Face.contents.charmap)
charmap = property( _get_charmap,
doc = '''The current active charmap for this face.''')
# -----------------------------------------------------------------------------
# SfntName wrapper
# -----------------------------------------------------------------------------
class SfntName( object ):
'''
SfntName wrapper
A structure used to model an SFNT 'name' table entry.
'''
def __init__(self, name):
'''
Create a new SfntName object.
:param name : SFNT 'name' table entry.
'''
self._FT_SfntName = name
platform_id = property(lambda self: self._FT_SfntName.platform_id,
doc = '''The platform ID for 'string'.''')
encoding_id = property(lambda self: self._FT_SfntName.encoding_id,
doc = '''The encoding ID for 'string'.''')
language_id = property(lambda self: self._FT_SfntName.language_id,
doc = '''The language ID for 'string'.''')
name_id = property(lambda self: self._FT_SfntName.name_id,
doc = '''An identifier for 'string'.''')
#string = property(lambda self: self._FT_SfntName.string)
string_len = property(lambda self: self._FT_SfntName.string_len,
doc = '''The length of 'string' in bytes.''')
def _get_string(self):
# #s = self._FT_SfntName
s = string_at(self._FT_SfntName.string, self._FT_SfntName.string_len)
return s
# #return s.decode('utf-16be', 'ignore')
# return s.decode('utf-8', 'ignore')
# #n = s.string_len
# #data = [s.string[i] for i in range(n)]
# #return data
string = property(_get_string,
doc = '''The 'name' string. Note that its format differs depending on
the (platform,encoding) pair. It can be a Pascal String, a
UTF-16 one, etc.
Generally speaking, the string is not zero-terminated. Please
refer to the TrueType specification for details.''')
# -----------------------------------------------------------------------------
class Stroker( object ):
'''
FT_Stroker wrapper
This component generates stroked outlines of a given vectorial glyph. It
also allows you to retrieve the 'outside' and/or the 'inside' borders of
the stroke.
This can be useful to generate 'bordered' glyph, i.e., glyphs displayed
with a coloured (and anti-aliased) border around their shape.
'''
def __init__( self ):
'''
Create a new Stroker object.
'''
library = get_handle( )
stroker = FT_Stroker( )
error = FT_Stroker_New( library, byref(stroker) )
if error: raise FT_Exception( error )
self._FT_Stroker = stroker
def __del__( self ):
'''
Destroy object.
'''
FT_Stroker_Done( self._FT_Stroker )
def set( self, radius, line_cap, line_join, miter_limit ):
'''
Reset a stroker object's attributes.
:param radius: The border radius.
:param line_cap: The line cap style.
:param line_join: The line join style.
:param miter_limit: The miter limit for the FT_STROKER_LINEJOIN_MITER
style, expressed as 16.16 fixed point value.
**Note**:
The radius is expressed in the same units as the outline coordinates.
'''
FT_Stroker_Set( self._FT_Stroker,
radius, line_cap, line_join, miter_limit )
def rewind( self ):
'''
Reset a stroker object without changing its attributes. You should call
this function before beginning a new series of calls to
FT_Stroker_BeginSubPath or FT_Stroker_EndSubPath.
'''
FT_Stroker_Rewind( self._FT_Stroker )
def parse_outline( self, outline, opened ):
'''
A convenience function used to parse a whole outline with the
stroker. The resulting outline(s) can be retrieved later by functions
like FT_Stroker_GetCounts and FT_Stroker_Export.
:param outline: The source outline.
:pram opened: A boolean. If 1, the outline is treated as an open path
instead of a closed one.
**Note**:
If 'opened' is 0 (the default), the outline is treated as a closed
path, and the stroker generates two distinct 'border' outlines.
If 'opened' is 1, the outline is processed as an open path, and the
stroker generates a single 'stroke' outline.
This function calls 'rewind' automatically.
'''
error = FT_Stroker_ParseOutline( self._FT_Stroker, byref(outline._FT_Outline), opened)
if error: raise FT_Exception( error )
def begin_subpath( self, to, _open ):
'''
Start a new sub-path in the stroker.
:param to A pointer to the start vector.
:param _open: A boolean. If 1, the sub-path is treated as an open one.
**Note**:
This function is useful when you need to stroke a path that is not
stored as an 'Outline' object.
'''
error = FT_Stroker_BeginSubPath( self._FT_Stroker, to, _open )
if error: raise FT_Exception( error )
def end_subpath( self ):
'''
Close the current sub-path in the stroker.
**Note**:
You should call this function after 'begin_subpath'. If the subpath
was not 'opened', this function 'draws' a single line segment to the
start position when needed.
'''
error = FT_Stroker_EndSubPath( self._FT_Stroker)
if error: raise FT_Exception( error )
def line_to( self, to ):
'''
'Draw' a single line segment in the stroker's current sub-path, from
the last position.
:param to: A pointer to the destination point.
**Note**:
You should call this function between 'begin_subpath' and
'end_subpath'.
'''
error = FT_Stroker_LineTo( self._FT_Stroker, to )
if error: raise FT_Exception( error )
def conic_to( self, control, to ):
'''
'Draw' a single quadratic Bezier in the stroker's current sub-path,
from the last position.
:param control: A pointer to a Bezier control point.
:param to: A pointer to the destination point.
**Note**:
You should call this function between 'begin_subpath' and
'end_subpath'.
'''
error = FT_Stroker_ConicTo( self._FT_Stroker, control, to )
if error: raise FT_Exception( error )
def cubic_to( self, control1, control2, to ):
'''
'Draw' a single quadratic Bezier in the stroker's current sub-path,
from the last position.
:param control1: A pointer to the first Bezier control point.
:param control2: A pointer to second Bezier control point.
:param to: A pointer to the destination point.
**Note**:
You should call this function between 'begin_subpath' and
'end_subpath'.
'''
error = FT_Stroker_CubicTo( self._FT_Stroker, control1, control2, to )
if error: raise FT_Exception( error )
def get_border_counts( self, border ):
'''
Call this function once you have finished parsing your paths with the
stroker. It returns the number of points and contours necessary to
export one of the 'border' or 'stroke' outlines generated by the
stroker.
:param border: The border index.
:return: number of points, number of contours
'''
anum_points = FT_UInt()
anum_contours = FT_UInt()
error = FT_Stroker_GetBorderCounts( self._FT_Stroker, border,
byref(anum_points), byref(anum_contours) )
if error: raise FT_Exception( error )
return anum_points.value, anum_contours.value
def export_border( self , border, outline ):
'''
Call this function after 'get_border_counts' to export the
corresponding border to your own 'Outline' structure.
Note that this function appends the border points and contours to your
outline, but does not try to resize its arrays.
:param border: The border index.
:param outline: The target outline.
**Note**:
Always call this function after get_border_counts to get sure that
there is enough room in your 'Outline' object to receive all new
data.
When an outline, or a sub-path, is 'closed', the stroker generates two
independent 'border' outlines, named 'left' and 'right'
When the outline, or a sub-path, is 'opened', the stroker merges the
'border' outlines with caps. The 'left' border receives all points,
while the 'right' border becomes empty.
Use the function export instead if you want to retrieve all borders
at once.
'''
FT_Stroker_ExportBorder( self._FT_Stroker, border, byref(outline._FT_Outline) )
def get_counts( self ):
'''
Call this function once you have finished parsing your paths with the
stroker. It returns the number of points and contours necessary to
export all points/borders from the stroked outline/path.
:return: number of points, number of contours
'''
anum_points = FT_UInt()
anum_contours = FT_UInt()
error = FT_Stroker_GetCounts( self._FT_Stroker,
byref(anum_points), byref(anum_contours) )
if error: raise FT_Exception( error )
return anum_points.value, anum_contours.value
def export( self, outline ):
'''
Call this function after get_border_counts to export all borders to
your own 'Outline' structure.
Note that this function appends the border points and contours to your
outline, but does not try to resize its arrays.
:param outline: The target outline.
'''
FT_Stroker_Export( self._FT_Stroker, byref(outline._FT_Outline) )
# -----------------------------------------------------------------------------
# Classes related to Variable Font support
#
class VariationAxis(object):
tag = None
coords = tuple()
def __init__(self, ftvaraxis):
self.tag = unmake_tag(ftvaraxis.tag)
self.name = ftvaraxis.name.decode('ascii')
self.minimum = ftvaraxis.minimum/65536.0
self.default = ftvaraxis.default/65536.0
self.maximum = ftvaraxis.maximum/65536.0
self.strid = ftvaraxis.strid # do we need this? Should be same as 'name'...
def __repr__(self):
return "<VariationAxis '{}' ('{}') [{}, {}, {}]>".format(
self.tag, self.name, self.minimum, self.default, self.maximum)
class VariationInstance(object):
def __init__(self, name, psname, coords):
self.name = name
self.psname = psname
self.coords = coords
def __repr__(self):
return "<VariationInstance '{}' {}>".format(
self.name, self.coords)
class VariationSpaceInfo(object):
"""
VF info (axes & instances).
"""
def __init__(self, face, p_ftmmvar):
"""
Build a VariationSpaceInfo object given face (freetype.Face) and
p_ftmmvar (pointer to FT_MM_Var).
"""
ftmv = p_ftmmvar.contents
axes = []
for axidx in range(ftmv.num_axis):
axes.append(VariationAxis(ftmv.axis[axidx]))
self.axes = tuple(axes)
inst = []
for instidx in range(ftmv.num_namedstyles):
instinfo = ftmv.namedstyle[instidx]
nid = instinfo.strid
name = face.get_best_name_string(nid)
psid = instinfo.psid
psname = face.get_best_name_string(psid)
coords = []
for cidx in range(len(self.axes)):
coords.append(instinfo.coords[cidx]/65536.0)
inst.append(VariationInstance(name, psname, tuple(coords)))
self.instances = tuple(inst)
|