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

Header

Untracked file

Line Code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* ***** BEGIN LICENSE BLOCK *****
 * Version: NPL 1.1/GPL 2.0/LGPL 2.1
 *
 * The contents of this file are subject to the Netscape Public License
 * Version 1.1 (the "License"); you may not use this file except in
 * compliance with the License. You may obtain a copy of the License at
 * http://www.mozilla.org/NPL/
 *
 * Software distributed under the License is distributed on an "AS IS" basis,
 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
 * for the specific language governing rights and limitations under the
 * License.
 *
 * The Original Code is mozilla.org code.
 *
 * The Initial Developer of the Original Code is 
 * Netscape Communications Corporation.
 * Portions created by the Initial Developer are Copyright (C) 1998
 * the Initial Developer. All Rights Reserved.
 *
 * Contributor(s):
 *   Patrick C. Beard <beard@netscape.com>
 *   Kevin McCluskey  <kmcclusk@netscape.com>
 *   Robert O'Callahan <roc+@cs.cmu.edu>
 *   Roland Mainz <roland.mainz@informatik.med.uni-giessen.de>
 *
 * Alternatively, the contents of this file may be used under the terms of
 * either the GNU General Public License Version 2 or later (the "GPL"), or 
 * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
 * in which case the provisions of the GPL or the LGPL are applicable instead
 * of those above. If you wish to allow use of your version of this file only
 * under the terms of either the GPL or the LGPL, and not to allow others to
 * use your version of this file under the terms of the NPL, indicate your
 * decision by deleting the provisions above and replace them with the notice
 * and other provisions required by the GPL or the LGPL. If you do not delete
 * the provisions above, a recipient may use your version of this file under
 * the terms of any one of the NPL, the GPL or the LGPL.
 *
 * ***** END LICENSE BLOCK ***** */

#include "nsViewManager.h"
#include "nsUnitConversion.h"
#include "nsIRenderingContext.h"
#include "nsIDeviceContext.h"
#include "nsGfxCIID.h"
#include "nsIScrollableView.h"
#include "nsView.h"
#include "nsISupportsArray.h"
#include "nsICompositeListener.h"
#include "nsCOMPtr.h"
#include "nsIEventQueue.h"
#include "nsIEventQueueService.h"
#include "nsIServiceManager.h"
#include "nsGUIEvent.h"
#include "nsIPrefBranch.h"
#include "nsIPrefService.h"
#include "nsRegion.h"
#include "nsInt64.h"
#include "nsScrollPortView.h"

static NS_DEFINE_IID(kBlenderCID, NS_BLENDER_CID);
static NS_DEFINE_IID(kRegionCID, NS_REGION_CID);
static NS_DEFINE_IID(kRenderingContextCID, NS_RENDERING_CONTEXT_CID);
static NS_DEFINE_CID(kEventQueueServiceCID, NS_EVENTQUEUESERVICE_CID);

/**
   XXX TODO XXX

   DeCOMify newly private methods
   Optimize view storage
*/

/**
   A note about platform assumptions:

   We assume all native widgets are opaque.
   
   We assume that a widget is z-ordered on top of its parent.
   
   We do NOT assume anything about the relative z-ordering of sibling widgets. Even though
   we ask for a specific z-order, we don't assume that widget z-ordering actually works.
*/

// if defined widget changes like moves and resizes are defered until and done
// all in one pass.
//#define CACHE_WIDGET_CHANGES

// display list flags
#define VIEW_RENDERED     0x00000001
#define PUSH_CLIP         0x00000002
#define POP_CLIP          0x00000004
#define VIEW_TRANSPARENT  0x00000008
#define VIEW_TRANSLUCENT  0x00000010
#define VIEW_CLIPPED      0x00000020
// used only by CanScrollWithBitBlt
#define VIEW_ISSCROLLED   0x00000040
#define PUSH_FILTER       0x00000080
#define POP_FILTER        0x00000100

#define NSCOORD_NONE      PR_INT32_MIN

#define SUPPORT_TRANSLUCENT_VIEWS

/*
  This class represents an offscreen buffer which may have an alpha channel.
  Currently, if an alpha channel is required, we implement it by rendering into
  two buffers: one with a black background, one with a white background. We can
  recover the alpha values by comparing corresponding final values for each pixel.
*/
class BlendingBuffers {
public:
  BlendingBuffers(nsIRenderingContext* aCleanupContext);
  ~BlendingBuffers();

  // used by the destructor to cleanup resources
  nsCOMPtr<nsIRenderingContext> mCleanupContext;
  // The primary rendering context. When an alpha channel is in use, this
  // holds the black background.
  nsCOMPtr<nsIRenderingContext> mBlackCX;
  // Only used when an alpha channel is required; holds the white background.
  nsCOMPtr<nsIRenderingContext> mWhiteCX;

  PRBool mOwnBlackSurface;
  // drawing surface for mBlackCX
  nsDrawingSurface  mBlack;
  // drawing surface for mWhiteCX
  nsDrawingSurface  mWhite;

  // The offset within the current widget at which this buffer will
  // eventually be composited
  nsPoint mOffset;
};

// A DisplayListElement2 records the information needed to paint one view.
// Note that child views get their own DisplayListElement2s; painting a view
// paints that view's frame and all its child frames EXCEPT for the child frames
// that have their own views.
struct DisplayListElement2 {
  nsView*       mView;        
  nsRect        mBounds;      // coordinates relative to the view manager root
  nscoord       mAbsX, mAbsY; // coordinates relative to the view that we're Refreshing 
  PRUint32      mFlags;       // see above
  nsInt64       mZIndex;      // temporary used during z-index processing (see below)
};

/*
  IMPLEMENTING Z-INDEX

  Implementing z-index:auto and negative z-indices properly is hard. Here's how we do it.

  In CreateDisplayList, the display list elements above are inserted into a tree rather
  than a simple list. The tree structure mimics the view hierarchy (except for fixed-position
  stuff, see below for more about that), except that in the tree, only leaf nodes can do
  actual painting (i.e., correspond to display list elements). Therefore every leaf view
  (i.e., no child views) has one corresponding leaf tree node containing its
  DisplayListElement2. OTOH, every non-leaf view corresponds to an interior tree node
  which contains the tree nodes for the child views, and which also contains a leaf tree
  node which does the painting for the non-leaf view. Initially sibling tree nodes are
  ordered in the same order as their views, which Layout should have arranged in document
  order.

  For example, given the view hierarchy and z-indices, and assuming lower-
  numbered views precede higher-numbered views in the document order,
    V0(auto) --> V1(0) --> V2(auto) --> V3(0)
     |            |         +---------> V4(2)
     |            +------> V5(1)
     +---------> V6(1)
  CreateDisplayList would create the following z-tree (z-order increases from top to bottom)
    Ta(V0) --> Tb*(V0)
     +-------> Tc(V1) --> Td*(V1)
     |          +-------> Te(V2) --> Tf*(V2)
     |          |          +-------> Tg*(V3)
     |          |          +-------> Th*(V4)
     |          +-------> Ti*(V5)
     +-------> Tj*(V6)
  (* indicates leaf nodes marked with display list elements)

  Once the Z-tree has been built we call SortByZOrder to compute a real linear display list.
  It recursively computes a display list for each tree node, by computing the display lists
  for all child nodes, then concatenating those lists and sorting them by z-index. The trick
  is that the z-indices for display list elements are updated during the process; after
  a display list is calculated for a tree node, the elements of the display list are all
  assigned the z-index specified for the tree node's view (unless the view has z-index
  'auto'). This ensures that a tree node's display list elements will be sorted correctly
  relative to the siblings of the tree node.

  The above example is processed as follows:
  The child nodes of Te(V2) are display list elements [ Tf*(V2)(0), Tg*(V3)(0), Th*(V4)(2) ].
  (The display list element for the frames of a non-leaf view always has z-index 0 relative
  to the children of the view.)
  Te(V2) is 'auto' so its display list is [ Tf*(V2)(0), Tg*(V3)(0), Th*(V4)(2) ].
  Tc(V1)'s child display list elements are [ Td*(V1)(0), Tf*(V2)(0), Tg*(V3)(0), Th*(V4)(2),
  Ti*(V5)(1) ].
  The nodes are sorted and then reassigned z-index 0, so Tc(V1) is replaced with the list
  [ Td*(V1)(0), Tf*(V2)(0), Tg*(V3)(0), Ti*(V5)(0), Th*(V4)(0) ].
  Finally we collect the elements for Ta(V0):
  [ Tb*(V0), Td*(V1)(0), Tf*(V2)(0), Tg*(V3)(0), Ti*(V5)(0), Th*(V4)(0), Tj*(V6)(1) ].
*/

struct DisplayZTreeNode {
  nsView*              mView;            // Null for tree leaf nodes
  DisplayZTreeNode*    mZSibling;

  // We can't have BOTH an mZChild and an mDisplayElement
  DisplayZTreeNode*    mZChild;          // tree interior nodes
  DisplayListElement2* mDisplayElement;  // tree leaf nodes
};

void nsViewManager::DestroyZTreeNode(DisplayZTreeNode* aNode) 
{
  if (aNode) {
    if (mMapPlaceholderViewToZTreeNode.Count() > 0) {
       nsVoidKey key(aNode->mView);
       mMapPlaceholderViewToZTreeNode.Remove(&key);
    }
  
    DestroyZTreeNode(aNode->mZChild);
    DestroyZTreeNode(aNode->mZSibling);
    delete aNode->mDisplayElement;
    delete aNode;
  }
}

#ifdef DEBUG
static PRInt32 PrintDisplayListElement(DisplayListElement2* element,
                                       PRInt32 aNestCount) {
    nsView*              view = element->mView;
    nsRect               rect = element->mBounds;
    PRUint32             flags = element->mFlags;
    PRUint32             viewFlags = view ? view->GetViewFlags() : 0;
    nsRect               dim;
    if (view) {
      view->GetDimensions(dim);
    }
    nsPoint              v = view ? view->GetPosition() : nsPoint(0, 0);
    nsView* parent = view ? view->GetParent() : nsnull;
    PRInt32 zindex = view ? view->GetZIndex() : 0;
    nsView* zParent = view ? view->GetZParent() : nsnull;
    nsViewManager* viewMan = view ? view->GetViewManager() : nsnull;

    printf("%*snsIView@%p{%d,%d,%d,%d @ %d,%d; p=%p,m=%p z=%d,zp=%p} [x=%d, y=%d, w=%d, h=%d, absX=%d, absY=%d]\n",
           aNestCount*2, "", (void*)view,
           dim.x, dim.y, dim.width, dim.height,
           v.x, v.y,
           (void*)parent, (void*)viewMan, zindex, (void*)zParent,
           rect.x, rect.y, rect.width, rect.height,
           element->mAbsX, element->mAbsY);

    PRInt32 newnestcnt = aNestCount;

    if (flags)
      {
        printf("%*s", aNestCount*2, "");

        if (flags & POP_CLIP) {
          printf("POP_CLIP ");
          newnestcnt--;
        }

        if (flags & PUSH_CLIP) {
          printf("PUSH_CLIP ");
          newnestcnt++;
        }

        if (flags & POP_FILTER) {
          printf("POP_FILTER ");
          newnestcnt--;
        }

        if (flags & PUSH_FILTER) {
          printf("PUSH_FILTER ");
          newnestcnt++;
        }

        if (flags & VIEW_RENDERED) 
          printf("VIEW_RENDERED ");

        if (flags & VIEW_ISSCROLLED)
          printf("VIEW_ISSCROLLED ");

        if (flags & VIEW_CLIPPED)
          printf("VIEW_ISCLIPPED ");

        if (flags & VIEW_TRANSLUCENT)
          printf("VIEW_ISTRANSLUCENT ");

        if (flags & VIEW_TRANSPARENT)
          printf("VIEW_ISTRANSPARENT ");

        if (viewFlags & NS_VIEW_FLAG_DONT_BITBLT)
          printf("NS_VIEW_FLAG_DONT_BITBLT ");

        printf("\n");
      }
    return newnestcnt;
}

static void PrintZTreeNode(DisplayZTreeNode* aNode, PRInt32 aIndent) 
{
  if (aNode) {
    printf("%*sDisplayZTreeNode@%p\n", aIndent*2, "", (void*)aNode);
    if (aNode->mDisplayElement) {
      PrintDisplayListElement(aNode->mDisplayElement, 0);
    }

    aIndent += 2;

    for (DisplayZTreeNode* child = aNode->mZChild; child;
         child = child->mZSibling) {
      PrintZTreeNode(child, aIndent);
    }
  }
}
#endif

#ifdef NS_VM_PERF_METRICS
#include "nsITimeRecorder.h"
#endif

//-------------- Begin Invalidate Event Definition ------------------------

struct nsInvalidateEvent : public PLEvent {
  nsInvalidateEvent(nsViewManager* aViewManager);
  ~nsInvalidateEvent() { }

  void HandleEvent() {  
    NS_ASSERTION(nsnull != mViewManager,"ViewManager is null");
    // Search for valid view manager before trying to access it
    // This is just a safety check. We should never have a circumstance
    // where the view manager has been destroyed and the invalidate event
    // which it owns is still around. The invalidate event should be destroyed
    // by the RevokeEvent in the viewmanager's destructor.
    PRBool found = PR_FALSE;
    PRInt32 index;
    PRInt32 count = nsViewManager::GetViewManagerCount();
    const nsVoidArray* viewManagers = nsViewManager::GetViewManagerArray();
    for (index = 0; index < count; index++) {
      nsViewManager* vm = (nsViewManager*)viewManagers->ElementAt(index);
      if (vm == mViewManager) {
        found = PR_TRUE;
      }
    }

    if (found) {
      mViewManager->ProcessInvalidateEvent();
    } else {
      NS_ASSERTION(PR_FALSE, "bad view manager asked to process invalidate event");
    }
  };
 
  nsViewManager* mViewManager; // Weak Reference. The viewmanager will destroy any pending
  // invalidate events in it's destructor.
};

static void* PR_CALLBACK HandlePLEvent(PLEvent* aEvent)
{
  NS_ASSERTION(nsnull != aEvent,"Event is null");
  nsInvalidateEvent *event = NS_STATIC_CAST(nsInvalidateEvent*, aEvent);
  event->HandleEvent();
  return nsnull;
}

static void PR_CALLBACK DestroyPLEvent(PLEvent* aEvent)
{
  NS_ASSERTION(nsnull != aEvent,"Event is null");
  nsInvalidateEvent *event = NS_STATIC_CAST(nsInvalidateEvent*, aEvent);
  delete event;
}

nsInvalidateEvent::nsInvalidateEvent(nsViewManager* aViewManager)
{
  NS_ASSERTION(aViewManager, "null parameter");  
  mViewManager = aViewManager; // Assign weak reference
  PL_InitEvent(this, aViewManager, ::HandlePLEvent, ::DestroyPLEvent);  
}

//-------------- End Invalidate Event Definition ---------------------------

// Compare two Z-index values taking into account topmost and 
// auto flags. the topmost flag is only used when both views are
// zindex:auto.  (XXXldb Lying!)
// 
// returns 0 if equal
//         > 0 if first z-index is greater than the second
//         < 0 if first z-index is less than the second

static PRInt32 CompareZIndex(PRInt32 aZIndex1, PRBool aTopMost1, PRBool aIsAuto1,
                             PRInt32 aZIndex2, PRBool aTopMost2, PRBool aIsAuto2) 
{
  NS_ASSERTION(!aIsAuto1 || aZIndex1 == 0,"auto is set and the z-index is not 0");
  NS_ASSERTION(!aIsAuto2 || aZIndex2 == 0,"auto is set and the z-index is not 0");

  if (aZIndex1 != aZIndex2) {
    return aZIndex1 - aZIndex2;
  } else {
    return aTopMost1 - aTopMost2;
  }
}

static PRBool IsViewVisible(nsView *aView)
{
  for (nsIView *view = aView; view; view = view->GetParent()) {
    // We don't check widget visibility here because in the future (with
    // the better approach to this that's in attachment 160801 on bug
    // 227361), callers of the equivalent to this function should be able
    // to rely on being notified when the result of this function changes.
    if (view->GetVisibility() == nsViewVisibility_kHide)
      return PR_FALSE;
  }
  // Find out if the root view is visible by asking the view observer
  // (this won't be needed anymore if we link view trees across chrome /
  // content boundaries in DocumentViewerImpl::MakeWindow).
  nsCOMPtr<nsIViewObserver> vo;
  aView->GetViewManager()->GetViewObserver(*getter_AddRefs(vo));
  return vo && vo->IsVisible();
}

void
nsViewManager::PostInvalidateEvent()
{
  nsCOMPtr<nsIEventQueue> eventQueue;
  mEventQueueService->GetSpecialEventQueue(
    nsIEventQueueService::UI_THREAD_EVENT_QUEUE, getter_AddRefs(eventQueue));
  NS_ASSERTION(nsnull != eventQueue, "Event queue is null");

  if (eventQueue != mInvalidateEventQueue) {
    nsInvalidateEvent* ev = new nsInvalidateEvent(this);
    eventQueue->PostEvent(ev);
    mInvalidateEventQueue = eventQueue;
  }
}

PRInt32 nsViewManager::mVMCount = 0;
nsIRenderingContext* nsViewManager::gCleanupContext = nsnull;

// Weakly held references to all of the view managers
nsVoidArray* nsViewManager::gViewManagers = nsnull;
PRUint32 nsViewManager::gLastUserEventTime = 0;

nsViewManager::nsViewManager()
  : mDelayedResize(NSCOORD_NONE, NSCOORD_NONE)
{
  if (gViewManagers == nsnull) {
    NS_ASSERTION(mVMCount == 0, "View Manager count is incorrect");
    // Create an array to hold a list of view managers
    gViewManagers = new nsVoidArray;
  }
 
  if (gCleanupContext == nsnull) {
    /* XXX: This should use a device to create a matching |nsIRenderingContext| object */
    CallCreateInstance(kRenderingContextCID, &gCleanupContext);
    NS_ASSERTION(gCleanupContext,
                 "Wasn't able to create a graphics context for cleanup");
  }

  gViewManagers->AppendElement(this);

  mVMCount++;
  // NOTE:  we use a zeroing operator new, so all data members are
  // assumed to be cleared here.
  mX = 0;
  mY = 0;
  mCachingWidgetChanges = 0;
  mDefaultBackgroundColor = NS_RGBA(0, 0, 0, 0);
  mAllowDoubleBuffering = PR_TRUE; 
  mHasPendingInvalidates = PR_FALSE;
  mRecursiveRefreshPending = PR_FALSE;
}

nsViewManager::~nsViewManager()
{
  if (mRootView) {
    // Destroy any remaining views
    mRootView->Destroy();
    mRootView = nsnull;
  }

  nsCOMPtr<nsIEventQueue> eventQueue;
  mEventQueueService->GetSpecialEventQueue(nsIEventQueueService::UI_THREAD_EVENT_QUEUE,
                                           getter_AddRefs(eventQueue));
  NS_ASSERTION(nsnull != eventQueue, "Event queue is null"); 
  eventQueue->RevokeEvents(this);
  mInvalidateEventQueue = nsnull;  

  NS_IF_RELEASE(mRootWindow);

  mRootScrollable = nsnull;

  NS_ASSERTION((mVMCount > 0), "underflow of viewmanagers");
  --mVMCount;

#ifdef DEBUG
  PRBool removed =
#endif
    gViewManagers->RemoveElement(this);
  NS_ASSERTION(removed, "Viewmanager instance not was not in the global list of viewmanagers");

  if (0 == mVMCount) {
    // There aren't any more view managers so
    // release the global array of view managers
   
    NS_ASSERTION(gViewManagers != nsnull, "About to delete null gViewManagers");
    delete gViewManagers;
    gViewManagers = nsnull;

    // Cleanup all of the offscreen drawing surfaces if the last view manager
    // has been destroyed and there is something to cleanup

    // Note: A global rendering context is needed because it is not possible 
    // to create a nsIRenderingContext during the shutdown of XPCOM. The last
    // viewmanager is typically destroyed during XPCOM shutdown.

    if (gCleanupContext) {

      gCleanupContext->DestroyCachedBackbuffer();
    } else {
      NS_ASSERTION(PR_FALSE, "Cleanup of drawing surfaces + offscreen buffer failed");
    }

    NS_IF_RELEASE(gCleanupContext);
  }

  mObserver = nsnull;
  mContext = nsnull;

  if (nsnull != mCompositeListeners) {
    mCompositeListeners->Clear();
    NS_RELEASE(mCompositeListeners);
  }
}

NS_IMPL_ISUPPORTS1(nsViewManager, nsIViewManager)

nsresult
nsViewManager::CreateRegion(nsIRegion* *result)
{
  nsresult rv;

  if (!mRegionFactory) {
    nsCOMPtr<nsIComponentManager> compMgr;
    rv = NS_GetComponentManager(getter_AddRefs(compMgr));

    if (NS_SUCCEEDED(rv))
      rv = compMgr->GetClassObject(kRegionCID,
                                   NS_GET_IID(nsIFactory),
                                   getter_AddRefs(mRegionFactory));

    if (!mRegionFactory) {
      *result = nsnull;
      return NS_ERROR_FAILURE;
    }
  }

  nsIRegion* region = nsnull;
  rv = mRegionFactory->CreateInstance(nsnull, NS_GET_IID(nsIRegion), (void**)&region);
  if (NS_SUCCEEDED(rv)) {
    rv = region->Init();
    *result = region;
  }
  return rv;
}

// We don't hold a reference to the presentation context because it
// holds a reference to us.
NS_IMETHODIMP nsViewManager::Init(nsIDeviceContext* aContext)
{
  NS_PRECONDITION(nsnull != aContext, "null ptr");

  if (nsnull == aContext) {
    return NS_ERROR_NULL_POINTER;
  }
  if (nsnull != mContext) {
    return NS_ERROR_ALREADY_INITIALIZED;
  }
  mContext = aContext;
  mTwipsToPixels = mContext->AppUnitsToDevUnits();
  mPixelsToTwips = mContext->DevUnitsToAppUnits();

  mRefreshEnabled = PR_TRUE;

  mMouseGrabber = nsnull;
  mKeyGrabber = nsnull;

  if (nsnull == mEventQueueService) {
    mEventQueueService = do_GetService(kEventQueueServiceCID);
    NS_ASSERTION(mEventQueueService, "couldn't get event queue service");
  }
  
  return NS_OK;
}

NS_IMETHODIMP nsViewManager::GetRootView(nsIView *&aView)
{
  aView = mRootView;
  return NS_OK;
}

NS_IMETHODIMP nsViewManager::SetRootView(nsIView *aView, nsIWidget* aWidget)
{
  nsView* view = NS_STATIC_CAST(nsView*, aView);

  // Do NOT destroy the current root view. It's the caller's responsibility
  // to destroy it
  mRootView = view;

  //now get the window too.
  NS_IF_RELEASE(mRootWindow);

  // The window must be specified through one of the following:
  //* a) The aView has a nsIWidget instance or
  //* b) the aWidget parameter is an nsIWidget instance to render into 
  //*    that is not owned by a view.
  //* c) aView has a parent view managed by a different view manager or

  if (nsnull != aWidget) {
    mRootWindow = aWidget;
    NS_ADDREF(mRootWindow);
    return NS_OK;
  }

  // case b) The aView has a nsIWidget instance
  if (nsnull != mRootView) {
    nsView* parent = mRootView->GetParent();
    if (parent) {
      parent->InsertChild(mRootView, nsnull);
    }

    mRootView->SetZIndex(PR_FALSE, 0, PR_FALSE);

    mRootWindow = mRootView->GetWidget();
    if (mRootWindow) {
      NS_ADDREF(mRootWindow);
      return NS_OK;
    }
  }

  // case c)  aView has a parent view managed by a different view manager

  return NS_OK;
}

NS_IMETHODIMP nsViewManager::GetWindowOffset(nscoord *aX, nscoord *aY)
{
  NS_ASSERTION(aX != nsnull, "aX pointer is null");
  NS_ASSERTION(aY != nsnull, "aY pointer is null");

  *aX = mX;
  *aY = mY;
  return NS_OK;
}

NS_IMETHODIMP nsViewManager::SetWindowOffset(nscoord aX, nscoord aY)
{
  mX = aX;
  mY = aY;
  return NS_OK;
}

NS_IMETHODIMP nsViewManager::GetWindowDimensions(nscoord *aWidth, nscoord *aHeight)
{
  if (nsnull != mRootView) {
    if (mDelayedResize == nsSize(NSCOORD_NONE, NSCOORD_NONE)) {
      nsRect dim;
      mRootView->GetDimensions(dim);
      *aWidth = dim.width;
      *aHeight = dim.height;
    } else {
      *aWidth = mDelayedResize.width;
      *aHeight = mDelayedResize.height;
    }
  }
  else
    {
      *aWidth = 0;
      *aHeight = 0;
    }
  return NS_OK;
}

NS_IMETHODIMP nsViewManager::SetWindowDimensions(nscoord aWidth, nscoord aHeight)
{
  if (mRootView) {
    if (IsViewVisible(mRootView)) {
      mDelayedResize.SizeTo(NSCOORD_NONE, NSCOORD_NONE);
      DoSetWindowDimensions(aWidth, aHeight);
    } else {
      mDelayedResize.SizeTo(aWidth, aHeight);
    }
  }

  return NS_OK;
}

NS_IMETHODIMP nsViewManager::ResetScrolling(void)
{
  if (nsnull != mRootScrollable)
    mRootScrollable->ComputeScrollOffsets(PR_TRUE);

  return NS_OK;
}

/* Check the prefs to see whether we should do double buffering or not... */
static
PRBool DoDoubleBuffering(void)
{
  static PRBool gotDoublebufferPrefs = PR_FALSE;
  static PRBool doDoublebuffering    = PR_TRUE;  /* Double-buffering is ON by default */
  
  if (!gotDoublebufferPrefs) {
    nsCOMPtr<nsIPrefBranch> prefBranch = do_GetService(NS_PREFSERVICE_CONTRACTID);
    if (prefBranch) {
      PRBool val;
      if (NS_SUCCEEDED(prefBranch->GetBoolPref("viewmanager.do_doublebuffering", &val))) {
        doDoublebuffering = val;
      }
    }

#ifdef DEBUG
    if (!doDoublebuffering) {
      printf("nsViewManager: Note: Double-buffering disabled via prefs.\n");
    }
#endif /* DEBUG */

    gotDoublebufferPrefs = PR_TRUE;
  }
  
  return doDoublebuffering;
}

static void ConvertNativeRegionToAppRegion(nsIRegion* aIn, nsRegion* aOut,
                                           nsIDeviceContext* context)
{
  nsRegionRectSet* rects = nsnull;
  aIn->GetRects(&rects);
  if (!rects)
    return;
  
  float  p2t;
  p2t = context->DevUnitsToAppUnits();

  PRUint32 i;
  for (i = 0; i < rects->mNumRects; i++) {
    const nsRegionRect& inR = rects->mRects[i];
    nsRect outR;
    outR.x = NSToIntRound(inR.x * p2t);
    outR.y = NSToIntRound(inR.y * p2t);
    outR.width = NSToIntRound(inR.width * p2t);
    outR.height = NSToIntRound(inR.height * p2t);
    aOut->Or(*aOut, outR);
  }

  aIn->FreeRects(rects);
}

/**
   aRegion is given in device coordinates!!
*/
void nsViewManager::Refresh(nsView *aView, nsIRenderingContext *aContext,
                            nsIRegion *aRegion, PRUint32 aUpdateFlags)
{
  NS_ASSERTION(aRegion != nsnull, "Null aRegion");

  if (PR_FALSE == mRefreshEnabled)
    return;

  nsRect viewRect;
  aView->GetDimensions(viewRect);

  // damageRegion is the damaged area, in twips, relative to the view origin
  nsRegion damageRegion;
  // convert pixels-relative-to-widget-origin to twips-relative-to-widget-origin
  ConvertNativeRegionToAppRegion(aRegion, &damageRegion, mContext);
  // move it from widget coordinates into view coordinates
  damageRegion.MoveBy(viewRect.x, viewRect.y);

  // Clip it to the view; shouldn't be necessary, but do it for sanity
  damageRegion.And(damageRegion, viewRect);
  if (damageRegion.IsEmpty()) {
#ifdef DEBUG_roc
    nsRect damageRect = damageRegion.GetBounds();
    printf("XXX Damage rectangle (%d,%d,%d,%d) does not intersect the widget's view (%d,%d,%d,%d)!\n",
           damageRect.x, damageRect.y, damageRect.width, damageRect.height,
           viewRect.x, viewRect.y, viewRect.width, viewRect.height);
#endif
    return;
  }

#ifdef NS_VM_PERF_METRICS
  MOZ_TIMER_DEBUGLOG(("Reset nsViewManager::Refresh(region), this=%p\n", this));
  MOZ_TIMER_RESET(mWatch);

  MOZ_TIMER_DEBUGLOG(("Start: nsViewManager::Refresh(region)\n"));
  MOZ_TIMER_START(mWatch);
#endif

  NS_ASSERTION(!mPainting, "recursive painting not permitted");
  if (mPainting) {
    mRecursiveRefreshPending = PR_TRUE;
    return;
  }  
  mPainting = PR_TRUE;

  // force double buffering in general
  aUpdateFlags |= NS_VMREFRESH_DOUBLE_BUFFER;

  if (!DoDoubleBuffering())
    aUpdateFlags &= ~NS_VMREFRESH_DOUBLE_BUFFER;

  // check if the rendering context wants double-buffering or not
  if (aContext) {
    PRBool contextWantsBackBuffer = PR_TRUE;
    aContext->UseBackbuffer(&contextWantsBackBuffer);
    if (!contextWantsBackBuffer)
      aUpdateFlags &= ~NS_VMREFRESH_DOUBLE_BUFFER;
  }
  
  if (PR_FALSE == mAllowDoubleBuffering) {
    // Turn off double-buffering of the display
    aUpdateFlags &= ~NS_VMREFRESH_DOUBLE_BUFFER;
  }

  nsCOMPtr<nsIRenderingContext> localcx;
  nsDrawingSurface    ds = nsnull;

  if (nsnull == aContext)
    {
      localcx = getter_AddRefs(CreateRenderingContext(*aView));

      //couldn't get rendering context. this is ok at init time atleast
      if (nsnull == localcx) {
        mPainting = PR_FALSE;
        return;
      }
    } else {
      // plain assignment grabs another reference.
      localcx = aContext;
    }

  // notify the listeners.
  if (nsnull != mCompositeListeners) {
    PRUint32 listenerCount;
    if (NS_SUCCEEDED(mCompositeListeners->Count(&listenerCount))) {
      nsCOMPtr<nsICompositeListener> listener;
      for (PRUint32 i = 0; i < listenerCount; i++) {
        if (NS_SUCCEEDED(mCompositeListeners->QueryElementAt(i, NS_GET_IID(nsICompositeListener), getter_AddRefs(listener)))) {
          listener->WillRefreshRegion(this, aView, aContext, aRegion, aUpdateFlags);
        }
      }
    }
  }

  // damageRect is the clipped damage area bounds, in twips-relative-to-view-origin
  nsRect damageRect = damageRegion.GetBounds();
  // widgetDamageRectInPixels is the clipped damage area bounds,
  // in pixels-relative-to-widget-origin
  nsRect widgetDamageRectInPixels = damageRect;
  widgetDamageRectInPixels.MoveBy(-viewRect.x, -viewRect.y);
  float t2p;
  t2p = mContext->AppUnitsToDevUnits();
  widgetDamageRectInPixels.ScaleRoundOut(t2p);

  // On the Mac, we normally turn doublebuffering off because Quartz is
  // doublebuffering for us. But we need to turn it on anyway if we need
  // to use our blender, which requires access to the "current pixel values"
  // when it blends onto the canvas.
  nsAutoVoidArray displayList;
  PRBool anyTransparentPixels
    = BuildRenderingDisplayList(aView, damageRegion, &displayList);
  if (!(aUpdateFlags & NS_VMREFRESH_DOUBLE_BUFFER)) {
    for (PRInt32 i = 0; i < displayList.Count(); i++) {
      DisplayListElement2* element = NS_STATIC_CAST(DisplayListElement2*, displayList.ElementAt(i));
      if (element->mFlags & PUSH_FILTER) {
        aUpdateFlags |= NS_VMREFRESH_DOUBLE_BUFFER;
        break;
      }
    }
  } 

  if (aUpdateFlags & NS_VMREFRESH_DOUBLE_BUFFER)
  {
    nsRect maxWidgetSize;
    GetMaxWidgetBounds(maxWidgetSize);

    nsRect r(0, 0, widgetDamageRectInPixels.width, widgetDamageRectInPixels.height);
    if (NS_FAILED(localcx->GetBackbuffer(r, maxWidgetSize, ds))) {
      //Failed to get backbuffer so turn off double buffering
      aUpdateFlags &= ~NS_VMREFRESH_DOUBLE_BUFFER;
    }
  }

  // painting will be done in aView's coordinates
  PRBool usingDoubleBuffer = (aUpdateFlags & NS_VMREFRESH_DOUBLE_BUFFER) && ds;
  if (usingDoubleBuffer) {
    // Adjust translations because the backbuffer holds just the damaged area,
    // not the whole widget

    // RenderViews draws in view coordinates. We want (damageRect.x, damageRect.y)
    // to be translated to (0,0) in the backbuffer. So:
    localcx->Translate(-damageRect.x, -damageRect.y);
    // We're going to reset the clip region for the backbuffer. We can't
    // just use damageRegion because nsIRenderingContext::SetClipRegion doesn't
    // translate/scale the coordinates (grrrrrrrrrr)
    // So we have to translate the region before we use it. aRegion is in
    // pixels-relative-to-widget-origin, so:
    aRegion->Offset(-widgetDamageRectInPixels.x, -widgetDamageRectInPixels.y);
  } else {
    // RenderViews draws in view coordinates. We want (viewRect.x, viewRect.y)
    // to be translated to (0,0) in the widget. So:
    localcx->Translate(-viewRect.x, -viewRect.y);
  }

  // Note that nsIRenderingContext::SetClipRegion always works in pixel coordinates,
  // and nsIRenderingContext::SetClipRect always works in app coordinates. Stupid huh?
  // Also, SetClipRegion doesn't subject its argument to the current transform, but
  // SetClipRect does.
  PRBool isClipped;
  localcx->SetClipRegion(*aRegion, nsClipCombine_kReplace, isClipped);
  localcx->SetClipRect(damageRect, nsClipCombine_kIntersect, isClipped);

  if (anyTransparentPixels) {
    // There are some bits here that aren't going to be completely painted unless we do it now.
    // XXX Which color should we use for these bits?
    localcx->SetColor(NS_RGB(128, 128, 128));
    localcx->FillRect(damageRegion.GetBounds());
  }
  RenderViews(aView, *localcx, damageRegion, ds, displayList);

  if (usingDoubleBuffer) {
    // Flush bits back to the screen

    // Restore aRegion to pixels-relative-to-widget-origin
    aRegion->Offset(widgetDamageRectInPixels.x, widgetDamageRectInPixels.y);
    // Restore translation to its previous state (so that (0,0) is the widget origin)
    localcx->Translate(damageRect.x, damageRect.y);
    // Make damageRect twips-relative-to-widget-origin
    damageRect.MoveBy(-viewRect.x, -viewRect.y);
    // Reset clip region to widget-relative
    localcx->SetClipRegion(*aRegion, nsClipCombine_kReplace, isClipped);
    localcx->SetClipRect(damageRect, nsClipCombine_kIntersect, isClipped);
    // neither source nor destination are transformed
    localcx->CopyOffScreenBits(ds, 0, 0, widgetDamageRectInPixels, NS_COPYBITS_USE_SOURCE_CLIP_REGION);
  } else {
    // undo earlier translation
    localcx->Translate(viewRect.x, viewRect.y);
  }

  mPainting = PR_FALSE;

  // notify the listeners.
  if (nsnull != mCompositeListeners) {
    PRUint32 listenerCount;
    if (NS_SUCCEEDED(mCompositeListeners->Count(&listenerCount))) {
      nsCOMPtr<nsICompositeListener> listener;
      for (PRUint32 i = 0; i < listenerCount; i++) {
        if (NS_SUCCEEDED(mCompositeListeners->QueryElementAt(i, NS_GET_IID(nsICompositeListener), getter_AddRefs(listener)))) {
          listener->DidRefreshRegion(this, aView, aContext, aRegion, aUpdateFlags);
        }
      }
    }
  }

  if (mRecursiveRefreshPending) {
    UpdateAllViews(aUpdateFlags);
    mRecursiveRefreshPending = PR_FALSE;
  }

  localcx->ReleaseBackbuffer();

#ifdef NS_VM_PERF_METRICS
  MOZ_TIMER_DEBUGLOG(("Stop: nsViewManager::Refresh(region), this=%p\n", this));
  MOZ_TIMER_STOP(mWatch);
  MOZ_TIMER_LOG(("vm2 Paint time (this=%p): ", this));
  MOZ_TIMER_PRINT(mWatch);
#endif

}

void nsViewManager::DefaultRefresh(nsView* aView, const nsRect* aRect)
{
  nsCOMPtr<nsIWidget> widget;
  GetWidgetForView(aView, getter_AddRefs(widget));
  if (! widget)
    return;

  nsCOMPtr<nsIRenderingContext> context
    = getter_AddRefs(CreateRenderingContext(*aView));

  if (! context)
    return;

  nscolor bgcolor = mDefaultBackgroundColor;

  if (NS_GET_A(mDefaultBackgroundColor) == 0) {
    NS_WARNING("nsViewManager: Asked to paint a default background, but no default background color is set!");
    return;
  }

  context->SetColor(bgcolor);
  context->FillRect(*aRect);
}

// Perform a *stable* sort of the buffer by increasing Z-index. The common case is
// when many or all z-indices are equal and the list is mostly sorted; make sure
// that's fast (should be linear time if all z-indices are equal).
static void ApplyZOrderStableSort(nsVoidArray &aBuffer, nsVoidArray &aMergeTmp, PRInt32 aStart, PRInt32 aEnd) {
  if (aEnd - aStart <= 6) {
    // do a fast bubble sort for the small sizes
    for (PRInt32 i = aEnd - 1; i > aStart; i--) {
      PRBool sorted = PR_TRUE;
      for (PRInt32 j = aStart; j < i; j++) {
        DisplayListElement2* e1 = NS_STATIC_CAST(DisplayListElement2*, aBuffer.ElementAt(j));
        DisplayListElement2* e2 = NS_STATIC_CAST(DisplayListElement2*, aBuffer.ElementAt(j + 1));
        if (e1->mZIndex > e2->mZIndex) {
          sorted = PR_FALSE;
          // We could use aBuffer.MoveElement(), but it wouldn't be much of
          // a win if any for swapping two elements.
          aBuffer.ReplaceElementAt(e2, j);
          aBuffer.ReplaceElementAt(e1, j + 1);
        }
      }
      if (sorted) {
        return;
      }
    }
  } else {
    // merge sort for the rest
    PRInt32 mid = (aEnd + aStart)/2;

    ApplyZOrderStableSort(aBuffer, aMergeTmp, aStart, mid);
    ApplyZOrderStableSort(aBuffer, aMergeTmp, mid, aEnd);

    DisplayListElement2* e1 = NS_STATIC_CAST(DisplayListElement2*, aBuffer.ElementAt(mid - 1));
    DisplayListElement2* e2 = NS_STATIC_CAST(DisplayListElement2*, aBuffer.ElementAt(mid));

    // fast common case: the list is already completely sorted
    if (e1->mZIndex <= e2->mZIndex) {
      return;
    }
    // we have some merging to do.

    PRInt32 i1 = aStart;
    PRInt32 i2 = mid;

    e1 = NS_STATIC_CAST(DisplayListElement2*, aBuffer.ElementAt(i1));
    e2 = NS_STATIC_CAST(DisplayListElement2*, aBuffer.ElementAt(i2));
    while (i1 < mid || i2 < aEnd) {
      if (i1 < mid && (i2 == aEnd || e1->mZIndex <= e2->mZIndex)) {
        aMergeTmp.AppendElement(e1);
        i1++;
        if (i1 < mid) {
          e1 = NS_STATIC_CAST(DisplayListElement2*, aBuffer.ElementAt(i1));
        }
      } else {
        aMergeTmp.AppendElement(e2);
        i2++;
        if (i2 < aEnd) {
          e2 = NS_STATIC_CAST(DisplayListElement2*, aBuffer.ElementAt(i2));
        }
      }
    }

    for (PRInt32 i = aStart; i < aEnd; i++) {
      aBuffer.ReplaceElementAt(aMergeTmp.ElementAt(i - aStart), i);
    }

    aMergeTmp.Clear();
  }
}

static nsInt64 BuildExtendedZIndex(nsView* aView) {
  return (nsInt64(aView->GetZIndex()) << 1) | nsInt64(aView->IsTopMost() ? 1 : 0);
}

// The display-element (indirect) children of aNode are extracted and appended to aBuffer in
// z-order, with the bottom-most elements first.
// Their z-index is set to the z-index they will have in aNode's parent.
// I.e. if aNode's view has "z-index: auto", the nodes will keep their z-index, otherwise
// their z-indices will all be equal to the z-index value of aNode's view.
static void SortByZOrder(DisplayZTreeNode *aNode, nsVoidArray &aBuffer, nsVoidArray &aMergeTmp, PRBool aForceSort) {
  PRBool autoZIndex = PR_TRUE;
  nsInt64 explicitZIndex = 0;

  if (nsnull != aNode->mView) {
    // Hixie says only non-translucent elements can have z-index:auto
    autoZIndex = aNode->mView->GetZIndexIsAuto() && aNode->mView->GetOpacity() == 1.0f;
    explicitZIndex = BuildExtendedZIndex(aNode->mView);
  }

  if (nsnull == aNode->mZChild) {
    if (nsnull != aNode->mDisplayElement) {
      aBuffer.AppendElement(aNode->mDisplayElement);
      aNode->mDisplayElement->mZIndex = explicitZIndex;
      aNode->mDisplayElement = nsnull;
    }
    return;
  }

  DisplayZTreeNode *child;
  PRInt32 childStartIndex = aBuffer.Count();
  for (child = aNode->mZChild; nsnull != child; child = child->mZSibling) {
    SortByZOrder(child, aBuffer, aMergeTmp, PR_FALSE);
  }
  PRInt32 childEndIndex = aBuffer.Count();
  PRInt32 sortStartIndex = childStartIndex;
  PRInt32 sortEndIndex = childEndIndex;
  PRBool hasClip = PR_FALSE;
  DisplayListElement2* ePush = nsnull;
  DisplayListElement2* ePop = nsnull;

  // When we sort the children by z-index, don't sort any PUSH_ or POP_ instructions
  // which are bracketing the children.
  while (sortEndIndex - sortStartIndex >= 2) {
    DisplayListElement2* childElem =
      NS_STATIC_CAST(DisplayListElement2*, aBuffer.ElementAt(sortStartIndex));
    if (childElem->mView == aNode->mView) {
      if (childElem->mFlags & PUSH_CLIP) {
        hasClip = PR_TRUE;
        // remember where the push and pop instructions are so we can
        // duplicate them later, if necessary
        ePush = NS_STATIC_CAST(DisplayListElement2*, aBuffer.ElementAt(sortStartIndex));
        ePop = NS_STATIC_CAST(DisplayListElement2*, aBuffer.ElementAt(sortEndIndex - 1));
        sortStartIndex++;
        sortEndIndex--;
      } else if (childElem->mFlags & PUSH_FILTER) {
        NS_ASSERTION(!autoZIndex, "FILTER cannot apply to z-index:auto view");
        sortStartIndex++;
        sortEndIndex--;
      } else {
        break;
      }
    } else {
      break;
    }
  }

  if (hasClip) {
    ApplyZOrderStableSort(aBuffer, aMergeTmp, sortStartIndex, sortEndIndex);
    
    if (autoZIndex && sortEndIndex - sortStartIndex >= 1) {
      // If we're an auto-z-index, then we have to worry about the possibility that some of
      // our children may be moved by the z-sorter beyond the bounds of the PUSH...POP clip
      // instructions. So basically, we ensure that around every group of children of
      // equal z-index, there is a PUSH...POP element pair with the same z-index. The stable
      // z-sorter will not break up such a group.
      // Note that if we're not an auto-z-index set, then our children will never be broken
      // up so we don't need to do this.
      // We also don't have to worry if we have no real children.
      // We don't have to do the same thing for PUSH_FILTER/POP_FILTER because
      // a filter always corresponds to non-auto z-index; there is no way children
      // can be sorted beyond the PUSH/POP instructions.
      DisplayListElement2* eFirstChild = NS_STATIC_CAST(DisplayListElement2*, aBuffer.ElementAt(sortStartIndex));

      ePush->mZIndex = eFirstChild->mZIndex;

      DisplayListElement2* eLastChild = NS_STATIC_CAST(DisplayListElement2*, aBuffer.ElementAt(sortEndIndex - 1));

      ePop->mZIndex = eLastChild->mZIndex;

      DisplayListElement2* e = eFirstChild;
      for (PRInt32 i = sortStartIndex; i < sortEndIndex - 1; i++) {
        DisplayListElement2* eNext = NS_STATIC_CAST(DisplayListElement2*, aBuffer.ElementAt(i + 1));
        NS_ASSERTION(e->mZIndex <= eNext->mZIndex, "Display Z-list is not sorted!!");
        if (e->mZIndex != eNext->mZIndex) {
          // need to insert a POP for the last sequence and a PUSH for the next sequence
          DisplayListElement2* newPop = new DisplayListElement2;
          DisplayListElement2* newPush = new DisplayListElement2;

          *newPop = *ePop;
          newPop->mZIndex = e->mZIndex;
          *newPush = *ePush;
          newPush->mZIndex = eNext->mZIndex;
          aBuffer.InsertElementAt(newPop, i + 1);
          aBuffer.InsertElementAt(newPush, i + 2);
          i += 2;
          childEndIndex += 2;
          sortEndIndex += 2;
        }
        e = eNext;
      }
    }
  } else if (aForceSort || !autoZIndex) {
    ApplyZOrderStableSort(aBuffer, aMergeTmp, sortStartIndex, sortEndIndex);
  }

  for (PRInt32 i = childStartIndex; i < childEndIndex; i++) {
    DisplayListElement2* element = NS_STATIC_CAST(DisplayListElement2*, aBuffer.ElementAt(i));
    if (!autoZIndex) {
      element->mZIndex = explicitZIndex;
    } else if (aNode->mView->IsTopMost()) {
      // promote children to topmost if this view is topmost
      element->mZIndex |= nsInt64(1);
    }
  }
}

static void PushStateAndClip(nsIRenderingContext** aRCs, PRInt32 aCount, nsRect &aRect) {
  for (int i = 0; i < aCount; i++) {
    if (aRCs[i]) {
      PRBool clipEmpty;
      aRCs[i]->PushState();
      aRCs[i]->SetClipRect(aRect, nsClipCombine_kIntersect, clipEmpty);
    }
  }
}

static void PopState(nsIRenderingContext **aRCs, PRInt32 aCount) {
  for (int i = 0; i < aCount; i++) {
    if (aRCs[i]) {
      PRBool clipEmpty;
      aRCs[i]->PopState(clipEmpty);
    }
  }
}

void nsViewManager::AddCoveringWidgetsToOpaqueRegion(nsRegion &aRgn, nsIDeviceContext* aContext,
                                                     nsView* aRootView) {
  // We accumulate the bounds of widgets obscuring aRootView's widget into opaqueRgn.
  // In OptimizeDisplayList, display list elements which lie behind obscuring native
  // widgets are dropped.
  // This shouldn't really be necessary, since the GFX/Widget toolkit should remove these
  // covering widgets from the clip region passed into the paint command. But right now
  // they only give us a paint rect and not a region, so we can't access that information.
  // It's important to identifying areas that are covered by native widgets to avoid
  // painting their views many times as we process invalidates from the root widget all the
  // way down to the nested widgets.
  // 
  // NB: we must NOT add widgets that correspond to floating views!
  // We may be required to paint behind them
  aRgn.SetEmpty();

  nsCOMPtr<nsIWidget> widget;
  GetWidgetForView(aRootView, getter_AddRefs(widget));
  if (!widget) {
    return;
  }

  nsCOMPtr<nsIEnumerator> children(dont_AddRef(widget->GetChildren()));
  if (!children) {
    return;
  }

  children->First();
  do {
    nsCOMPtr<nsISupports> child;
    if (!NS_SUCCEEDED(children->CurrentItem(getter_AddRefs(child)))) {
      return;
    }

    nsCOMPtr<nsIWidget> childWidget = do_QueryInterface(child);
    if (childWidget) {
      PRBool widgetVisible;
      childWidget->IsVisible(widgetVisible);
      if (widgetVisible) {
        nsView* view = nsView::GetViewFor(childWidget);
        if (view && view->GetVisibility() == nsViewVisibility_kShow
            && !view->GetFloating()) {
          nsRect bounds = view->GetBounds();
          if (bounds.width > 0 && bounds.height > 0) {
            nsView* viewParent = view->GetParent();
            
            while (viewParent && viewParent != aRootView) {
              viewParent->ConvertToParentCoords(&bounds.x, &bounds.y);
              viewParent = viewParent->GetParent();
            }
            
            // maybe we couldn't get the view into the coordinate
            // system of aRootView (maybe it's not a descendant
            // view of aRootView?); if so, don't use it
            if (viewParent) {
              aRgn.Or(aRgn, bounds);
            }
          }
        }
      }
    }
  } while (NS_SUCCEEDED(children->Next()));
}

PRBool nsViewManager::BuildRenderingDisplayList(nsIView* aRootView,
  const nsRegion& aRegion, nsVoidArray* aDisplayList) {
  BuildDisplayList(NS_STATIC_CAST(nsView*, aRootView),
                   aRegion.GetBounds(), PR_FALSE, PR_FALSE, aDisplayList);

  nsRegion opaqueRgn;
  AddCoveringWidgetsToOpaqueRegion(opaqueRgn, mContext,
                                   NS_STATIC_CAST(nsView*, aRootView));

  nsRect finalTransparentRect;
  OptimizeDisplayList(aDisplayList, aRegion, finalTransparentRect, opaqueRgn, PR_FALSE);

#ifdef DEBUG_roc
  if (!finalTransparentRect.IsEmpty()) {
    printf("XXX: Using final transparent rect, x=%d, y=%d, width=%d, height=%d\n",
           finalTransparentRect.x, finalTransparentRect.y, finalTransparentRect.width, finalTransparentRect.height);
  }
#endif

  return !finalTransparentRect.IsEmpty();
}

/*
  aRCSurface is the drawing surface being used to double-buffer aRC, or null
  if no double-buffering is happening. We pass this in here so that we can
  blend directly into the double-buffer offscreen memory.
*/
void nsViewManager::RenderViews(nsView *aRootView, nsIRenderingContext& aRC,
                                const nsRegion& aRegion, nsDrawingSurface aRCSurface,
                                const nsVoidArray& aDisplayList)
{
#ifdef DEBUG_roc
  if (getenv("MOZ_SHOW_DISPLAY_LIST")) ShowDisplayList(&aDisplayList);
#endif

  PRInt32 index = 0;
  nsRect fakeClipRect;
  PRBool anyRendered;
  OptimizeDisplayListClipping(&aDisplayList, PR_FALSE, fakeClipRect, index, anyRendered);

  index = 0;
  OptimizeTranslucentRegions(aDisplayList, &index, nsnull);

  nsIWidget* widget = aRootView->GetWidget();
  PRBool translucentWindow = PR_FALSE;
  if (widget) {
    widget->GetWindowTranslucency(translucentWindow);
    if (translucentWindow) {
      NS_WARNING("Transparent window enabled");
      NS_ASSERTION(aRCSurface, "Cannot support transparent windows with doublebuffering disabled");
    }
  }

  // Create a buffer wrapping aRC (which is usually the double-buffering offscreen buffer).
  BlendingBuffers* buffers =
    CreateBlendingBuffers(&aRC, PR_TRUE, aRCSurface, translucentWindow, aRegion.GetBounds());
  NS_ASSERTION(buffers, "Failed to create rendering buffers");
  if (!buffers)
    return;

  nsAutoVoidArray filterStack;

  // draw all views in the display list, from back to front.
  for (PRInt32 i = 0; i < aDisplayList.Count(); i++) {
    DisplayListElement2* element = NS_STATIC_CAST(DisplayListElement2*, aDisplayList.ElementAt(i));

    nsIRenderingContext* RCs[2] = { buffers->mBlackCX, buffers->mWhiteCX };

    if (element->mFlags & PUSH_CLIP) {
      PushStateAndClip(RCs, 2, element->mBounds);
    }
    if (element->mFlags & PUSH_FILTER) {
      NS_ASSERTION(aRCSurface,
                   "Cannot support translucent elements with doublebuffering disabled");

      // Save current buffer on the stack and start rendering into a new
      // offscreen buffer
      filterStack.AppendElement(buffers);
      buffers = CreateBlendingBuffers(&aRC, PR_FALSE, nsnull,
                                      (element->mFlags & VIEW_TRANSPARENT) != 0,
                                      element->mBounds);
    }

    if (element->mFlags & VIEW_RENDERED) {
      if (element->mFlags & VIEW_CLIPPED) {
        PushStateAndClip(RCs, 2, element->mBounds);
      }
      
      RenderDisplayListElement(element, RCs[0]);
      // RenderDisplayListElement won't do anything if the context is null
      RenderDisplayListElement(element, RCs[1]);

      if (element->mFlags & VIEW_CLIPPED) {
        PopState(RCs, 2);
      }
    }

    if (element->mFlags & POP_FILTER) {
      // Pop the last buffer off the stack and composite the current buffer into
      // the last buffer
      BlendingBuffers* doneBuffers = buffers;
      buffers = NS_STATIC_CAST(BlendingBuffers*,
                               filterStack.ElementAt(filterStack.Count() - 1));
      filterStack.RemoveElementAt(filterStack.Count() - 1);

      // perform the blend itself.
      nsRect damageRectInPixels = element->mBounds;
      damageRectInPixels -= buffers->mOffset;
      damageRectInPixels *= mTwipsToPixels;
      if (damageRectInPixels.width > 0 && damageRectInPixels.height > 0) {
        nsIRenderingContext* targets[2] = { buffers->mBlackCX, buffers->mWhiteCX };
        for (int j = 0; j < 2; j++) {
          if (targets[j]) {
            mBlender->Blend(0, 0,
                            damageRectInPixels.width, damageRectInPixels.height,
                            doneBuffers->mBlackCX, targets[j],
                            damageRectInPixels.x, damageRectInPixels.y,
                            element->mView->GetOpacity(), doneBuffers->mWhiteCX,
                            NS_RGB(0, 0, 0), NS_RGB(255, 255, 255));
          }
        }
      }
      // probably should recycle these so we don't eat the cost of graphics memory
      // allocation
      delete doneBuffers;
    }
    if (element->mFlags & POP_CLIP) {
      PopState(RCs, 2);
    }
      
    delete element;
  }
    
  if (translucentWindow) {
    // Get the alpha channel into an array so we can send it to the widget
    nsRect r = aRegion.GetBounds();
    r *= mTwipsToPixels;
    nsRect bufferRect(0, 0, r.width, r.height);
    PRUint8* alphas = nsnull;
    nsresult rv = mBlender->GetAlphas(bufferRect, buffers->mBlack,
                                      buffers->mWhite, &alphas);
    
    if (NS_SUCCEEDED(rv)) {
      widget->UpdateTranslucentWindowAlpha(r, alphas);
    }
    delete[] alphas;
  }

  delete buffers;
}

void nsViewManager::RenderDisplayListElement(DisplayListElement2* element,
                                             nsIRenderingContext* aRC) {
  if (!aRC)
    return;
  
  PRBool clipEmpty;
  nsRect r;
  nsView* view = element->mView;

  view->GetDimensions(r);

  aRC->PushState();

  nscoord x = element->mAbsX - r.x, y = element->mAbsY - r.y;
  aRC->Translate(x, y);

  nsRect drect(element->mBounds.x - x, element->mBounds.y - y,
               element->mBounds.width, element->mBounds.height);
  
  element->mView->Paint(*aRC, drect, 0, clipEmpty);
  
  aRC->PopState(clipEmpty);
}

void nsViewManager::PaintView(nsView *aView, nsIRenderingContext &aRC, nscoord x, nscoord y,
                              const nsRect &aDamageRect)
{
  aRC.PushState();
  aRC.Translate(x, y);
  PRBool unused;
  aView->Paint(aRC, aDamageRect, 0, unused);
  aRC.PopState(unused);
}

static nsresult NewOffscreenContext(nsIDeviceContext* deviceContext, nsDrawingSurface surface,
                                    const nsRect& aRect, nsIRenderingContext* *aResult)
{
  nsresult             rv;
  nsIRenderingContext *context = nsnull;

  rv = deviceContext->CreateRenderingContext(surface, context);
  if (NS_FAILED(rv))
    return rv;

  // always initialize clipping, linux won't draw images otherwise.
  PRBool clipEmpty;
  nsRect clip(0, 0, aRect.width, aRect.height);
  context->SetClipRect(clip, nsClipCombine_kReplace, clipEmpty);

  context->Translate(-aRect.x, -aRect.y);
  
  *aResult = context;
  return NS_OK;
}

BlendingBuffers::BlendingBuffers(nsIRenderingContext* aCleanupContext) {
  mCleanupContext = aCleanupContext;

  mOwnBlackSurface = PR_FALSE;
  mWhite = nsnull;
  mBlack = nsnull;
}

BlendingBuffers::~BlendingBuffers() {
  if (mWhite)
    mCleanupContext->DestroyDrawingSurface(mWhite);

  if (mBlack && mOwnBlackSurface)
    mCleanupContext->DestroyDrawingSurface(mBlack);
}

/*
@param aBorrowContext set to PR_TRUE if the BlendingBuffers' "black" context
  should be just aRC; set to PR_FALSE if we should create a new offscreen context
@param aBorrowSurface if aBorrowContext is PR_TRUE, then this is the offscreen surface
  corresponding to aRC, or nsnull if aRC doesn't have one; if aBorrowContext is PR_FALSE,
  this parameter is ignored
@param aNeedAlpha set to PR_FALSE if the caller guarantees that every pixel of the
  BlendingBuffers will be drawn with opacity 1.0, PR_TRUE otherwise
@param aRect the screen rectangle covered by the new BlendingBuffers, in app units, and
  relative to the origin of aRC
*/
BlendingBuffers*
nsViewManager::CreateBlendingBuffers(nsIRenderingContext *aRC,
                                     PRBool aBorrowContext,
                                     nsDrawingSurface aBorrowSurface,
                                     PRBool aNeedAlpha,
                                     const nsRect& aRect)
{
  nsresult rv;

  // create a blender, if none exists already.
  if (!mBlender) {
    mBlender = do_CreateInstance(kBlenderCID, &rv);
    if (NS_FAILED(rv))
      return nsnull;
    rv = mBlender->Init(mContext);
    if (NS_FAILED(rv))
      return nsnull;
  }

  BlendingBuffers* buffers = new BlendingBuffers(aRC);
  if (!buffers)
    return nsnull;

  buffers->mOffset = nsPoint(aRect.x, aRect.y);

  nsRect offscreenBounds(0, 0, aRect.width, aRect.height);
  offscreenBounds.ScaleRoundOut(mTwipsToPixels);

  if (aBorrowContext) {
    buffers->mBlackCX = aRC;
    buffers->mBlack = aBorrowSurface;
  } else {
    rv = aRC->CreateDrawingSurface(offscreenBounds, NS_CREATEDRAWINGSURFACE_FOR_PIXEL_ACCESS, buffers->mBlack);
    if (NS_FAILED(rv)) {
      delete buffers;
      return nsnull;
    }
    buffers->mOwnBlackSurface = PR_TRUE;
    
    rv = NewOffscreenContext(mContext, buffers->mBlack, aRect, getter_AddRefs(buffers->mBlackCX));
    if (NS_FAILED(rv)) {
      delete buffers;
      return nsnull;
    }
  }

  if (aNeedAlpha) {
    rv = aRC->CreateDrawingSurface(offscreenBounds, NS_CREATEDRAWINGSURFACE_FOR_PIXEL_ACCESS, buffers->mWhite);
    if (NS_FAILED(rv)) {
      delete buffers;
      return nsnull;
    }
    
    rv = NewOffscreenContext(mContext, buffers->mWhite, aRect, getter_AddRefs(buffers->mWhiteCX));
    if (NS_FAILED(rv)) {
      delete buffers;
      return nsnull;
    }
    
    // Note that we only need to fill mBlackCX with black when some pixels are going
    // to be transparent.
    buffers->mBlackCX->SetColor(NS_RGB(0, 0, 0));
    buffers->mBlackCX->FillRect(aRect);
    buffers->mWhiteCX->SetColor(NS_RGB(255, 255, 255));
    buffers->mWhiteCX->FillRect(aRect);
  }

  return buffers;
}

void nsViewManager::ProcessPendingUpdates(nsView* aView)
{
  // Protect against a null-view.
  if (!aView) {
    return;
  }
  if (aView->HasWidget()) {
    nsCOMPtr<nsIRegion> dirtyRegion;
    aView->GetDirtyRegion(*getter_AddRefs(dirtyRegion));
    if (dirtyRegion && !dirtyRegion->IsEmpty()) {
      aView->GetWidget()->InvalidateRegion(dirtyRegion, PR_FALSE);
      dirtyRegion->Init();
    }
  }

  // process pending updates in child view.
  for (nsView* childView = aView->GetFirstChild(); childView;
       childView = childView->GetNextSibling()) {
    if (childView->GetViewManager() == this) {
      ProcessPendingUpdates(childView);
    }
  }
}

NS_IMETHODIMP nsViewManager::Composite()
{
  if (mUpdateCnt > 0)
    {
      if (nsnull != mRootWindow)
        mRootWindow->Update();
  
      mUpdateCnt = 0;
    }

  return NS_OK;
}

NS_IMETHODIMP nsViewManager::UpdateView(nsIView *aView, PRUint32 aUpdateFlags)
{
  // Mark the entire view as damaged
  nsView* view = NS_STATIC_CAST(nsView*, aView);

  nsRect bounds = view->GetBounds();
  view->ConvertFromParentCoords(&bounds.x, &bounds.y);
  return UpdateView(view, bounds, aUpdateFlags);
}


// Invalidate all widgets which overlap the view, other than the view's own widgets.
void
nsViewManager::UpdateViewAfterScroll(nsIView *aView, PRInt32 aDX, PRInt32 aDY)
{
  nsView* view = NS_STATIC_CAST(nsView*, aView);

  // Look at the view's clipped rect. It may be that part of the view is clipped out
  // in which case we don't need to worry about invalidating the clipped-out part.
  nsRect damageRect = view->GetClippedRect();
  if (damageRect.IsEmpty()) {
    return;
  }
  damageRect.MoveBy(ComputeViewOffset(view));

  // if this is a floating view, it isn't covered by any widgets other than
  // its children, which are handled by the widget scroller.
  if (view->GetFloating()) {
    return;
  }

  nsView* realRoot = mRootView;
  while (realRoot->GetParent()) {
    realRoot = realRoot->GetParent();
  }

  UpdateWidgetArea(realRoot, damageRect, view);

  Composite();
}

// Returns true if this view's widget(s) completely cover the rectangle
// The specified rectangle, relative to aWidgetView, is invalidated in every widget child of aWidgetView,
// plus aWidgetView's own widget
// If non-null, the aIgnoreWidgetView's widget and its children are not updated.
PRBool nsViewManager::UpdateWidgetArea(nsView *aWidgetView, const nsRect &aDamagedRect, nsView* aIgnoreWidgetView)
{
  // If the bounds don't overlap at all, there's nothing to do
  nsRect bounds;
  aWidgetView->GetDimensions(bounds);

  PRBool overlap = bounds.IntersectRect(bounds, aDamagedRect);
  if (!overlap) {
    return PR_FALSE;
  }

  // If the widget is hidden, it don't cover nothing
  if (nsViewVisibility_kHide == aWidgetView->GetVisibility()) {
#ifdef DEBUG
    // Assert if view is hidden but widget is visible
    nsCOMPtr<nsIWidget> widget;
    GetWidgetForView(aWidgetView, getter_AddRefs(widget));
    if (widget) {
      PRBool visible;
      widget->IsVisible(visible);
      NS_ASSERTION(!visible, "View is hidden but widget is visible!");
    }
#endif
    return PR_FALSE;
  }

  PRBool noCropping = bounds == aDamagedRect;
  if (aWidgetView == aIgnoreWidgetView) {
    // the widget for aIgnoreWidgetView (and its children) should be treated as already updated.
    // We still need to report whether this widget covers the rectangle.
    return noCropping;
  }

  nsCOMPtr<nsIWidget> widget;
  GetWidgetForView(aWidgetView, getter_AddRefs(widget));
  if (!widget) {
    // The root view or a scrolling view might not have a widget
    // (for example, during printing). We get here when we scroll
    // during printing to show selected options in a listbox, for example.
    return PR_FALSE;
  }

  PRBool childCovers = PR_FALSE;
  nsCOMPtr<nsIEnumerator> children(dont_AddRef(widget->GetChildren()));
  if (children) {
    children->First();
    do {
      nsCOMPtr<nsISupports> child;
      if (NS_SUCCEEDED(children->CurrentItem(getter_AddRefs(child)))) {
        nsCOMPtr<nsIWidget> childWidget = do_QueryInterface(child);
        if (childWidget) {
          nsView* view = nsView::GetViewFor(childWidget);
          if (nsnull != view) {
            nsRect damage = bounds;
            nsView* vp = view;
            while (vp != aWidgetView && nsnull != vp) {
              vp->ConvertFromParentCoords(&damage.x, &damage.y);
              vp = vp->GetParent();
            }
            
            if (nsnull != vp) { // vp == nsnull means it's in a different hierarchy so we ignore it
              if (UpdateWidgetArea(view, damage, aIgnoreWidgetView)) {
                childCovers = PR_TRUE;
              }
            }
          }
        }
      }
    } while (NS_SUCCEEDED(children->Next()));
  }

  if (!childCovers) {
    nsViewManager* vm = aWidgetView->GetViewManager();
    ++vm->mUpdateCnt;

    if (!vm->mRefreshEnabled) {
      // accumulate this rectangle in the view's dirty region, so we can process it later.
      vm->AddRectToDirtyRegion(aWidgetView, bounds);
      vm->mHasPendingInvalidates = PR_TRUE;
    } else {
      ViewToWidget(aWidgetView, aWidgetView, bounds);
      widget->Invalidate(bounds, PR_FALSE);
    }
  }

  return noCropping;
}

NS_IMETHODIMP nsViewManager::UpdateView(nsIView *aView, const nsRect &aRect, PRUint32 aUpdateFlags)
{
  NS_PRECONDITION(nsnull != aView, "null view");

  nsView* view = NS_STATIC_CAST(nsView*, aView);

  // Only Update the rectangle region of the rect that intersects the view's non clipped rectangle
  nsRect clippedRect = view->GetClippedRect();
  if (clippedRect.IsEmpty()) {
    return NS_OK;
  }

  nsRect damagedRect;
  damagedRect.IntersectRect(aRect, clippedRect);

   // If the rectangle is not visible then abort
   // without invalidating. This is a performance 
   // enhancement since invalidating a native widget
   // can be expensive.
   // This also checks for silly request like damagedRect.width = 0 or damagedRect.height = 0
  nsRectVisibility rectVisibility;
  GetRectVisibility(view, damagedRect, 0, &rectVisibility);
  if (rectVisibility != nsRectVisibility_kVisible) {
    return NS_OK;
  }

  // if this is a floating view, it isn't covered by any widgets other than
  // its children. In that case we walk up to its parent widget and use
  // that as the root to update from. This also means we update areas that
  // may be outside the parent view(s), which is necessary for floats.
  if (view->GetFloating()) {
    nsView* widgetParent = view;

    while (!widgetParent->HasWidget()) {
      widgetParent->ConvertToParentCoords(&damagedRect.x, &damagedRect.y);
      widgetParent = widgetParent->GetParent();
    }

    UpdateWidgetArea(widgetParent, damagedRect, nsnull);
  } else {
    damagedRect.MoveBy(ComputeViewOffset(view));

    nsView* realRoot = mRootView;
    while (realRoot->GetParent()) {
      realRoot = realRoot->GetParent();
    }

    UpdateWidgetArea(realRoot, damagedRect, nsnull);
  }

  ++mUpdateCnt;

  if (!mRefreshEnabled) {
    return NS_OK;
  }

  // See if we should do an immediate refresh or wait
  if (aUpdateFlags & NS_VMREFRESH_IMMEDIATE) {
    Composite();
  } 

  return NS_OK;
}

NS_IMETHODIMP nsViewManager::UpdateAllViews(PRUint32 aUpdateFlags)
{
  UpdateViews(mRootView, aUpdateFlags);
  return NS_OK;
}

void nsViewManager::UpdateViews(nsView *aView, PRUint32 aUpdateFlags)
{
  // update this view.
  UpdateView(aView, aUpdateFlags);

  // update all children as well.
  nsView* childView = aView->GetFirstChild();
  while (nsnull != childView)  {
    if (childView->GetViewManager() == this) {
      UpdateViews(childView, aUpdateFlags);
    }
    childView = childView->GetNextSibling();
  }
}

NS_IMETHODIMP nsViewManager::DispatchEvent(nsGUIEvent *aEvent, nsEventStatus *aStatus)
{
  *aStatus = nsEventStatus_eIgnore;

  switch(aEvent->message)
    {
    case NS_SIZE:
      {
        nsView* view = nsView::GetViewFor(aEvent->widget);

        if (nsnull != view)
          {
            nscoord width = ((nsSizeEvent*)aEvent)->windowSize->width;
            nscoord height = ((nsSizeEvent*)aEvent)->windowSize->height;
            width = ((nsSizeEvent*)aEvent)->mWinWidth;
            height = ((nsSizeEvent*)aEvent)->mWinHeight;

            // The root view may not be set if this is the resize associated with
            // window creation

            if (view == mRootView)
              {
                // Convert from pixels to twips
                float p2t;
                p2t = mContext->DevUnitsToAppUnits();

                //printf("resize: (pix) %d, %d\n", width, height);
                SetWindowDimensions(NSIntPixelsToTwips(width, p2t),
                                    NSIntPixelsToTwips(height, p2t));
                *aStatus = nsEventStatus_eConsumeNoDefault;
              }
          }

        break;
      }

    case NS_PAINT:
      {
        nsPaintEvent *event = NS_STATIC_CAST(nsPaintEvent*, aEvent);
        nsView *view = nsView::GetViewFor(aEvent->widget);

        if (!view || !mContext)
          break;

        *aStatus = nsEventStatus_eConsumeNoDefault;

        // The rect is in device units, and it's in the coordinate space of its
        // associated window.
        nsCOMPtr<nsIRegion> region = event->region;
        if (!region) {
          if (NS_FAILED(CreateRegion(getter_AddRefs(region))))
            break;

          const nsRect& damrect = *event->rect;
          region->SetTo(damrect.x, damrect.y, damrect.width, damrect.height);
        }
        
        if (region->IsEmpty())
          break;

        // Refresh the view
        if (mRefreshEnabled) {
          // If an ancestor widget was hidden and then shown, we could
          // have a delayed resize to handle.
          if (mDelayedResize != nsSize(NSCOORD_NONE, NSCOORD_NONE) &&
              IsViewVisible(mRootView)) {
            DoSetWindowDimensions(mDelayedResize.width, mDelayedResize.height);
            mDelayedResize.SizeTo(NSCOORD_NONE, NSCOORD_NONE);
            
            // Paint later.
            UpdateView(view, NS_VMREFRESH_NO_SYNC);
          } else {
            //NS_ASSERTION(IsViewVisible(view), "painting an invisible view");
            Refresh(view, event->renderingContext, region,
                    NS_VMREFRESH_DOUBLE_BUFFER);
          }
        } else {
          // since we got an NS_PAINT event, we need to
          // draw something so we don't get blank areas.
          nsRect damRect;
          region->GetBoundingBox(&damRect.x, &damRect.y, &damRect.width, &damRect.height);
          float p2t;
          p2t = mContext->DevUnitsToAppUnits();
          damRect.ScaleRoundOut(p2t);
          DefaultRefresh(view, &damRect);
        
          // Clients like the editor can trigger multiple
          // reflows during what the user perceives as a single
          // edit operation, so it disables view manager
          // refreshing until the edit operation is complete
          // so that users don't see the intermediate steps.
          // 
          // Unfortunately some of these reflows can trigger
          // nsScrollPortView and nsScrollingView Scroll() calls
          // which in most cases force an immediate BitBlt and
          // synchronous paint to happen even if the view manager's
          // refresh is disabled. (Bug 97674)
          //
          // Calling UpdateView() here, is neccessary to add
          // the exposed region specified in the synchronous paint
          // event to  the view's damaged region so that it gets
          // painted properly when refresh is enabled.
          //
          // Note that calling UpdateView() here was deemed
          // to have the least impact on performance, since the
          // other alternative was to make Scroll() post an
          // async paint event for the *entire* ScrollPort or
          // ScrollingView's viewable area. (See bug 97674 for this
          // alternate patch.)
          
          UpdateView(view, damRect, NS_VMREFRESH_NO_SYNC);
        }

        break;
      }

    case NS_CREATE:
    case NS_DESTROY:
    case NS_SETZLEVEL:
    case NS_MOVE:
      /* Don't pass these events through. Passing them through
         causes performance problems on pages with lots of views/frames 
         @see bug 112861 */
      *aStatus = nsEventStatus_eConsumeNoDefault;
      break;


    case NS_DISPLAYCHANGED:

      //Destroy the cached backbuffer to force a new backbuffer
      //be constructed with the appropriate display depth.
      //@see bugzilla bug 6061
      *aStatus = nsEventStatus_eConsumeDoDefault;
      if (gCleanupContext) {
        gCleanupContext->DestroyCachedBackbuffer();
      }
      break;

    case NS_SYSCOLORCHANGED:
      {
        nsView *view = nsView::GetViewFor(aEvent->widget);
        nsCOMPtr<nsIViewObserver> obs;
        GetViewObserver(*getter_AddRefs(obs));
        if (obs) {
          PRBool handled;
          obs->HandleEvent(view, aEvent, aStatus, PR_TRUE, handled);
        }
      }
      break; 

    default:
      {
        nsView* baseView;
        nsView* view;
        nsPoint offset;
        PRBool capturedEvent = PR_FALSE;

        if (NS_IS_MOUSE_EVENT(aEvent) || NS_IS_KEY_EVENT(aEvent) ||
            NS_IS_IME_EVENT(aEvent)) {
          gLastUserEventTime = PR_IntervalToMicroseconds(PR_IntervalNow());
        }

        //Find the view whose coordinates system we're in.
        baseView = nsView::GetViewFor(aEvent->widget);

        if (aEvent->message == NS_DEACTIVATE)
          mMouseGrabber = mKeyGrabber = nsnull;

        //Find the view to which we're initially going to send the event 
        //for hittesting.
        if (nsnull != mMouseGrabber && (NS_IS_MOUSE_EVENT(aEvent) || (NS_IS_DRAG_EVENT(aEvent)))) {
          view = mMouseGrabber;
          capturedEvent = PR_TRUE;
        }
        else if (nsnull != mKeyGrabber && (NS_IS_KEY_EVENT(aEvent) || NS_IS_IME_EVENT(aEvent))) {
          view = mKeyGrabber;
          capturedEvent = PR_TRUE;
        }
        else {
          view = baseView;
        }

        if (nsnull != view) {
          //Calculate the proper offset for the view we're going to
          offset.x = offset.y = 0;
          if (baseView != view) {
            //Get offset from root of baseView
            nsView *parent;

            parent = baseView;
            while (mRootView != parent) {
              parent->ConvertToParentCoords(&offset.x, &offset.y);
              parent = parent->GetParent();
            }

            //Subtract back offset from root of view
            parent = view;
            while (mRootView != parent) {
              parent->ConvertFromParentCoords(&offset.x, &offset.y);
              parent = parent->GetParent();
            }
      
          }

          //Dispatch the event
          //Before we start mucking with coords, make sure we know our baseline
          aEvent->refPoint.x = aEvent->point.x;
          aEvent->refPoint.y = aEvent->point.y;

          nsRect baseViewDimensions;
          if (baseView != nsnull) {
            baseView->GetDimensions(baseViewDimensions);
          }

          float t2p = mContext->AppUnitsToDevUnits();
          float p2t = mContext->DevUnitsToAppUnits();

          aEvent->point.x = baseViewDimensions.x + NSIntPixelsToTwips(aEvent->point.x, p2t);
          aEvent->point.y = baseViewDimensions.y + NSIntPixelsToTwips(aEvent->point.y, p2t);

          aEvent->point.x += offset.x;
          aEvent->point.y += offset.y;

          *aStatus = HandleEvent(view, aEvent, capturedEvent);

          // From here on out, "this" could have been deleted!!!

          aEvent->point.x -= offset.x;
          aEvent->point.y -= offset.y;

          aEvent->point.x = NSTwipsToIntPixels(aEvent->point.x - baseViewDimensions.x, t2p);
          aEvent->point.y = NSTwipsToIntPixels(aEvent->point.y - baseViewDimensions.y, t2p);

          //
          // if the event is an nsTextEvent, we need to map the reply back into platform coordinates
          //
          if (aEvent->message==NS_TEXT_TEXT) {
            ((nsTextEvent*)aEvent)->theReply.mCursorPosition.x=NSTwipsToIntPixels(((nsTextEvent*)aEvent)->theReply.mCursorPosition.x, t2p);
            ((nsTextEvent*)aEvent)->theReply.mCursorPosition.y=NSTwipsToIntPixels(((nsTextEvent*)aEvent)->theReply.mCursorPosition.y, t2p);
            ((nsTextEvent*)aEvent)->theReply.mCursorPosition.width=NSTwipsToIntPixels(((nsTextEvent*)aEvent)->theReply.mCursorPosition.width, t2p);
            ((nsTextEvent*)aEvent)->theReply.mCursorPosition.height=NSTwipsToIntPixels(((nsTextEvent*)aEvent)->theReply.mCursorPosition.height, t2p);
          }
          if((aEvent->message==NS_COMPOSITION_START) ||
             (aEvent->message==NS_COMPOSITION_QUERY)) {
            ((nsCompositionEvent*)aEvent)->theReply.mCursorPosition.x=NSTwipsToIntPixels(((nsCompositionEvent*)aEvent)->theReply.mCursorPosition.x,t2p);
            ((nsCompositionEvent*)aEvent)->theReply.mCursorPosition.y=NSTwipsToIntPixels(((nsCompositionEvent*)aEvent)->theReply.mCursorPosition.y,t2p);
            ((nsCompositionEvent*)aEvent)->theReply.mCursorPosition.width=NSTwipsToIntPixels(((nsCompositionEvent*)aEvent)->theReply.mCursorPosition.width,t2p);
            ((nsCompositionEvent*)aEvent)->theReply.mCursorPosition.height=NSTwipsToIntPixels(((nsCompositionEvent*)aEvent)->theReply.mCursorPosition.height,t2p);
          }
        }
    
        break;
      }
    }

  return NS_OK;
}

void nsViewManager::ReparentViews(DisplayZTreeNode* aNode) {
  if (aNode == nsnull) {
    return;
  }

  DisplayZTreeNode* child;
  DisplayZTreeNode** prev = &aNode->mZChild;
  for (child = aNode->mZChild; nsnull != child; child = *prev) {
    ReparentViews(child);

    nsZPlaceholderView *zParent = nsnull;
    if (nsnull != child->mView) {
      zParent = child->mView->GetZParent();
    }
    if (nsnull != zParent) {
      nsVoidKey key(zParent);
      DisplayZTreeNode* placeholder = (DisplayZTreeNode *)mMapPlaceholderViewToZTreeNode.Get(&key);

      if (placeholder == child) {
        // don't do anything if we already reparented this node;
        // just advance to the next child
        prev = &child->mZSibling;
      } else {
        // unlink the child from the tree
        *prev = child->mZSibling;
        child->mZSibling = nsnull;
        
        if (nsnull != placeholder) {
          NS_ASSERTION((placeholder->mDisplayElement == nsnull), "placeholder already has elements?");
          NS_ASSERTION((placeholder->mZChild == nsnull), "placeholder already has Z-children?");
          placeholder->mDisplayElement = child->mDisplayElement;
          placeholder->mView = child->mView;
          placeholder->mZChild = child->mZChild;
          delete child;
        } else {
          // the placeholder was not added to the display list
          // we don't need the real view then, either
          DestroyZTreeNode(child);
        }
      }
    } else {
      prev = &child->mZSibling;
    }
  }
}

static PRBool ComputePlaceholderContainment(nsView* aView) {
  PRBool containsPlaceholder = aView->IsZPlaceholderView();

  nsView* child;
  for (child = aView->GetFirstChild(); child != nsnull; child = child->GetNextSibling()) {
    if (ComputePlaceholderContainment(child)) {
      containsPlaceholder = PR_TRUE;
    }
  }

  if (containsPlaceholder) {
    aView->SetViewFlags(aView->GetViewFlags() | NS_VIEW_FLAG_CONTAINS_PLACEHOLDER);
  } else {
    aView->SetViewFlags(aView->GetViewFlags() & ~NS_VIEW_FLAG_CONTAINS_PLACEHOLDER);
  }

  return containsPlaceholder;
}

/*
  Fills aDisplayList with DisplayListElement2* pointers. The caller is responsible
  for freeing these structs. The display list elements are ordered by z-order so
  that the first element of the array is at the bottom in z-order and the last element
  in the array is at the top in z-order.

  This should be changed so that the display list array is passed in as a parameter. There
  is no need to have the display list as a member of nsViewManager.

  aRect is the area in aView which we want to build a display list for.
  Set aEventProcesing when the list is required for event processing.
  Set aCaptured if the event is being captured by the given view.
*/
void nsViewManager::BuildDisplayList(nsView* aView, const nsRect& aRect, PRBool aEventProcessing,
                                     PRBool aCaptured, nsVoidArray* aDisplayList) {
  // compute this view's origin
  nsPoint origin = ComputeViewOffset(aView);
    
  nsView *displayRoot = aView;
  if (!aCaptured) {
    for (;;) {
      nsView *displayParent = displayRoot->GetParent();

      if (nsnull == displayParent) {
        break;
      }

      if (displayRoot->GetFloating() && !displayParent->GetFloating()) {
        break;
      }
      displayRoot = displayParent;
    }
  }
    
  DisplayZTreeNode *zTree;

  nsPoint displayRootOrigin = ComputeViewOffset(displayRoot);
  displayRoot->ConvertFromParentCoords(&displayRootOrigin.x, &displayRootOrigin.y);
    
  // Determine, for each view, whether it is or contains a ZPlaceholderView
  ComputePlaceholderContainment(displayRoot);

  // Create the Z-ordered view tree
  PRBool paintFloats;
  if (aEventProcessing) {
    paintFloats = PR_TRUE;
  } else {
    paintFloats = displayRoot->GetFloating();
  }
  CreateDisplayList(displayRoot, PR_FALSE, zTree, origin.x, origin.y,
                    aView, &aRect, displayRoot, displayRootOrigin.x, displayRootOrigin.y,
                    paintFloats, aEventProcessing);

  // Reparent any views that need reparenting in the Z-order tree
  ReparentViews(zTree);
  mMapPlaceholderViewToZTreeNode.Reset();
    
  if (nsnull != zTree) {
    // Apply proper Z-order handling
    nsAutoVoidArray mergeTmp;

    SortByZOrder(zTree, *aDisplayList, mergeTmp, PR_TRUE);
  }
    
  DestroyZTreeNode(zTree);
}

void nsViewManager::BuildEventTargetList(nsVoidArray &aTargets, nsView* aView, nsGUIEvent* aEvent,
  PRBool aCaptured) {
  NS_ASSERTION(!mPainting, "View manager cannot handle events during a paint");
  if (mPainting) {
    return;
  }

  nsRect eventRect(aEvent->point.x, aEvent->point.y, 1, 1);
  nsAutoVoidArray displayList;
  BuildDisplayList(aView, eventRect, PR_TRUE, aCaptured, &displayList);

#ifdef DEBUG_roc
  if (getenv("MOZ_SHOW_DISPLAY_LIST")) ShowDisplayList(&displayList);
#endif

  // The display list is in order from back to front. We return the target list in order from
  // front to back.
  for (PRInt32 i = displayList.Count() - 1; i >= 0; --i) {
    DisplayListElement2* element = NS_STATIC_CAST(DisplayListElement2*, displayList.ElementAt(i));
    if (element->mFlags & VIEW_RENDERED) {
      aTargets.AppendElement(element);
    } else {
      delete element;
    }
  }
}

nsEventStatus nsViewManager::HandleEvent(nsView* aView, nsGUIEvent* aEvent, PRBool aCaptured) {
//printf(" %d %d %d %d (%d,%d) \n", this, event->widget, event->widgetSupports, 
//       event->message, event->point.x, event->point.y);

  // Hold a refcount to the observer. The continued existence of the observer will
  // delay deletion of this view hierarchy should the event want to cause its
  // destruction in, say, some JavaScript event handler.
  nsCOMPtr<nsIViewObserver> obs;
  GetViewObserver(*getter_AddRefs(obs));

  // accessibility events and key events are dispatched directly to the focused view
  if (aEvent->eventStructType == NS_ACCESSIBLE_EVENT
      || aEvent->message == NS_CONTEXTMENU_KEY
      || aEvent->message == NS_MOUSE_EXIT
      || NS_IS_KEY_EVENT(aEvent) || NS_IS_IME_EVENT(aEvent) || NS_IS_FOCUS_EVENT(aEvent)) {
    nsEventStatus status = nsEventStatus_eIgnore;
    if (obs) {
       PRBool handled;
       obs->HandleEvent(aView, aEvent, &status, PR_TRUE, handled);
    }
    return status;
  }
    
  nsAutoVoidArray targetViews;
  nsAutoVoidArray heldRefCountsToOtherVMs;

  // In fact, we only need to take this expensive path when the event is a mouse event ... riiiight?
  BuildEventTargetList(targetViews, aView, aEvent, aCaptured);

  nsEventStatus status = nsEventStatus_eIgnore;

  // get a death grip on any view managers' view observers (other than this one)
  PRInt32 i;
  for (i = 0; i < targetViews.Count(); i++) {
    DisplayListElement2* element = NS_STATIC_CAST(DisplayListElement2*, targetViews.ElementAt(i));
    nsView* v = element->mView;
    nsViewManager* vVM = v->GetViewManager();
    if (vVM != this) {
      nsIViewObserver* vobs = nsnull;
      vVM->GetViewObserver(vobs);
      if (nsnull != vobs) {
        heldRefCountsToOtherVMs.AppendElement(vobs);
      }
    }
  }

  for (i = 0; i < targetViews.Count(); i++) {
    DisplayListElement2* element = NS_STATIC_CAST(DisplayListElement2*, targetViews.ElementAt(i));
    nsView* v = element->mView;

    if (nsnull != v->GetClientData()) {
      PRBool handled = PR_FALSE;
      nsRect r;
      v->GetDimensions(r);

      nscoord x = element->mAbsX - r.x;
      nscoord y = element->mAbsY - r.y;

      aEvent->point.x -= x;
      aEvent->point.y -= y;

      nsViewManager* vVM = v->GetViewManager();
      if (vVM == this) {
        if (nsnull != obs) {
          obs->HandleEvent(v, aEvent, &status, i == targetViews.Count() - 1, handled);
        }
      } else {
        nsCOMPtr<nsIViewObserver> vobs;
        vVM->GetViewObserver(*getter_AddRefs(vobs));
        if (vobs) {
          vobs->HandleEvent(v, aEvent, &status, i == targetViews.Count() - 1, handled);
        }
      }

      aEvent->point.x += x;
      aEvent->point.y += y;

      if (handled) {
        while (i < targetViews.Count()) {
          DisplayListElement2* e = NS_STATIC_CAST(DisplayListElement2*, targetViews.ElementAt(i));
          delete e;
          i++;
        }
        break;
      }
      // if the child says "not handled" but did something which deleted the entire view hierarchy,
      // we'll crash in the next iteration. Oh well. The old code would have crashed too.
    }

    delete element;
  }

  // release death grips
  for (i = 0; i < heldRefCountsToOtherVMs.Count(); i++) {
    nsIViewObserver* element = NS_STATIC_CAST(nsIViewObserver*, heldRefCountsToOtherVMs.ElementAt(i));
    NS_RELEASE(element);
  }  

  return status;
}

NS_IMETHODIMP nsViewManager::GrabMouseEvents(nsIView *aView, PRBool &aResult)
{
  // Along with nsView::SetVisibility, we enforce that the mouse grabber
  // can never be a hidden view.
  if (aView && NS_STATIC_CAST(nsView*, aView)->GetVisibility()
               == nsViewVisibility_kHide) {
    aView = nsnull;
  }

#ifdef DEBUG_mjudge
  if (aView)
    {
      printf("capturing mouse events for view %x\n",aView);
    }
  printf("removing mouse capture from view %x\n",mMouseGrabber);
#endif

  mMouseGrabber = NS_STATIC_CAST(nsView*, aView);
  aResult = PR_TRUE;
  return NS_OK;
}

NS_IMETHODIMP nsViewManager::GrabKeyEvents(nsIView *aView, PRBool &aResult)
{
  mKeyGrabber = NS_STATIC_CAST(nsView*, aView);
  aResult = PR_TRUE;
  return NS_OK;
}

NS_IMETHODIMP nsViewManager::GetMouseEventGrabber(nsIView *&aView)
{
  aView = mMouseGrabber;
  return NS_OK;
}

NS_IMETHODIMP nsViewManager::GetKeyEventGrabber(nsIView *&aView)
{
  aView = mKeyGrabber;
  return NS_OK;
}


// Recursively reparent widgets if necessary 

void nsViewManager::ReparentChildWidgets(nsIView* aView, nsIWidget *aNewWidget)
{
  if (aView->HasWidget()) {
    // Check to see if the parent widget is the
    // same as the new parent. If not then reparent
    // the widget, otherwise there is nothing more
    // to do for the view and its descendants
    nsIWidget* widget = aView->GetWidget();
    nsCOMPtr<nsIWidget> parentWidget = getter_AddRefs(widget->GetParent());
    if (parentWidget.get() != aNewWidget) {
      nsresult rv = widget->SetParent(aNewWidget);
      NS_ASSERTION(NS_SUCCEEDED(rv), "SetParent failed!");
    }
    return;
  }

  // Need to check each of the views children to see
  // if they have a widget and reparent it.

  nsView* view = NS_STATIC_CAST(nsView*, aView);
  for (nsView *kid = view->GetFirstChild(); kid; kid = kid->GetNextSibling()) {
    ReparentChildWidgets(kid, aNewWidget);
  }
}

// Reparent a view and its descendant views widgets if necessary

void nsViewManager::ReparentWidgets(nsIView* aView, nsIView *aParent)
{
  // Quickly determine whether the view has pre-existing children or a
  // widget. In most cases the view will not have any pre-existing 
  // children when this is called.  Only in the case
  // where a view has been reparented by removing it from
  // a reinserting it into a new location in the view hierarchy do we
  // have to consider reparenting the existing widgets for the view and
  // it's descendants.
  nsView* view = NS_STATIC_CAST(nsView*, aView);
  if (view->HasWidget() || view->GetFirstChild()) {
    nsCOMPtr<nsIWidget> parentWidget;
    GetWidgetForView(aParent, getter_AddRefs(parentWidget));
    if (parentWidget) {
      ReparentChildWidgets(aView, parentWidget);
      return;
    }
    NS_WARNING("Can not find a widget for the parent view");
  }
}

NS_IMETHODIMP nsViewManager::InsertChild(nsIView *aParent, nsIView *aChild, nsIView *aSibling,
                                         PRBool aAfter)
{
  nsView* parent = NS_STATIC_CAST(nsView*, aParent);
  nsView* child = NS_STATIC_CAST(nsView*, aChild);
  nsView* sibling = NS_STATIC_CAST(nsView*, aSibling);
  
  NS_PRECONDITION(nsnull != parent, "null ptr");
  NS_PRECONDITION(nsnull != child, "null ptr");
  NS_ASSERTION(sibling == nsnull || sibling->GetParent() == parent,
               "tried to insert view with invalid sibling");
  NS_ASSERTION(!IsViewInserted(child), "tried to insert an already-inserted view");

  if ((nsnull != parent) && (nsnull != child))
    {
      // if aAfter is set, we will insert the child after 'prev' (i.e. after 'kid' in document
      // order, otherwise after 'kid' (i.e. before 'kid' in document order).

#if 1
      if (nsnull == aSibling) {
        if (aAfter) {
          // insert at end of document order, i.e., before first view
          // this is the common case, by far
          parent->InsertChild(child, nsnull);
          ReparentWidgets(child, parent);
        } else {
          // insert at beginning of document order, i.e., after last view
          nsView *kid = parent->GetFirstChild();
          nsView *prev = nsnull;
          while (kid) {
            prev = kid;
            kid = kid->GetNextSibling();
          }
          // prev is last view or null if there are no children
          parent->InsertChild(child, prev);
          ReparentWidgets(child, parent);
        }
      } else {
        nsView *kid = parent->GetFirstChild();
        nsView *prev = nsnull;
        while (kid && sibling != kid) {
          //get the next sibling view
          prev = kid;
          kid = kid->GetNextSibling();
        }
        NS_ASSERTION(kid != nsnull,
                     "couldn't find sibling in child list");
        if (aAfter) {
          // insert after 'kid' in document order, i.e. before in view order
          parent->InsertChild(child, prev);
          ReparentWidgets(child, parent);
        } else {
          // insert before 'kid' in document order, i.e. after in view order
          parent->InsertChild(child, kid);
          ReparentWidgets(child, parent);
        }
      }
#else // don't keep consistent document order, but order things by z-index instead
      // essentially we're emulating the old InsertChild(parent, child, zindex)
      PRInt32 zIndex = child->GetZIndex();
      while (nsnull != kid)
        {
          PRInt32 idx = kid->GetZIndex();

          if (CompareZIndex(zIndex, child->IsTopMost(), child->GetZIndexIsAuto(),
                            idx, kid->IsTopMost(), kid->GetZIndexIsAuto()) >= 0)
            break;

          prev = kid;
          kid = kid->GetNextSibling();
        }

      parent->InsertChild(child, prev);
      ReparentWidgets(child, parent);
#endif

      // if the parent view is marked as "floating", make the newly added view float as well.
      if (parent->GetFloating())
        child->SetFloating(PR_TRUE);

      //and mark this area as dirty if the view is visible...

      if (nsViewVisibility_kHide != child->GetVisibility())
        UpdateView(child, NS_VMREFRESH_NO_SYNC);
    }
  return NS_OK;
}

NS_IMETHODIMP nsViewManager::InsertZPlaceholder(nsIView *aParent, nsIView *aChild,
                                                nsIView *aSibling, PRBool aAfter)
{
  nsView* parent = NS_STATIC_CAST(nsView*, aParent);
  nsView* child = NS_STATIC_CAST(nsView*, aChild);

  NS_PRECONDITION(nsnull != parent, "null ptr");
  NS_PRECONDITION(nsnull != child, "null ptr");

  nsZPlaceholderView* placeholder = new nsZPlaceholderView();
  nsRect bounds(0, 0, 0, 0);
  // mark the placeholder as "shown" so that it will be included in a built display list
  placeholder->Init(this, bounds, parent, nsViewVisibility_kShow);
  placeholder->SetReparentedView(child);
  placeholder->SetZIndex(child->GetZIndexIsAuto(), child->GetZIndex(), child->IsTopMost());
  child->SetZParent(placeholder);
  
  return InsertChild(parent, placeholder, aSibling, aAfter);
}

NS_IMETHODIMP nsViewManager::InsertChild(nsIView *aParent, nsIView *aChild, PRInt32 aZIndex)
{
  // no-one really calls this with anything other than aZIndex == 0 on a fresh view
  // XXX this method should simply be eliminated and its callers redirected to the real method
  SetViewZIndex(aChild, PR_FALSE, aZIndex, PR_FALSE);
  return InsertChild(aParent, aChild, nsnull, PR_TRUE);
}

NS_IMETHODIMP nsViewManager::RemoveChild(nsIView *aChild)
{
  nsView* child = NS_STATIC_CAST(nsView*, aChild);

  NS_PRECONDITION(nsnull != child, "null ptr");

  nsView* parent = child->GetParent();

  if ((nsnull != parent) && (nsnull != child))
    {
      UpdateView(child, NS_VMREFRESH_NO_SYNC);
      parent->RemoveChild(child);
    }

  return NS_OK;
}

NS_IMETHODIMP nsViewManager::MoveViewBy(nsIView *aView, nscoord aX, nscoord aY)
{
  nsView* view = NS_STATIC_CAST(nsView*, aView);

  nsPoint pt = view->GetPosition();
  MoveViewTo(view, aX + pt.x, aY + pt.y);
  return NS_OK;
}

NS_IMETHODIMP nsViewManager::MoveViewTo(nsIView *aView, nscoord aX, nscoord aY)
{
  nsView* view = NS_STATIC_CAST(nsView*, aView);
  nsPoint oldPt = view->GetPosition();
  nsRect oldArea = view->GetBounds();
  view->SetPosition(aX, aY);

  // only do damage control if the view is visible

  if ((aX != oldPt.x) || (aY != oldPt.y)) {
    if (view->GetVisibility() != nsViewVisibility_kHide) {
      nsView* parentView = view->GetParent();
      UpdateView(parentView, oldArea, NS_VMREFRESH_NO_SYNC);
      UpdateView(parentView, view->GetBounds(), NS_VMREFRESH_NO_SYNC);
    }
  }
  return NS_OK;
}

void nsViewManager::InvalidateHorizontalBandDifference(nsView *aView, const nsRect& aRect, const nsRect& aCutOut,
  PRUint32 aUpdateFlags, nscoord aY1, nscoord aY2, PRBool aInCutOut) {
  nscoord height = aY2 - aY1;
  if (aRect.x < aCutOut.x) {
    nsRect r(aRect.x, aY1, aCutOut.x - aRect.x, height);
    UpdateView(aView, r, aUpdateFlags);
  }
  if (!aInCutOut && aCutOut.x < aCutOut.XMost()) {
    nsRect r(aCutOut.x, aY1, aCutOut.width, height);
    UpdateView(aView, r, aUpdateFlags);
  }
  if (aCutOut.XMost() < aRect.XMost()) {
    nsRect r(aCutOut.XMost(), aY1, aRect.XMost() - aCutOut.XMost(), height);
    UpdateView(aView, r, aUpdateFlags);
  }
}

void nsViewManager::InvalidateRectDifference(nsView *aView, const nsRect& aRect, const nsRect& aCutOut,
  PRUint32 aUpdateFlags) {
  if (aRect.y < aCutOut.y) {
    InvalidateHorizontalBandDifference(aView, aRect, aCutOut, aUpdateFlags, aRect.y, aCutOut.y, PR_FALSE);
  }
  if (aCutOut.y < aCutOut.YMost()) {
    InvalidateHorizontalBandDifference(aView, aRect, aCutOut, aUpdateFlags, aCutOut.y, aCutOut.YMost(), PR_TRUE);
  }
  if (aCutOut.YMost() < aRect.YMost()) {
    InvalidateHorizontalBandDifference(aView, aRect, aCutOut, aUpdateFlags, aCutOut.YMost(), aRect.YMost(), PR_FALSE);
  }
}

NS_IMETHODIMP nsViewManager::ResizeView(nsIView *aView, const nsRect &aRect, PRBool aRepaintExposedAreaOnly)
{
  nsView* view = NS_STATIC_CAST(nsView*, aView);
  nsRect oldDimensions;

  view->GetDimensions(oldDimensions);
  if (oldDimensions != aRect) {
    nsView* parentView = view->GetParent();
    if (parentView == nsnull)
      parentView = view;

    // resize the view.
    // Prevent Invalidation of hidden views 
    if (view->GetVisibility() == nsViewVisibility_kHide) {  
      view->SetDimensions(aRect, PR_FALSE);
    } else {
      if (!aRepaintExposedAreaOnly) {
        //Invalidate the union of the old and new size
        view->SetDimensions(aRect, PR_TRUE);

        UpdateView(view, aRect, NS_VMREFRESH_NO_SYNC);
        view->ConvertToParentCoords(&oldDimensions.x, &oldDimensions.y);
        UpdateView(parentView, oldDimensions, NS_VMREFRESH_NO_SYNC);
      } else {
        view->SetDimensions(aRect, PR_TRUE);

        InvalidateRectDifference(view, aRect, oldDimensions, NS_VMREFRESH_NO_SYNC);
        nsRect r = aRect;
        view->ConvertToParentCoords(&r.x, &r.y);
        view->ConvertToParentCoords(&oldDimensions.x, &oldDimensions.y);
        InvalidateRectDifference(parentView, oldDimensions, r, NS_VMREFRESH_NO_SYNC);
      } 
    }
  }

  // Note that if layout resizes the view and the view has a custom clip
  // region set, then we expect layout to update the clip region too. Thus
  // in the case where mClipRect has been optimized away to just be a null
  // pointer, and this resize is implicitly changing the clip rect, it's OK
  // because layout will change it back again if necessary.

  return NS_OK;
}

NS_IMETHODIMP nsViewManager::SetViewChildClipRegion(nsIView *aView, const nsRegion *aRegion)
{
  nsView* view = NS_STATIC_CAST(nsView*, aView);
 
  NS_ASSERTION(!(nsnull == view), "no view");

  const nsRect* oldClipRect = view->GetClipChildrenToRect();

  nsRect newClipRectStorage = view->GetDimensions();
  nsRect* newClipRect = nsnull;
  if (aRegion) {
    newClipRectStorage = aRegion->GetBounds();
    newClipRect = &newClipRectStorage;
  }

  if ((oldClipRect != nsnull) == (newClipRect != nsnull)
      && (!newClipRect || *newClipRect == *oldClipRect)) {
    return NS_OK;
  }
  nsRect oldClipRectStorage =
    oldClipRect ? *oldClipRect : view->GetDimensions();
 
  // Update the view properties
  view->SetClipChildrenToRect(newClipRect);

  if (IsViewInserted(view)) {
    // Invalidate changed areas
    // Paint (new - old) in the current view
    InvalidateRectDifference(view, newClipRectStorage, oldClipRectStorage, NS_VMREFRESH_NO_SYNC);
    // Paint (old - new) in the parent view, since it'll be clipped out of the current view
    nsView* parent = view->GetParent();
    if (parent) {
      oldClipRectStorage += view->GetPosition();
      newClipRectStorage += view->GetPosition();
      InvalidateRectDifference(parent, oldClipRectStorage, newClipRectStorage, NS_VMREFRESH_NO_SYNC);
    }
  }

  return NS_OK;
}

/*
  Returns PR_TRUE if and only if aView is a (possibly indirect) child of aAncestor.
*/
static PRBool IsAncestorOf(const nsView* aAncestor, const nsView* aView) 
{
  while (nsnull != aView) {
    aView = aView->GetParent();
    if (aView == aAncestor) {
      return PR_TRUE;
    }
  }
  return PR_FALSE;
}

/*
  This function returns TRUE only if we are sure that scrolling
  aView's widget and moving its child widgets, followed by
  UpdateViewAfterScroll, will result in correct painting (i.e. the
  same results as just invalidating the entire view). If we're not
  sure then we return FALSE to cause a full update of the view's area.

  The way we check this is quite subtle, because there are all sorts
  of complicated things that can happen.

  Conceptually what we do is compute the display list for the "after
  scrolling" situation and compare it to a translation of the display
  list for the "before scrolling" situation.  If the two lists are
  equal then we return TRUE.

  We could implement this directly, but that would be rather
  complex. In particular it's hard to build the display list for the
  "before scrolling" situation since this function is called after
  scrolling. So instead we just build the "after scrolling" display
  list and do some analysis of it, making some approximations along
  the way.

  Display list elements for aView's descendants will always be the
  same "before" (plus translation) and "after", because they get
  scrolled by the same amount as the translation. Display list
  elements for other views will be in different positions "before"
  (plus translation) and "after" because they don't get
  scrolled. These elements are the ones that force us to return
  PR_FALSE. Unfortunately we can't just scan the "after" display list
  and ensure no elements are not descendants of aView: there could
  have been some non-aView-descendant which appeared in the "before"
  list but does not show up in the "after" list because it ended up
  completely hidden by some opaque aView-descendant.

  So here's what we have to do: we compute an "after" display list but
  before performing the optimization pass to eliminate completely
  covered views, we mark all aView-descendant display list elements as
  transparent. Thus we can be sure that any non-aView-descendant
  display list elements that would have shown up in the translated "before"
  list will still show up in the "after" list (since the only views which
  can cover them are non-aView-descendants, which haven't moved). Then
  we check the final display list to make sure only aView-descendant
  display list elements are included.

  NOTE: We also scan the "after" display list to find views whose contents
  depend on their scroll position (e.g., CSS attachment-fixed backgrounds),
  which are flagged with NS_VIEW_FLAG_DONT_BITBLT. If any are found, we return
  PR_FALSE.

  XXX Post-1.0 we should consider instead of returning a boolean,
  actually computing a rectangle or region which can be safely
  scrolled with bitblt.  This would be the area which is aView's
  rectangle minus the area covered by any non-aView-descendant views
  in the translated "before" or "after" lists. Then we could scroll
  that area and explicitly invalidate the rest. This would give us
  high performance scrolling even in the presence of overlapping
  content and eliminate the need for native widgets for fixed position
  elements.
*/
PRBool nsViewManager::CanScrollWithBitBlt(nsView* aView)
{
  NS_ASSERTION(!mPainting, "View manager shouldn't be scrolling during a paint");
  if (mPainting) {
    return PR_FALSE; // do the safe thing
  }

  nsRect r = aView->GetClippedRect();
  // Only check the area that intersects the view's non clipped rectangle
  if (r.IsEmpty()) {
    return PR_TRUE; // nothing to scroll
  }

  nsAutoVoidArray displayList;
  BuildDisplayList(aView, r, PR_FALSE, PR_FALSE, &displayList);

  PRInt32 i;
  for (i = 0; i < displayList.Count(); i++) {
    DisplayListElement2* element = NS_STATIC_CAST(DisplayListElement2*, displayList.ElementAt(i));
    if ((element->mFlags & VIEW_RENDERED) != 0) {
      if (IsAncestorOf(aView, element->mView)) {
        element->mFlags |= (VIEW_ISSCROLLED | VIEW_TRANSPARENT);
      }
    }
  }

  nsRect finalTransparentRect;

  // We DON'T use AddCoveringWidgetsToOpaqueRegion here. Our child widgets are going to be moved
  // as if they were scrolled, so we need to examine the display list elements that might be covered by
  // child widgets.

  // However, we do want to ignore areas that are covered by widgets which have not moved.
  // Unfortunately figuring out that area is not easy, because we don't yet trust the native
  // widget layer to tell us the correct z-order of native widgets.
  // We still have to handle at least one case well:
  // widgets for fixed-position elements when we are scrolling the root scrollable (or something inside
  // the root scrollable) are on top.
  nsRegion opaqueRegion;
  if (mRootScrollable != nsnull) {
    const nsIView* scrollableClipView;
    mRootScrollable->GetClipView(&scrollableClipView);
    if (IsAncestorOf(NS_STATIC_CAST(const nsView*, scrollableClipView), aView)) {
      // add areas of fixed views to the opaque area.
      // This is a bit of a hack. We should not be doing special case processing for fixed views.
      nsView* fixedView = mRootView->GetFirstChild();
      while (fixedView != nsnull) {
        if (fixedView->GetZParent() != nsnull && fixedView->GetZIndex() >= 0) {
          opaqueRegion.Or(opaqueRegion, fixedView->GetBounds());
        }
        fixedView = fixedView->GetNextSibling();
      }

      // get the region into the coordinates of aView
      nscoord deltaX = 0, deltaY = 0;
      for (nsView* v = aView; v; v = v->GetParent()) {
        v->ConvertToParentCoords(&deltaX, &deltaY);
      }
      opaqueRegion.MoveBy(-deltaX, -deltaY);
    }
  }

  // We DO need to use OptimizeDisplayList here to eliminate views
  // that are covered by views we know are opaque. Typically aView's
  // scrolled view is opaque and we want to eliminate views behind it,
  // such as aView itself, that aren't being moved and would otherwise
  // cause us to decide not to blit.  Note that if for some view,
  // view->HasUniformBackground(), that's also sufficient to ignore
  // views behind 'view'; we've been promised that they produce only a
  // uniform background, which is still blittable. So we can treat
  // 'view' as opaque.

  // (Note that it's possible for aView's parent to actually be in
  // front of aView (if aView has a negative z-index) but if so, this
  // code still does the right thing. Yay for the display list based
  // approach!)

  OptimizeDisplayList(&displayList, nsRegion(r), finalTransparentRect, opaqueRegion, PR_TRUE);

  PRBool anyUnscrolledViews = PR_FALSE;
  PRBool anyUnblittableViews = PR_FALSE;

  for (i = 0; i < displayList.Count(); i++) {
    DisplayListElement2* element = NS_STATIC_CAST(DisplayListElement2*, displayList.ElementAt(i));
    if ((element->mFlags & VIEW_RENDERED) != 0) {
      if ((element->mFlags & VIEW_ISSCROLLED) == 0 && element->mView != aView) {
        anyUnscrolledViews = PR_TRUE;
      } else if ((element->mView->GetViewFlags() & NS_VIEW_FLAG_DONT_BITBLT) != 0) {
        anyUnblittableViews = PR_TRUE;
      }
    }
      
    delete element;
  }

  return !anyUnscrolledViews && !anyUnblittableViews;
}

NS_IMETHODIMP nsViewManager::SetViewBitBltEnabled(nsIView *aView, PRBool aEnable)
{
  nsView* view = NS_STATIC_CAST(nsView*, aView);

  NS_ASSERTION(!(nsnull == view), "no view");

  if (aEnable) {
    view->SetViewFlags(view->GetViewFlags() & ~NS_VIEW_FLAG_DONT_BITBLT);
  } else {
    view->SetViewFlags(view->GetViewFlags() | NS_VIEW_FLAG_DONT_BITBLT);
  }

  return NS_OK;
}

NS_IMETHODIMP nsViewManager::SetViewCheckChildEvents(nsIView *aView, PRBool aEnable)
{
  nsView* view = NS_STATIC_CAST(nsView*, aView);

  NS_ASSERTION(!(nsnull == view), "no view");

  if (aEnable) {
    view->SetViewFlags(view->GetViewFlags() & ~NS_VIEW_FLAG_DONT_CHECK_CHILDREN);
  } else {
    view->SetViewFlags(view->GetViewFlags() | NS_VIEW_FLAG_DONT_CHECK_CHILDREN);
  }

  return NS_OK;
}

NS_IMETHODIMP nsViewManager::SetViewFloating(nsIView *aView, PRBool aFloating)
{
  nsView* view = NS_STATIC_CAST(nsView*, aView);

  NS_ASSERTION(!(nsnull == view), "no view");

  view->SetFloating(aFloating);

  return NS_OK;
}

NS_IMETHODIMP nsViewManager::SetViewVisibility(nsIView *aView, nsViewVisibility aVisible)
{
  nsView* view = NS_STATIC_CAST(nsView*, aView);

  if (aVisible != view->GetVisibility()) {
    view->SetVisibility(aVisible);

    if (IsViewInserted(view)) {
      if (!view->HasWidget()) {
        if (nsViewVisibility_kHide == aVisible) {
          nsView* parentView = view->GetParent();
          if (parentView) {
            UpdateView(parentView, view->GetBounds(), NS_VMREFRESH_NO_SYNC);
          }
        }
        else {
          UpdateView(view, NS_VMREFRESH_NO_SYNC);
        }
      }
    }
  }
  return NS_OK;
}

PRBool nsViewManager::IsViewInserted(nsView *aView)
{
  if (mRootView == aView) {
    return PR_TRUE;
  } else if (aView->GetParent() == nsnull) {
    return PR_FALSE;
  } else {
    nsView* view = aView->GetParent()->GetFirstChild();
    while (view != nsnull) {
      if (view == aView) {
        return PR_TRUE;
      }        
      view = view->GetNextSibling();
    }
    return PR_FALSE;
  }
}

NS_IMETHODIMP nsViewManager::SetViewZIndex(nsIView *aView, PRBool aAutoZIndex, PRInt32 aZIndex, PRBool aTopMost)
{
  nsView* view = NS_STATIC_CAST(nsView*, aView);
  nsresult  rv = NS_OK;

  NS_ASSERTION((view != nsnull), "no view");

  // don't allow the root view's z-index to be changed. It should always be zero.
  // This could be removed and replaced with a style rule, or just removed altogether, with interesting consequences
  if (aView == mRootView) {
    return rv;
  }

  PRBool oldTopMost = view->IsTopMost();
  PRBool oldIsAuto = view->GetZIndexIsAuto();

  if (aAutoZIndex) {
    aZIndex = 0;
  }

  PRInt32 oldidx = view->GetZIndex();
  view->SetZIndex(aAutoZIndex, aZIndex, aTopMost);

  if (CompareZIndex(oldidx, oldTopMost, oldIsAuto,
                    aZIndex, aTopMost, aAutoZIndex) != 0) {
    UpdateView(view, NS_VMREFRESH_NO_SYNC);
  }

  // Native widgets ultimately just can't deal with the awesome power
  // of CSS2 z-index. However, we set the z-index on the widget anyway
  // because in many simple common cases the widgets do end up in the
  // right order. Even if they don't, we'll still render correctly as
  // long as there are no plugins around (although there may be more
  // flickering and other perf issues than if the widgets were in a
  // good order).
  if (view->HasWidget()) {
    view->GetWidget()->SetZIndex(aZIndex);
  }

  nsZPlaceholderView* zParentView = view->GetZParent();
  if (nsnull != zParentView) {
    SetViewZIndex(zParentView, aAutoZIndex, aZIndex, aTopMost);
  }

  return rv;
}

NS_IMETHODIMP nsViewManager::SetViewContentTransparency(nsIView *aView, PRBool aTransparent)
{
  nsView* view = NS_STATIC_CAST(nsView*, aView);

  if (view->IsTransparent() != aTransparent) {
    view->SetContentTransparency(aTransparent);

    if (IsViewInserted(view)) {
      UpdateView(view, NS_VMREFRESH_NO_SYNC);
    }
  }

  return NS_OK;
}

NS_IMETHODIMP nsViewManager::SetViewOpacity(nsIView *aView, float aOpacity)
{
  nsView* view = NS_STATIC_CAST(nsView*, aView);

  if (view->GetOpacity() != aOpacity)
    {
      view->SetOpacity(aOpacity);

      if (IsViewInserted(view)) {
        UpdateView(view, NS_VMREFRESH_NO_SYNC);
      }
    }

  return NS_OK;
}

NS_IMETHODIMP nsViewManager::SetViewObserver(nsIViewObserver *aObserver)
{
  mObserver = aObserver;
  return NS_OK;
}

NS_IMETHODIMP nsViewManager::GetViewObserver(nsIViewObserver *&aObserver)
{
  if (nsnull != mObserver) {
    aObserver = mObserver;
    NS_ADDREF(mObserver);
    return NS_OK;
  } else
    return NS_ERROR_NO_INTERFACE;
}

NS_IMETHODIMP nsViewManager::GetDeviceContext(nsIDeviceContext *&aContext)
{
  NS_IF_ADDREF(mContext);
  aContext = mContext;
  return NS_OK;
}

void nsViewManager::GetMaxWidgetBounds(nsRect& aMaxWidgetBounds) const
{
  // Go through the list of viewmanagers and get the maximum width and 
  // height of their widgets
  aMaxWidgetBounds.width = 0;
  aMaxWidgetBounds.height = 0;
  PRInt32 index = 0;
  for (index = 0; index < mVMCount; index++) {

    nsViewManager* vm = (nsViewManager*)gViewManagers->ElementAt(index);
    nsCOMPtr<nsIWidget> rootWidget;

    if(NS_SUCCEEDED(vm->GetWidget(getter_AddRefs(rootWidget))) && rootWidget)
      {
        nsRect widgetBounds;
        rootWidget->GetBounds(widgetBounds);
        aMaxWidgetBounds.width = PR_MAX(aMaxWidgetBounds.width, widgetBounds.width);
        aMaxWidgetBounds.height = PR_MAX(aMaxWidgetBounds.height, widgetBounds.height);
      }
  }

  //   printf("WIDGET BOUNDS %d %d\n", aMaxWidgetBounds.width, aMaxWidgetBounds.height);
}

PRInt32 nsViewManager::GetViewManagerCount()
{
  return mVMCount;
}

const nsVoidArray* nsViewManager::GetViewManagerArray() 
{
  return gViewManagers;
}

nsIRenderingContext * nsViewManager::CreateRenderingContext(nsView &aView)
{
  nsView              *par = &aView;
  nsIWidget*          win;
  nsIRenderingContext *cx = nsnull;
  nscoord             ax = 0, ay = 0;

  do
    {
      win = par->GetWidget();
      if (win)
        break;

      //get absolute coordinates of view, but don't
      //add in view pos since the first thing you ever
      //need to do when painting a view is to translate
      //the rendering context by the views pos and other parts
      //of the code do this for us...

      if (par != &aView)
        {
          par->ConvertToParentCoords(&ax, &ay);
        }

      par = par->GetParent();
    }
  while (nsnull != par);

  if (nsnull != win)
    {
      mContext->CreateRenderingContext(&aView, cx);

      if (nsnull != cx)
        cx->Translate(ax, ay);
    }

  return cx;
}

void nsViewManager::AddRectToDirtyRegion(nsView* aView, const nsRect &aRect) const
{
  // Find a view with an associated widget. We'll transform this rect from the
  // current view's coordinate system to a "heavyweight" parent view, then convert
  // the rect to pixel coordinates, and accumulate the rect into that view's dirty region.
  nsView* widgetView = GetWidgetView(aView);
  if (widgetView != nsnull) {
    nsRect widgetRect = aRect;
    ViewToWidget(aView, widgetView, widgetRect);

    // Get the dirty region associated with the widget view
    nsCOMPtr<nsIRegion> dirtyRegion;
    if (NS_SUCCEEDED(widgetView->GetDirtyRegion(*getter_AddRefs(dirtyRegion)))) {
      // add this rect to the widget view's dirty region.
      dirtyRegion->Union(widgetRect.x, widgetRect.y, widgetRect.width, widgetRect.height);
    }
  }
}

NS_IMETHODIMP nsViewManager::DisableRefresh(void)
{
  if (mUpdateBatchCnt > 0)
    return NS_OK;

  mRefreshEnabled = PR_FALSE;
  return NS_OK;
}

NS_IMETHODIMP nsViewManager::EnableRefresh(PRUint32 aUpdateFlags)
{
  if (mUpdateBatchCnt > 0)
    return NS_OK;

  mRefreshEnabled = PR_TRUE;

  if (aUpdateFlags & NS_VMREFRESH_IMMEDIATE) {
    ProcessPendingUpdates(mRootView);
    mHasPendingInvalidates = PR_FALSE;
    Composite();
  } else {
    PostInvalidateEvent();
  }

  return NS_OK;
}

NS_IMETHODIMP nsViewManager::BeginUpdateViewBatch(void)
{
  nsresult result = NS_OK;
  
  if (mUpdateBatchCnt == 0)
    result = DisableRefresh();

  if (NS_SUCCEEDED(result))
    ++mUpdateBatchCnt;

  return result;
}

NS_IMETHODIMP nsViewManager::EndUpdateViewBatch(PRUint32 aUpdateFlags)
{
  nsresult result = NS_OK;

  --mUpdateBatchCnt;

  NS_ASSERTION(mUpdateBatchCnt >= 0, "Invalid batch count!");

  if (mUpdateBatchCnt < 0)
    {
      mUpdateBatchCnt = 0;
      return NS_ERROR_FAILURE;
    }

  if (mUpdateBatchCnt == 0)
    result = EnableRefresh(aUpdateFlags);

  return result;
}

NS_IMETHODIMP nsViewManager::SetRootScrollableView(nsIScrollableView *aScrollable)
{
  if (mRootScrollable) {
    NS_STATIC_CAST(nsScrollPortView*, mRootScrollable)->
      SetClipPlaceholdersToBounds(PR_FALSE);
  }
  mRootScrollable = aScrollable;
  if (mRootScrollable) {
    NS_STATIC_CAST(nsScrollPortView*, mRootScrollable)->
      SetClipPlaceholdersToBounds(PR_TRUE);
  }
  return NS_OK;
}

NS_IMETHODIMP nsViewManager::GetRootScrollableView(nsIScrollableView **aScrollable)
{
  *aScrollable = mRootScrollable;
  return NS_OK;
}

NS_IMETHODIMP nsViewManager::Display(nsIView* aView, nscoord aX, nscoord aY, const nsRect& aClipRect)
{
  nsView              *view = NS_STATIC_CAST(nsView*, aView);
  nsIRenderingContext *localcx = nsnull;

  if (PR_FALSE == mRefreshEnabled)
    return NS_OK;

  NS_ASSERTION(!(PR_TRUE == mPainting), "recursive painting not permitted");

  mPainting = PR_TRUE;

  mContext->CreateRenderingContext(localcx);

  //couldn't get rendering context. this is ok if at startup
  if (nsnull == localcx)
    {
      mPainting = PR_FALSE;
      return NS_ERROR_FAILURE;
    }

  nsRect trect = view->GetBounds();
  view->ConvertFromParentCoords(&trect.x, &trect.y);

  localcx->Translate(aX, aY);

  PRBool isClipped;
  localcx->SetClipRect(aClipRect, nsClipCombine_kReplace, isClipped);

  // Paint the view. The clipping rect was set above set don't clip again.
  //aView->Paint(*localcx, trect, NS_VIEW_FLAG_CLIP_SET, result);
  nsAutoVoidArray displayList;
  BuildRenderingDisplayList(view, nsRegion(trect), &displayList);
  RenderViews(view, *localcx, nsRegion(trect), PR_FALSE, displayList);

  NS_RELEASE(localcx);

  mPainting = PR_FALSE;

  return NS_OK;

}

NS_IMETHODIMP nsViewManager::AddCompositeListener(nsICompositeListener* aListener)
{
  if (nsnull == mCompositeListeners) {
    nsresult rv = NS_NewISupportsArray(&mCompositeListeners);
    if (NS_FAILED(rv))
      return rv;
  }
  return mCompositeListeners->AppendElement(aListener);
}

NS_IMETHODIMP nsViewManager::RemoveCompositeListener(nsICompositeListener* aListener)
{
  if (nsnull != mCompositeListeners) {
    return mCompositeListeners->RemoveElement(aListener);
  }
  return NS_ERROR_FAILURE;
}

NS_IMETHODIMP nsViewManager::GetWidgetForView(nsIView *aView, nsIWidget **aWidget)
{
  nsView *view = NS_STATIC_CAST(nsView*, aView);

  while (view && !view->HasWidget()) {
    view = view->GetParent();
  }

  if (view) {
    // Widget was found in the view hierarchy
    *aWidget = view->GetWidget();
    NS_ADDREF(*aWidget);
  } else {
    // No widget was found in the view hierachy, so use try to use the mRootWindow
    if (nsnull != mRootWindow) {
      NS_ASSERTION(this == view->GetViewManager(),
                   "Must use the view instance's view manager when calling GetWidgetForView");
      *aWidget = mRootWindow;
      NS_ADDREF(mRootWindow);
    } else {
      *aWidget = nsnull;
    }
  }

  return NS_OK;
}


NS_IMETHODIMP nsViewManager::GetWidget(nsIWidget **aWidget)
{
  NS_IF_ADDREF(mRootWindow);
  *aWidget = mRootWindow;
  return NS_OK;
}

NS_IMETHODIMP nsViewManager::ForceUpdate()
{
  if (mRootWindow)
    mRootWindow->Update();
  return NS_OK;
}

static nsresult EnsureZTreeNodeCreated(nsView* aView, DisplayZTreeNode* &aNode) {
  if (nsnull == aNode) {
    aNode = new DisplayZTreeNode;

    if (nsnull == aNode) {
      return NS_ERROR_OUT_OF_MEMORY;
    }
    aNode->mView = aView;
    aNode->mDisplayElement = nsnull;
    aNode->mZChild = nsnull;
    aNode->mZSibling = nsnull;
  }
  return NS_OK;
}

/**
 * XXX this needs major simplification and cleanup
 * @param aView the view are visiting to create display list element(s) for
 * @param aReparentedViewsPresent unused, always PR_FALSE
 * @param aResult insert display list elements under here
 * @param aOriginX/aOriginY the offset from the origin of aTopView
 * to the origin of the view that is being painted (aRealView)
 * @param aRealView the view that is being painted
 * @param aDamageRect the rect that needs to be painted, relative to the origin
 * of aRealView
 * @param aTopView the displayRoot, the root of the collection of views
 * to be painted
 * @param aX/aY the offset from aTopView to the origin of the parent of aView
 * @param aPaintFloats PR_TRUE if we should paint floating views, PR_FALSE
 * if we should avoid descending into any floating views
 * @param aEventProcessing PR_TRUE if we intend to do event processing with
 * this display list
 */
PRBool nsViewManager::CreateDisplayList(nsView *aView, PRBool aReparentedViewsPresent,
                                        DisplayZTreeNode* &aResult,
                                        nscoord aOriginX, nscoord aOriginY, nsView *aRealView,
                                        const nsRect *aDamageRect, nsView *aTopView,
                                        nscoord aX, nscoord aY, PRBool aPaintFloats,
                                        PRBool aEventProcessing)
{
  PRBool retval = PR_FALSE;

  aResult = nsnull;

  NS_ASSERTION((aView != nsnull), "no view");

  if (nsViewVisibility_kHide == aView->GetVisibility()) {
    // bail out if the view is marked invisible; all children are invisible
    return retval;
  }

  nsRect bounds = aView->GetBounds();
  nsPoint pos = aView->GetPosition();

  // -> to global coordinates (relative to aTopView)
  bounds.x += aX;
  bounds.y += aY;
  pos.MoveBy(aX, aY);

  // does this view clip all its children?
  PRBool isClipView =
    (aView->GetClipChildrenToBounds(PR_FALSE)
     && !(aView->GetViewFlags() & NS_VIEW_FLAG_CONTAINS_PLACEHOLDER))
    || aView->GetClipChildrenToBounds(PR_TRUE);
  PRBool overlap;
  nsRect irect;
    
  // -> to refresh-frame coordinates (relative to aRealView)
  bounds.x -= aOriginX;
  bounds.y -= aOriginY;
  if (aDamageRect) {
    overlap = irect.IntersectRect(bounds, *aDamageRect);
    if (isClipView) {
      aDamageRect = &irect;
    }
    if (aEventProcessing && aRealView == aView) {
      // Always deliver an event somewhere, at least to the top-level target.
      // There may be mouse capturing going on.
      overlap = PR_TRUE;
    }
  }
  else
    overlap = PR_TRUE;

  // -> to global coordinates (relative to aTopView)
  bounds.x += aOriginX;
  bounds.y += aOriginY;

  // if there's no overlap between the dirty area and the bounds of
  // the view, we should be able to ignore the view and all its
  // children. Unfortunately there is the possibility of reparenting:
  // some other view in the tree might want to be reparented to one of
  // our children, and that view might lie outside our
  // bounds. Typically we need to go ahead and add this view and its
  // children to the ZTree in case someone wants to reparent into it.
  //
  // We can avoid this in two cases: if we clip our children to our
  // bounds, then even if a view is reparented under us, none of its
  // visible area can lie outside our bounds, so it can't intersect
  // the dirty area.  Also, if we don't contain any placeholder views,
  // then there is no way for anyone to reparent below us.
  if (!overlap && !(aView->GetViewFlags() & NS_VIEW_FLAG_CONTAINS_PLACEHOLDER)) {
    return PR_FALSE;
  }

  // Don't paint floating views unless the root view being painted is a floating view.
  // This is important because we may be asked to paint
  // a window that's behind a transient float; in this case we must paint the real window
  // contents, not the float contents (bug 63496)
  if (!aPaintFloats && aView->GetFloating()) {
    return PR_FALSE;
  }

  PRBool anyChildren = aView->GetFirstChild() != nsnull;

  if (aEventProcessing
      && (aView->GetViewFlags() & NS_VIEW_FLAG_DONT_CHECK_CHILDREN) != 0) {
    anyChildren = PR_FALSE;
  }

  PRBool hasFilter = aView->GetOpacity() != 1.0f;
  if (hasFilter) {
    // -> to refresh-frame coordinates (relative to aRealView)
    bounds.x -= aOriginX;
    bounds.y -= aOriginY;
    
    // Add POP first because the z-tree is in reverse order
    retval = AddToDisplayList(aView, aResult, bounds, bounds,
                              POP_FILTER, aX - aOriginX, aY - aOriginY, PR_TRUE);