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.

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
/* 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/. */

use api::{AddFont, BlobImageResources, AsyncBlobImageRasterizer, ResourceUpdate};
use api::{BlobImageDescriptor, BlobImageHandler, BlobImageRequest, RasterizedBlobImage};
use api::{ClearCache, DebugFlags, FontInstanceKey, FontKey, FontTemplate, GlyphIndex};
use api::{ExternalImageData, ExternalImageType, BlobImageResult, BlobImageParams};
use api::{FontInstanceData, FontInstanceOptions, FontInstancePlatformOptions, FontVariation};
use api::{DirtyRect, GlyphDimensions, IdNamespace};
use api::{ImageData, ImageDescriptor, ImageKey, ImageRendering, TileSize};
use api::{BlobImageData, BlobImageKey, MemoryReport, VoidPtrToSizeFn};
use api::units::*;
#[cfg(feature = "capture")]
use crate::capture::ExternalCaptureImage;
#[cfg(feature = "replay")]
use crate::capture::PlainExternalImage;
#[cfg(any(feature = "replay", feature = "png"))]
use crate::capture::CaptureConfig;
use crate::composite::{NativeSurfaceId, NativeSurfaceOperation, NativeTileId, NativeSurfaceOperationDetails};
use crate::device::TextureFilter;
use euclid::{point2, size2};
use crate::glyph_cache::GlyphCache;
use crate::glyph_cache::GlyphCacheEntry;
use crate::glyph_rasterizer::{GLYPH_FLASHING, BaseFontInstance, FontInstance, GlyphFormat, GlyphKey, GlyphRasterizer};
use crate::gpu_cache::{GpuCache, GpuCacheAddress, GpuCacheHandle};
use crate::gpu_types::UvRectKind;
use crate::image::{compute_tile_size, compute_tile_rect, compute_tile_range, for_each_tile_in_range};
use crate::image::compute_valid_tiles_if_bounds_change;
use crate::internal_types::{FastHashMap, FastHashSet, TextureSource, ResourceUpdateList};
use crate::profiler::{ResourceProfileCounters, TextureCacheProfileCounters};
use crate::render_backend::{FrameId, FrameStamp};
use crate::render_task_graph::{RenderTaskGraph, RenderTaskId};
use crate::render_task_cache::{RenderTaskCache, RenderTaskCacheKey};
use crate::render_task_cache::{RenderTaskCacheEntry, RenderTaskCacheEntryHandle};
use smallvec::SmallVec;
use std::collections::hash_map::Entry::{self, Occupied, Vacant};
use std::collections::hash_map::{Iter, IterMut};
use std::collections::VecDeque;
use std::{cmp, mem};
use std::fmt::Debug;
use std::hash::Hash;
use std::os::raw::c_void;
#[cfg(any(feature = "capture", feature = "replay"))]
use std::path::PathBuf;
use std::sync::{Arc, RwLock};
use std::sync::atomic::{AtomicU64, Ordering};
use std::time::SystemTime;
use std::u32;
use crate::texture_cache::{TextureCache, TextureCacheHandle, Eviction};
use crate::util::drain_filter;

const DEFAULT_TILE_SIZE: TileSize = 512;

// Counter for generating unique native surface ids
static NEXT_NATIVE_SURFACE_ID: AtomicU64 = AtomicU64::new(0);

#[cfg_attr(feature = "capture", derive(Serialize))]
#[cfg_attr(feature = "replay", derive(Deserialize))]
pub struct GlyphFetchResult {
    pub index_in_text_run: i32,
    pub uv_rect_address: GpuCacheAddress,
}

// These coordinates are always in texels.
// They are converted to normalized ST
// values in the vertex shader. The reason
// for this is that the texture may change
// dimensions (e.g. the pages in a texture
// atlas can grow). When this happens, by
// storing the coordinates as texel values
// we don't need to go through and update
// various CPU-side structures.
#[derive(Debug, Clone)]
#[cfg_attr(feature = "capture", derive(Serialize))]
#[cfg_attr(feature = "replay", derive(Deserialize))]
pub struct CacheItem {
    pub texture_id: TextureSource,
    pub uv_rect_handle: GpuCacheHandle,
    pub uv_rect: DeviceIntRect,
    pub texture_layer: i32,
}

impl CacheItem {
    pub fn invalid() -> Self {
        CacheItem {
            texture_id: TextureSource::Invalid,
            uv_rect_handle: GpuCacheHandle::new(),
            uv_rect: DeviceIntRect::zero(),
            texture_layer: 0,
        }
    }
}

/// Represents the backing store of an image in the cache.
/// This storage can take several forms.
#[derive(Clone, Debug)]
pub enum CachedImageData {
    /// A simple series of bytes, provided by the embedding and owned by WebRender.
    /// The format is stored out-of-band, currently in ImageDescriptor.
    Raw(Arc<Vec<u8>>),
    /// An series of commands that can be rasterized into an image via an
    /// embedding-provided callback.
    ///
    /// The commands are stored elsewhere and this variant is used as a placeholder.
    Blob,
    /// An image owned by the embedding, and referenced by WebRender. This may
    /// take the form of a texture or a heap-allocated buffer.
    External(ExternalImageData),
}

impl From<ImageData> for CachedImageData {
    fn from(img_data: ImageData) -> Self {
        match img_data {
            ImageData::Raw(data) => CachedImageData::Raw(data),
            ImageData::External(data) => CachedImageData::External(data),
        }
    }
}

impl CachedImageData {
    /// Returns true if this represents a blob.
    #[inline]
    pub fn is_blob(&self) -> bool {
        match *self {
            CachedImageData::Blob => true,
            _ => false,
        }
    }

    /// Returns true if this variant of CachedImageData should go through the texture
    /// cache.
    #[inline]
    pub fn uses_texture_cache(&self) -> bool {
        match *self {
            CachedImageData::External(ref ext_data) => match ext_data.image_type {
                ExternalImageType::TextureHandle(_) => false,
                ExternalImageType::Buffer => true,
            },
            CachedImageData::Blob => true,
            CachedImageData::Raw(_) => true,
        }
    }
}

#[derive(Debug)]
#[cfg_attr(feature = "capture", derive(Serialize))]
#[cfg_attr(feature = "replay", derive(Deserialize))]
pub struct ImageProperties {
    pub descriptor: ImageDescriptor,
    pub external_image: Option<ExternalImageData>,
    pub tiling: Option<TileSize>,
    // Potentially a subset of the image's total rectangle. This rectangle is what
    // we map to the (layout space) display item bounds.
    pub visible_rect: DeviceIntRect,
}

#[derive(Debug, Copy, Clone, PartialEq)]
enum State {
    Idle,
    AddResources,
    QueryResources,
}

/// Post scene building state.
enum RasterizedBlob {
    Tiled(FastHashMap<TileOffset, RasterizedBlobImage>),
    NonTiled(Vec<RasterizedBlobImage>),
}

/// Pre scene building state.
/// We use this to generate the async blob rendering requests.
struct BlobImageTemplate {
    descriptor: ImageDescriptor,
    tiling: Option<TileSize>,
    dirty_rect: BlobDirtyRect,
    /// See ImageResource::visible_rect.
    visible_rect: DeviceIntRect,
    // If the active rect of the blob changes, this represents the
    // range of tiles that remain valid. This must be taken into
    // account in addition to the valid rect when submitting blob
    // rasterization requests.
    // `None` means the bounds have not changed (tiles are still valid).
    // `Some(TileRange::zero())` means all of the tiles are invalid.
    valid_tiles_after_bounds_change: Option<TileRange>,
}

#[cfg_attr(feature = "capture", derive(Serialize))]
#[cfg_attr(feature = "replay", derive(Deserialize))]
#[derive(Debug, Copy, Clone, PartialEq)]
pub struct ImageGeneration(pub u32);

impl ImageGeneration {
    pub const INVALID: ImageGeneration = ImageGeneration(u32::MAX);
}

struct ImageResource {
    data: CachedImageData,
    descriptor: ImageDescriptor,
    tiling: Option<TileSize>,
    /// This is used to express images that are virtually very large
    /// but with only a visible sub-set that is valid at a given time.
    visible_rect: DeviceIntRect,
    generation: ImageGeneration,
}

#[derive(Clone, Debug)]
pub struct ImageTiling {
    pub image_size: DeviceIntSize,
    pub tile_size: TileSize,
}

#[derive(Default)]
struct ImageTemplates {
    images: FastHashMap<ImageKey, ImageResource>,
}

impl ImageTemplates {
    fn insert(&mut self, key: ImageKey, resource: ImageResource) {
        self.images.insert(key, resource);
    }

    fn remove(&mut self, key: ImageKey) -> Option<ImageResource> {
        self.images.remove(&key)
    }

    fn get(&self, key: ImageKey) -> Option<&ImageResource> {
        self.images.get(&key)
    }

    fn get_mut(&mut self, key: ImageKey) -> Option<&mut ImageResource> {
        self.images.get_mut(&key)
    }
}

#[cfg_attr(feature = "capture", derive(Serialize))]
#[cfg_attr(feature = "replay", derive(Deserialize))]
struct CachedImageInfo {
    texture_cache_handle: TextureCacheHandle,
    dirty_rect: ImageDirtyRect,
    manual_eviction: bool,
}

impl CachedImageInfo {
    fn mark_unused(&mut self, texture_cache: &mut TextureCache) {
        texture_cache.mark_unused(&self.texture_cache_handle);
        self.manual_eviction = false;
    }
}

#[cfg(debug_assertions)]
impl Drop for CachedImageInfo {
    fn drop(&mut self) {
        debug_assert!(!self.manual_eviction, "Manual eviction requires cleanup");
    }
}

#[cfg_attr(feature = "capture", derive(Serialize))]
#[cfg_attr(feature = "replay", derive(Deserialize))]
pub struct ResourceClassCache<K: Hash + Eq, V, U: Default> {
    resources: FastHashMap<K, V>,
    pub user_data: U,
}

impl<K, V, U> ResourceClassCache<K, V, U>
where
    K: Clone + Hash + Eq + Debug,
    U: Default,
{
    pub fn new() -> Self {
        ResourceClassCache {
            resources: FastHashMap::default(),
            user_data: Default::default(),
        }
    }

    pub fn get(&self, key: &K) -> &V {
        self.resources.get(key)
            .expect("Didn't find a cached resource with that ID!")
    }

    pub fn try_get(&self, key: &K) -> Option<&V> {
        self.resources.get(key)
    }

    pub fn insert(&mut self, key: K, value: V) {
        self.resources.insert(key, value);
    }

    pub fn remove(&mut self, key: &K) -> Option<V> {
        self.resources.remove(key)
    }

    pub fn get_mut(&mut self, key: &K) -> &mut V {
        self.resources.get_mut(key)
            .expect("Didn't find a cached resource with that ID!")
    }

    pub fn try_get_mut(&mut self, key: &K) -> Option<&mut V> {
        self.resources.get_mut(key)
    }

    pub fn entry(&mut self, key: K) -> Entry<K, V> {
        self.resources.entry(key)
    }

    pub fn iter(&self) -> Iter<K, V> {
        self.resources.iter()
    }

    pub fn iter_mut(&mut self) -> IterMut<K, V> {
        self.resources.iter_mut()
    }

    pub fn is_empty(&mut self) -> bool {
        self.resources.is_empty()
    }

    pub fn clear(&mut self) {
        self.resources.clear();
    }

    pub fn retain<F>(&mut self, f: F)
    where
        F: FnMut(&K, &mut V) -> bool,
    {
        self.resources.retain(f);
    }
}

#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
#[cfg_attr(feature = "capture", derive(Serialize))]
#[cfg_attr(feature = "replay", derive(Deserialize))]
struct CachedImageKey {
    pub rendering: ImageRendering,
    pub tile: Option<TileOffset>,
}

#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
#[cfg_attr(feature = "capture", derive(Serialize))]
#[cfg_attr(feature = "replay", derive(Deserialize))]
pub struct ImageRequest {
    pub key: ImageKey,
    pub rendering: ImageRendering,
    pub tile: Option<TileOffset>,
}

impl ImageRequest {
    pub fn with_tile(&self, offset: TileOffset) -> Self {
        ImageRequest {
            key: self.key,
            rendering: self.rendering,
            tile: Some(offset),
        }
    }

    pub fn is_untiled_auto(&self) -> bool {
        self.tile.is_none() && self.rendering == ImageRendering::Auto
    }
}

impl Into<BlobImageRequest> for ImageRequest {
    fn into(self) -> BlobImageRequest {
        BlobImageRequest {
            key: BlobImageKey(self.key),
            tile: self.tile,
        }
    }
}

impl Into<CachedImageKey> for ImageRequest {
    fn into(self) -> CachedImageKey {
        CachedImageKey {
            rendering: self.rendering,
            tile: self.tile,
        }
    }
}

#[derive(Debug)]
#[cfg_attr(feature = "capture", derive(Clone, Serialize))]
#[cfg_attr(feature = "replay", derive(Deserialize))]
pub enum ImageCacheError {
    OverLimitSize,
}

#[cfg_attr(feature = "capture", derive(Serialize))]
#[cfg_attr(feature = "replay", derive(Deserialize))]
enum ImageResult {
    UntiledAuto(CachedImageInfo),
    Multi(ResourceClassCache<CachedImageKey, CachedImageInfo, ()>),
    Err(ImageCacheError),
}

impl ImageResult {
    /// Releases any texture cache entries held alive by this ImageResult.
    fn drop_from_cache(&mut self, texture_cache: &mut TextureCache) {
        match *self {
            ImageResult::UntiledAuto(ref mut entry) => {
                entry.mark_unused(texture_cache);
            },
            ImageResult::Multi(ref mut entries) => {
                for (_, entry) in &mut entries.resources {
                    entry.mark_unused(texture_cache);
                }
            },
            ImageResult::Err(_) => {},
        }
    }
}

type ImageCache = ResourceClassCache<ImageKey, ImageResult, ()>;
pub type FontInstanceMap = Arc<RwLock<FastHashMap<FontInstanceKey, Arc<BaseFontInstance>>>>;

#[derive(Default)]
struct Resources {
    font_templates: FastHashMap<FontKey, FontTemplate>,
    font_instances: FontInstanceMap,
    image_templates: ImageTemplates,
}

impl BlobImageResources for Resources {
    fn get_font_data(&self, key: FontKey) -> &FontTemplate {
        self.font_templates.get(&key).unwrap()
    }
    fn get_font_instance_data(&self, key: FontInstanceKey) -> Option<FontInstanceData> {
        match self.font_instances.read().unwrap().get(&key) {
            Some(instance) => Some(FontInstanceData {
                font_key: instance.font_key,
                size: instance.size,
                options: Some(FontInstanceOptions {
                  render_mode: instance.render_mode,
                  flags: instance.flags,
                  bg_color: instance.bg_color,
                  synthetic_italics: instance.synthetic_italics,
                }),
                platform_options: instance.platform_options,
                variations: instance.variations.clone(),
            }),
            None => None,
        }
    }
}

// We only use this to report glyph dimensions to the user of the API, so using
// the font instance key should be enough. If we start using it to cache dimensions
// for internal font instances we should change the hash key accordingly.
pub type GlyphDimensionsCache = FastHashMap<(FontInstanceKey, GlyphIndex), Option<GlyphDimensions>>;

#[derive(Clone, Copy, Debug, PartialEq)]
pub struct BlobImageRasterizerEpoch(usize);

/// Stores parameters for clearing blob image tiles.
///
/// TODO(nical) this can be removed.
#[derive(Clone, Copy, Debug)]
pub struct BlobImageClearParams {
    pub key: BlobImageKey,
    /// Originally requested tile range to rasterize.
    pub original_tile_range: TileRange,
    /// Actual tile range that is requested to rasterize by
    /// AsyncBlobImageRasterizer.
    pub actual_tile_range: TileRange,
}

/// Information attached to AsyncBlobImageRasterizer.
#[derive(Clone, Debug)]
pub struct AsyncBlobImageInfo {
    pub epoch: BlobImageRasterizerEpoch,
    pub clear_requests: Vec<BlobImageClearParams>,
}

/// High-level container for resources managed by the `RenderBackend`.
///
/// This includes a variety of things, including images, fonts, and glyphs,
/// which may be stored as memory buffers, GPU textures, or handles to resources
/// managed by the OS or other parts of WebRender.
pub struct ResourceCache {
    cached_glyphs: GlyphCache,
    cached_images: ImageCache,
    cached_render_tasks: RenderTaskCache,

    resources: Resources,
    state: State,
    current_frame_id: FrameId,

    pub texture_cache: TextureCache,

    /// TODO(gw): We should expire (parts of) this cache semi-regularly!
    cached_glyph_dimensions: GlyphDimensionsCache,
    glyph_rasterizer: GlyphRasterizer,

    /// The set of images that aren't present or valid in the texture cache,
    /// and need to be rasterized and/or uploaded this frame. This includes
    /// both blobs and regular images.
    pending_image_requests: FastHashSet<ImageRequest>,

    blob_image_handler: Option<Box<dyn BlobImageHandler>>,
    rasterized_blob_images: FastHashMap<BlobImageKey, RasterizedBlob>,
    blob_image_templates: FastHashMap<BlobImageKey, BlobImageTemplate>,

    /// If while building a frame we encounter blobs that we didn't already
    /// rasterize, add them to this list and rasterize them synchronously.
    missing_blob_images: Vec<BlobImageParams>,
    /// The rasterizer associated with the current scene.
    blob_image_rasterizer: Option<Box<dyn AsyncBlobImageRasterizer>>,
    /// An epoch of the stored blob image rasterizer, used to skip the ones
    /// coming from low-priority scene builds if the current one is newer.
    /// This is to be removed when we get rid of the whole "missed" blob
    /// images concept.
    /// The produced one gets bumped whenever we produce a rasteriezer,
    /// which then travels through the scene building and eventually gets
    /// consumed back by us, bumping the consumed epoch.
    blob_image_rasterizer_produced_epoch: BlobImageRasterizerEpoch,
    blob_image_rasterizer_consumed_epoch: BlobImageRasterizerEpoch,
    /// A log of the last three frames worth of deleted image keys kept
    /// for debugging purposes.
    deleted_blob_keys: VecDeque<Vec<BlobImageKey>>,

    /// A list of queued compositor surface updates to apply next frame.
    pending_native_surface_updates: Vec<NativeSurfaceOperation>,
}

impl ResourceCache {
    pub fn new(
        texture_cache: TextureCache,
        glyph_rasterizer: GlyphRasterizer,
        cached_glyphs: GlyphCache,
        blob_image_handler: Option<Box<dyn BlobImageHandler>>,
    ) -> Self {
        ResourceCache {
            cached_glyphs,
            cached_images: ResourceClassCache::new(),
            cached_render_tasks: RenderTaskCache::new(),
            resources: Resources::default(),
            cached_glyph_dimensions: FastHashMap::default(),
            texture_cache,
            state: State::Idle,
            current_frame_id: FrameId::INVALID,
            pending_image_requests: FastHashSet::default(),
            glyph_rasterizer,
            blob_image_handler,
            rasterized_blob_images: FastHashMap::default(),
            blob_image_templates: FastHashMap::default(),
            missing_blob_images: Vec::new(),
            blob_image_rasterizer: None,
            blob_image_rasterizer_produced_epoch: BlobImageRasterizerEpoch(0),
            blob_image_rasterizer_consumed_epoch: BlobImageRasterizerEpoch(0),
            // We want to keep three frames worth of delete blob keys
            deleted_blob_keys: vec![Vec::new(), Vec::new(), Vec::new()].into(),
            pending_native_surface_updates: Vec::new(),
        }
    }

    pub fn max_texture_size(&self) -> i32 {
        self.texture_cache.max_texture_size()
    }

    fn should_tile(limit: i32, descriptor: &ImageDescriptor, data: &CachedImageData) -> bool {
        let size_check = descriptor.size.width > limit || descriptor.size.height > limit;
        match *data {
            CachedImageData::Raw(_) | CachedImageData::Blob => size_check,
            CachedImageData::External(info) => {
                // External handles already represent existing textures so it does
                // not make sense to tile them into smaller ones.
                info.image_type == ExternalImageType::Buffer && size_check
            }
        }
    }

    // Request the texture cache item for a cacheable render
    // task. If the item is already cached, the texture cache
    // handle will be returned. Otherwise, the user supplied
    // closure will be invoked to generate the render task
    // chain that is required to draw this task.
    pub fn request_render_task<F>(
        &mut self,
        key: RenderTaskCacheKey,
        gpu_cache: &mut GpuCache,
        render_tasks: &mut RenderTaskGraph,
        user_data: Option<[f32; 3]>,
        is_opaque: bool,
        f: F,
    ) -> RenderTaskCacheEntryHandle
    where
        F: FnOnce(&mut RenderTaskGraph) -> RenderTaskId,
    {
        self.cached_render_tasks.request_render_task(
            key,
            &mut self.texture_cache,
            gpu_cache,
            render_tasks,
            user_data,
            is_opaque,
            |render_graph| Ok(f(render_graph))
        ).expect("Failed to request a render task from the resource cache!")
    }

    pub fn post_scene_building_update(
        &mut self,
        updates: Vec<ResourceUpdate>,
        profile_counters: &mut ResourceProfileCounters,
    ) {
        // TODO, there is potential for optimization here, by processing updates in
        // bulk rather than one by one (for example by sorting allocations by size or
        // in a way that reduces fragmentation in the atlas).

        for update in updates {
            match update {
                ResourceUpdate::AddImage(img) => {
                    if let ImageData::Raw(ref bytes) = img.data {
                        profile_counters.image_templates.inc(bytes.len());
                    }
                    self.add_image_template(
                        img.key,
                        img.descriptor,
                        img.data.into(),
                        &img.descriptor.size.into(),
                        img.tiling,
                    );
                }
                ResourceUpdate::UpdateImage(img) => {
                    self.update_image_template(img.key, img.descriptor, img.data.into(), &img.dirty_rect);
                }
                ResourceUpdate::AddBlobImage(img) => {
                    self.add_image_template(
                        img.key.as_image(),
                        img.descriptor,
                        CachedImageData::Blob,
                        &img.visible_rect,
                        img.tiling,
                    );
                }
                ResourceUpdate::UpdateBlobImage(img) => {
                    self.update_image_template(
                        img.key.as_image(),
                        img.descriptor,
                        CachedImageData::Blob,
                        &to_image_dirty_rect(
                            &img.dirty_rect
                        ),
                    );
                    self.discard_tiles_outside_visible_area(img.key, &img.visible_rect); // TODO: remove?
                    self.set_image_visible_rect(img.key.as_image(), &img.visible_rect);
                }
                ResourceUpdate::DeleteImage(img) => {
                    self.delete_image_template(img);
                }
                ResourceUpdate::DeleteFont(font) => {
                    self.delete_font_template(font);
                }
                ResourceUpdate::DeleteFontInstance(font) => {
                    self.delete_font_instance(font);
                }
                ResourceUpdate::SetBlobImageVisibleArea(key, area) => {
                    self.discard_tiles_outside_visible_area(key, &area);
                    self.set_image_visible_rect(key.as_image(), &area);
                }
                ResourceUpdate::AddFont(_) |
                ResourceUpdate::AddFontInstance(_) => {
                    // Handled in update_resources_pre_scene_building
                }
            }
        }
    }

    pub fn pre_scene_building_update(
        &mut self,
        updates: &mut Vec<ResourceUpdate>,
        profile_counters: &mut ResourceProfileCounters,
    ) {
        for update in updates.iter() {
            match *update {
                ResourceUpdate::AddBlobImage(ref img) => {
                    self.add_blob_image(
                        img.key,
                        &img.descriptor,
                        img.tiling,
                        Arc::clone(&img.data),
                        &img.visible_rect,
                    );
                }
                ResourceUpdate::UpdateBlobImage(ref img) => {
                    debug_assert_eq!(img.visible_rect.size, img.descriptor.size);
                    self.update_blob_image(
                        img.key,
                        Some(&img.descriptor),
                        Some(&img.dirty_rect),
                        Some(Arc::clone(&img.data)),
                        &img.visible_rect,
                    );
                }
                ResourceUpdate::SetBlobImageVisibleArea(ref key, ref area) => {
                    self.update_blob_image(*key, None, None, None, area);
                }
                _ => {}
            }
        }

        drain_filter(
            updates,
            |update| match *update {
                ResourceUpdate::AddFont(_) |
                ResourceUpdate::AddFontInstance(_) => true,
                _ => false,
            },
            // Updates that were moved out of the array:
            |update: ResourceUpdate| match update {
                ResourceUpdate::AddFont(font) => {
                    match font {
                        AddFont::Raw(id, bytes, index) => {
                            profile_counters.font_templates.inc(bytes.len());
                            self.add_font_template(id, FontTemplate::Raw(Arc::new(bytes), index));
                        }
                        AddFont::Native(id, native_font_handle) => {
                            self.add_font_template(id, FontTemplate::Native(native_font_handle));
                        }
                    }
                }
                ResourceUpdate::AddFontInstance(instance) => {
                    self.add_font_instance(
                        instance.key,
                        instance.font_key,
                        instance.glyph_size,
                        instance.options,
                        instance.platform_options,
                        instance.variations,
                    );
                }
                _ => { unreachable!(); }
            }
        );
    }

    pub fn set_blob_rasterizer(
        &mut self, rasterizer: Box<dyn AsyncBlobImageRasterizer>,
        supp: AsyncBlobImageInfo,
    ) {
        if self.blob_image_rasterizer_consumed_epoch.0 < supp.epoch.0 {
            self.blob_image_rasterizer = Some(rasterizer);
            self.blob_image_rasterizer_consumed_epoch = supp.epoch;
        }
    }

    pub fn add_rasterized_blob_images(
        &mut self,
        images: Vec<(BlobImageRequest, BlobImageResult)>,
        texture_cache_profile: &mut TextureCacheProfileCounters,
    ) {
        for (request, result) in images {
            let data = match result {
                Ok(data) => data,
                Err(..) => {
                    warn!("Failed to rasterize a blob image");
                    continue;
                }
            };

            texture_cache_profile.rasterized_blob_pixels.inc(data.rasterized_rect.area() as usize);

            // First make sure we have an entry for this key (using a placeholder
            // if need be).
            let image = self.rasterized_blob_images.entry(request.key).or_insert_with(
                || { RasterizedBlob::Tiled(FastHashMap::default()) }
            );

            if let Some(tile) = request.tile {
                if let RasterizedBlob::NonTiled(..) = *image {
                    *image = RasterizedBlob::Tiled(FastHashMap::default());
                }

                if let RasterizedBlob::Tiled(ref mut tiles) = *image {
                    tiles.insert(tile, data);
                }

                match self.cached_images.try_get_mut(&request.key.as_image()) {
                    Some(&mut ImageResult::Multi(ref mut entries)) => {
                        let cached_key = CachedImageKey {
                            rendering: ImageRendering::Auto, // TODO(nical)
                            tile: Some(tile),
                        };
                        if let Some(entry) = entries.try_get_mut(&cached_key) {
                            entry.dirty_rect = DirtyRect::All;
                        }
                    }
                    _ => {}
                }

            } else {
                if let RasterizedBlob::NonTiled(ref mut queue) = *image {
                    // If our new rasterized rect overwrites items in the queue, discard them.
                    queue.retain(|img| {
                        !data.rasterized_rect.contains_rect(&img.rasterized_rect)
                    });

                    queue.push(data);
                } else {
                    *image = RasterizedBlob::NonTiled(vec![data]);
                }
            }
        }
    }

    pub fn add_font_template(&mut self, font_key: FontKey, template: FontTemplate) {
        // Push the new font to the font renderer, and also store
        // it locally for glyph metric requests.
        self.glyph_rasterizer.add_font(font_key, template.clone());
        self.resources.font_templates.insert(font_key, template);
    }

    pub fn delete_font_template(&mut self, font_key: FontKey) {
        self.glyph_rasterizer.delete_font(font_key);
        self.resources.font_templates.remove(&font_key);
        self.cached_glyphs
            .clear_fonts(&mut self.texture_cache, |font| font.font_key == font_key);
        if let Some(ref mut r) = self.blob_image_handler {
            r.delete_font(font_key);
        }
    }

    pub fn add_font_instance(
        &mut self,
        instance_key: FontInstanceKey,
        font_key: FontKey,
        size: Au,
        options: Option<FontInstanceOptions>,
        platform_options: Option<FontInstancePlatformOptions>,
        variations: Vec<FontVariation>,
    ) {
        let FontInstanceOptions {
            render_mode,
            flags,
            bg_color,
            synthetic_italics,
            ..
        } = options.unwrap_or_default();
        let instance = Arc::new(BaseFontInstance {
            instance_key,
            font_key,
            size,
            bg_color,
            render_mode,
            flags,
            synthetic_italics,
            platform_options,
            variations,
        });
        self.resources.font_instances
            .write()
            .unwrap()
            .insert(instance_key, instance);
    }

    pub fn delete_font_instance(&mut self, instance_key: FontInstanceKey) {
        self.resources.font_instances
            .write()
            .unwrap()
            .remove(&instance_key);
        if let Some(ref mut r) = self.blob_image_handler {
            r.delete_font_instance(instance_key);
        }
    }

    pub fn get_font_instances(&self) -> FontInstanceMap {
        self.resources.font_instances.clone()
    }

    pub fn get_font_instance(&self, instance_key: FontInstanceKey) -> Option<Arc<BaseFontInstance>> {
        let instance_map = self.resources.font_instances.read().unwrap();
        instance_map.get(&instance_key).map(|instance| { Arc::clone(instance) })
    }

    pub fn add_image_template(
        &mut self,
        image_key: ImageKey,
        descriptor: ImageDescriptor,
        data: CachedImageData,
        visible_rect: &DeviceIntRect,
        mut tiling: Option<TileSize>,
    ) {
        if tiling.is_none() && Self::should_tile(self.max_texture_size(), &descriptor, &data) {
            // We aren't going to be able to upload a texture this big, so tile it, even
            // if tiling was not requested.
            tiling = Some(DEFAULT_TILE_SIZE);
        }

        let resource = ImageResource {
            descriptor,
            data,
            tiling,
            visible_rect: *visible_rect,
            generation: ImageGeneration(0),
        };

        self.resources.image_templates.insert(image_key, resource);
    }

    pub fn update_image_template(
        &mut self,
        image_key: ImageKey,
        descriptor: ImageDescriptor,
        data: CachedImageData,
        dirty_rect: &ImageDirtyRect,
    ) {
        let max_texture_size = self.max_texture_size();
        let image = match self.resources.image_templates.get_mut(image_key) {
            Some(res) => res,
            None => panic!("Attempt to update non-existent image"),
        };

        let mut tiling = image.tiling;
        if tiling.is_none() && Self::should_tile(max_texture_size, &descriptor, &data) {
            tiling = Some(DEFAULT_TILE_SIZE);
        }

        // Each cache entry stores its own copy of the image's dirty rect. This allows them to be
        // updated independently.
        match self.cached_images.try_get_mut(&image_key) {
            Some(&mut ImageResult::UntiledAuto(ref mut entry)) => {
                entry.dirty_rect = entry.dirty_rect.union(dirty_rect);
            }
            Some(&mut ImageResult::Multi(ref mut entries)) => {
                for (key, entry) in entries.iter_mut() {
                    // We want the dirty rect relative to the tile and not the whole image.
                    let local_dirty_rect = match (tiling, key.tile) {
                        (Some(tile_size), Some(tile)) => {
                            dirty_rect.map(|mut rect|{
                                let tile_offset = DeviceIntPoint::new(
                                    tile.x as i32,
                                    tile.y as i32,
                                ) * tile_size as i32;
                                rect.origin -= tile_offset.to_vector();

                                let tile_rect = compute_tile_size(
                                    &descriptor.size.into(),
                                    tile_size,
                                    tile,
                                ).into();

                                rect.intersection(&tile_rect).unwrap_or(DeviceIntRect::zero())
                            })
                        }
                        (None, Some(..)) => DirtyRect::All,
                        _ => *dirty_rect,
                    };
                    entry.dirty_rect = entry.dirty_rect.union(&local_dirty_rect);
                }
            }
            _ => {}
        }

        if image.descriptor.format != descriptor.format {
            // could be a stronger warning/error?
            trace!("Format change {:?} -> {:?}", image.descriptor.format, descriptor.format);
        }
        *image = ImageResource {
            descriptor,
            data,
            tiling,
            visible_rect: descriptor.size.into(),
            generation: ImageGeneration(image.generation.0 + 1),
        };
    }

    // Happens before scene building.
    pub fn add_blob_image(
        &mut self,
        key: BlobImageKey,
        descriptor: &ImageDescriptor,
        mut tiling: Option<TileSize>,
        data: Arc<BlobImageData>,
        visible_rect: &DeviceIntRect,
    ) {
        let max_texture_size = self.max_texture_size();
        tiling = get_blob_tiling(tiling, visible_rect.size, max_texture_size);

        self.blob_image_handler.as_mut().unwrap().add(key, data, visible_rect, tiling);

        self.blob_image_templates.insert(
            key,
            BlobImageTemplate {
                descriptor: *descriptor,
                tiling,
                dirty_rect: DirtyRect::All,
                valid_tiles_after_bounds_change: None,
                visible_rect: *visible_rect,
            },
        );
    }

    // Happens before scene building.
    pub fn update_blob_image(
        &mut self,
        key: BlobImageKey,
        descriptor: Option<&ImageDescriptor>,
        dirty_rect: Option<&BlobDirtyRect>,
        data: Option<Arc<BlobImageData>>,
        visible_rect: &DeviceIntRect,
    ) {
        if let Some(data) = data {
            let dirty_rect = dirty_rect.unwrap();
            self.blob_image_handler.as_mut().unwrap().update(key, data, visible_rect, dirty_rect);
        }

        let max_texture_size = self.max_texture_size();

        let image = self.blob_image_templates
            .get_mut(&key)
            .expect("Attempt to update non-existent blob image");

        let mut valid_tiles_after_bounds_change = None;

        if let Some(tile_size) = image.tiling {
            valid_tiles_after_bounds_change = compute_valid_tiles_if_bounds_change(
                &image.visible_rect,
                visible_rect,
                tile_size,
            );
        }

        match (image.valid_tiles_after_bounds_change, valid_tiles_after_bounds_change) {
            (Some(old), Some(ref mut new)) => {
                *new = new.intersection(&old).unwrap_or(TileRange::zero());
            }
            (Some(old), None) => {
                valid_tiles_after_bounds_change = Some(old);
            }
            _ => {}
        }

        let blob_size = visible_rect.size;

        if let Some(descriptor) = descriptor {
            image.descriptor = *descriptor;
        } else {
            // make sure the descriptor size matches the visible rect.
            // This might not be necessary but let's stay on the safe side.
            image.descriptor.size = blob_size;
        }

        if let Some(dirty_rect) = dirty_rect {
            image.dirty_rect = image.dirty_rect.union(dirty_rect);
        }

        image.tiling = get_blob_tiling(image.tiling, blob_size, max_texture_size);
        image.valid_tiles_after_bounds_change = valid_tiles_after_bounds_change;
        image.visible_rect = *visible_rect;
    }

    pub fn delete_image_template(&mut self, image_key: ImageKey) {
        // Remove the template.
        let value = self.resources.image_templates.remove(image_key);

        // Release the corresponding texture cache entry, if any.
        if let Some(mut cached) = self.cached_images.remove(&image_key) {
            cached.drop_from_cache(&mut self.texture_cache);
        }

        match value {
            Some(image) => if image.data.is_blob() {
                let blob_key = BlobImageKey(image_key);
                self.blob_image_handler.as_mut().unwrap().delete(blob_key);
                self.deleted_blob_keys.back_mut().unwrap().push(blob_key);
                self.blob_image_templates.remove(&blob_key);
                self.rasterized_blob_images.remove(&blob_key);
            },
            None => {
                warn!("Delete the non-exist key");
                debug!("key={:?}", image_key);
            }
        }
    }

    /// Return the current generation of an image template
    pub fn get_image_generation(&self, key: ImageKey) -> ImageGeneration {
        self.resources
            .image_templates
            .get(key)
            .map_or(ImageGeneration::INVALID, |template| template.generation)
    }

    pub fn request_image(
        &mut self,
        request: ImageRequest,
        gpu_cache: &mut GpuCache,
    ) {
        debug_assert_eq!(self.state, State::AddResources);

        let template = match self.resources.image_templates.get(request.key) {
            Some(template) => template,
            None => {
                warn!("ERROR: Trying to render deleted / non-existent key");
                debug!("key={:?}", request.key);
                return
            }
        };

        // Images that don't use the texture cache can early out.
        if !template.data.uses_texture_cache() {
            return;
        }

        let side_size =
            template.tiling.map_or(cmp::max(template.descriptor.size.width, template.descriptor.size.height),
                                   |tile_size| tile_size as i32);
        if side_size > self.texture_cache.max_texture_size() {
            // The image or tiling size is too big for hardware texture size.
            warn!("Dropping image, image:(w:{},h:{}, tile:{}) is too big for hardware!",
                  template.descriptor.size.width, template.descriptor.size.height, template.tiling.unwrap_or(0));
            self.cached_images.insert(request.key, ImageResult::Err(ImageCacheError::OverLimitSize));
            return;
        }

        let storage = match self.cached_images.entry(request.key) {
            Occupied(e) => {
                // We might have an existing untiled entry, and need to insert
                // a second entry. In such cases we need to move the old entry
                // out first, replacing it with a dummy entry, and then creating
                // the tiled/multi-entry variant.
                let entry = e.into_mut();
                if !request.is_untiled_auto() {
                    let untiled_entry = match entry {
                        &mut ImageResult::UntiledAuto(ref mut entry) => {
                            Some(mem::replace(entry, CachedImageInfo {
                                texture_cache_handle: TextureCacheHandle::invalid(),
                                dirty_rect: DirtyRect::All,
                                manual_eviction: false,
                            }))
                        }
                        _ => None
                    };

                    if let Some(untiled_entry) = untiled_entry {
                        let mut entries = ResourceClassCache::new();
                        let untiled_key = CachedImageKey {
                            rendering: ImageRendering::Auto,
                            tile: None,
                        };
                        entries.insert(untiled_key, untiled_entry);
                        *entry = ImageResult::Multi(entries);
                    }
                }
                entry
            }
            Vacant(entry) => {
                entry.insert(if request.is_untiled_auto() {
                    ImageResult::UntiledAuto(CachedImageInfo {
                        texture_cache_handle: TextureCacheHandle::invalid(),
                        dirty_rect: DirtyRect::All,
                        manual_eviction: false,
                    })
                } else {
                    ImageResult::Multi(ResourceClassCache::new())
                })
            }
        };

        // If this image exists in the texture cache, *and* the dirty rect
        // in the cache is empty, then it is valid to use as-is.
        let entry = match *storage {
            ImageResult::UntiledAuto(ref mut entry) => entry,
            ImageResult::Multi(ref mut entries) => {
                entries.entry(request.into())
                    .or_insert(CachedImageInfo {
                        texture_cache_handle: TextureCacheHandle::invalid(),
                        dirty_rect: DirtyRect::All,
                        manual_eviction: false,
                    })
            },
            ImageResult::Err(_) => panic!("Errors should already have been handled"),
        };

        let needs_upload = self.texture_cache.request(&entry.texture_cache_handle, gpu_cache);

        if !needs_upload && entry.dirty_rect.is_empty() {
            return
        }

        if !self.pending_image_requests.insert(request) {
            return
        }

        if template.data.is_blob() {
            let request: BlobImageRequest = request.into();
            let missing = match (self.rasterized_blob_images.get(&request.key), request.tile) {
                (Some(RasterizedBlob::Tiled(tiles)), Some(tile)) => !tiles.contains_key(&tile),
                (Some(RasterizedBlob::NonTiled(ref queue)), None) => queue.is_empty(),
                _ => true,
            };

            // For some reason the blob image is missing. We'll fall back to
            // rasterizing it on the render backend thread.
            if missing {
                let descriptor = BlobImageDescriptor {
                    rect: match template.tiling {
                        Some(tile_size) => {
                            let tile = request.tile.unwrap();
                            blob_rect(compute_tile_rect(
                                &template.visible_rect,
                                tile_size,
                                tile,
                            ))
                        }
                        None => blob_size(template.visible_rect.size).into(),
                    },
                    format: template.descriptor.format,
                };

                assert!(!descriptor.rect.is_empty());

                if !self.blob_image_templates.contains_key(&request.key) {
                    panic!("already missing blob image key {:?} deleted: {:?}", request, self.deleted_blob_keys);
                }

                self.missing_blob_images.push(
                    BlobImageParams {
                        request,
                        descriptor,
                        dirty_rect: DirtyRect::All,
                    }
                );
            }
        }
    }

    pub fn create_blob_scene_builder_requests(
        &mut self,
        keys: &[BlobImageKey]
    ) -> (Option<(Box<dyn AsyncBlobImageRasterizer>, AsyncBlobImageInfo)>, Vec<BlobImageParams>) {
        if self.blob_image_handler.is_none() || keys.is_empty() {
            return (None, Vec::new());
        }

        let mut blob_request_params = Vec::new();
        for key in keys {
            let template = self.blob_image_templates.get_mut(key).unwrap();

            if let Some(tile_size) = template.tiling {
                // If we know that only a portion of the blob image is in the viewport,
                // only request these visible tiles since blob images can be huge.
                let tiles = compute_tile_range(
                    &template.visible_rect,
                    tile_size,
                );

                let image_dirty_rect = to_image_dirty_rect(&template.dirty_rect);
                // Don't request tiles that weren't invalidated.
                let dirty_tiles = match image_dirty_rect {
                    DirtyRect::Partial(dirty_rect) => {
                        let dirty_rect = DeviceIntRect {
                            origin: point2(
                                dirty_rect.origin.x,
                                dirty_rect.origin.y,
                            ),
                            size: size2(
                                dirty_rect.size.width,
                                dirty_rect.size.height,
                            ),
                        };

                        compute_tile_range(
                            &dirty_rect,
                            tile_size,
                        )
                    }
                    DirtyRect::All => tiles,
                };

                for_each_tile_in_range(&tiles, |tile| {
                    let still_valid = template.valid_tiles_after_bounds_change
                        .map(|valid_tiles| valid_tiles.contains(tile))
                        .unwrap_or(true);

                    if still_valid && !dirty_tiles.contains(tile) {
                        return;
                    }

                    let descriptor = BlobImageDescriptor {
                        rect: blob_rect(compute_tile_rect(
                            &template.visible_rect,
                            tile_size,
                            tile,
                        )),
                        format: template.descriptor.format,
                    };

                    assert!(descriptor.rect.size.width > 0 && descriptor.rect.size.height > 0);
                    // TODO: We only track dirty rects for non-tiled blobs but we
                    // should also do it with tiled ones unless we settle for a small
                    // tile size.
                    blob_request_params.push(
                        BlobImageParams {
                            request: BlobImageRequest {
                                key: *key,
                                tile: Some(tile),
                            },
                            descriptor,
                            dirty_rect: DirtyRect::All,
                        }
                    );
                });

                template.valid_tiles_after_bounds_change = None;
            } else {
                let mut needs_upload = match self.cached_images.try_get(&key.as_image()) {
                    Some(&ImageResult::UntiledAuto(ref entry)) => {
                        self.texture_cache.needs_upload(&entry.texture_cache_handle)
                    }
                    _ => true,
                };

                // If the queue of rasterized updates is growing it probably means that
                // the texture is not getting uploaded because the display item is off-screen.
                // In that case we are better off
                // - Either not kicking rasterization for that image (avoid wasted cpu work
                //   but will jank next time the item is visible because of lazy rasterization.
                // - Clobber the update queue by pushing an update with a larger dirty rect
                //   to prevent it from accumulating.
                //
                // We do the latter here but it's not ideal and might want to revisit and do
                // the former instead.
                match self.rasterized_blob_images.get(key) {
                    Some(RasterizedBlob::NonTiled(ref queue)) => {
                        if queue.len() > 2 {
                            needs_upload = true;
                        }
                    }
                    _ => {},
                };

                let dirty_rect = if needs_upload {
                    // The texture cache entry has been evicted, treat it as all dirty.
                    DirtyRect::All
                } else {
                    template.dirty_rect
                };

                assert!(template.visible_rect.size.width > 0 && template.visible_rect.size.height > 0);
                blob_request_params.push(
                    BlobImageParams {
                        request: BlobImageRequest {
                            key: *key,
                            tile: None,
                        },
                        descriptor: BlobImageDescriptor {
                            rect: blob_size(template.visible_rect.size).into(),
                            format: template.descriptor.format,
                        },
                        dirty_rect,
                    }
                );
            }
            template.dirty_rect = DirtyRect::empty();
        }
        self.blob_image_rasterizer_produced_epoch.0 += 1;
        let info = AsyncBlobImageInfo {
            epoch: self.blob_image_rasterizer_produced_epoch,
            clear_requests: Vec::new(),
        };
        let handler = self.blob_image_handler.as_mut().unwrap();
        handler.prepare_resources(&self.resources, &blob_request_params);
        (Some((handler.create_blob_rasterizer(), info)), blob_request_params)
    }

    fn discard_tiles_outside_visible_area(
        &mut self,
        key: BlobImageKey,
        area: &DeviceIntRect
    ) {
        let template = match self.blob_image_templates.get(&key) {
            Some(template) => template,
            None => {
                //println!("Missing image template (key={:?})!", key);
                return;
            }
        };
        let tile_size = match template.tiling {
            Some(size) => size,
            None => { return; }
        };

        let tiles = match self.rasterized_blob_images.get_mut(&key) {
            Some(RasterizedBlob::Tiled(tiles)) => tiles,
            _ => { return; }
        };

        let tile_range = compute_tile_range(
            &area,
            tile_size,
        );

        tiles.retain(|tile, _| { tile_range.contains(*tile) });

        let texture_cache = &mut self.texture_cache;
        match self.cached_images.try_get_mut(&key.as_image()) {
            Some(&mut ImageResult::Multi(ref mut entries)) => {
                entries.retain(|key, entry| {
                    if key.tile.is_none() || tile_range.contains(key.tile.unwrap()) {
                        return true;
                    }
                    entry.mark_unused(texture_cache);
                    return false;
                });
            }
            _ => {}
        }
    }

    fn set_image_visible_rect(&mut self, key: ImageKey, rect: &DeviceIntRect) {
        if let Some(image) = self.resources.image_templates.get_mut(key) {
            image.visible_rect = *rect;
            image.descriptor.size = rect.size;
        }
    }

    pub fn request_glyphs(
        &mut self,
        mut font: FontInstance,
        glyph_keys: &[GlyphKey],
        gpu_cache: &mut GpuCache,
        render_task_tree: &mut RenderTaskGraph,
    ) {
        debug_assert_eq!(self.state, State::AddResources);

        self.glyph_rasterizer.prepare_font(&mut font);
        self.glyph_rasterizer.request_glyphs(
            &mut self.cached_glyphs,
            font,
            glyph_keys,
            &mut self.texture_cache,
            gpu_cache,
            &mut self.cached_render_tasks,
            render_task_tree,
        );
    }

    pub fn pending_updates(&mut self) -> ResourceUpdateList {
        ResourceUpdateList {
            texture_updates: self.texture_cache.pending_updates(),
            native_surface_updates: mem::replace(&mut self.pending_native_surface_updates, Vec::new()),
        }
    }

    pub fn fetch_glyphs<F>(
        &self,
        mut font: FontInstance,
        glyph_keys: &[GlyphKey],
        fetch_buffer: &mut Vec<GlyphFetchResult>,
        gpu_cache: &mut GpuCache,
        mut f: F,
    ) where
        F: FnMut(TextureSource, GlyphFormat, &[GlyphFetchResult]),
    {
        debug_assert_eq!(self.state, State::QueryResources);

        self.glyph_rasterizer.prepare_font(&mut font);
        let glyph_key_cache = self.cached_glyphs.get_glyph_key_cache_for_font(&font);

        let mut current_texture_id = TextureSource::Invalid;
        let mut current_glyph_format = GlyphFormat::Subpixel;
        debug_assert!(fetch_buffer.is_empty());

        for (loop_index, key) in glyph_keys.iter().enumerate() {
            let (cache_item, glyph_format) = match *glyph_key_cache.get(key) {
                GlyphCacheEntry::Cached(ref glyph) => {
                    (self.texture_cache.get(&glyph.texture_cache_handle), glyph.format)
                }
                GlyphCacheEntry::Blank | GlyphCacheEntry::Pending => continue,
            };
            if current_texture_id != cache_item.texture_id ||
                current_glyph_format != glyph_format {
                if !fetch_buffer.is_empty() {
                    f(current_texture_id, current_glyph_format, fetch_buffer);
                    fetch_buffer.clear();
                }
                current_texture_id = cache_item.texture_id;
                current_glyph_format = glyph_format;
            }
            fetch_buffer.push(GlyphFetchResult {
                index_in_text_run: loop_index as i32,
                uv_rect_address: gpu_cache.get_address(&cache_item.uv_rect_handle),
            });
        }

        if !fetch_buffer.is_empty() {
            f(current_texture_id, current_glyph_format, fetch_buffer);
            fetch_buffer.clear();
        }
    }

    pub fn get_glyph_dimensions(
        &mut self,
        font: &FontInstance,
        glyph_index: GlyphIndex,
    ) -> Option<GlyphDimensions> {
        match self.cached_glyph_dimensions.entry((font.instance_key, glyph_index)) {
            Occupied(entry) => *entry.get(),
            Vacant(entry) => *entry.insert(
                self.glyph_rasterizer
                    .get_glyph_dimensions(font, glyph_index),
            ),
        }
    }

    pub fn get_glyph_index(&mut self, font_key: FontKey, ch: char) -> Option<u32> {
        self.glyph_rasterizer.get_glyph_index(font_key, ch)
    }

    #[inline]
    pub fn get_cached_image(&self, request: ImageRequest) -> Result<CacheItem, ()> {
        debug_assert_eq!(self.state, State::QueryResources);
        let image_info = self.get_image_info(request)?;
        Ok(self.get_texture_cache_item(&image_info.texture_cache_handle))
    }

    pub fn get_cached_render_task(
        &self,
        handle: &RenderTaskCacheEntryHandle,
    ) -> &RenderTaskCacheEntry {
        self.cached_render_tasks.get_cache_entry(handle)
    }

    #[inline]
    fn get_image_info(&self, request: ImageRequest) -> Result<&CachedImageInfo, ()> {
        // TODO(Jerry): add a debug option to visualize the corresponding area for
        // the Err() case of CacheItem.
        match *self.cached_images.get(&request.key) {
            ImageResult::UntiledAuto(ref image_info) => Ok(image_info),
            ImageResult::Multi(ref entries) => Ok(entries.get(&request.into())),
            ImageResult::Err(_) => Err(()),
        }
    }

    #[inline]
    pub fn get_texture_cache_item(&self, handle: &TextureCacheHandle) -> CacheItem {
        self.texture_cache.get(handle)
    }

    pub fn get_image_properties(&self, image_key: ImageKey) -> Option<ImageProperties> {
        let image_template = &self.resources.image_templates.get(image_key);

        image_template.map(|image_template| {
            let external_image = match image_template.data {
                CachedImageData::External(ext_image) => match ext_image.image_type {
                    ExternalImageType::TextureHandle(_) => Some(ext_image),
                    // external buffer uses resource_cache.
                    ExternalImageType::Buffer => None,
                },
                // raw and blob image are all using resource_cache.
                CachedImageData::Raw(..) | CachedImageData::Blob => None,
            };

            ImageProperties {
                descriptor: image_template.descriptor,
                external_image,
                tiling: image_template.tiling,
                visible_rect: image_template.visible_rect,
            }
        })
    }

    pub fn prepare_for_frames(&mut self, time: SystemTime) {
        self.texture_cache.prepare_for_frames(time);
    }

    pub fn bookkeep_after_frames(&mut self) {
        self.texture_cache.bookkeep_after_frames();
    }

    pub fn requires_frame_build(&self) -> bool {
        self.texture_cache.requires_frame_build()
    }

    pub fn begin_frame(&mut self, stamp: FrameStamp) {
        debug_assert_eq!(self.state, State::Idle);
        self.state = State::AddResources;
        self.texture_cache.begin_frame(stamp);
        self.cached_glyphs.begin_frame(
            stamp,
            &mut self.texture_cache,
            &self.cached_render_tasks,
            &mut self.glyph_rasterizer,
        );
        self.cached_render_tasks.begin_frame(&mut self.texture_cache);
        self.current_frame_id = stamp.frame_id();

        // pop the old frame and push a new one
        self.deleted_blob_keys.pop_front();
        self.deleted_blob_keys.push_back(Vec::new());
    }

    pub fn block_until_all_resources_added(
        &mut self,
        gpu_cache: &mut GpuCache,
        render_tasks: &mut RenderTaskGraph,
        texture_cache_profile: &mut TextureCacheProfileCounters,
    ) {
        profile_scope!("block_until_all_resources_added");

        debug_assert_eq!(self.state, State::AddResources);
        self.state = State::QueryResources;

        self.glyph_rasterizer.resolve_glyphs(
            &mut self.cached_glyphs,
            &mut self.texture_cache,
            gpu_cache,
            &mut self.cached_render_tasks,
            render_tasks,
            texture_cache_profile,
        );

        self.rasterize_missing_blob_images(texture_cache_profile);

        // Apply any updates of new / updated images (incl. blobs) to the texture cache.
        self.update_texture_cache(gpu_cache);
    }

    fn rasterize_missing_blob_images(
        &mut self,
        texture_cache_profile: &mut TextureCacheProfileCounters,
    ) {
        if self.missing_blob_images.is_empty() {
            return;
        }

        self.blob_image_handler
            .as_mut()
            .unwrap()
            .prepare_resources(&self.resources, &self.missing_blob_images);


        for blob_image in &self.missing_blob_images {
            if !self.blob_image_templates.contains_key(&blob_image.request.key) {
                panic!("missing blob image key {:?} deleted: {:?}", blob_image, self.deleted_blob_keys);
            }
        }
        let is_low_priority = false;
        let rasterized_blobs = self.blob_image_rasterizer
            .as_mut()
            .unwrap()
            .rasterize(&self.missing_blob_images, is_low_priority);

        self.add_rasterized_blob_images(rasterized_blobs, texture_cache_profile);

        self.missing_blob_images.clear();
    }

    fn update_texture_cache(&mut self, gpu_cache: &mut GpuCache) {
        for request in self.pending_image_requests.drain() {
            let image_template = self.resources.image_templates.get_mut(request.key).unwrap();
            debug_assert!(image_template.data.uses_texture_cache());

            let mut updates: SmallVec<[(CachedImageData, Option<DeviceIntRect>); 1]> = SmallVec::new();

            match image_template.data {
                CachedImageData::Raw(..) | CachedImageData::External(..) => {
                    // Safe to clone here since the Raw image data is an
                    // Arc, and the external image data is small.
                    updates.push((image_template.data.clone(), None));
                }
                CachedImageData::Blob => {

                    let blob_image = self.rasterized_blob_images.get_mut(&BlobImageKey(request.key)).unwrap();
                    match (blob_image, request.tile) {
                        (RasterizedBlob::Tiled(ref tiles), Some(tile)) => {
                            let img = &tiles[&tile];
                            updates.push((
                                CachedImageData::Raw(Arc::clone(&img.data)),
                                Some(img.rasterized_rect)
                            ));
                        }
                        (RasterizedBlob::NonTiled(ref mut queue), None) => {
                            for img in queue.drain(..) {
                                updates.push((
                                    CachedImageData::Raw(img.data),
                                    Some(img.rasterized_rect)
                                ));
                            }
                        }
                        _ =>  {
                            debug_assert!(false, "invalid blob image request during frame building");
                            continue;
                        }
                    }
                }
            };

            for (image_data, blob_rasterized_rect) in updates {
                let entry = match *self.cached_images.get_mut(&request.key) {
                    ImageResult::UntiledAuto(ref mut entry) => entry,
                    ImageResult::Multi(ref mut entries) => entries.get_mut(&request.into()),
                    ImageResult::Err(_) => panic!("Update requested for invalid entry")
                };

                let mut descriptor = image_template.descriptor.clone();
                let mut dirty_rect = entry.dirty_rect.replace_with_empty();

                if let Some(tile) = request.tile {
                    let tile_size = image_template.tiling.unwrap();
                    let clipped_tile_size = compute_tile_size(&image_template.visible_rect, tile_size, tile);
                    // The tiled image could be stored on the CPU as one large image or be
                    // already broken up into tiles. This affects the way we compute the stride
                    // and offset.
                    let tiled_on_cpu = image_template.data.is_blob();
                    if !tiled_on_cpu {
                        // we don't expect to have partial tiles at the top and left of non-blob
                        // images.
                        debug_assert_eq!(image_template.visible_rect.origin, point2(0, 0));
                        let bpp = descriptor.format.bytes_per_pixel();
                        let stride = descriptor.compute_stride();
                        descriptor.stride = Some(stride);
                        descriptor.offset +=
                            tile.y as i32 * tile_size as i32 * stride +
                            tile.x as i32 * tile_size as i32 * bpp;
                    }

                    descriptor.size = clipped_tile_size;
                }

                // If we are uploading the dirty region of a blob image we might have several
                // rects to upload so we use each of these rasterized rects rather than the
                // overall dirty rect of the image.
                if let Some(rect) = blob_rasterized_rect {
                    dirty_rect = DirtyRect::Partial(rect);
                }

                let filter = match request.rendering {
                    ImageRendering::Pixelated => {
                        TextureFilter::Nearest
                    }
                    ImageRendering::Auto | ImageRendering::CrispEdges => {
                        // If the texture uses linear filtering, enable mipmaps and
                        // trilinear filtering, for better image quality. We only
                        // support this for now on textures that are not placed
                        // into the shared cache. This accounts for any image
                        // that is > 512 in either dimension, so it should cover
                        // the most important use cases. We may want to support
                        // mip-maps on shared cache items in the future.
                        if descriptor.allow_mipmaps() &&
                           descriptor.size.width > 512 &&
                           descriptor.size.height > 512 &&
                           !self.texture_cache.is_allowed_in_shared_cache(
                            TextureFilter::Linear,
                            &descriptor,
                        ) {
                            TextureFilter::Trilinear
                        } else {
                            TextureFilter::Linear
                        }
                    }
                };

                let eviction = if image_template.data.is_blob() {
                    entry.manual_eviction = true;
                    Eviction::Manual
                } else {
                    Eviction::Auto
                };

                //Note: at this point, the dirty rectangle is local to the descriptor space
                self.texture_cache.update(
                    &mut entry.texture_cache_handle,
                    descriptor,
                    filter,
                    Some(image_data),
                    [0.0; 3],
                    dirty_rect,
                    gpu_cache,
                    None,
                    UvRectKind::Rect,
                    eviction,
                );
            }
        }
    }

    /// Queue up allocation of a new OS native compositor surface with the
    /// specified tile size.
    pub fn create_compositor_surface(
        &mut self,
        tile_size: DeviceIntSize,
    ) -> NativeSurfaceId {
        let id = NativeSurfaceId(NEXT_NATIVE_SURFACE_ID.fetch_add(1, Ordering::Relaxed));

        self.pending_native_surface_updates.push(
            NativeSurfaceOperation {
                details: NativeSurfaceOperationDetails::CreateSurface {
                    id,
                    tile_size,
                },
            }
        );

        id
    }

    /// Queue up destruction of an existing native OS surface. This is used when
    /// a picture cache surface is dropped or resized.
    pub fn destroy_compositor_surface(
        &mut self,
        id: NativeSurfaceId,
    ) {
        self.pending_native_surface_updates.push(
            NativeSurfaceOperation {
                details: NativeSurfaceOperationDetails::DestroySurface {
                    id,
                }
            }
        );
    }

    /// Queue construction of a native compositor tile on a given surface.
    pub fn create_compositor_tile(
        &mut self,
        id: NativeTileId,
        is_opaque: bool,
    ) {
        self.pending_native_surface_updates.push(
            NativeSurfaceOperation {
                details: NativeSurfaceOperationDetails::CreateTile {
                    id,
                    is_opaque,
                },
            }
        );
    }

    /// Queue destruction of a native compositor tile.
    pub fn destroy_compositor_tile(
        &mut self,
        id: NativeTileId,
    ) {
        self.pending_native_surface_updates.push(
            NativeSurfaceOperation {
                details: NativeSurfaceOperationDetails::DestroyTile {
                    id,
                },
            }
        );
    }

    pub fn end_frame(&mut self, texture_cache_profile: &mut TextureCacheProfileCounters) {
        debug_assert_eq!(self.state, State::QueryResources);
        self.state = State::Idle;
        self.texture_cache.end_frame(texture_cache_profile);
    }

    pub fn set_debug_flags(&mut self, flags: DebugFlags) {
        GLYPH_FLASHING.store(flags.contains(DebugFlags::GLYPH_FLASHING), std::sync::atomic::Ordering::Relaxed);
        self.texture_cache.set_debug_flags(flags);
    }

    pub fn clear(&mut self, what: ClearCache) {
        if what.contains(ClearCache::IMAGES) {
            for (_key, mut cached) in self.cached_images.resources.drain() {
                cached.drop_from_cache(&mut self.texture_cache);
            }
        }
        if what.contains(ClearCache::GLYPHS) {
            self.cached_glyphs.clear();
        }
        if what.contains(ClearCache::GLYPH_DIMENSIONS) {
            self.cached_glyph_dimensions.clear();
        }
        if what.contains(ClearCache::RENDER_TASKS) {
            self.cached_render_tasks.clear();
        }
        if what.contains(ClearCache::TEXTURE_CACHE) {
            self.texture_cache.clear_all();
        }
        if what.contains(ClearCache::RASTERIZED_BLOBS) {
            self.rasterized_blob_images.clear();
        }
    }

    pub fn clear_namespace(&mut self, namespace: IdNamespace) {
        self.clear_images(|k| k.0 == namespace);

        self.resources.font_instances
            .write()
            .unwrap()
            .retain(|key, _| key.0 != namespace);
        for &key in self.resources.font_templates.keys().filter(|key| key.0 == namespace) {
            self.glyph_rasterizer.delete_font(key);
        }
        self.resources
            .font_templates
            .retain(|key, _| key.0 != namespace);
        self.cached_glyphs
            .clear_fonts(&mut self.texture_cache, |font| font.font_key.0 == namespace);

        if let Some(ref mut r) = self.blob_image_handler {
            r.clear_namespace(namespace);
        }
    }

    /// Reports the CPU heap usage of this ResourceCache.
    ///
    /// NB: It would be much better to use the derive(MallocSizeOf) machinery
    /// here, but the Arcs complicate things. The two ways to handle that would
    /// be to either (a) Implement MallocSizeOf manually for the things that own
    /// them and manually avoid double-counting, or (b) Use the "seen this pointer
    /// yet" machinery from the proper malloc_size_of crate. We can do this if/when
    /// more accurate memory reporting on these resources becomes a priority.
    pub fn report_memory(&self, op: VoidPtrToSizeFn) -> MemoryReport {
        let mut report = MemoryReport::default();

        // Measure fonts. We only need the templates here, because the instances
        // don't have big buffers.
        for (_, font) in self.resources.font_templates.iter() {
            if let FontTemplate::Raw(ref raw, _) = font {
                report.fonts += unsafe { op(raw.as_ptr() as *const c_void) };
            }
        }

        // Measure images.
        for (_, image) in self.resources.image_templates.images.iter() {
            report.images += match image.data {
                CachedImageData::Raw(ref v) => unsafe { op(v.as_ptr() as *const c_void) },
                CachedImageData::Blob | CachedImageData::External(..) => 0,
            }
        }

        // Mesure rasterized blobs.
        // TODO(gw): Temporarily disabled while we roll back a crash. We can re-enable
        //           these when that crash is fixed.
        /*
        for (_, image) in self.rasterized_blob_images.iter() {
            let mut accumulate = |b: &RasterizedBlobImage| {
                report.rasterized_blobs += unsafe { op(b.data.as_ptr() as *const c_void) };
            };
            match image {
                RasterizedBlob::Tiled(map) => map.values().for_each(&mut accumulate),
                RasterizedBlob::NonTiled(vec) => vec.iter().for_each(&mut accumulate),
            };
        }
        */

        report
    }

    /// Properly deletes all images matching the predicate.
    fn clear_images<F: Fn(&ImageKey) -> bool>(&mut self, f: F) {
        let keys = self.resources.image_templates.images.keys().filter(|k| f(*k))
            .cloned().collect::<SmallVec<[ImageKey; 16]>>();

        for key in keys {
            self.delete_image_template(key);
        }

        #[cfg(features="leak_checks")]
        let check_leaks = true;
        #[cfg(not(features="leak_checks"))]
        let check_leaks = false;

        if check_leaks {
            let blob_f = |key: &BlobImageKey| { f(&key.as_image()) };
            assert!(!self.resources.image_templates.images.keys().any(&f));
            assert!(!self.cached_images.resources.keys().any(&f));
            assert!(!self.blob_image_templates.keys().any(&blob_f));
            assert!(!self.rasterized_blob_images.keys().any(&blob_f));
        }
    }
}

impl Drop for ResourceCache {
    fn drop(&mut self) {
        self.clear_images(|_| true);
    }
}

pub fn get_blob_tiling(
    tiling: Option<TileSize>,
    size: DeviceIntSize,
    max_texture_size: i32,
) -> Option<TileSize> {
    if tiling.is_none() &&
        (size.width > max_texture_size ||
         size.height > max_texture_size) {
        return Some(DEFAULT_TILE_SIZE);
    }

    tiling
}

#[cfg(any(feature = "capture", feature = "replay"))]
#[cfg_attr(feature = "capture", derive(Serialize))]
#[cfg_attr(feature = "replay", derive(Deserialize))]
struct PlainFontTemplate {
    data: String,
    index: u32,
}

#[cfg(any(feature = "capture", feature = "replay"))]
#[cfg_attr(feature = "capture", derive(Serialize))]
#[cfg_attr(feature = "replay", derive(Deserialize))]
struct PlainImageTemplate {
    data: String,
    descriptor: ImageDescriptor,
    tiling: Option<TileSize>,
    generation: ImageGeneration,
}

#[cfg(any(feature = "capture", feature = "replay"))]
#[cfg_attr(feature = "capture", derive(Serialize))]
#[cfg_attr(feature = "replay", derive(Deserialize))]
pub struct PlainResources {
    font_templates: FastHashMap<FontKey, PlainFontTemplate>,
    font_instances: FastHashMap<FontInstanceKey, Arc<BaseFontInstance>>,
    image_templates: FastHashMap<ImageKey, PlainImageTemplate>,
}

#[cfg(feature = "capture")]
#[derive(Serialize)]
pub struct PlainCacheRef<'a> {
    current_frame_id: FrameId,
    glyphs: &'a GlyphCache,
    glyph_dimensions: &'a GlyphDimensionsCache,
    images: &'a ImageCache,
    render_tasks: &'a RenderTaskCache,
    textures: &'a TextureCache,
}

#[cfg(feature = "replay")]
#[derive(Deserialize)]
pub struct PlainCacheOwn {
    current_frame_id: FrameId,
    glyphs: GlyphCache,
    glyph_dimensions: GlyphDimensionsCache,
    images: ImageCache,
    render_tasks: RenderTaskCache,
    textures: TextureCache,
}

#[cfg(feature = "replay")]
const NATIVE_FONT: &'static [u8] = include_bytes!("../res/Proggy.ttf");

// This currently only casts the unit but will soon apply an offset
fn to_image_dirty_rect(blob_dirty_rect: &BlobDirtyRect) -> ImageDirtyRect {
    match *blob_dirty_rect {
        DirtyRect::Partial(rect) => DirtyRect::Partial(
            DeviceIntRect {
                origin: DeviceIntPoint::new(rect.origin.x, rect.origin.y),
                size: DeviceIntSize::new(rect.size.width, rect.size.height),
            }
        ),
        DirtyRect::All => DirtyRect::All,
    }
}

impl ResourceCache {
    #[cfg(feature = "capture")]
    pub fn save_capture(
        &mut self, root: &PathBuf
    ) -> (PlainResources, Vec<ExternalCaptureImage>) {
        use std::fs;
        use std::io::Write;

        info!("saving resource cache");
        let res = &self.resources;
        let path_fonts = root.join("fonts");
        if !path_fonts.is_dir() {
            fs::create_dir(&path_fonts).unwrap();
        }
        let path_images = root.join("images");
        if !path_images.is_dir() {
            fs::create_dir(&path_images).unwrap();
        }
        let path_blobs = root.join("blobs");
        if !path_blobs.is_dir() {
            fs::create_dir(&path_blobs).unwrap();
        }
        let path_externals = root.join("externals");
        if !path_externals.is_dir() {
            fs::create_dir(&path_externals).unwrap();
        }

        info!("\tfont templates");
        let mut font_paths = FastHashMap::default();
        for template in res.font_templates.values() {
            let data: &[u8] = match *template {
                FontTemplate::Raw(ref arc, _) => arc,
                FontTemplate::Native(_) => continue,
            };
            let font_id = res.font_templates.len() + 1;
            let entry = match font_paths.entry(data.as_ptr()) {
                Entry::Occupied(_) => continue,
                Entry::Vacant(e) => e,
            };
            let file_name = format!("{}.raw", font_id);
            let short_path = format!("fonts/{}", file_name);
            fs::File::create(path_fonts.join(file_name))
                .expect(&format!("Unable to create {}", short_path))
                .write_all(data)
                .unwrap();
            entry.insert(short_path);
        }

        info!("\timage templates");
        let mut image_paths = FastHashMap::default();
        let mut other_paths = FastHashMap::default();
        let mut num_blobs = 0;
        let mut external_images = Vec::new();
        for (&key, template) in res.image_templates.images.iter() {
            let desc = &template.descriptor;
            match template.data {
                CachedImageData::Raw(ref arc) => {
                    let image_id = image_paths.len() + 1;
                    let entry = match image_paths.entry(arc.as_ptr()) {
                        Entry::Occupied(_) => continue,
                        Entry::Vacant(e) => e,
                    };

                    #[cfg(feature = "png")]
                    CaptureConfig::save_png(
                        root.join(format!("images/{}.png", image_id)),
                        desc.size,
                        desc.format,
                        desc.stride,
                        &arc,
                    );
                    let file_name = format!("{}.raw", image_id);
                    let short_path = format!("images/{}", file_name);
                    fs::File::create(path_images.join(file_name))
                        .expect(&format!("Unable to create {}", short_path))
                        .write_all(&*arc)
                        .unwrap();
                    entry.insert(short_path);
                }
                CachedImageData::Blob => {
                    let blob_request_params = &[
                        BlobImageParams {
                            request: BlobImageRequest {
                                key: BlobImageKey(key),
                                //TODO: support tiled blob images
                                // https://github.com/servo/webrender/issues/2236
                                tile: template.tiling.map(|_| TileOffset::origin()),
                            },
                            descriptor: BlobImageDescriptor {
                                rect: blob_size(desc.size).into(),
                                format: desc.format,
                            },
                            dirty_rect: DirtyRect::All,
                        }
                    ];

                    let requires_tiling = match template.tiling {
                        Some(tile_size) => desc.size.width > tile_size as i32 || desc.size.height > tile_size as i32,
                        None => false,
                    };

                    let result = if requires_tiling {
                        warn!("Tiled blob images aren't supported yet");
                        RasterizedBlobImage {
                            rasterized_rect: desc.size.into(),
                            data: Arc::new(vec![0; desc.compute_total_size() as usize])
                        }
                    } else {
                        let blob_handler = self.blob_image_handler.as_mut().unwrap();
                        blob_handler.prepare_resources(&self.resources, blob_request_params);
                        let mut rasterizer = blob_handler.create_blob_rasterizer();
                        let (_, result) = rasterizer.rasterize(blob_request_params, false).pop().unwrap();
                        result.expect("Blob rasterization failed")
                    };

                    assert_eq!(result.rasterized_rect.size, desc.size);
                    assert_eq!(result.data.len(), desc.compute_total_size() as usize);

                    num_blobs += 1;
                    #[cfg(feature = "png")]
                    CaptureConfig::save_png(
                        root.join(format!("blobs/{}.png", num_blobs)),
                        desc.size,
                        desc.format,
                        desc.stride,
                        &result.data,
                    );
                    let file_name = format!("{}.raw", num_blobs);
                    let short_path = format!("blobs/{}", file_name);
                    let full_path = path_blobs.clone().join(&file_name);
                    fs::File::create(full_path)
                        .expect(&format!("Unable to create {}", short_path))
                        .write_all(&result.data)
                        .unwrap();
                    other_paths.insert(key, short_path);
                }
                CachedImageData::External(ref ext) => {
                    let short_path = format!("externals/{}", external_images.len() + 1);
                    other_paths.insert(key, short_path.clone());
                    external_images.push(ExternalCaptureImage {
                        short_path,
                        descriptor: desc.clone(),
                        external: ext.clone(),
                    });
                }
            }
        }

        let resources = PlainResources {
            font_templates: res.font_templates
                .iter()
                .map(|(key, template)| {
                    (*key, match *template {
                        FontTemplate::Raw(ref arc, index) => {
                            PlainFontTemplate {
                                data: font_paths[&arc.as_ptr()].clone(),
                                index,
                            }
                        }
                        #[cfg(not(target_os = "macos"))]
                        FontTemplate::Native(ref native) => {
                            PlainFontTemplate {
                                data: native.path.to_string_lossy().to_string(),
                                index: native.index,
                            }
                        }
                        #[cfg(target_os = "macos")]
                        FontTemplate::Native(ref native) => {
                            PlainFontTemplate {
                                data: native.0.postscript_name().to_string(),
                                index: 0,
                            }
                        }
                    })
                })
                .collect(),
            font_instances: res.font_instances.read().unwrap().clone(),
            image_templates: res.image_templates.images
                .iter()
                .map(|(key, template)| {
                    (*key, PlainImageTemplate {
                        data: match template.data {
                            CachedImageData::Raw(ref arc) => image_paths[&arc.as_ptr()].clone(),
                            _ => other_paths[key].clone(),
                        },
                        descriptor: template.descriptor.clone(),
                        tiling: template.tiling,
                        generation: template.generation,
                    })
                })
                .collect(),
        };

        (resources, external_images)
    }

    #[cfg(feature = "capture")]
    pub fn save_caches(&self, _root: &PathBuf) -> PlainCacheRef {
        PlainCacheRef {
            current_frame_id: self.current_frame_id,
            glyphs: &self.cached_glyphs,
            glyph_dimensions: &self.cached_glyph_dimensions,
            images: &self.cached_images,
            render_tasks: &self.cached_render_tasks,
            textures: &self.texture_cache,
        }
    }

    #[cfg(feature = "replay")]
    pub fn load_capture(
        &mut self,
        resources: PlainResources,
        caches: Option<PlainCacheOwn>,
        root: &PathBuf,
    ) -> Vec<PlainExternalImage> {
        use std::{fs, path::Path};

        info!("loading resource cache");
        //TODO: instead of filling the local path to Arc<data> map as we process
        // each of the resource types, we could go through all of the local paths
        // and fill out the map as the first step.
        let mut raw_map = FastHashMap::<String, Arc<Vec<u8>>>::default();

        self.clear(ClearCache::all());
        self.clear_images(|_| true);

        match caches {
            Some(cached) => {
                self.current_frame_id = cached.current_frame_id;
                self.cached_glyphs = cached.glyphs;
                self.cached_glyph_dimensions = cached.glyph_dimensions;
                self.cached_images = cached.images;
                self.cached_render_tasks = cached.render_tasks;
                self.texture_cache = cached.textures;
            }
            None => {
                self.current_frame_id = FrameId::INVALID;
                self.texture_cache = TextureCache::new(
                    self.texture_cache.max_texture_size(),
                    self.texture_cache.max_texture_layers(),
                    &self.texture_cache.picture_tile_sizes(),
                    DeviceIntSize::zero(),
                    self.texture_cache.color_formats(),
                    self.texture_cache.swizzle_settings(),
                );
            }
        }

        self.glyph_rasterizer.reset();
        let res = &mut self.resources;
        res.font_templates.clear();
        *res.font_instances.write().unwrap() = resources.font_instances;
        res.image_templates.images.clear();

        info!("\tfont templates...");
        let native_font_replacement = Arc::new(NATIVE_FONT.to_vec());
        for (key, plain_template) in resources.font_templates {
            let arc = match raw_map.entry(plain_template.data) {
                Entry::Occupied(e) => {
                    e.get().clone()
                }
                Entry::Vacant(e) => {
                    let file_path = if Path::new(e.key()).is_absolute() {
                        PathBuf::from(e.key())
                    } else {
                        root.join(e.key())
                    };
                    let arc = match fs::read(file_path) {
                        Ok(buffer) => Arc::new(buffer),
                        Err(err) => {
                            error!("Unable to open font template {:?}: {:?}", e.key(), err);
                            Arc::clone(&native_font_replacement)
                        }
                    };
                    e.insert(arc).clone()
                }
            };

            let template = FontTemplate::Raw(arc, plain_template.index);
            self.glyph_rasterizer.add_font(key, template.clone());
            res.font_templates.insert(key, template);
        }

        info!("\timage templates...");
        let mut external_images = Vec::new();
        for (key, template) in resources.image_templates {
            let data = match CaptureConfig::deserialize::<PlainExternalImage, _>(root, &template.data) {
                Some(plain) => {
                    let ext_data = plain.external;
                    external_images.push(plain);
                    CachedImageData::External(ext_data)
                }
                None => {
                    let arc = match raw_map.entry(template.data) {
                        Entry::Occupied(e) => {
                            e.get().clone()
                        }
                        Entry::Vacant(e) => {
                            let buffer = fs::read(root.join(e.key()))
                                .expect(&format!("Unable to open {}", e.key()));
                            e.insert(Arc::new(buffer))
                                .clone()
                        }
                    };
                    CachedImageData::Raw(arc)
                }
            };

            res.image_templates.images.insert(key, ImageResource {
                data,
                descriptor: template.descriptor,
                tiling: template.tiling,
                visible_rect: template.descriptor.size.into(),
                generation: template.generation,
            });
        }

        external_images
    }
}

/// For now the blob's coordinate space have the same pixel sizes as the
/// rendered texture's device space (only a translation is applied).
/// So going from one to the other is only a matter of casting away the unit
/// for sizes.
#[inline]
fn blob_size(device_size: DeviceIntSize) -> LayoutIntSize {
    size2(device_size.width, device_size.height)
}

#[inline]
fn blob_rect(device_rect: DeviceIntRect) -> LayoutIntRect {
    LayoutIntRect {
        origin: point2(device_rect.origin.x, device_rect.origin.y),
        size: blob_size(device_rect.size),
    }
}