DXR is a code search and navigation tool aimed at making sense of large projects. It supports full-text and regex searches as well as structural queries.

Header

Mercurial (d0034f14b705)

VCS Links

Line Code
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 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626
/* -*- Mode: C++; tab-width: 20; indent-tabs-mode: nil; c-basic-offset: 2 -*-
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

#include "mozilla/Logging.h"

#include "gfxFcPlatformFontList.h"
#include "gfxFont.h"
#include "gfxFontConstants.h"
#include "gfxFontFamilyList.h"
#include "gfxFT2Utils.h"
#include "gfxPlatform.h"
#include "mozilla/ArrayUtils.h"
#include "mozilla/dom/ContentChild.h"
#include "mozilla/dom/ContentParent.h"
#include "mozilla/Preferences.h"
#include "mozilla/Sprintf.h"
#include "mozilla/TimeStamp.h"
#include "nsGkAtoms.h"
#include "nsUnicodeProperties.h"
#include "nsDirectoryServiceUtils.h"
#include "nsDirectoryServiceDefs.h"
#include "nsAppDirectoryServiceDefs.h"
#include "nsCharSeparatedTokenizer.h"
#include "nsXULAppAPI.h"
#include "SharedFontList-impl.h"

#include "mozilla/gfx/HelpersCairo.h"

#include <fontconfig/fcfreetype.h>
#include <dlfcn.h>
#include <unistd.h>

#ifdef MOZ_WIDGET_GTK
#  include <gdk/gdk.h>
#  include "gfxPlatformGtk.h"
#endif

#ifdef MOZ_X11
#  include "mozilla/X11Util.h"
#endif

#if defined(MOZ_SANDBOX) && defined(XP_LINUX)
#  include "mozilla/SandboxBrokerPolicyFactory.h"
#  include "mozilla/SandboxSettings.h"
#endif

#include FT_MULTIPLE_MASTERS_H

using namespace mozilla;
using namespace mozilla::gfx;
using namespace mozilla::unicode;

using mozilla::dom::FontPatternListEntry;
using mozilla::dom::SystemFontListEntry;

#ifndef FC_POSTSCRIPT_NAME
#  define FC_POSTSCRIPT_NAME "postscriptname" /* String */
#endif
#ifndef FC_VARIABLE
#  define FC_VARIABLE "variable" /* Bool */
#endif

#define PRINTING_FC_PROPERTY "gfx.printing"

#define LOG_FONTLIST(args) \
  MOZ_LOG(gfxPlatform::GetLog(eGfxLog_fontlist), LogLevel::Debug, args)
#define LOG_FONTLIST_ENABLED() \
  MOZ_LOG_TEST(gfxPlatform::GetLog(eGfxLog_fontlist), LogLevel::Debug)
#define LOG_CMAPDATA_ENABLED() \
  MOZ_LOG_TEST(gfxPlatform::GetLog(eGfxLog_cmapdata), LogLevel::Debug)

template <>
class nsAutoRefTraits<FcFontSet> : public nsPointerRefTraits<FcFontSet> {
 public:
  static void Release(FcFontSet* ptr) { FcFontSetDestroy(ptr); }
};

template <>
class nsAutoRefTraits<FcObjectSet> : public nsPointerRefTraits<FcObjectSet> {
 public:
  static void Release(FcObjectSet* ptr) { FcObjectSetDestroy(ptr); }
};

static const FcChar8* ToFcChar8Ptr(const char* aStr) {
  return reinterpret_cast<const FcChar8*>(aStr);
}

static const char* ToCharPtr(const FcChar8* aStr) {
  return reinterpret_cast<const char*>(aStr);
}

FT_Library gfxFcPlatformFontList::sCairoFTLibrary = nullptr;

static cairo_user_data_key_t sFcFontlistUserFontDataKey;

// canonical name ==> first en name or first name if no en name
// This is the required logic for fullname lookups as per CSS3 Fonts spec.
static uint32_t FindCanonicalNameIndex(FcPattern* aFont,
                                       const char* aLangField) {
  uint32_t n = 0, en = 0;
  FcChar8* lang;
  while (FcPatternGetString(aFont, aLangField, n, &lang) == FcResultMatch) {
    // look for 'en' or variants, en-US, en-JP etc.
    uint32_t len = strlen(ToCharPtr(lang));
    bool enPrefix = (strncmp(ToCharPtr(lang), "en", 2) == 0);
    if (enPrefix && (len == 2 || (len > 2 && aLangField[2] == '-'))) {
      en = n;
      break;
    }
    n++;
  }
  return en;
}

static void GetFaceNames(FcPattern* aFont, const nsACString& aFamilyName,
                         nsACString& aPostscriptName, nsACString& aFullname) {
  // get the Postscript name
  FcChar8* psname;
  if (FcPatternGetString(aFont, FC_POSTSCRIPT_NAME, 0, &psname) ==
      FcResultMatch) {
    aPostscriptName = ToCharPtr(psname);
  }

  // get the canonical fullname (i.e. en name or first name)
  uint32_t en = FindCanonicalNameIndex(aFont, FC_FULLNAMELANG);
  FcChar8* fullname;
  if (FcPatternGetString(aFont, FC_FULLNAME, en, &fullname) == FcResultMatch) {
    aFullname = ToCharPtr(fullname);
  }

  // if have fullname, done
  if (!aFullname.IsEmpty()) {
    return;
  }

  // otherwise, set the fullname to family + style name [en] and use that
  aFullname = aFamilyName;

  // figure out the en style name
  en = FindCanonicalNameIndex(aFont, FC_STYLELANG);
  nsAutoCString style;
  FcChar8* stylename = nullptr;
  FcPatternGetString(aFont, FC_STYLE, en, &stylename);
  if (stylename) {
    style = ToCharPtr(stylename);
  }

  if (!style.IsEmpty() && !style.EqualsLiteral("Regular")) {
    aFullname.Append(' ');
    aFullname.Append(style);
  }
}

static FontWeight MapFcWeight(int aFcWeight) {
  if (aFcWeight <= (FC_WEIGHT_THIN + FC_WEIGHT_EXTRALIGHT) / 2) {
    return FontWeight(100);
  }
  if (aFcWeight <= (FC_WEIGHT_EXTRALIGHT + FC_WEIGHT_LIGHT) / 2) {
    return FontWeight(200);
  }
  if (aFcWeight <= (FC_WEIGHT_LIGHT + FC_WEIGHT_BOOK) / 2) {
    return FontWeight(300);
  }
  if (aFcWeight <= (FC_WEIGHT_REGULAR + FC_WEIGHT_MEDIUM) / 2) {
    // This includes FC_WEIGHT_BOOK
    return FontWeight(400);
  }
  if (aFcWeight <= (FC_WEIGHT_MEDIUM + FC_WEIGHT_DEMIBOLD) / 2) {
    return FontWeight(500);
  }
  if (aFcWeight <= (FC_WEIGHT_DEMIBOLD + FC_WEIGHT_BOLD) / 2) {
    return FontWeight(600);
  }
  if (aFcWeight <= (FC_WEIGHT_BOLD + FC_WEIGHT_EXTRABOLD) / 2) {
    return FontWeight(700);
  }
  if (aFcWeight <= (FC_WEIGHT_EXTRABOLD + FC_WEIGHT_BLACK) / 2) {
    return FontWeight(800);
  }
  if (aFcWeight <= FC_WEIGHT_BLACK) {
    return FontWeight(900);
  }

  // including FC_WEIGHT_EXTRABLACK
  return FontWeight(901);
}

// TODO(emilio, jfkthame): I think this can now be more fine-grained.
static FontStretch MapFcWidth(int aFcWidth) {
  if (aFcWidth <= (FC_WIDTH_ULTRACONDENSED + FC_WIDTH_EXTRACONDENSED) / 2) {
    return FontStretch::UltraCondensed();
  }
  if (aFcWidth <= (FC_WIDTH_EXTRACONDENSED + FC_WIDTH_CONDENSED) / 2) {
    return FontStretch::ExtraCondensed();
  }
  if (aFcWidth <= (FC_WIDTH_CONDENSED + FC_WIDTH_SEMICONDENSED) / 2) {
    return FontStretch::Condensed();
  }
  if (aFcWidth <= (FC_WIDTH_SEMICONDENSED + FC_WIDTH_NORMAL) / 2) {
    return FontStretch::SemiCondensed();
  }
  if (aFcWidth <= (FC_WIDTH_NORMAL + FC_WIDTH_SEMIEXPANDED) / 2) {
    return FontStretch::Normal();
  }
  if (aFcWidth <= (FC_WIDTH_SEMIEXPANDED + FC_WIDTH_EXPANDED) / 2) {
    return FontStretch::SemiExpanded();
  }
  if (aFcWidth <= (FC_WIDTH_EXPANDED + FC_WIDTH_EXTRAEXPANDED) / 2) {
    return FontStretch::Expanded();
  }
  if (aFcWidth <= (FC_WIDTH_EXTRAEXPANDED + FC_WIDTH_ULTRAEXPANDED) / 2) {
    return FontStretch::ExtraExpanded();
  }
  return FontStretch::UltraExpanded();
}

static void GetFontProperties(FcPattern* aFontPattern, WeightRange* aWeight,
                              StretchRange* aStretch,
                              SlantStyleRange* aSlantStyle) {
  // weight
  int weight;
  if (FcPatternGetInteger(aFontPattern, FC_WEIGHT, 0, &weight) !=
      FcResultMatch) {
    weight = FC_WEIGHT_REGULAR;
  }
  *aWeight = WeightRange(MapFcWeight(weight));

  // width
  int width;
  if (FcPatternGetInteger(aFontPattern, FC_WIDTH, 0, &width) != FcResultMatch) {
    width = FC_WIDTH_NORMAL;
  }
  *aStretch = StretchRange(MapFcWidth(width));

  // italic
  int slant;
  if (FcPatternGetInteger(aFontPattern, FC_SLANT, 0, &slant) != FcResultMatch) {
    slant = FC_SLANT_ROMAN;
  }
  if (slant == FC_SLANT_OBLIQUE) {
    *aSlantStyle = SlantStyleRange(FontSlantStyle::Oblique());
  } else if (slant > 0) {
    *aSlantStyle = SlantStyleRange(FontSlantStyle::Italic());
  }
}

gfxFontconfigFontEntry::gfxFontconfigFontEntry(const nsACString& aFaceName,
                                               FcPattern* aFontPattern,
                                               bool aIgnoreFcCharmap)
    : gfxFontEntry(aFaceName),
      mFontPattern(aFontPattern),
      mFTFace(nullptr),
      mFTFaceInitialized(false),
      mIgnoreFcCharmap(aIgnoreFcCharmap),
      mHasVariationsInitialized(false),
      mAspect(0.0),
      mFontData(nullptr),
      mLength(0) {
  GetFontProperties(aFontPattern, &mWeightRange, &mStretchRange, &mStyleRange);
}

gfxFontEntry* gfxFontconfigFontEntry::Clone() const {
  MOZ_ASSERT(!IsUserFont(), "we can only clone installed fonts!");
  return new gfxFontconfigFontEntry(Name(), mFontPattern, mIgnoreFcCharmap);
}

static FcPattern* CreatePatternForFace(FT_Face aFace) {
  // Use fontconfig to fill out the pattern from the FTFace.
  // The "file" argument cannot be nullptr (in fontconfig-2.6.0 at
  // least). The dummy file passed here is removed below.
  //
  // When fontconfig scans the system fonts, FcConfigGetBlanks(nullptr)
  // is passed as the "blanks" argument, which provides that unexpectedly
  // blank glyphs are elided.  Here, however, we pass nullptr for
  // "blanks", effectively assuming that, if the font has a blank glyph,
  // then the author intends any associated character to be rendered
  // blank.
  FcPattern* pattern = FcFreeTypeQueryFace(aFace, ToFcChar8Ptr(""), 0, nullptr);
  // given that we have a FT_Face, not really sure this is possible...
  if (!pattern) {
    pattern = FcPatternCreate();
  }
  FcPatternDel(pattern, FC_FILE);
  FcPatternDel(pattern, FC_INDEX);

  // Make a new pattern and store the face in it so that cairo uses
  // that when creating a cairo font face.
  FcPatternAddFTFace(pattern, FC_FT_FACE, aFace);

  return pattern;
}

static FT_Face CreateFaceForPattern(FcPattern* aPattern) {
  FcChar8* filename;
  if (FcPatternGetString(aPattern, FC_FILE, 0, &filename) != FcResultMatch) {
    return nullptr;
  }
  int index;
  if (FcPatternGetInteger(aPattern, FC_INDEX, 0, &index) != FcResultMatch) {
    index = 0;  // default to 0 if not found in pattern
  }
  return Factory::NewFTFace(nullptr, ToCharPtr(filename), index);
}

gfxFontconfigFontEntry::gfxFontconfigFontEntry(const nsACString& aFaceName,
                                               WeightRange aWeight,
                                               StretchRange aStretch,
                                               SlantStyleRange aStyle,
                                               const uint8_t* aData,
                                               uint32_t aLength, FT_Face aFace)
    : gfxFontEntry(aFaceName),
      mFTFace(aFace),
      mFTFaceInitialized(true),
      mIgnoreFcCharmap(true),
      mHasVariationsInitialized(false),
      mAspect(0.0),
      mFontData(aData),
      mLength(aLength) {
  mWeightRange = aWeight;
  mStyleRange = aStyle;
  mStretchRange = aStretch;
  mIsDataUserFont = true;

  mFontPattern = CreatePatternForFace(mFTFace);

  mUserFontData = new FTUserFontData(mFTFace, mFontData);
}

gfxFontconfigFontEntry::gfxFontconfigFontEntry(const nsACString& aFaceName,
                                               FcPattern* aFontPattern,
                                               WeightRange aWeight,
                                               StretchRange aStretch,
                                               SlantStyleRange aStyle)
    : gfxFontEntry(aFaceName),
      mFontPattern(aFontPattern),
      mFTFace(nullptr),
      mFTFaceInitialized(false),
      mHasVariationsInitialized(false),
      mAspect(0.0),
      mFontData(nullptr),
      mLength(0) {
  mWeightRange = aWeight;
  mStyleRange = aStyle;
  mStretchRange = aStretch;
  mIsLocalUserFont = true;

  // The proper setting of mIgnoreFcCharmap is tricky for fonts loaded
  // via src:local()...
  // If the local font happens to come from the application fontset,
  // we want to set it to true so that color/svg fonts will work even
  // if the default glyphs are blank; but if the local font is a non-
  // sfnt face (e.g. legacy type 1) then we need to set it to false
  // because our cmap-reading code will fail and we depend on FT+Fc to
  // determine the coverage.
  // We set the flag here, but may flip it the first time TestCharacterMap
  // is called, at which point we'll look to see whether a 'cmap' is
  // actually present in the font.
  mIgnoreFcCharmap = true;
}

typedef FT_Error (*GetVarFunc)(FT_Face, FT_MM_Var**);
typedef FT_Error (*DoneVarFunc)(FT_Library, FT_MM_Var*);
static GetVarFunc sGetVar;
static DoneVarFunc sDoneVar;
static bool sInitializedVarFuncs = false;

static void InitializeVarFuncs() {
  if (sInitializedVarFuncs) {
    return;
  }
  sInitializedVarFuncs = true;
#if MOZ_TREE_FREETYPE
  sGetVar = &FT_Get_MM_Var;
  sDoneVar = &FT_Done_MM_Var;
#else
  sGetVar = (GetVarFunc)dlsym(RTLD_DEFAULT, "FT_Get_MM_Var");
  sDoneVar = (DoneVarFunc)dlsym(RTLD_DEFAULT, "FT_Done_MM_Var");
#endif
}

gfxFontconfigFontEntry::~gfxFontconfigFontEntry() {
  if (mMMVar) {
    // Prior to freetype 2.9, there was no specific function to free the
    // FT_MM_Var record, and the docs just said to use free().
    // InitializeVarFuncs must have been called in order for mMMVar to be
    // non-null here, so we don't need to do it again.
    if (sDoneVar) {
      MOZ_ASSERT(mFTFace, "How did mMMVar get set without a face?");
      (*sDoneVar)(mFTFace->glyph->library, mMMVar);
    } else {
      free(mMMVar);
    }
  }
}

nsresult gfxFontconfigFontEntry::ReadCMAP(FontInfoData* aFontInfoData) {
  // attempt this once, if errors occur leave a blank cmap
  if (mCharacterMap) {
    return NS_OK;
  }

  RefPtr<gfxCharacterMap> charmap;
  nsresult rv;

  if (aFontInfoData &&
      (charmap = GetCMAPFromFontInfo(aFontInfoData, mUVSOffset))) {
    rv = NS_OK;
  } else {
    uint32_t kCMAP = TRUETYPE_TAG('c', 'm', 'a', 'p');
    charmap = new gfxCharacterMap();
    AutoTable cmapTable(this, kCMAP);

    if (cmapTable) {
      uint32_t cmapLen;
      const uint8_t* cmapData = reinterpret_cast<const uint8_t*>(
          hb_blob_get_data(cmapTable, &cmapLen));
      rv = gfxFontUtils::ReadCMAP(cmapData, cmapLen, *charmap, mUVSOffset);
    } else {
      rv = NS_ERROR_NOT_AVAILABLE;
    }
  }

  mHasCmapTable = NS_SUCCEEDED(rv);
  if (mHasCmapTable) {
    gfxPlatformFontList* pfl = gfxPlatformFontList::PlatformFontList();
    fontlist::FontList* sharedFontList = pfl->SharedFontList();
    if (!IsUserFont() && mShmemFace) {
      mShmemFace->SetCharacterMap(sharedFontList, charmap);  // async
      if (!TrySetShmemCharacterMap()) {
        // Temporarily retain charmap, until the shared version is
        // ready for use.
        mCharacterMap = charmap;
      }
    } else {
      mCharacterMap = pfl->FindCharMap(charmap);
    }
  } else {
    // if error occurred, initialize to null cmap
    mCharacterMap = new gfxCharacterMap();
  }

  LOG_FONTLIST(("(fontlist-cmap) name: %s, size: %zu hash: %8.8x%s\n",
                mName.get(), charmap->SizeOfIncludingThis(moz_malloc_size_of),
                charmap->mHash, mCharacterMap == charmap ? " new" : ""));
  if (LOG_CMAPDATA_ENABLED()) {
    char prefix[256];
    SprintfLiteral(prefix, "(cmapdata) name: %.220s", mName.get());
    charmap->Dump(prefix, eGfxLog_cmapdata);
  }

  return rv;
}

static bool HasChar(FcPattern* aFont, FcChar32 aCh) {
  FcCharSet* charset = nullptr;
  FcPatternGetCharSet(aFont, FC_CHARSET, 0, &charset);
  return charset && FcCharSetHasChar(charset, aCh);
}

bool gfxFontconfigFontEntry::TestCharacterMap(uint32_t aCh) {
  // For user fonts, or for fonts bundled with the app (which might include
  // color/svg glyphs where the default glyphs may be blank, and thus confuse
  // fontconfig/freetype's char map checking), we instead check the cmap
  // directly for character coverage.
  if (mIgnoreFcCharmap) {
    // If it does not actually have a cmap, switch our strategy to use
    // fontconfig's charmap after all (except for data fonts, which must
    // always have a cmap to have passed OTS validation).
    if (!mIsDataUserFont && !HasFontTable(TRUETYPE_TAG('c', 'm', 'a', 'p'))) {
      mIgnoreFcCharmap = false;
      // ...and continue with HasChar() below.
    } else {
      return gfxFontEntry::TestCharacterMap(aCh);
    }
  }
  // otherwise (for system fonts), use the charmap in the pattern
  return HasChar(mFontPattern, aCh);
}

hb_blob_t* gfxFontconfigFontEntry::GetFontTable(uint32_t aTableTag) {
  // for data fonts, read directly from the font data
  if (mFontData) {
    return gfxFontUtils::GetTableFromFontData(mFontData, aTableTag);
  }

  return gfxFontEntry::GetFontTable(aTableTag);
}

void gfxFontconfigFontEntry::MaybeReleaseFTFace() {
  // don't release if either HB or Gr face still exists
  if (mHBFace || mGrFace) {
    return;
  }
  // only close out FT_Face for system fonts, not for data fonts
  if (!mIsDataUserFont) {
    if (mFTFace) {
      if (mMMVar) {
        if (sDoneVar) {
          (*sDoneVar)(mFTFace->glyph->library, mMMVar);
        } else {
          free(mMMVar);
        }
        mMMVar = nullptr;
      }
      Factory::ReleaseFTFace(mFTFace);
      mFTFace = nullptr;
    }
    mFTFaceInitialized = false;
  }
}

void gfxFontconfigFontEntry::ForgetHBFace() {
  gfxFontEntry::ForgetHBFace();
  MaybeReleaseFTFace();
}

void gfxFontconfigFontEntry::ReleaseGrFace(gr_face* aFace) {
  gfxFontEntry::ReleaseGrFace(aFace);
  MaybeReleaseFTFace();
}

double gfxFontconfigFontEntry::GetAspect() {
  if (mAspect != 0.0) {
    return mAspect;
  }

  // try to compute aspect from OS/2 metrics if available
  AutoTable os2Table(this, TRUETYPE_TAG('O', 'S', '/', '2'));
  if (os2Table) {
    uint16_t upem = UnitsPerEm();
    if (upem != kInvalidUPEM) {
      uint32_t len;
      auto os2 =
          reinterpret_cast<const OS2Table*>(hb_blob_get_data(os2Table, &len));
      if (uint16_t(os2->version) >= 2) {
        if (len >= offsetof(OS2Table, sxHeight) + sizeof(int16_t) &&
            int16_t(os2->sxHeight) > 0.1 * upem) {
          mAspect = double(int16_t(os2->sxHeight)) / upem;
          return mAspect;
        }
      }
    }
  }

  // default to aspect = 0.5 if the code below fails
  mAspect = 0.5;

  // create a font to calculate x-height / em-height
  gfxFontStyle s;
  s.size = 100.0;  // pick large size to avoid possible hinting artifacts
  RefPtr<gfxFont> font = FindOrMakeFont(&s);
  if (font) {
    const gfxFont::Metrics& metrics =
        font->GetMetrics(nsFontMetrics::eHorizontal);

    // The factor of 0.1 ensures that xHeight is sane so fonts don't
    // become huge.  Strictly ">" ensures that xHeight and emHeight are
    // not both zero.
    if (metrics.xHeight > 0.1 * metrics.emHeight) {
      mAspect = metrics.xHeight / metrics.emHeight;
    }
  }

  return mAspect;
}

static void PrepareFontOptions(FcPattern* aPattern,
                               cairo_font_options_t* aFontOptions) {
  NS_ASSERTION(aFontOptions, "null font options passed to PrepareFontOptions");

  // xxx - taken from the gfxFontconfigFonts code, needs to be reviewed

  FcBool printing;
  if (FcPatternGetBool(aPattern, PRINTING_FC_PROPERTY, 0, &printing) !=
      FcResultMatch) {
    printing = FcFalse;
  }

  // Font options are set explicitly here to improve cairo's caching
  // behavior and to record the relevant parts of the pattern for
  // SetupCairoFont (so that the pattern can be released).
  //
  // Most font_options have already been set as defaults on the FcPattern
  // with cairo_ft_font_options_substitute(), then user and system
  // fontconfig configurations were applied.  The resulting font_options
  // have been recorded on the face during
  // cairo_ft_font_face_create_for_pattern().
  //
  // None of the settings here cause this scaled_font to behave any
  // differently from how it would behave if it were created from the same
  // face with default font_options.
  //
  // We set options explicitly so that the same scaled_font will be found in
  // the cairo_scaled_font_map when cairo loads glyphs from a context with
  // the same font_face, font_matrix, ctm, and surface font_options.
  //
  // Unfortunately, _cairo_scaled_font_keys_equal doesn't know about the
  // font_options on the cairo_ft_font_face, and doesn't consider default
  // option values to not match any explicit values.
  //
  // Even after cairo_set_scaled_font is used to set font_options for the
  // cairo context, when cairo looks for a scaled_font for the context, it
  // will look for a font with some option values from the target surface if
  // any values are left default on the context font_options.  If this
  // scaled_font is created with default font_options, cairo will not find
  // it.
  //
  // The one option not recorded in the pattern is hint_metrics, which will
  // affect glyph metrics.  The default behaves as CAIRO_HINT_METRICS_ON.
  // We should be considering the font_options of the surface on which this
  // font will be used, but currently we don't have different gfxFonts for
  // different surface font_options, so we'll create a font suitable for the
  // Screen. Image and xlib surfaces default to CAIRO_HINT_METRICS_ON.
  if (printing) {
    cairo_font_options_set_hint_metrics(aFontOptions, CAIRO_HINT_METRICS_OFF);
  } else {
    cairo_font_options_set_hint_metrics(aFontOptions, CAIRO_HINT_METRICS_ON);
  }

  // The remaining options have been recorded on the pattern and the face.
  // _cairo_ft_options_merge has some logic to decide which options from the
  // scaled_font or from the cairo_ft_font_face take priority in the way the
  // font behaves.
  //
  // In the majority of cases, _cairo_ft_options_merge uses the options from
  // the cairo_ft_font_face, so sometimes it is not so important which
  // values are set here so long as they are not defaults, but we'll set
  // them to the exact values that we expect from the font, to be consistent
  // and to protect against changes in cairo.
  //
  // In some cases, _cairo_ft_options_merge uses some options from the
  // scaled_font's font_options rather than options on the
  // cairo_ft_font_face (from fontconfig).
  // https://bugs.freedesktop.org/show_bug.cgi?id=11838
  //
  // Surface font options were set on the pattern in
  // cairo_ft_font_options_substitute.  If fontconfig has changed the
  // hint_style then that is what the user (or distribution) wants, so we
  // use the setting from the FcPattern.
  //
  // Fallback values here mirror treatment of defaults in cairo-ft-font.c.
  FcBool hinting = FcFalse;
  if (FcPatternGetBool(aPattern, FC_HINTING, 0, &hinting) != FcResultMatch) {
    hinting = FcTrue;
  }

  cairo_hint_style_t hint_style;
  if (printing || !hinting) {
    hint_style = CAIRO_HINT_STYLE_NONE;
  } else {
    int fc_hintstyle;
    if (FcPatternGetInteger(aPattern, FC_HINT_STYLE, 0, &fc_hintstyle) !=
        FcResultMatch) {
      fc_hintstyle = FC_HINT_FULL;
    }
    switch (fc_hintstyle) {
      case FC_HINT_NONE:
        hint_style = CAIRO_HINT_STYLE_NONE;
        break;
      case FC_HINT_SLIGHT:
        hint_style = CAIRO_HINT_STYLE_SLIGHT;
        break;
      case FC_HINT_MEDIUM:
      default:  // This fallback mirrors _get_pattern_ft_options in cairo.
        hint_style = CAIRO_HINT_STYLE_MEDIUM;
        break;
      case FC_HINT_FULL:
        hint_style = CAIRO_HINT_STYLE_FULL;
        break;
    }
  }
  cairo_font_options_set_hint_style(aFontOptions, hint_style);

  int rgba;
  if (FcPatternGetInteger(aPattern, FC_RGBA, 0, &rgba) != FcResultMatch) {
    rgba = FC_RGBA_UNKNOWN;
  }
  cairo_subpixel_order_t subpixel_order = CAIRO_SUBPIXEL_ORDER_DEFAULT;
  switch (rgba) {
    case FC_RGBA_UNKNOWN:
    case FC_RGBA_NONE:
    default:
      // There is no CAIRO_SUBPIXEL_ORDER_NONE.  Subpixel antialiasing
      // is disabled through cairo_antialias_t.
      rgba = FC_RGBA_NONE;
      // subpixel_order won't be used by the font as we won't use
      // CAIRO_ANTIALIAS_SUBPIXEL, but don't leave it at default for
      // caching reasons described above.  Fall through:
      MOZ_FALLTHROUGH;
    case FC_RGBA_RGB:
      subpixel_order = CAIRO_SUBPIXEL_ORDER_RGB;
      break;
    case FC_RGBA_BGR:
      subpixel_order = CAIRO_SUBPIXEL_ORDER_BGR;
      break;
    case FC_RGBA_VRGB:
      subpixel_order = CAIRO_SUBPIXEL_ORDER_VRGB;
      break;
    case FC_RGBA_VBGR:
      subpixel_order = CAIRO_SUBPIXEL_ORDER_VBGR;
      break;
  }
  cairo_font_options_set_subpixel_order(aFontOptions, subpixel_order);

  FcBool fc_antialias;
  if (FcPatternGetBool(aPattern, FC_ANTIALIAS, 0, &fc_antialias) !=
      FcResultMatch) {
    fc_antialias = FcTrue;
  }
  cairo_antialias_t antialias;
  if (!fc_antialias) {
    antialias = CAIRO_ANTIALIAS_NONE;
  } else if (rgba == FC_RGBA_NONE) {
    antialias = CAIRO_ANTIALIAS_GRAY;
  } else {
    antialias = CAIRO_ANTIALIAS_SUBPIXEL;
  }
  cairo_font_options_set_antialias(aFontOptions, antialias);
}

static void ReleaseFTUserFontData(void* aData) {
  static_cast<FTUserFontData*>(aData)->Release();
}

static cairo_user_data_key_t sFcFontlistFTFaceKey;

static void ReleaseFTFace(void* aData) {
  Factory::ReleaseFTFace(static_cast<FT_Face>(aData));
}

cairo_scaled_font_t* gfxFontconfigFontEntry::CreateScaledFont(
    FcPattern* aRenderPattern, gfxFloat aAdjustedSize,
    const gfxFontStyle* aStyle, FT_Face aFTFace) {
  if (aStyle->NeedsSyntheticBold(this)) {
    FcPatternAddBool(aRenderPattern, FC_EMBOLDEN, FcTrue);
  }

  // will synthetic oblique be applied using a transform?
  bool needsOblique = IsUpright() &&
                      aStyle->style != FontSlantStyle::Normal() &&
                      aStyle->allowSyntheticStyle;

  if (needsOblique) {
    // disable embedded bitmaps (mimics behavior in 90-synthetic.conf)
    FcPatternDel(aRenderPattern, FC_EMBEDDED_BITMAP);
    FcPatternAddBool(aRenderPattern, FC_EMBEDDED_BITMAP, FcFalse);
  }

  AutoTArray<FT_Fixed, 8> coords;
  if (HasVariations()) {
    FT_Face ftFace = GetFTFace();
    if (ftFace) {
      AutoTArray<gfxFontVariation, 8> settings;
      GetVariationsForStyle(settings, *aStyle);
      gfxFT2FontBase::SetupVarCoords(GetMMVar(), settings, &coords);
    }
  }

  cairo_font_face_t* face = cairo_ft_font_face_create_for_pattern(
      aRenderPattern, coords.Elements(), coords.Length());

  if (aFTFace) {
    if (cairo_font_face_set_user_data(face, &sFcFontlistFTFaceKey, aFTFace,
                                      ReleaseFTFace) != CAIRO_STATUS_SUCCESS) {
      NS_WARNING("Failed binding FT_Face to Cairo font face");
      cairo_font_face_destroy(face);
      Factory::ReleaseFTFace(aFTFace);
      return nullptr;
    }
  }

  if (mFontData) {
    // for data fonts, add the face/data pointer to the cairo font face
    // so that it ges deleted whenever cairo decides
    NS_ASSERTION(mFTFace, "FT_Face is null when setting user data");
    NS_ASSERTION(mUserFontData,
                 "user font data is null when setting user data");
    mUserFontData.get()->AddRef();
    if (cairo_font_face_set_user_data(face, &sFcFontlistUserFontDataKey,
                                      mUserFontData, ReleaseFTUserFontData) !=
        CAIRO_STATUS_SUCCESS) {
      NS_WARNING("Failed binding FTUserFontData to Cairo font face");
      mUserFontData.get()->Release();
      cairo_font_face_destroy(face);
      return nullptr;
    }
  }

  cairo_scaled_font_t* scaledFont = nullptr;

  cairo_matrix_t sizeMatrix;
  cairo_matrix_t identityMatrix;

  cairo_matrix_init_scale(&sizeMatrix, aAdjustedSize, aAdjustedSize);
  cairo_matrix_init_identity(&identityMatrix);

  cairo_font_options_t* fontOptions = cairo_font_options_create();
  PrepareFontOptions(aRenderPattern, fontOptions);

  scaledFont =
      cairo_scaled_font_create(face, &sizeMatrix, &identityMatrix, fontOptions);
  cairo_font_options_destroy(fontOptions);

  NS_ASSERTION(cairo_scaled_font_status(scaledFont) == CAIRO_STATUS_SUCCESS,
               "Failed to make scaled font");

  cairo_font_face_destroy(face);

  return scaledFont;
}

#ifdef MOZ_WIDGET_GTK
// defintion included below
static void ApplyGdkScreenFontOptions(FcPattern* aPattern);
#endif

#ifdef MOZ_X11
static bool GetXftInt(Display* aDisplay, const char* aName, int* aResult) {
  if (!aDisplay) {
    return false;
  }
  char* value = XGetDefault(aDisplay, "Xft", aName);
  if (!value) {
    return false;
  }
  if (FcNameConstant(const_cast<FcChar8*>(ToFcChar8Ptr(value)), aResult)) {
    return true;
  }
  char* end;
  *aResult = strtol(value, &end, 0);
  if (end != value) {
    return true;
  }
  return false;
}
#endif

static void PreparePattern(FcPattern* aPattern, bool aIsPrinterFont) {
  FcConfigSubstitute(nullptr, aPattern, FcMatchPattern);

  // This gets cairo_font_options_t for the Screen.  We should have
  // different font options for printing (no hinting) but we are not told
  // what we are measuring for.
  //
  // If cairo adds support for lcd_filter, gdk will not provide the default
  // setting for that option.  We could get the default setting by creating
  // an xlib surface once, recording its font_options, and then merging the
  // gdk options.
  //
  // Using an xlib surface would also be an option to get Screen font
  // options for non-GTK X11 toolkits, but less efficient than using GDK to
  // pick up dynamic changes.
  if (aIsPrinterFont) {
    cairo_font_options_t* options = cairo_font_options_create();
    cairo_font_options_set_hint_style(options, CAIRO_HINT_STYLE_NONE);
    cairo_font_options_set_antialias(options, CAIRO_ANTIALIAS_GRAY);
    cairo_ft_font_options_substitute(options, aPattern);
    cairo_font_options_destroy(options);
    FcPatternAddBool(aPattern, PRINTING_FC_PROPERTY, FcTrue);
  } else if (!gfxPlatform::IsHeadless()) {
#ifdef MOZ_WIDGET_GTK
    ApplyGdkScreenFontOptions(aPattern);

#  ifdef MOZ_X11
    FcValue value;
    int lcdfilter;
    if (FcPatternGet(aPattern, FC_LCD_FILTER, 0, &value) == FcResultNoMatch) {
      GdkDisplay* dpy = gdk_display_get_default();
      if (GDK_IS_X11_DISPLAY(dpy) &&
          GetXftInt(GDK_DISPLAY_XDISPLAY(dpy), "lcdfilter", &lcdfilter)) {
        FcPatternAddInteger(aPattern, FC_LCD_FILTER, lcdfilter);
      }
    }
#  endif  // MOZ_X11
#endif    // MOZ_WIDGET_GTK
  }

  FcDefaultSubstitute(aPattern);
}

void gfxFontconfigFontEntry::UnscaledFontCache::MoveToFront(size_t aIndex) {
  if (aIndex > 0) {
    ThreadSafeWeakPtr<UnscaledFontFontconfig> front =
        std::move(mUnscaledFonts[aIndex]);
    for (size_t i = aIndex; i > 0; i--) {
      mUnscaledFonts[i] = std::move(mUnscaledFonts[i - 1]);
    }
    mUnscaledFonts[0] = std::move(front);
  }
}

already_AddRefed<UnscaledFontFontconfig>
gfxFontconfigFontEntry::UnscaledFontCache::Lookup(const char* aFile,
                                                  uint32_t aIndex) {
  for (size_t i = 0; i < kNumEntries; i++) {
    RefPtr<UnscaledFontFontconfig> entry(mUnscaledFonts[i]);
    if (entry && !strcmp(entry->GetFile(), aFile) &&
        entry->GetIndex() == aIndex) {
      MoveToFront(i);
      return entry.forget();
    }
  }
  return nullptr;
}

static inline gfxFloat SizeForStyle(gfxFontconfigFontEntry* aEntry,
                                    const gfxFontStyle& aStyle) {
  return aStyle.sizeAdjust >= 0.0 ? aStyle.GetAdjustedSize(aEntry->GetAspect())
                                  : aStyle.size;
}

static double ChooseFontSize(gfxFontconfigFontEntry* aEntry,
                             const gfxFontStyle& aStyle) {
  double requestedSize = SizeForStyle(aEntry, aStyle);
  double bestDist = -1.0;
  double bestSize = requestedSize;
  double size;
  int v = 0;
  while (FcPatternGetDouble(aEntry->GetPattern(), FC_PIXEL_SIZE, v, &size) ==
         FcResultMatch) {
    ++v;
    double dist = fabs(size - requestedSize);
    if (bestDist < 0.0 || dist < bestDist) {
      bestDist = dist;
      bestSize = size;
    }
  }
  // If the font has bitmaps but wants to be scaled, then let it scale.
  if (bestSize >= 0.0) {
    FcBool scalable;
    if (FcPatternGetBool(aEntry->GetPattern(), FC_SCALABLE, 0, &scalable) ==
            FcResultMatch &&
        scalable) {
      return requestedSize;
    }
  }
  return bestSize;
}

gfxFont* gfxFontconfigFontEntry::CreateFontInstance(
    const gfxFontStyle* aFontStyle) {
  FcPattern* fontPattern = mFontPattern;
  if (!fontPattern) {
    return nullptr;
  }

  nsAutoRef<FcPattern> pattern(FcPatternCreate());
  if (!pattern) {
    NS_WARNING("Failed to create Fontconfig pattern for font instance");
    return nullptr;
  }

  double size = ChooseFontSize(this, *aFontStyle);
  FcPatternAddDouble(pattern, FC_PIXEL_SIZE, size);

  FT_Face face = mFTFace;
  if (face && face->face_flags & FT_FACE_FLAG_MULTIPLE_MASTERS) {
    // For variation fonts, we create a new FT_Face and FcPattern here
    // so that variation coordinates from the style can be applied
    // without affecting other font instances created from the same
    // entry (font resource).
    if (mFontData) {
      // For user fonts: create a new FT_Face from the font data, and then
      // make a pattern from that.
      face = Factory::NewFTFaceFromData(nullptr, mFontData, mLength, 0);
      fontPattern = CreatePatternForFace(face);
    } else {
      // For system fonts: create a new FT_Face and store it in a copy of
      // the original mFontPattern.
      fontPattern = FcPatternDuplicate(mFontPattern);
      face = CreateFaceForPattern(fontPattern);
      if (face) {
        FcPatternAddFTFace(fontPattern, FC_FT_FACE, face);
      } else {
        // I don't think CreateFaceForPattern above should ever fail,
        // but just in case let's fall back here.
        face = mFTFace;
      }
    }
  }

  PreparePattern(pattern, aFontStyle->printerFont);
  nsAutoRef<FcPattern> renderPattern(
      FcFontRenderPrepare(nullptr, pattern, fontPattern));
  if (fontPattern != mFontPattern) {
    // Discard temporary pattern used for variation support
    FcPatternDestroy(fontPattern);
  }
  if (!renderPattern) {
    NS_WARNING("Failed to prepare Fontconfig pattern for font instance");
    if (face != mFTFace) {
      Factory::ReleaseFTFace(face);
    }
    return nullptr;
  }

  cairo_scaled_font_t* scaledFont = CreateScaledFont(
      renderPattern, size, aFontStyle, face != mFTFace ? face : nullptr);

  const FcChar8* file = ToFcChar8Ptr("");
  int index = 0;
  if (!mFontData) {
    if (FcPatternGetString(renderPattern, FC_FILE, 0,
                           const_cast<FcChar8**>(&file)) != FcResultMatch ||
        FcPatternGetInteger(renderPattern, FC_INDEX, 0, &index) !=
            FcResultMatch) {
      NS_WARNING("No file in Fontconfig pattern for font instance");
      return nullptr;
    }
  }

  RefPtr<UnscaledFontFontconfig> unscaledFont =
      mUnscaledFontCache.Lookup(ToCharPtr(file), index);
  if (!unscaledFont) {
    unscaledFont = mFontData
                       ? new UnscaledFontFontconfig(mFTFace)
                       : new UnscaledFontFontconfig(ToCharPtr(file), index);
    mUnscaledFontCache.Add(unscaledFont);
  }

  gfxFont* newFont = new gfxFontconfigFont(
      unscaledFont, scaledFont, renderPattern, size, this, aFontStyle);
  cairo_scaled_font_destroy(scaledFont);

  return newFont;
}

FT_Face gfxFontconfigFontEntry::GetFTFace() {
  if (!mFTFaceInitialized) {
    mFTFaceInitialized = true;
    mFTFace = CreateFaceForPattern(mFontPattern);
  }
  return mFTFace;
}

bool gfxFontconfigFontEntry::HasVariations() {
  if (mHasVariationsInitialized) {
    return mHasVariations;
  }
  mHasVariationsInitialized = true;
  mHasVariations = false;

  if (!gfxPlatform::GetPlatform()->HasVariationFontSupport()) {
    return mHasVariations;
  }

  // For installed fonts, query the fontconfig pattern rather than paying
  // the cost of loading a FT_Face that we otherwise might never need.
  if (!IsUserFont() || IsLocalUserFont()) {
    FcBool variable;
    if ((FcPatternGetBool(mFontPattern, FC_VARIABLE, 0, &variable) ==
         FcResultMatch) &&
        variable) {
      mHasVariations = true;
    }
  } else {
    FT_Face face = GetFTFace();
    if (face) {
      mHasVariations = face->face_flags & FT_FACE_FLAG_MULTIPLE_MASTERS;
    }
  }

  return mHasVariations;
}

FT_MM_Var* gfxFontconfigFontEntry::GetMMVar() {
  if (mMMVarInitialized) {
    return mMMVar;
  }
  mMMVarInitialized = true;
  InitializeVarFuncs();
  if (!sGetVar) {
    return nullptr;
  }
  FT_Face face = GetFTFace();
  if (!face) {
    return nullptr;
  }
  if (FT_Err_Ok != (*sGetVar)(face, &mMMVar)) {
    mMMVar = nullptr;
  }
  return mMMVar;
}

void gfxFontconfigFontEntry::GetVariationAxes(
    nsTArray<gfxFontVariationAxis>& aAxes) {
  if (!HasVariations()) {
    return;
  }
  gfxFT2Utils::GetVariationAxes(GetMMVar(), aAxes);
}

void gfxFontconfigFontEntry::GetVariationInstances(
    nsTArray<gfxFontVariationInstance>& aInstances) {
  if (!HasVariations()) {
    return;
  }
  gfxFT2Utils::GetVariationInstances(this, GetMMVar(), aInstances);
}

nsresult gfxFontconfigFontEntry::CopyFontTable(uint32_t aTableTag,
                                               nsTArray<uint8_t>& aBuffer) {
  NS_ASSERTION(!mIsDataUserFont,
               "data fonts should be reading tables directly from memory");

  FT_Face face = GetFTFace();
  if (!face) {
    return NS_ERROR_NOT_AVAILABLE;
  }

  FT_ULong length = 0;
  if (FT_Load_Sfnt_Table(face, aTableTag, 0, nullptr, &length) != 0) {
    return NS_ERROR_NOT_AVAILABLE;
  }
  if (!aBuffer.SetLength(length, fallible)) {
    return NS_ERROR_OUT_OF_MEMORY;
  }
  if (FT_Load_Sfnt_Table(face, aTableTag, 0, aBuffer.Elements(), &length) !=
      0) {
    aBuffer.Clear();
    return NS_ERROR_FAILURE;
  }

  return NS_OK;
}

void gfxFontconfigFontFamily::FindStyleVariations(FontInfoData* aFontInfoData) {
  if (mHasStyles) {
    return;
  }

  // add font entries for each of the faces
  uint32_t numFonts = mFontPatterns.Length();
  NS_ASSERTION(numFonts, "font family containing no faces!!");
  uint32_t numRegularFaces = 0;
  for (uint32_t i = 0; i < numFonts; i++) {
    FcPattern* face = mFontPatterns[i];

    // figure out the psname/fullname and choose which to use as the facename
    nsAutoCString psname, fullname;
    GetFaceNames(face, mName, psname, fullname);
    const nsAutoCString& faceName = !psname.IsEmpty() ? psname : fullname;

    gfxFontconfigFontEntry* fontEntry =
        new gfxFontconfigFontEntry(faceName, face, mContainsAppFonts);

    if (gfxPlatform::GetPlatform()->HasVariationFontSupport()) {
      fontEntry->SetupVariationRanges();
    }

    AddFontEntry(fontEntry);

    if (fontEntry->IsNormalStyle()) {
      numRegularFaces++;
    }

    if (LOG_FONTLIST_ENABLED()) {
      nsAutoCString weightString;
      fontEntry->Weight().ToString(weightString);
      nsAutoCString stretchString;
      fontEntry->Stretch().ToString(stretchString);
      nsAutoCString styleString;
      fontEntry->SlantStyle().ToString(styleString);
      LOG_FONTLIST(
          ("(fontlist) added (%s) to family (%s)"
           " with style: %s weight: %s stretch: %s"
           " psname: %s fullname: %s",
           fontEntry->Name().get(), Name().get(), styleString.get(),
           weightString.get(), stretchString.get(), psname.get(),
           fullname.get()));
    }
  }

  // somewhat arbitrary, but define a family with two or more regular
  // faces as a family for which intra-family fallback should be used
  if (numRegularFaces > 1) {
    mCheckForFallbackFaces = true;
  }
  mFaceNamesInitialized = true;
  mFontPatterns.Clear();
  SetHasStyles(true);
}

void gfxFontconfigFontFamily::AddFontPattern(FcPattern* aFontPattern) {
  NS_ASSERTION(
      !mHasStyles,
      "font patterns must not be added to already enumerated families");

  FcBool outline;
  if (FcPatternGetBool(aFontPattern, FC_OUTLINE, 0, &outline) !=
          FcResultMatch ||
      !outline) {
    mHasNonScalableFaces = true;

    FcBool scalable;
    if (FcPatternGetBool(aFontPattern, FC_SCALABLE, 0, &scalable) ==
            FcResultMatch &&
        scalable) {
      mForceScalable = true;
    }
  }

  nsCountedRef<FcPattern> pattern(aFontPattern);
  mFontPatterns.AppendElement(pattern);
}

static const double kRejectDistance = 10000.0;

// Calculate a distance score representing the size disparity between the
// requested style's size and the font entry's size.
static double SizeDistance(gfxFontconfigFontEntry* aEntry,
                           const gfxFontStyle& aStyle, bool aForceScalable) {
  double requestedSize = SizeForStyle(aEntry, aStyle);
  double bestDist = -1.0;
  double size;
  int v = 0;
  while (FcPatternGetDouble(aEntry->GetPattern(), FC_PIXEL_SIZE, v, &size) ==
         FcResultMatch) {
    ++v;
    double dist = fabs(size - requestedSize);
    if (bestDist < 0.0 || dist < bestDist) {
      bestDist = dist;
    }
  }
  if (bestDist < 0.0) {
    // No size means scalable
    return -1.0;
  } else if (aForceScalable || 5.0 * bestDist < requestedSize) {
    // fontconfig prefers a matching family or lang to pixelsize of bitmap
    // fonts. CSS suggests a tolerance of 20% on pixelsize.
    return bestDist;
  } else {
    // Reject any non-scalable fonts that are not within tolerance.
    return kRejectDistance;
  }
}

void gfxFontconfigFontFamily::FindAllFontsForStyle(
    const gfxFontStyle& aFontStyle, nsTArray<gfxFontEntry*>& aFontEntryList,
    bool aIgnoreSizeTolerance) {
  gfxFontFamily::FindAllFontsForStyle(aFontStyle, aFontEntryList,
                                      aIgnoreSizeTolerance);

  if (!mHasNonScalableFaces) {
    return;
  }

  // Iterate over the the available fonts while compacting any groups
  // of unscalable fonts with matching styles into a single entry
  // corresponding to the closest available size. If the closest
  // available size is rejected for being outside tolerance, then the
  // entire group will be skipped.
  size_t skipped = 0;
  gfxFontconfigFontEntry* bestEntry = nullptr;
  double bestDist = -1.0;
  for (size_t i = 0; i < aFontEntryList.Length(); i++) {
    gfxFontconfigFontEntry* entry =
        static_cast<gfxFontconfigFontEntry*>(aFontEntryList[i]);
    double dist =
        SizeDistance(entry, aFontStyle, mForceScalable || aIgnoreSizeTolerance);
    // If the entry is scalable or has a style that does not match
    // the group of unscalable fonts, then start a new group.
    if (dist < 0.0 || !bestEntry || bestEntry->Stretch() != entry->Stretch() ||
        bestEntry->Weight() != entry->Weight() ||
        bestEntry->SlantStyle() != entry->SlantStyle()) {
      // If the best entry in this group is still outside the tolerance,
      // then skip the entire group.
      if (bestDist >= kRejectDistance) {
        skipped++;
      }
      // Remove any compacted entries from the previous group.
      if (skipped) {
        i -= skipped;
        aFontEntryList.RemoveElementsAt(i, skipped);
        skipped = 0;
      }
      // Mark the start of the new group.
      bestEntry = entry;
      bestDist = dist;
    } else {
      // If this entry more closely matches the requested size than the
      // current best in the group, then take this entry instead.
      if (dist < bestDist) {
        aFontEntryList[i - 1 - skipped] = entry;
        bestEntry = entry;
        bestDist = dist;
      }
      skipped++;
    }
  }
  // If the best entry in this group is still outside the tolerance,
  // then skip the entire group.
  if (bestDist >= kRejectDistance) {
    skipped++;
  }
  // Remove any compacted entries from the current group.
  if (skipped) {
    aFontEntryList.TruncateLength(aFontEntryList.Length() - skipped);
  }
}

static bool PatternHasLang(const FcPattern* aPattern, const FcChar8* aLang) {
  FcLangSet* langset;

  if (FcPatternGetLangSet(aPattern, FC_LANG, 0, &langset) != FcResultMatch) {
    return false;
  }

  if (FcLangSetHasLang(langset, aLang) != FcLangDifferentLang) {
    return true;
  }
  return false;
}

bool gfxFontconfigFontFamily::SupportsLangGroup(nsAtom* aLangGroup) const {
  if (!aLangGroup || aLangGroup == nsGkAtoms::Unicode) {
    return true;
  }

  nsAutoCString fcLang;
  gfxFcPlatformFontList* pfl = gfxFcPlatformFontList::PlatformFontList();
  pfl->GetSampleLangForGroup(aLangGroup, fcLang);
  if (fcLang.IsEmpty()) {
    return true;
  }

  // Before FindStyleVariations has been called, mFontPatterns will contain
  // the font patterns.  Afterward, it'll be empty, but mAvailableFonts
  // will contain the font entries, each of which holds a reference to its
  // pattern.  We only check the first pattern in each list, because support
  // for langs is considered to be consistent across all faces in a family.
  FcPattern* fontPattern;
  if (mFontPatterns.Length()) {
    fontPattern = mFontPatterns[0];
  } else if (mAvailableFonts.Length()) {
    fontPattern = static_cast<gfxFontconfigFontEntry*>(mAvailableFonts[0].get())
                      ->GetPattern();
  } else {
    return true;
  }

  // is lang included in the underlying pattern?
  return PatternHasLang(fontPattern, ToFcChar8Ptr(fcLang.get()));
}

/* virtual */
gfxFontconfigFontFamily::~gfxFontconfigFontFamily() {
  // Should not be dropped by stylo
  MOZ_ASSERT(NS_IsMainThread());
}

template <typename Func>
void gfxFontconfigFontFamily::AddFacesToFontList(Func aAddPatternFunc) {
  if (HasStyles()) {
    for (auto& fe : mAvailableFonts) {
      if (!fe) {
        continue;
      }
      auto fce = static_cast<gfxFontconfigFontEntry*>(fe.get());
      aAddPatternFunc(fce->GetPattern(), mContainsAppFonts);
    }
  } else {
    for (auto& pat : mFontPatterns) {
      aAddPatternFunc(pat, mContainsAppFonts);
    }
  }
}

gfxFontconfigFont::gfxFontconfigFont(
    const RefPtr<UnscaledFontFontconfig>& aUnscaledFont,
    cairo_scaled_font_t* aScaledFont, FcPattern* aPattern,
    gfxFloat aAdjustedSize, gfxFontEntry* aFontEntry,
    const gfxFontStyle* aFontStyle)
    : gfxFT2FontBase(aUnscaledFont, aScaledFont, aFontEntry, aFontStyle),
      mPattern(aPattern) {
  mAdjustedSize = aAdjustedSize;
}

gfxFontconfigFont::~gfxFontconfigFont() {}

already_AddRefed<ScaledFont> gfxFontconfigFont::GetScaledFont(
    mozilla::gfx::DrawTarget* aTarget) {
  if (!mAzureScaledFont) {
    NativeFont nativeFont;
    nativeFont.mType = NativeFontType::FONTCONFIG_PATTERN;
    nativeFont.mFont = GetPattern();

    mAzureScaledFont = Factory::CreateScaledFontForNativeFont(
        nativeFont, GetUnscaledFont(), GetAdjustedSize(), GetCairoScaledFont());
    InitializeScaledFont();
  }

  RefPtr<ScaledFont> scaledFont(mAzureScaledFont);
  return scaledFont.forget();
}

gfxFcPlatformFontList::gfxFcPlatformFontList()
    : mLocalNames(64),
      mGenericMappings(32),
      mFcSubstituteCache(64),
      mLastConfig(nullptr),
      mAlwaysUseFontconfigGenerics(true) {
  if (XRE_IsParentProcess()) {
    // if the rescan interval is set, start the timer
    int rescanInterval = FcConfigGetRescanInterval(nullptr);
    if (rescanInterval) {
      mLastConfig = FcConfigGetCurrent();
      NS_NewTimerWithFuncCallback(
          getter_AddRefs(mCheckFontUpdatesTimer), CheckFontUpdates, this,
          (rescanInterval + 1) * 1000, nsITimer::TYPE_REPEATING_SLACK,
          "gfxFcPlatformFontList::gfxFcPlatformFontList");
      if (!mCheckFontUpdatesTimer) {
        NS_WARNING("Failure to create font updates timer");
      }
    }
  }

#ifdef MOZ_BUNDLED_FONTS
  mBundledFontsInitialized = false;
#endif
}

gfxFcPlatformFontList::~gfxFcPlatformFontList() {
  if (mCheckFontUpdatesTimer) {
    mCheckFontUpdatesTimer->Cancel();
    mCheckFontUpdatesTimer = nullptr;
  }
}

void gfxFcPlatformFontList::AddFontSetFamilies(FcFontSet* aFontSet,
                                               const SandboxPolicy* aPolicy,
                                               bool aAppFonts) {
  // This iterates over the fonts in a font set and adds in gfxFontFamily
  // objects for each family. Individual gfxFontEntry objects for each face
  // are not created here; the patterns are just stored in the family. When
  // a family is actually used, it will be populated with gfxFontEntry
  // records and the patterns moved to those.

  if (!aFontSet) {
    NS_WARNING("AddFontSetFamilies called with a null font set.");
    return;
  }

  FcChar8* lastFamilyName = (FcChar8*)"";
  RefPtr<gfxFontconfigFontFamily> fontFamily;
  nsAutoCString familyName;
  for (int f = 0; f < aFontSet->nfont; f++) {
    FcPattern* pattern = aFontSet->fonts[f];

    // Skip any fonts that aren't readable for us (e.g. due to restrictive
    // file ownership/permissions).
    FcChar8* path;
    if (FcPatternGetString(pattern, FC_FILE, 0, &path) != FcResultMatch) {
      continue;
    }
    if (access(reinterpret_cast<const char*>(path), F_OK | R_OK) != 0) {
      continue;
    }

#if defined(MOZ_SANDBOX) && defined(XP_LINUX)
    // Skip any fonts that will be blocked by the content-process sandbox
    // policy.
    if (aPolicy && !(aPolicy->Lookup(reinterpret_cast<const char*>(path)) &
                     SandboxBroker::Perms::MAY_READ)) {
      continue;
    }
#endif

    AddPatternToFontList(pattern, lastFamilyName, familyName, fontFamily,
                         aAppFonts);
  }
}

void gfxFcPlatformFontList::AddPatternToFontList(
    FcPattern* aFont, FcChar8*& aLastFamilyName, nsACString& aFamilyName,
    RefPtr<gfxFontconfigFontFamily>& aFontFamily, bool aAppFonts) {
  // get canonical name
  uint32_t cIndex = FindCanonicalNameIndex(aFont, FC_FAMILYLANG);
  FcChar8* canonical = nullptr;
  FcPatternGetString(aFont, FC_FAMILY, cIndex, &canonical);
  if (!canonical) {
    return;
  }

  // same as the last one? no need to add a new family, skip
  if (FcStrCmp(canonical, aLastFamilyName) != 0) {
    aLastFamilyName = canonical;

    // add new family if one doesn't already exist
    aFamilyName.Truncate();
    aFamilyName = ToCharPtr(canonical);
    nsAutoCString keyName(aFamilyName);
    ToLowerCase(keyName);

    aFontFamily =
        static_cast<gfxFontconfigFontFamily*>(mFontFamilies.GetWeak(keyName));
    if (!aFontFamily) {
      aFontFamily = new gfxFontconfigFontFamily(aFamilyName);
      mFontFamilies.Put(keyName, aFontFamily);
    }
    // Record if the family contains fonts from the app font set
    // (in which case we won't rely on fontconfig's charmap, due to
    // bug 1276594).
    if (aAppFonts) {
      aFontFamily->SetFamilyContainsAppFonts(true);
    }

    // Add pointers to other localized family names. Most fonts
    // only have a single name, so the first call to GetString
    // will usually not match
    FcChar8* otherName;
    int n = (cIndex == 0 ? 1 : 0);
    while (FcPatternGetString(aFont, FC_FAMILY, n, &otherName) ==
           FcResultMatch) {
      nsAutoCString otherFamilyName(ToCharPtr(otherName));
      AddOtherFamilyName(aFontFamily, otherFamilyName);
      n++;
      if (n == int(cIndex)) {
        n++;  // skip over canonical name
      }
    }
  }

  MOZ_ASSERT(aFontFamily, "font must belong to a font family");
  aFontFamily->AddFontPattern(aFont);

  // map the psname, fullname ==> font family for local font lookups
  nsAutoCString psname, fullname;
  GetFaceNames(aFont, aFamilyName, psname, fullname);
  if (!psname.IsEmpty()) {
    ToLowerCase(psname);
    mLocalNames.Put(psname, aFont);
  }
  if (!fullname.IsEmpty()) {
    ToLowerCase(fullname);
    mLocalNames.Put(fullname, aFont);
  }
}

nsresult gfxFcPlatformFontList::InitFontListForPlatform() {
#ifdef MOZ_BUNDLED_FONTS
  ActivateBundledFonts();
#endif

  mLocalNames.Clear();
  mFcSubstituteCache.Clear();

  mAlwaysUseFontconfigGenerics = PrefFontListsUseOnlyGenerics();
  mOtherFamilyNamesInitialized = true;

  if (XRE_IsContentProcess()) {
    // Content process: use the font list passed from the chrome process,
    // because we can't rely on fontconfig in the presence of sandboxing;
    // it may report fonts that we can't actually access.

    FcChar8* lastFamilyName = (FcChar8*)"";
    RefPtr<gfxFontconfigFontFamily> fontFamily;
    nsAutoCString familyName;

    // Get font list that was passed during XPCOM startup
    // or in an UpdateFontList message.
    auto& fontList = dom::ContentChild::GetSingleton()->SystemFontList();

    // For fontconfig versions between 2.10.94 and 2.11.1 inclusive,
    // we need to escape any leading space in the charset element,
    // otherwise FcNameParse will fail. :(
    //
    // The bug was introduced on 2013-05-24 by
    //   https://cgit.freedesktop.org/fontconfig/commit/?id=cd9b1033a68816a7acfbba1718ba0aa5888f6ec7
    //   "Bug 64906 - FcNameParse() should ignore leading whitespace in
    //   parameters"
    // because ignoring a leading space in the encoded value of charset
    // causes erroneous decoding of the whole element.
    // This first shipped in version 2.10.94, and was eventually fixed as
    // a side-effect of switching to the "human-readable" representation of
    // charsets on 2014-07-03 in
    //   https://cgit.freedesktop.org/fontconfig/commit/?id=e708e97c351d3bc9f7030ef22ac2f007d5114730
    //   "Change charset parse/unparse format to be human readable"
    // (with a followup fix next day) which means a leading space is no
    // longer significant. This fix landed after 2.11.1 had been shipped,
    // so the first version tag without the bug is 2.11.91.
    int fcVersion = FcGetVersion();
    bool fcCharsetParseBug = fcVersion >= 21094 && fcVersion <= 21101;

    for (SystemFontListEntry& fle : fontList) {
      MOZ_ASSERT(fle.type() ==
                 SystemFontListEntry::Type::TFontPatternListEntry);
      FontPatternListEntry& fpe(fle);
      nsCString& patternStr = fpe.pattern();
      if (fcCharsetParseBug) {
        int32_t index = patternStr.Find(":charset= ");
        if (index != kNotFound) {
          // insert backslash after the =, before the space
          patternStr.Insert('\\', index + 9);
        }
      }
      FcPattern* pattern = FcNameParse((const FcChar8*)patternStr.get());
      AddPatternToFontList(pattern, lastFamilyName, familyName, fontFamily,
                           fpe.appFontFamily());
      FcPatternDestroy(pattern);
    }

    LOG_FONTLIST(
        ("got font list from chrome process: "
         "%u faces in %u families",
         (unsigned)fontList.Length(), mFontFamilies.Count()));

    fontList.Clear();

    return NS_OK;
  }

  mLastConfig = FcConfigGetCurrent();

  UniquePtr<SandboxPolicy> policy;

#if defined(MOZ_SANDBOX) && defined(XP_LINUX)
  // If read sandboxing is enabled, create a temporary SandboxPolicy to
  // check font paths; use a fake PID to avoid picking up any PID-specific
  // rules by accident.
  SandboxBrokerPolicyFactory policyFactory;
  if (GetEffectiveContentSandboxLevel() > 2 &&
      !PR_GetEnv("MOZ_DISABLE_CONTENT_SANDBOX")) {
    policy = policyFactory.GetContentPolicy(-1, false);
  }
#endif

  // iterate over available fonts
  FcFontSet* systemFonts = FcConfigGetFonts(nullptr, FcSetSystem);
  AddFontSetFamilies(systemFonts, policy.get(), /* aAppFonts = */ false);

#ifdef MOZ_BUNDLED_FONTS
  FcFontSet* appFonts = FcConfigGetFonts(nullptr, FcSetApplication);
  AddFontSetFamilies(appFonts, policy.get(), /* aAppFonts = */ true);
#endif

  return NS_OK;
}

void gfxFcPlatformFontList::ReadSystemFontList(
    InfallibleTArray<SystemFontListEntry>* retValue) {
  // Fontconfig versions below 2.9 drop the FC_FILE element in FcNameUnparse
  // (see https://bugs.freedesktop.org/show_bug.cgi?id=26718), so when using
  // an older version, we manually append it to the unparsed pattern.
  if (FcGetVersion() < 20900) {
    for (auto iter = mFontFamilies.Iter(); !iter.Done(); iter.Next()) {
      auto family = static_cast<gfxFontconfigFontFamily*>(iter.Data().get());
      family->AddFacesToFontList([&](FcPattern* aPat, bool aAppFonts) {
        char* s = (char*)FcNameUnparse(aPat);
        nsDependentCString patternStr(s);
        if (FcResultMatch ==
            FcPatternGetString(aPat, FC_FILE, 0, (FcChar8**)&s)) {
          patternStr.Append(":file=");
          patternStr.Append(s);
        }
        retValue->AppendElement(FontPatternListEntry(patternStr, aAppFonts));
        free(s);
      });
    }
  } else {
    for (auto iter = mFontFamilies.Iter(); !iter.Done(); iter.Next()) {
      auto family = static_cast<gfxFontconfigFontFamily*>(iter.Data().get());
      family->AddFacesToFontList([&](FcPattern* aPat, bool aAppFonts) {
        char* s = (char*)FcNameUnparse(aPat);
        nsDependentCString patternStr(s);
        retValue->AppendElement(FontPatternListEntry(patternStr, aAppFonts));
        free(s);
      });
    }
  }
}

void gfxFcPlatformFontList::InitSharedFontListForPlatform() {
  mLocalNames.Clear();
  mFcSubstituteCache.Clear();

  mAlwaysUseFontconfigGenerics = PrefFontListsUseOnlyGenerics();
  mOtherFamilyNamesInitialized = true;

  if (!XRE_IsParentProcess()) {
    // Content processes will access the shared-memory data created by the
    // parent, so they do not need to query fontconfig for the available
    // fonts themselves.
    return;
  }

#ifdef MOZ_BUNDLED_FONTS
  ActivateBundledFonts();
#endif

  mLastConfig = FcConfigGetCurrent();

  UniquePtr<SandboxPolicy> policy;

#if defined(MOZ_CONTENT_SANDBOX) && defined(XP_LINUX)
  // If read sandboxing is enabled, create a temporary SandboxPolicy to
  // check font paths; use a fake PID to avoid picking up any PID-specific
  // rules by accident.
  SandboxBrokerPolicyFactory policyFactory;
  if (GetEffectiveContentSandboxLevel() > 2 &&
      !PR_GetEnv("MOZ_DISABLE_CONTENT_SANDBOX")) {
    policy = policyFactory.GetContentPolicy(-1, false);
  }
#endif

  nsTArray<fontlist::Family::InitData> families;

  nsClassHashtable<nsCStringHashKey, nsTArray<fontlist::Face::InitData>> faces;

  auto addPattern = [this, &families, &faces](
                        FcPattern* aPattern, FcChar8*& aLastFamilyName,
                        nsCString& aFamilyName, bool aAppFont) -> void {
    // get canonical name
    uint32_t cIndex = FindCanonicalNameIndex(aPattern, FC_FAMILYLANG);
    FcChar8* canonical = nullptr;
    FcPatternGetString(aPattern, FC_FAMILY, cIndex, &canonical);
    if (!canonical) {
      return;
    }

    // same as the last one? definitely no need to add a new family
    if (FcStrCmp(canonical, aLastFamilyName) != 0) {
      aLastFamilyName = canonical;

      // add new family if one doesn't already exist
      aFamilyName = ToCharPtr(canonical);
      nsAutoCString keyName(aFamilyName);
      ToLowerCase(keyName);

      auto faceList = faces.Get(keyName);
      if (!faceList) {
        faceList = new nsTArray<fontlist::Face::InitData>;
        faces.Put(keyName, faceList);

        /* TODO:
        // Add pointers to other localized family names. Most fonts
        // only have a single name, so the first call to GetString
        // will usually not match
        FcChar8* otherName;
        int n = (cIndex == 0 ? 1 : 0);
        while (FcPatternGetString(aFont, FC_FAMILY, n, &otherName) ==
               FcResultMatch) {
          nsAutoCString otherFamilyName(ToCharPtr(otherName));
          AddOtherFamilyName(aFontFamily, otherFamilyName);
          n++;
          if (n == int(cIndex)) {
            n++;  // skip over canonical name
          }
        }
        */

        families.AppendElement(fontlist::Family::InitData(
            keyName, aFamilyName, /*index*/ 0, /*hidden*/ false,
            /*bundled*/ aAppFont, /*badUnderline*/ false));
      }
    }

    char* s = (char*)FcNameUnparse(aPattern);
    nsAutoCString descriptor(s);
    free(s);

    WeightRange weight(FontWeight::Normal());
    StretchRange stretch(FontStretch::Normal());
    SlantStyleRange style(FontSlantStyle::Normal());
    GetFontProperties(aPattern, &weight, &stretch, &style);

    nsAutoCString keyName(aFamilyName);
    ToLowerCase(keyName);
    auto faceList = faces.Get(keyName);
    uint32_t faceIndex = faceList->Length();
    faceList->AppendElement(
        fontlist::Face::InitData{descriptor, 0, false, weight, stretch, style});
    // map the psname, fullname ==> font family for local font lookups
    nsAutoCString psname, fullname;
    GetFaceNames(aPattern, aFamilyName, psname, fullname);
    if (!psname.IsEmpty()) {
      ToLowerCase(psname);
      mLocalNameTable.Put(psname,
                          fontlist::LocalFaceRec::InitData(keyName, faceIndex));
    }
    if (!fullname.IsEmpty()) {
      ToLowerCase(fullname);
      if (fullname != psname) {
        mLocalNameTable.Put(
            fullname, fontlist::LocalFaceRec::InitData(keyName, faceIndex));
      }
    }
  };

  auto addFontSetFamilies = [&addPattern](FcFontSet* aFontSet,
                                          SandboxPolicy* aPolicy,
                                          bool aAppFonts) -> void {
    FcChar8* lastFamilyName = (FcChar8*)"";
    RefPtr<gfxFontconfigFontFamily> fontFamily;
    nsAutoCString familyName;
    for (int f = 0; f < aFontSet->nfont; f++) {
      FcPattern* pattern = aFontSet->fonts[f];

      // Skip any fonts that aren't readable for us (e.g. due to restrictive
      // file ownership/permissions).
      FcChar8* path;
      if (FcPatternGetString(pattern, FC_FILE, 0, &path) != FcResultMatch) {
        continue;
      }
      if (access(reinterpret_cast<const char*>(path), F_OK | R_OK) != 0) {
        continue;
      }

#if defined(MOZ_CONTENT_SANDBOX) && defined(XP_LINUX)
      // Skip any fonts that will be blocked by the content-process sandbox
      // policy.
      if (aPolicy && !(aPolicy->Lookup(reinterpret_cast<const char*>(path)) &
                       SandboxBroker::Perms::MAY_READ)) {
        continue;
      }
#endif

      addPattern(pattern, lastFamilyName, familyName, aAppFonts);
    }
  };

  // iterate over available fonts
  FcFontSet* systemFonts = FcConfigGetFonts(nullptr, FcSetSystem);
  addFontSetFamilies(systemFonts, policy.get(), /* aAppFonts = */ false);

#ifdef MOZ_BUNDLED_FONTS
  FcFontSet* appFonts = FcConfigGetFonts(nullptr, FcSetApplication);
  addFontSetFamilies(appFonts, policy.get(), /* aAppFonts = */ true);
#endif

  ApplyWhitelist(families);
  families.Sort();

  mozilla::fontlist::FontList* list = SharedFontList();
  list->SetFamilyNames(families);

  for (uint32_t i = 0; i < families.Length(); i++) {
    list->Families()[i].AddFaces(list, *faces.Get(families[i].mKey));
  }
}

gfxFontEntry* gfxFcPlatformFontList::CreateFontEntry(
    fontlist::Face* aFace, const fontlist::Family* aFamily) {
  fontlist::FontList* list = SharedFontList();
  nsAutoCString desc(aFace->mDescriptor.AsString(list));
  FcPattern* pattern = FcNameParse((const FcChar8*)desc.get());
  gfxFontEntry* fe = new gfxFontconfigFontEntry(desc, pattern, true);
  FcPatternDestroy(pattern);
  fe->mStyleRange = aFace->mStyle;
  fe->mWeightRange = aFace->mWeight;
  fe->mStretchRange = aFace->mStretch;
  fe->mFixedPitch = aFace->mFixedPitch;
  fe->mIsBadUnderlineFont = aFamily->IsBadUnderlineFamily();
  fe->mShmemFace = aFace;
  fe->mFamilyName = aFamily->DisplayName().AsString(SharedFontList());
  return fe;
}

// For displaying the fontlist in UI, use explicit call to FcFontList. Using
// FcFontList results in the list containing the localized names as dictated
// by system defaults.
static void GetSystemFontList(nsTArray<nsString>& aListOfFonts,
                              nsAtom* aLangGroup) {
  aListOfFonts.Clear();

  nsAutoRef<FcPattern> pat(FcPatternCreate());
  if (!pat) {
    return;
  }

  nsAutoRef<FcObjectSet> os(FcObjectSetBuild(FC_FAMILY, nullptr));
  if (!os) {
    return;
  }

  // add the lang to the pattern
  nsAutoCString fcLang;
  gfxFcPlatformFontList* pfl = gfxFcPlatformFontList::PlatformFontList();
  pfl->GetSampleLangForGroup(aLangGroup, fcLang,
                             /*aForFontEnumerationThread*/ true);
  if (!fcLang.IsEmpty()) {
    FcPatternAddString(pat, FC_LANG, ToFcChar8Ptr(fcLang.get()));
  }

  nsAutoRef<FcFontSet> fs(FcFontList(nullptr, pat, os));
  if (!fs) {
    return;
  }

  for (int i = 0; i < fs->nfont; i++) {
    char* family;

    if (FcPatternGetString(fs->fonts[i], FC_FAMILY, 0, (FcChar8**)&family) !=
        FcResultMatch) {
      continue;
    }

    // Remove duplicates...
    nsAutoString strFamily;
    AppendUTF8toUTF16(MakeStringSpan(family), strFamily);
    if (aListOfFonts.Contains(strFamily)) {
      continue;
    }

    aListOfFonts.AppendElement(strFamily);
  }

  aListOfFonts.Sort();
}

void gfxFcPlatformFontList::GetFontList(nsAtom* aLangGroup,
                                        const nsACString& aGenericFamily,
                                        nsTArray<nsString>& aListOfFonts) {
  // Get the list of font family names using fontconfig
  GetSystemFontList(aListOfFonts, aLangGroup);

  // Under Linux, the generics "serif", "sans-serif" and "monospace"
  // are included in the pref fontlist. These map to whatever fontconfig
  // decides they should be for a given language, rather than one of the
  // fonts listed in the prefs font lists (e.g. font.name.*, font.name-list.*)
  bool serif = false, sansSerif = false, monospace = false;
  if (aGenericFamily.IsEmpty())
    serif = sansSerif = monospace = true;
  else if (aGenericFamily.LowerCaseEqualsLiteral("serif"))
    serif = true;
  else if (aGenericFamily.LowerCaseEqualsLiteral("sans-serif"))
    sansSerif = true;
  else if (aGenericFamily.LowerCaseEqualsLiteral("monospace"))
    monospace = true;
  else if (aGenericFamily.LowerCaseEqualsLiteral("cursive") ||
           aGenericFamily.LowerCaseEqualsLiteral("fantasy"))
    serif = sansSerif = true;
  else
    MOZ_ASSERT_UNREACHABLE("unexpected CSS generic font family");

  // The first in the list becomes the default in
  // FontBuilder.readFontSelection() if the preference-selected font is not
  // available, so put system configured defaults first.
  if (monospace)
    aListOfFonts.InsertElementAt(0, NS_LITERAL_STRING("monospace"));
  if (sansSerif)
    aListOfFonts.InsertElementAt(0, NS_LITERAL_STRING("sans-serif"));
  if (serif) aListOfFonts.InsertElementAt(0, NS_LITERAL_STRING("serif"));
}

FontFamily gfxFcPlatformFontList::GetDefaultFontForPlatform(
    const gfxFontStyle* aStyle) {
  // Get the default font by using a fake name to retrieve the first
  // scalable font that fontconfig suggests for the given language.
  PrefFontList* prefFonts =
      FindGenericFamilies(NS_LITERAL_CSTRING("-moz-default"), aStyle->language);
  NS_ASSERTION(prefFonts, "null list of generic fonts");
  if (prefFonts && !prefFonts->IsEmpty()) {
    return (*prefFonts)[0];
  }
  return FontFamily();
}

gfxFontEntry* gfxFcPlatformFontList::LookupLocalFont(
    const nsACString& aFontName, WeightRange aWeightForEntry,
    StretchRange aStretchForEntry, SlantStyleRange aStyleForEntry) {
  nsAutoCString keyName(aFontName);
  ToLowerCase(keyName);

  if (SharedFontList()) {
    return LookupInSharedFaceNameList(aFontName, aWeightForEntry,
                                      aStretchForEntry, aStyleForEntry);
  }

  // if name is not in the global list, done
  FcPattern* fontPattern = mLocalNames.Get(keyName);
  if (!fontPattern) {
    return nullptr;
  }

  return new gfxFontconfigFontEntry(aFontName, fontPattern, aWeightForEntry,
                                    aStretchForEntry, aStyleForEntry);
}

gfxFontEntry* gfxFcPlatformFontList::MakePlatformFont(
    const nsACString& aFontName, WeightRange aWeightForEntry,
    StretchRange aStretchForEntry, SlantStyleRange aStyleForEntry,
    const uint8_t* aFontData, uint32_t aLength) {
  FT_Face face = Factory::NewFTFaceFromData(nullptr, aFontData, aLength, 0);
  if (!face) {
    free((void*)aFontData);
    return nullptr;
  }
  if (FT_Err_Ok != FT_Select_Charmap(face, FT_ENCODING_UNICODE) &&
      FT_Err_Ok != FT_Select_Charmap(face, FT_ENCODING_MS_SYMBOL)) {
    Factory::ReleaseFTFace(face);
    free((void*)aFontData);
    return nullptr;
  }

  return new gfxFontconfigFontEntry(aFontName, aWeightForEntry,
                                    aStretchForEntry, aStyleForEntry, aFontData,
                                    aLength, face);
}

bool gfxFcPlatformFontList::FindAndAddFamilies(
    StyleGenericFontFamily aGeneric, const nsACString& aFamily,
    nsTArray<FamilyAndGeneric>* aOutput, FindFamiliesFlags aFlags,
    gfxFontStyle* aStyle, gfxFloat aDevToCssSize) {
  nsAutoCString familyName(aFamily);
  ToLowerCase(familyName);
  nsAtom* language = (aStyle ? aStyle->language.get() : nullptr);

  if (!(aFlags & FindFamiliesFlags::eQuotedFamilyName)) {
    // deprecated generic names are explicitly converted to standard generics
    bool isDeprecatedGeneric = false;
    if (familyName.EqualsLiteral("sans") ||
        familyName.EqualsLiteral("sans serif")) {
      familyName.AssignLiteral("sans-serif");
      isDeprecatedGeneric = true;
    } else if (familyName.EqualsLiteral("mono")) {
      familyName.AssignLiteral("monospace");
      isDeprecatedGeneric = true;
    }

    // fontconfig generics? use fontconfig to determine the family for lang
    if (isDeprecatedGeneric ||
        mozilla::FontFamilyName::Convert(familyName).IsGeneric()) {
      PrefFontList* prefFonts = FindGenericFamilies(familyName, language);
      if (prefFonts && !prefFonts->IsEmpty()) {
        aOutput->AppendElements(*prefFonts);
        return true;
      }
      return false;
    }
  }

  // fontconfig allows conditional substitutions in such a way that it's
  // difficult to distinguish an explicit substitution from other suggested
  // choices. To sniff out explicit substitutions, compare the substitutions
  // for "font, -moz-sentinel" to "-moz-sentinel" to sniff out the
  // substitutions
  //
  // Example:
  //
  //   serif ==> DejaVu Serif, ...
  //   Helvetica, serif ==> Helvetica, TeX Gyre Heros, Nimbus Sans L, DejaVu
  //   Serif
  //
  // In this case fontconfig is including Tex Gyre Heros and
  // Nimbus Sans L as alternatives for Helvetica.

  // Because the FcConfigSubstitute call is quite expensive, we cache the
  // actual font families found via this process. So check the cache first:
  AutoTArray<FamilyAndGeneric, 10> cachedFamilies;
  if (mFcSubstituteCache.Get(familyName, &cachedFamilies)) {
    if (cachedFamilies.IsEmpty()) {
      return false;
    }
    aOutput->AppendElements(cachedFamilies);
    return true;
  }

  // It wasn't in the cache, so we need to ask fontconfig...
  const FcChar8* kSentinelName = ToFcChar8Ptr("-moz-sentinel");
  FcChar8* sentinelFirstFamily = nullptr;
  nsAutoRef<FcPattern> sentinelSubst(FcPatternCreate());
  FcPatternAddString(sentinelSubst, FC_FAMILY, kSentinelName);
  FcConfigSubstitute(nullptr, sentinelSubst, FcMatchPattern);
  FcPatternGetString(sentinelSubst, FC_FAMILY, 0, &sentinelFirstFamily);

  // substitutions for font, -moz-sentinel pattern
  nsAutoRef<FcPattern> fontWithSentinel(FcPatternCreate());
  FcPatternAddString(fontWithSentinel, FC_FAMILY,
                     ToFcChar8Ptr(familyName.get()));
  FcPatternAddString(fontWithSentinel, FC_FAMILY, kSentinelName);
  FcConfigSubstitute(nullptr, fontWithSentinel, FcMatchPattern);

  // Add all font family matches until reaching the sentinel.
  FcChar8* substName = nullptr;
  for (int i = 0; FcPatternGetString(fontWithSentinel, FC_FAMILY, i,
                                     &substName) == FcResultMatch;
       i++) {
    if (sentinelFirstFamily && FcStrCmp(substName, sentinelFirstFamily) == 0) {
      break;
    }
    gfxPlatformFontList::FindAndAddFamilies(
        aGeneric, nsDependentCString(ToCharPtr(substName)), &cachedFamilies,
        aFlags);
  }

  // Cache the resulting list, so we don't have to do this again.
  mFcSubstituteCache.Put(familyName, cachedFamilies);

  if (cachedFamilies.IsEmpty()) {
    return false;
  }
  aOutput->AppendElements(cachedFamilies);
  return true;
}

bool gfxFcPlatformFontList::GetStandardFamilyName(const nsCString& aFontName,
                                                  nsACString& aFamilyName) {
  aFamilyName.Truncate();

  // The fontconfig list of fonts includes generic family names in the
  // font list. For these, just use the generic name.
  if (aFontName.EqualsLiteral("serif") ||
      aFontName.EqualsLiteral("sans-serif") ||
      aFontName.EqualsLiteral("monospace")) {
    aFamilyName.Assign(aFontName);
    return true;
  }

  nsAutoRef<FcPattern> pat(FcPatternCreate());
  if (!pat) {
    return true;
  }

  nsAutoRef<FcObjectSet> os(FcObjectSetBuild(FC_FAMILY, nullptr));
  if (!os) {
    return true;
  }

  // add the family name to the pattern
  FcPatternAddString(pat, FC_FAMILY, ToFcChar8Ptr(aFontName.get()));

  nsAutoRef<FcFontSet> givenFS(FcFontList(nullptr, pat, os));
  if (!givenFS) {
    return true;
  }

  // See if there is a font face with first family equal to the given family
  // (needs to be in sync with names coming from GetFontList())
  nsTArray<nsCString> candidates;
  for (int i = 0; i < givenFS->nfont; i++) {
    char* firstFamily;

    if (FcPatternGetString(givenFS->fonts[i], FC_FAMILY, 0,
                           (FcChar8**)&firstFamily) != FcResultMatch) {
      continue;
    }

    nsDependentCString first(firstFamily);
    if (!candidates.Contains(first)) {
      candidates.AppendElement(first);

      if (aFontName.Equals(first)) {
        aFamilyName.Assign(aFontName);
        return true;
      }
    }
  }

  // Because fontconfig conflates different family name types, need to
  // double check that the candidate name is not simply a different
  // name type. For example, if a font with nameID=16 "Minion Pro" and
  // nameID=21 "Minion Pro Caption" exists, calling FcFontList with
  // family="Minion Pro" will return a set of patterns some of which
  // will have a first family of "Minion Pro Caption". Ignore these
  // patterns and use the first candidate that maps to a font set with
  // the same number of faces and an identical set of patterns.
  for (uint32_t j = 0; j < candidates.Length(); ++j) {
    FcPatternDel(pat, FC_FAMILY);
    FcPatternAddString(pat, FC_FAMILY, (FcChar8*)candidates[j].get());

    nsAutoRef<FcFontSet> candidateFS(FcFontList(nullptr, pat, os));
    if (!candidateFS) {
      return true;
    }

    if (candidateFS->nfont != givenFS->nfont) {
      continue;
    }

    bool equal = true;
    for (int i = 0; i < givenFS->nfont; ++i) {
      if (!FcPatternEqual(candidateFS->fonts[i], givenFS->fonts[i])) {
        equal = false;
        break;
      }
    }
    if (equal) {
      aFamilyName = candidates[j];
      return true;
    }
  }

  // didn't find localized name, leave family name blank
  return true;
}

void gfxFcPlatformFontList::AddGenericFonts(
    StyleGenericFontFamily aGenericType, nsAtom* aLanguage,
    nsTArray<FamilyAndGeneric>& aFamilyList) {
  bool usePrefFontList = false;

  const char* generic = GetGenericName(aGenericType);
  NS_ASSERTION(generic, "weird generic font type");
  if (!generic) {
    return;
  }

  // By default, most font prefs on Linux map to "use fontconfig"
  // keywords. So only need to explicitly lookup font pref if
  // non-default settings exist
  nsAutoCString genericToLookup(generic);
  if ((!mAlwaysUseFontconfigGenerics && aLanguage) ||
      aLanguage == nsGkAtoms::x_math) {
    nsAtom* langGroup = GetLangGroup(aLanguage);
    nsAutoString fontlistValue;
    Preferences::GetString(NamePref(generic, langGroup).get(), fontlistValue);
    nsresult rv;
    if (fontlistValue.IsEmpty()) {
      // The font name list may have two or more family names as comma
      // separated list.  In such case, not matching with generic font
      // name is fine because if the list prefers specific font, we
      // should try to use the pref with complicated path.
      rv = Preferences::GetString(NameListPref(generic, langGroup).get(),
                                  fontlistValue);
    } else {
      rv = NS_OK;
    }
    if (NS_SUCCEEDED(rv)) {
      if (!fontlistValue.EqualsLiteral("serif") &&
          !fontlistValue.EqualsLiteral("sans-serif") &&
          !fontlistValue.EqualsLiteral("monospace")) {
        usePrefFontList = true;
      } else {
        // serif, sans-serif or monospace was specified
        genericToLookup.Truncate();
        AppendUTF16toUTF8(fontlistValue, genericToLookup);
      }
    }
  }

  // when pref fonts exist, use standard pref font lookup
  if (usePrefFontList) {
    return gfxPlatformFontList::AddGenericFonts(aGenericType, aLanguage,
                                                aFamilyList);
  }

  PrefFontList* prefFonts = FindGenericFamilies(genericToLookup, aLanguage);
  NS_ASSERTION(prefFonts, "null generic font list");
  aFamilyList.SetCapacity(aFamilyList.Length() + prefFonts->Length());
  for (auto& f : *prefFonts) {
    aFamilyList.AppendElement(FamilyAndGeneric(f, aGenericType));
  }
}

void gfxFcPlatformFontList::ClearLangGroupPrefFonts() {
  ClearGenericMappings();
  gfxPlatformFontList::ClearLangGroupPrefFonts();
  mAlwaysUseFontconfigGenerics = PrefFontListsUseOnlyGenerics();
}

/* static */
FT_Library gfxFcPlatformFontList::GetFTLibrary() {
  if (!sCairoFTLibrary) {
    // Use cairo's FT_Library so that cairo takes care of shutdown of the
    // FT_Library after it has destroyed its font_faces, and FT_Done_Face
    // has been called on each FT_Face, at least until this bug is fixed:
    // https://bugs.freedesktop.org/show_bug.cgi?id=18857
    //
    // Cairo keeps it's own FT_Library object for creating FT_Face
    // instances, so use that. There's no simple API for accessing this
    // so use the hacky method below of making a font and extracting
    // the library pointer from that.

    FcPattern* pat =
        FcPatternBuild(0, FC_FAMILY, FcTypeString, "serif", (char*)0);
    cairo_font_face_t* face =
        cairo_ft_font_face_create_for_pattern(pat, nullptr, 0);
    FcPatternDestroy(pat);

    cairo_matrix_t identity;
    cairo_matrix_init_identity(&identity);
    cairo_font_options_t* options = cairo_font_options_create();
    cairo_scaled_font_t* sf =
        cairo_scaled_font_create(face, &identity, &identity, options);
    cairo_font_options_destroy(options);
    cairo_font_face_destroy(face);

    FT_Face ft = cairo_ft_scaled_font_lock_face(sf);

    sCairoFTLibrary = ft->glyph->library;

    cairo_ft_scaled_font_unlock_face(sf);
    cairo_scaled_font_destroy(sf);
  }

  return sCairoFTLibrary;
}

gfxPlatformFontList::PrefFontList* gfxFcPlatformFontList::FindGenericFamilies(
    const nsCString& aGeneric, nsAtom* aLanguage) {
  // set up name
  nsAutoCString fcLang;
  GetSampleLangForGroup(aLanguage, fcLang);
  ToLowerCase(fcLang);

  nsAutoCString genericLang(aGeneric);
  if (fcLang.Length() > 0) {
    genericLang.Append('-');
  }
  genericLang.Append(fcLang);

  // try to get the family from the cache
  PrefFontList* prefFonts = mGenericMappings.Get(genericLang);
  if (prefFonts) {
    return prefFonts;
  }

  // if not found, ask fontconfig to pick the appropriate font
  nsAutoRef<FcPattern> genericPattern(FcPatternCreate());
  FcPatternAddString(genericPattern, FC_FAMILY, ToFcChar8Ptr(aGeneric.get()));

  // -- prefer scalable fonts
  FcPatternAddBool(genericPattern, FC_SCALABLE, FcTrue);

  // -- add the lang to the pattern
  if (!fcLang.IsEmpty()) {
    FcPatternAddString(genericPattern, FC_LANG, ToFcChar8Ptr(fcLang.get()));
  }

  // -- perform substitutions
  FcConfigSubstitute(nullptr, genericPattern, FcMatchPattern);
  FcDefaultSubstitute(genericPattern);

  // -- sort to get the closest matches
  FcResult result;
  nsAutoRef<FcFontSet> faces(
      FcFontSort(nullptr, genericPattern, FcFalse, nullptr, &result));

  if (!faces) {
    return nullptr;
  }

  // -- select the fonts to be used for the generic
  prefFonts = new PrefFontList;  // can be empty but in practice won't happen
  uint32_t limit = gfxPlatformGtk::GetPlatform()->MaxGenericSubstitions();
  bool foundFontWithLang = false;
  for (int i = 0; i < faces->nfont; i++) {
    FcPattern* font = faces->fonts[i];
    FcChar8* mappedGeneric = nullptr;

    FcPatternGetString(font, FC_FAMILY, 0, &mappedGeneric);
    if (mappedGeneric) {
      nsAutoCString mappedGenericName(ToCharPtr(mappedGeneric));
      AutoTArray<FamilyAndGeneric, 1> genericFamilies;
      if (gfxPlatformFontList::FindAndAddFamilies(
              StyleGenericFontFamily::None, mappedGenericName, &genericFamilies,
              FindFamiliesFlags(0))) {
        MOZ_ASSERT(genericFamilies.Length() == 1, "expected a single family");
        if (!prefFonts->Contains(genericFamilies[0].mFamily)) {
          prefFonts->AppendElement(genericFamilies[0].mFamily);
          bool foundLang = !fcLang.IsEmpty() &&
                           PatternHasLang(font, ToFcChar8Ptr(fcLang.get()));
          foundFontWithLang = foundFontWithLang || foundLang;
          // check to see if the list is full
          if (prefFonts->Length() >= limit) {
            break;
          }
        }
      }
    }
  }

  // if no font in the list matches the lang, trim all but the first one
  if (!prefFonts->IsEmpty() && !foundFontWithLang) {
    prefFonts->TruncateLength(1);
  }

  mGenericMappings.Put(genericLang, prefFonts);
  return prefFonts;
}

bool gfxFcPlatformFontList::PrefFontListsUseOnlyGenerics() {
  static const char kFontNamePrefix[] = "font.name.";

  bool prefFontsUseOnlyGenerics = true;
  uint32_t count;
  char** names;
  nsresult rv = Preferences::GetRootBranch()->GetChildList(kFontNamePrefix,
                                                           &count, &names);
  if (NS_SUCCEEDED(rv) && count) {
    for (size_t i = 0; i < count; i++) {
      // Check whether all font.name prefs map to generic keywords
      // and that the pref name and keyword match.
      //   Ex: font.name.serif.ar ==> "serif" (ok)
      //   Ex: font.name.serif.ar ==> "monospace" (return false)
      //   Ex: font.name.serif.ar ==> "DejaVu Serif" (return false)
      //   Ex: font.name.serif.ar ==> "" and
      //       font.name-list.serif.ar ==> "serif" (ok)
      //   Ex: font.name.serif.ar ==> "" and
      //       font.name-list.serif.ar ==> "Something, serif"
      //                                           (return false)

      nsDependentCString prefName(names[i] + ArrayLength(kFontNamePrefix) - 1);
      nsCCharSeparatedTokenizer tokenizer(prefName, '.');
      const nsDependentCSubstring& generic = tokenizer.nextToken();
      const nsDependentCSubstring& langGroup = tokenizer.nextToken();
      nsAutoCString fontPrefValue;
      Preferences::GetCString(names[i], fontPrefValue);
      if (fontPrefValue.IsEmpty()) {
        // The font name list may have two or more family names as comma
        // separated list.  In such case, not matching with generic font
        // name is fine because if the list prefers specific font, this
        // should return false.
        Preferences::GetCString(NameListPref(generic, langGroup).get(),
                                fontPrefValue);
      }

      if (!langGroup.EqualsLiteral("x-math") &&
          !generic.Equals(fontPrefValue)) {
        prefFontsUseOnlyGenerics = false;
        break;
      }
    }
    NS_FREE_XPCOM_ALLOCATED_POINTER_ARRAY(count, names);
  }
  return prefFontsUseOnlyGenerics;
}

/* static */
void gfxFcPlatformFontList::CheckFontUpdates(nsITimer* aTimer, void* aThis) {
  // A content process is not supposed to check this directly;
  // it will be notified by the parent when the font list changes.
  MOZ_ASSERT(XRE_IsParentProcess());

  // check for font updates
  FcInitBringUptoDate();

  // update fontlist if current config changed
  gfxFcPlatformFontList* pfl = static_cast<gfxFcPlatformFontList*>(aThis);
  FcConfig* current = FcConfigGetCurrent();
  if (current != pfl->GetLastConfig()) {
    pfl->UpdateFontList();
    pfl->ForceGlobalReflow();

    mozilla::dom::ContentParent::NotifyUpdatedFonts();
  }
}

gfxFontFamily* gfxFcPlatformFontList::CreateFontFamily(
    const nsACString& aName) const {
  return new gfxFontconfigFontFamily(aName);
}

// mapping of moz lang groups ==> default lang
struct MozLangGroupData {
  nsAtom* const& mozLangGroup;
  const char* defaultLang;
};

const MozLangGroupData MozLangGroups[] = {
    {nsGkAtoms::x_western, "en"},    {nsGkAtoms::x_cyrillic, "ru"},
    {nsGkAtoms::x_devanagari, "hi"}, {nsGkAtoms::x_tamil, "ta"},
    {nsGkAtoms::x_armn, "hy"},       {nsGkAtoms::x_beng, "bn"},
    {nsGkAtoms::x_cans, "iu"},       {nsGkAtoms::x_ethi, "am"},
    {nsGkAtoms::x_geor, "ka"},       {nsGkAtoms::x_gujr, "gu"},
    {nsGkAtoms::x_guru, "pa"},       {nsGkAtoms::x_khmr, "km"},
    {nsGkAtoms::x_knda, "kn"},       {nsGkAtoms::x_mlym, "ml"},
    {nsGkAtoms::x_orya, "or"},       {nsGkAtoms::x_sinh, "si"},
    {nsGkAtoms::x_tamil, "ta"},      {nsGkAtoms::x_telu, "te"},
    {nsGkAtoms::x_tibt, "bo"},       {nsGkAtoms::Unicode, 0}};

bool gfxFcPlatformFontList::TryLangForGroup(const nsACString& aOSLang,
                                            nsAtom* aLangGroup,
                                            nsACString& aFcLang,
                                            bool aForFontEnumerationThread) {
  // Truncate at '.' or '@' from aOSLang, and convert '_' to '-'.
  // aOSLang is in the form "language[_territory][.codeset][@modifier]".
  // fontconfig takes languages in the form "language-territory".
  // nsLanguageAtomService takes languages in the form language-subtag,
  // where subtag may be a territory.  fontconfig and nsLanguageAtomService
  // handle case-conversion for us.
  const char *pos, *end;
  aOSLang.BeginReading(pos);
  aOSLang.EndReading(end);
  aFcLang.Truncate();
  while (pos < end) {
    switch (*pos) {
      case '.':
      case '@':
        end = pos;
        break;
      case '_':
        aFcLang.Append('-');
        break;
      default:
        aFcLang.Append(*pos);
    }
    ++pos;
  }

  if (!aForFontEnumerationThread) {
    nsAtom* atom = mLangService->LookupLanguage(aFcLang);
    return atom == aLangGroup;
  }

  // If we were called by the font enumeration thread, we can't use
  // mLangService->LookupLanguage because it is not thread-safe.
  // Use GetUncachedLanguageGroup to avoid unsafe access to the lang-group
  // mapping cache hashtable.
  nsAutoCString lowered(aFcLang);
  ToLowerCase(lowered);
  RefPtr<nsAtom> lang = NS_Atomize(lowered);
  RefPtr<nsAtom> group = mLangService->GetUncachedLanguageGroup(lang);
  return group.get() == aLangGroup;
}

void gfxFcPlatformFontList::GetSampleLangForGroup(
    nsAtom* aLanguage, nsACString& aLangStr, bool aForFontEnumerationThread) {
  aLangStr.Truncate();
  if (!aLanguage) {
    return;
  }

  // set up lang string
  const MozLangGroupData* mozLangGroup = nullptr;

  // -- look it up in the list of moz lang groups
  for (unsigned int i = 0; i < ArrayLength(MozLangGroups); ++i) {
    if (aLanguage == MozLangGroups[i].mozLangGroup) {
      mozLangGroup = &MozLangGroups[i];
      break;
    }
  }

  // -- not a mozilla lang group? Just return the BCP47 string
  //    representation of the lang group
  if (!mozLangGroup) {
    // Not a special mozilla language group.
    // Use aLanguage as a language code.
    aLanguage->ToUTF8String(aLangStr);
    return;
  }

  // -- check the environment for the user's preferred language that
  //    corresponds to this mozilla lang group.
  const char* languages = getenv("LANGUAGE");
  if (languages) {
    const char separator = ':';

    for (const char* pos = languages; true; ++pos) {
      if (*pos == '\0' || *pos == separator) {
        if (languages < pos &&
            TryLangForGroup(Substring(languages, pos), aLanguage, aLangStr,
                            aForFontEnumerationThread)) {
          return;
        }

        if (*pos == '\0') {
          break;
        }

        languages = pos + 1;
      }
    }
  }
  const char* ctype = setlocale(LC_CTYPE, nullptr);
  if (ctype && TryLangForGroup(nsDependentCString(ctype), aLanguage, aLangStr,
                               aForFontEnumerationThread)) {
    return;
  }

  if (mozLangGroup->defaultLang) {
    aLangStr.Assign(mozLangGroup->defaultLang);
  } else {
    aLangStr.Truncate();
  }
}

#ifdef MOZ_BUNDLED_FONTS
void gfxFcPlatformFontList::ActivateBundledFonts() {
  if (!mBundledFontsInitialized) {
    mBundledFontsInitialized = true;
    nsCOMPtr<nsIFile> localDir;
    nsresult rv = NS_GetSpecialDirectory(NS_GRE_DIR, getter_AddRefs(localDir));
    if (NS_FAILED(rv)) {
      return;
    }
    if (NS_FAILED(localDir->Append(NS_LITERAL_STRING("fonts")))) {
      return;
    }
    bool isDir;
    if (NS_FAILED(localDir->IsDirectory(&isDir)) || !isDir) {
      return;
    }
    if (NS_FAILED(localDir->GetNativePath(mBundledFontsPath))) {
      return;
    }
  }
  if (!mBundledFontsPath.IsEmpty()) {
    FcConfigAppFontAddDir(nullptr, ToFcChar8Ptr(mBundledFontsPath.get()));
  }
}
#endif

#ifdef MOZ_WIDGET_GTK
/***************************************************************************
 *
 * This function must be last in the file because it uses the system cairo
 * library.  Above this point the cairo library used is the tree cairo if
 * MOZ_TREE_CAIRO.
 */

#  if MOZ_TREE_CAIRO
// Tree cairo symbols have different names.  Disable their activation through
// preprocessor macros.
#    undef cairo_ft_font_options_substitute

// The system cairo functions are not declared because the include paths cause
// the gdk headers to pick up the tree cairo.h.
extern "C" {
NS_VISIBILITY_DEFAULT void cairo_ft_font_options_substitute(
    const cairo_font_options_t* options, FcPattern* pattern);
}
#  endif

static void ApplyGdkScreenFontOptions(FcPattern* aPattern) {
  const cairo_font_options_t* options =
      gdk_screen_get_font_options(gdk_screen_get_default());

  cairo_ft_font_options_substitute(options, aPattern);
}

#endif  // MOZ_WIDGET_GTK