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
|
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim:set ts=2 sw=2 sts=2 ci et: */
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#include "ErrorList.h"
#include "mozilla/MathAlgorithms.h"
// Local includes
#include "AppWindow.h"
#include <algorithm>
// Helper classes
#include "nsPrintfCString.h"
#include "nsString.h"
#include "nsWidgetsCID.h"
#include "nsThreadUtils.h"
#include "nsNetCID.h"
#include "nsQueryObject.h"
#include "mozilla/ProfilerLabels.h"
#include "mozilla/Sprintf.h"
#include "mozilla/Try.h"
// Interfaces needed to be included
#include "nsGlobalWindowOuter.h"
#include "nsIAppShell.h"
#include "nsIAppShellService.h"
#include "nsIDocumentViewer.h"
#include "mozilla/dom/Document.h"
#include "mozilla/dom/CanonicalBrowsingContext.h"
#include "nsPIDOMWindow.h"
#include "nsScreen.h"
#include "nsIInterfaceRequestor.h"
#include "nsIInterfaceRequestorUtils.h"
#include "nsIIOService.h"
#include "nsIObserverService.h"
#include "nsIOpenWindowInfo.h"
#include "nsIWindowMediator.h"
#include "nsIScreenManager.h"
#include "nsIScreen.h"
#include "nsIWindowWatcher.h"
#include "nsIURI.h"
#include "nsAppShellCID.h"
#include "nsReadableUtils.h"
#include "nsStyleConsts.h"
#include "nsPresContext.h"
#include "nsContentUtils.h"
#include "nsXULTooltipListener.h"
#include "nsXULPopupManager.h"
#include "nsFocusManager.h"
#include "nsContentList.h"
#include "nsIDOMWindowUtils.h"
#include "nsServiceManagerUtils.h"
#include "prenv.h"
#include "mozilla/AppShutdown.h"
#include "mozilla/AutoRestore.h"
#include "mozilla/Preferences.h"
#include "mozilla/PresShell.h"
#include "mozilla/Services.h"
#include "mozilla/SpinEventLoopUntil.h"
#include "mozilla/StaticPrefs_browser.h"
#include "mozilla/dom/BarProps.h"
#include "mozilla/dom/DOMRect.h"
#include "mozilla/dom/Element.h"
#include "mozilla/dom/Event.h"
#include "mozilla/dom/ScriptSettings.h"
#include "mozilla/dom/BrowserHost.h"
#include "mozilla/dom/BrowserParent.h"
#include "mozilla/dom/LoadURIOptionsBinding.h"
#include "mozilla/intl/LocaleService.h"
#include "mozilla/EventDispatcher.h"
#ifdef XP_WIN
# include "mozilla/PreXULSkeletonUI.h"
# include "mozilla/WindowsVersion.h"
# include "nsIWindowsUIUtils.h"
#endif
#include "mozilla/dom/DocumentL10n.h"
#if defined(XP_MACOSX) || defined(MOZ_WIDGET_GTK)
# include "mozilla/widget/NativeMenuSupport.h"
# define USE_NATIVE_MENUS
#endif
#define SIZEMODE_NORMAL u"normal"_ns
#define SIZEMODE_MAXIMIZED u"maximized"_ns
#define SIZEMODE_MINIMIZED u"minimized"_ns
#define SIZEMODE_FULLSCREEN u"fullscreen"_ns
#define SIZE_PERSISTENCE_TIMEOUT 500 // msec
//*****************************************************************************
//*** AppWindow: Object Management
//*****************************************************************************
namespace mozilla {
using dom::AutoNoJSAPI;
using dom::BrowserHost;
using dom::BrowsingContext;
using dom::Document;
using dom::DocumentL10n;
using dom::Element;
using dom::EventTarget;
using dom::LoadURIOptions;
using dom::Promise;
AppWindow::AppWindow(uint32_t aChromeFlags)
: mChromeTreeOwner(nullptr),
mContentTreeOwner(nullptr),
mPrimaryContentTreeOwner(nullptr),
mModalStatus(NS_OK),
mFullscreenChangeState(FullscreenChangeState::NotChanging),
mContinueModalLoop(false),
mDebuting(false),
mChromeLoaded(false),
mSizingShellFromXUL(false),
mShowAfterLoad(false),
mIntrinsicallySized(false),
mCenterAfterLoad(false),
mIsHiddenWindow(false),
mLockedUntilChromeLoad(false),
mIgnoreXULSize(false),
mIgnoreXULPosition(false),
mChromeFlagsFrozen(false),
mIgnoreXULSizeMode(false),
mDestroying(false),
mRegistered(false),
mDominantClientSize(false),
mChromeFlags(aChromeFlags),
mWidgetListenerDelegate(this) {}
AppWindow::~AppWindow() {
if (mSPTimer) {
mSPTimer->Cancel();
mSPTimer = nullptr;
}
Destroy();
}
//*****************************************************************************
// AppWindow::nsISupports
//*****************************************************************************
NS_IMPL_ADDREF(AppWindow)
NS_IMPL_RELEASE(AppWindow)
NS_INTERFACE_MAP_BEGIN(AppWindow)
NS_INTERFACE_MAP_ENTRY_AMBIGUOUS(nsISupports, nsIAppWindow)
NS_INTERFACE_MAP_ENTRY(nsIAppWindow)
NS_INTERFACE_MAP_ENTRY(nsIBaseWindow)
NS_INTERFACE_MAP_ENTRY(nsIInterfaceRequestor)
NS_INTERFACE_MAP_ENTRY(nsISupportsWeakReference)
NS_INTERFACE_MAP_ENTRY(nsIWebProgressListener)
NS_INTERFACE_MAP_ENTRY_CONCRETE(AppWindow)
NS_INTERFACE_MAP_END
nsresult AppWindow::Initialize(nsIAppWindow* aParent, nsIAppWindow* aOpener,
int32_t aInitialWidth, int32_t aInitialHeight,
bool aIsHiddenWindow,
widget::InitData& widgetInitData) {
nsresult rv;
nsCOMPtr<nsIWidget> parentWidget;
mIsHiddenWindow = aIsHiddenWindow;
DesktopIntPoint initialPos;
nsCOMPtr<nsIBaseWindow> base(do_QueryInterface(aOpener));
if (base) {
LayoutDeviceIntRect rect = base->GetPositionAndSize();
mOpenerScreenRect =
DesktopIntRect::Round(rect / base->DevicePixelsPerDesktopPixel());
if (!mOpenerScreenRect.IsEmpty()) {
initialPos = mOpenerScreenRect.TopLeft();
ConstrainToOpenerScreen(&initialPos.x.value, &initialPos.y.value);
}
}
// XXX: need to get the default window size from prefs...
// Doesn't come from prefs... will come from CSS/XUL/RDF
DesktopIntRect deskRect(initialPos,
DesktopIntSize(aInitialWidth, aInitialHeight));
// Create top level window
if (gfxPlatform::IsHeadless()) {
mWindow = nsIWidget::CreateHeadlessWidget();
} else {
mWindow = nsIWidget::CreateTopLevelWindow();
}
if (!mWindow) {
return NS_ERROR_FAILURE;
}
/* This next bit is troublesome. We carry two different versions of a pointer
to our parent window. One is the parent window's widget, which is passed
to our own widget. The other is a weak reference we keep here to our
parent AppWindow. The former is useful to the widget, and we can't
trust its treatment of the parent reference because they're platform-
specific. The latter is useful to this class.
A better implementation would be one in which the parent keeps strong
references to its children and closes them before it allows itself
to be closed. This would mimic the behaviour of OSes that support
top-level child windows in OSes that do not. Later.
*/
if (nsCOMPtr<nsIBaseWindow> parent = do_QueryInterface(aParent)) {
parentWidget = parent->GetMainWidget();
mParentWindow = do_GetWeakReference(aParent);
}
mWindow->SetWidgetListener(&mWidgetListenerDelegate);
rv = mWindow->Create(parentWidget.get(), // Parent nsIWidget
deskRect, // Widget dimensions
widgetInitData); // Widget initialization data
NS_ENSURE_SUCCESS(rv, rv);
LayoutDeviceIntRect r = mWindow->GetClientBounds();
// Match the default background color of content. Previously important on
// Windows, but no longer has any effect there.
mWindow->SetBackgroundColor(NS_RGB(255, 255, 255));
// All Chrome BCs exist within the same BrowsingContextGroup, so we don't need
// to pass in the opener window here. The opener is set later, if needed, by
// nsWindowWatcher.
RefPtr<BrowsingContext> browsingContext =
BrowsingContext::CreateIndependent(BrowsingContext::Type::Chrome, false);
// Create web shell
mDocShell = nsDocShell::Create(browsingContext);
NS_ENSURE_TRUE(mDocShell, NS_ERROR_FAILURE);
// Make sure to set the item type on the docshell _before_ calling
// InitWindow() so it knows what type it is.
NS_ENSURE_SUCCESS(EnsureChromeTreeOwner(), NS_ERROR_FAILURE);
mDocShell->SetTreeOwner(mChromeTreeOwner);
r.MoveTo(0, 0);
NS_ENSURE_SUCCESS(
mDocShell->InitWindow(mWindow, r.X(), r.Y(), r.Width(), r.Height()),
NS_ERROR_FAILURE);
// Attach a WebProgress listener.during initialization...
mDocShell->AddProgressListener(this, nsIWebProgress::NOTIFY_STATE_NETWORK);
mWindow->MaybeDispatchInitialFocusEvent();
return rv;
}
//*****************************************************************************
// AppWindow::nsIIntefaceRequestor
//*****************************************************************************
NS_IMETHODIMP AppWindow::GetInterface(const nsIID& aIID, void** aSink) {
nsresult rv;
NS_ENSURE_ARG_POINTER(aSink);
if (aIID.Equals(NS_GET_IID(nsIPrompt))) {
rv = EnsurePrompter();
if (NS_FAILED(rv)) return rv;
return mPrompter->QueryInterface(aIID, aSink);
}
if (aIID.Equals(NS_GET_IID(nsIAuthPrompt))) {
rv = EnsureAuthPrompter();
if (NS_FAILED(rv)) return rv;
return mAuthPrompter->QueryInterface(aIID, aSink);
}
if (aIID.Equals(NS_GET_IID(mozIDOMWindowProxy))) {
return GetWindowDOMWindow(reinterpret_cast<mozIDOMWindowProxy**>(aSink));
}
if (aIID.Equals(NS_GET_IID(nsIDOMWindow))) {
nsCOMPtr<mozIDOMWindowProxy> window = nullptr;
rv = GetWindowDOMWindow(getter_AddRefs(window));
nsCOMPtr<nsIDOMWindow> domWindow = do_QueryInterface(window);
domWindow.forget(aSink);
return rv;
}
if (aIID.Equals(NS_GET_IID(nsIWebBrowserChrome)) &&
NS_SUCCEEDED(EnsureContentTreeOwner()) &&
NS_SUCCEEDED(mContentTreeOwner->QueryInterface(aIID, aSink))) {
return NS_OK;
}
return QueryInterface(aIID, aSink);
}
//*****************************************************************************
// AppWindow::nsIAppWindow
//*****************************************************************************
NS_IMETHODIMP AppWindow::GetDocShell(nsIDocShell** aDocShell) {
NS_ENSURE_ARG_POINTER(aDocShell);
*aDocShell = mDocShell;
NS_IF_ADDREF(*aDocShell);
return NS_OK;
}
NS_IMETHODIMP AppWindow::GetChromeFlags(uint32_t* aChromeFlags) {
NS_ENSURE_ARG_POINTER(aChromeFlags);
*aChromeFlags = mChromeFlags;
return NS_OK;
}
NS_IMETHODIMP AppWindow::SetChromeFlags(uint32_t aChromeFlags) {
NS_ASSERTION(!mChromeFlagsFrozen,
"SetChromeFlags() after AssumeChromeFlagsAreFrozen()!");
mChromeFlags = aChromeFlags;
if (mChromeLoaded) {
ApplyChromeFlags();
}
return NS_OK;
}
NS_IMETHODIMP AppWindow::AssumeChromeFlagsAreFrozen() {
mChromeFlagsFrozen = true;
return NS_OK;
}
NS_IMETHODIMP AppWindow::SetIntrinsicallySized(bool aIntrinsicallySized) {
mIntrinsicallySized = aIntrinsicallySized;
return NS_OK;
}
NS_IMETHODIMP AppWindow::GetIntrinsicallySized(bool* aIntrinsicallySized) {
NS_ENSURE_ARG_POINTER(aIntrinsicallySized);
*aIntrinsicallySized = mIntrinsicallySized;
return NS_OK;
}
NS_IMETHODIMP AppWindow::GetPrimaryContentShell(
nsIDocShellTreeItem** aDocShellTreeItem) {
NS_ENSURE_ARG_POINTER(aDocShellTreeItem);
NS_IF_ADDREF(*aDocShellTreeItem = mPrimaryContentShell);
return NS_OK;
}
NS_IMETHODIMP
AppWindow::RemoteTabAdded(nsIRemoteTab* aTab, bool aPrimary) {
if (aPrimary) {
mPrimaryBrowserParent = aTab;
mPrimaryContentShell = nullptr;
} else if (mPrimaryBrowserParent == aTab) {
mPrimaryBrowserParent = nullptr;
}
return NS_OK;
}
NS_IMETHODIMP
AppWindow::RemoteTabRemoved(nsIRemoteTab* aTab) {
if (aTab == mPrimaryBrowserParent) {
mPrimaryBrowserParent = nullptr;
}
return NS_OK;
}
NS_IMETHODIMP
AppWindow::GetPrimaryRemoteTab(nsIRemoteTab** aTab) {
nsCOMPtr<nsIRemoteTab> tab = mPrimaryBrowserParent;
tab.forget(aTab);
return NS_OK;
}
NS_IMETHODIMP
AppWindow::GetPrimaryContentBrowsingContext(
mozilla::dom::BrowsingContext** aBc) {
if (mPrimaryBrowserParent) {
return mPrimaryBrowserParent->GetBrowsingContext(aBc);
}
if (mPrimaryContentShell) {
return mPrimaryContentShell->GetBrowsingContextXPCOM(aBc);
}
*aBc = nullptr;
return NS_OK;
}
static LayoutDeviceIntSize GetOuterToInnerSizeDifference(nsIWidget* aWindow) {
if (!aWindow) {
return LayoutDeviceIntSize();
}
return aWindow->NormalSizeModeClientToWindowSizeDifference();
}
static CSSIntSize GetOuterToInnerSizeDifferenceInCSSPixels(
nsIWidget* aWindow, CSSToLayoutDeviceScale aScale) {
LayoutDeviceIntSize devPixelSize = GetOuterToInnerSizeDifference(aWindow);
return RoundedToInt(devPixelSize / aScale);
}
NS_IMETHODIMP
AppWindow::GetOuterToInnerHeightDifferenceInCSSPixels(uint32_t* aResult) {
if (mWindow && mWindow->PersistClientBounds()) {
*aResult = 0;
} else {
*aResult = GetOuterToInnerSizeDifferenceInCSSPixels(
mWindow, UnscaledDevicePixelsPerCSSPixel())
.height;
}
return NS_OK;
}
NS_IMETHODIMP
AppWindow::GetOuterToInnerWidthDifferenceInCSSPixels(uint32_t* aResult) {
if (mWindow && mWindow->PersistClientBounds()) {
*aResult = 0;
} else {
*aResult = GetOuterToInnerSizeDifferenceInCSSPixels(
mWindow, UnscaledDevicePixelsPerCSSPixel())
.width;
}
return NS_OK;
}
nsTArray<RefPtr<mozilla::LiveResizeListener>>
AppWindow::GetLiveResizeListeners() {
nsTArray<RefPtr<mozilla::LiveResizeListener>> listeners;
if (mPrimaryBrowserParent) {
BrowserHost* host = BrowserHost::GetFrom(mPrimaryBrowserParent.get());
RefPtr<mozilla::LiveResizeListener> actor = host->GetActor();
if (actor) {
listeners.AppendElement(actor);
}
}
return listeners;
}
NS_IMETHODIMP AppWindow::ShowModal() {
AUTO_PROFILER_LABEL("AppWindow::ShowModal", OTHER);
if (AppShutdown::IsInOrBeyond(ShutdownPhase::AppShutdownConfirmed)) {
MOZ_ASSERT_UNREACHABLE(
"Trying to show modal window after shutdown started.");
return NS_ERROR_ILLEGAL_DURING_SHUTDOWN;
}
// Store locally so it doesn't die on us
nsCOMPtr<nsIWidget> window = mWindow;
nsCOMPtr<nsIAppWindow> tempRef = this;
#ifdef USE_NATIVE_MENUS
if (!gfxPlatform::IsHeadless()) {
// On macOS, for modals created early in startup. (e.g.
// ProfileManager/ProfileDowngrade) this creates a fallback menu for the
// menu bar which only contains a "Quit" menu item. This allows the user to
// quit the application in a regular way with cmd+Q.
widget::NativeMenuSupport::CreateNativeMenuBar(mWindow, nullptr);
}
#endif
window->SetModal(true);
mContinueModalLoop = true;
EnableParent(false);
{
AutoNoJSAPI nojsapi;
SpinEventLoopUntil("AppWindow::ShowModal"_ns, [&]() {
if (MOZ_UNLIKELY(
AppShutdown::IsInOrBeyond(ShutdownPhase::AppShutdownConfirmed))) {
// TODO: Bug 1699041 would apply also here: Should we return an error
// if we are bailing out from a pre-existing modal dialog for shutdown?
ExitModalLoop(NS_OK);
}
return !mContinueModalLoop;
});
}
mContinueModalLoop = false;
window->SetModal(false);
/* Note there's no EnableParent(true) here to match the false one
above. That's done in ExitModalLoop. It's important that the parent
be re-enabled before this window is made invisible; to do otherwise
causes bizarre z-ordering problems. At this point, the window is
already invisible.
No known current implementation of Enable would have a problem with
re-enabling the parent twice, so we could do it again here without
breaking any current implementation. But that's unnecessary if the
modal loop is always exited using ExitModalLoop (the other way would be
to change the protected member variable directly.)
*/
return mModalStatus;
}
NS_IMETHODIMP AppWindow::RollupAllPopups() {
if (nsXULPopupManager* pm = nsXULPopupManager::GetInstance()) {
pm->Rollup({});
}
return NS_OK;
}
//*****************************************************************************
// AppWindow::nsIBaseWindow
//*****************************************************************************
NS_IMETHODIMP AppWindow::InitWindow(nsIWidget* parentWidget, int32_t x,
int32_t y, int32_t cx, int32_t cy) {
// XXX First Check In
NS_ASSERTION(false, "Not Yet Implemented");
return NS_OK;
}
NS_IMETHODIMP AppWindow::Destroy() {
nsCOMPtr<nsIAppWindow> kungFuDeathGrip(this);
if (mDocShell) {
mDocShell->RemoveProgressListener(this);
}
if (mSPTimer) {
mSPTimer->Cancel();
SavePersistentAttributes();
mSPTimer = nullptr;
}
if (!mWindow) return NS_OK;
// Ensure we don't reenter this code
if (mDestroying) return NS_OK;
mozilla::AutoRestore<bool> guard(mDestroying);
mDestroying = true;
nsCOMPtr<nsIAppShellService> appShell(
do_GetService(NS_APPSHELLSERVICE_CONTRACTID));
NS_ASSERTION(appShell, "Couldn't get appShell... xpcom shutdown?");
if (appShell) {
appShell->UnregisterTopLevelWindow(static_cast<nsIAppWindow*>(this));
}
// Remove modality (if any) and hide while destroying. More than
// a convenience, the hide prevents user interaction with the partially
// destroyed window. This is especially necessary when the eldest window
// in a stack of modal windows is destroyed first. It happens.
ExitModalLoop(NS_OK);
// XXX: Skip unmapping the window on Linux due to GLX hangs on the compositor
// thread with NVIDIA driver 310.32. We don't need to worry about user
// interactions with destroyed windows on X11 either.
#ifndef MOZ_WIDGET_GTK
if (mWindow) mWindow->Show(false);
#endif
// Raise and focus our parent explicitly on Windows, if visible. Apparently
// Windows gets the z-order and focus wrong otherwise for nested modal
// windows, see bug 1977581.
#ifdef XP_WIN
if (nsCOMPtr<nsIBaseWindow> parent = do_QueryReferent(mParentWindow)) {
if (nsCOMPtr<nsIWidget> parentWidget = parent->GetMainWidget();
parentWidget && parentWidget->IsVisible()) {
parentWidget->SetFocus(nsIWidget::Raise::Yes, dom::CallerType::System);
}
}
#endif
RemoveTooltipSupport();
mDOMWindow = nullptr;
if (mDocShell) {
RefPtr<BrowsingContext> bc(mDocShell->GetBrowsingContext());
mDocShell->Destroy();
bc->Detach();
mDocShell = nullptr; // this can cause reentrancy of this function
}
mPrimaryContentShell = nullptr;
if (mContentTreeOwner) {
mContentTreeOwner->AppWindow(nullptr);
NS_RELEASE(mContentTreeOwner);
}
if (mPrimaryContentTreeOwner) {
mPrimaryContentTreeOwner->AppWindow(nullptr);
NS_RELEASE(mPrimaryContentTreeOwner);
}
if (mChromeTreeOwner) {
mChromeTreeOwner->AppWindow(nullptr);
NS_RELEASE(mChromeTreeOwner);
}
if (mWindow) {
mWindow->SetWidgetListener(nullptr); // nsWebShellWindow hackery
mWindow->Destroy();
mWindow = nullptr;
}
if (!mIsHiddenWindow && mRegistered) {
/* Inform appstartup we've destroyed this window and it could
quit now if it wanted. This must happen at least after mDocShell
is destroyed, because onunload handlers fire then, and those being
script, anything could happen. A new window could open, even.
See bug 130719. */
nsCOMPtr<nsIObserverService> obssvc = services::GetObserverService();
NS_ASSERTION(obssvc, "Couldn't get observer service?");
if (obssvc)
obssvc->NotifyObservers(nullptr, "xul-window-destroyed", nullptr);
}
return NS_OK;
}
NS_IMETHODIMP AppWindow::GetDevicePixelsPerDesktopPixel(double* aScale) {
*aScale = mWindow ? mWindow->GetDesktopToDeviceScale().scale : 1.0;
return NS_OK;
}
double AppWindow::GetWidgetCSSToDeviceScale() {
return mWindow ? mWindow->GetDefaultScale().scale : 1.0;
}
NS_IMETHODIMP AppWindow::SetPositionDesktopPix(int32_t aX, int32_t aY) {
return MoveResize(Some(DesktopIntPoint(aX, aY)), Nothing(), false);
}
// The parameters here are device pixels; do the best we can to convert to
// desktop px, using the window's current scale factor (if available).
NS_IMETHODIMP AppWindow::SetPosition(int32_t aX, int32_t aY) {
// Don't reset the window's size mode here - platforms that don't want to move
// maximized windows should reset it in their respective Move implementation.
return MoveResize(Some(LayoutDeviceIntPoint(aX, aY)), Nothing(), false);
}
NS_IMETHODIMP AppWindow::GetPosition(int32_t* aX, int32_t* aY) {
return GetPositionAndSize(aX, aY, nullptr, nullptr);
}
NS_IMETHODIMP AppWindow::SetSize(int32_t aCX, int32_t aCY, bool aRepaint) {
/* any attempt to set the window's size or position overrides the window's
zoom state. this is important when these two states are competing while
the window is being opened. but it should probably just always be so. */
return MoveResize(Nothing(), Some(LayoutDeviceIntSize(aCX, aCY)), aRepaint);
}
NS_IMETHODIMP AppWindow::GetSize(int32_t* aCX, int32_t* aCY) {
return GetPositionAndSize(nullptr, nullptr, aCX, aCY);
}
NS_IMETHODIMP AppWindow::SetPositionAndSize(int32_t aX, int32_t aY, int32_t aCX,
int32_t aCY, uint32_t aFlags) {
/* any attempt to set the window's size or position overrides the window's
zoom state. this is important when these two states are competing while
the window is being opened. but it should probably just always be so. */
return MoveResize(Some(LayoutDeviceIntPoint(aX, aY)),
Some(LayoutDeviceIntSize(aCX, aCY)),
!!(aFlags & nsIBaseWindow::eRepaint));
}
NS_IMETHODIMP AppWindow::GetPositionAndSize(int32_t* x, int32_t* y, int32_t* cx,
int32_t* cy) {
if (!mWindow) return NS_ERROR_FAILURE;
LayoutDeviceIntRect rect = mWindow->GetScreenBounds();
if (x) *x = rect.X();
if (y) *y = rect.Y();
if (cx) *cx = rect.Width();
if (cy) *cy = rect.Height();
return NS_OK;
}
NS_IMETHODIMP
AppWindow::SetDimensions(DimensionRequest&& aRequest) {
if (aRequest.mDimensionKind == DimensionKind::Inner) {
// For the chrome the inner size is the root shell size, and for the
// content it's the primary content size. We lack an indicator here that
// would allow us to distinguish between the two.
return NS_ERROR_NOT_IMPLEMENTED;
}
MOZ_TRY(aRequest.SupplementFrom(this));
return aRequest.ApplyOuterTo(this);
}
NS_IMETHODIMP
AppWindow::GetDimensions(DimensionKind aDimensionKind, int32_t* aX, int32_t* aY,
int32_t* aCX, int32_t* aCY) {
if (aDimensionKind == DimensionKind::Inner) {
// For the chrome the inner size is the root shell size, and for the
// content it's the primary content size. We lack an indicator here that
// would allow us to distinguish between the two.
return NS_ERROR_NOT_IMPLEMENTED;
}
return GetPositionAndSize(aX, aY, aCX, aCY);
}
nsresult AppWindow::MoveResize(const Maybe<LayoutDeviceIntPoint>& aPosition,
const Maybe<LayoutDeviceIntSize>& aSize,
bool aRepaint) {
NS_ENSURE_STATE(mWindow);
DesktopToLayoutDeviceScale scale = mWindow->GetDesktopToDeviceScale();
return MoveResize(aPosition ? Some(*aPosition / scale) : Nothing(),
aSize ? Some(*aSize / scale) : Nothing(), aRepaint);
}
nsresult AppWindow::MoveResize(const Maybe<DesktopPoint>& aPosition,
const Maybe<DesktopSize>& aSize, bool aRepaint) {
NS_ENSURE_STATE(mWindow);
PersistentAttributes dirtyAttributes;
if (!aPosition && !aSize) {
MOZ_ASSERT_UNREACHABLE("Doing nothing?");
return NS_ERROR_UNEXPECTED;
}
if (aSize) {
mWindow->SetSizeMode(nsSizeMode_Normal);
mIntrinsicallySized = false;
mDominantClientSize = false;
}
if (aPosition && aSize) {
mWindow->Resize(DesktopRect(*aPosition, *aSize), aRepaint);
dirtyAttributes = {PersistentAttribute::Size,
PersistentAttribute::Position};
} else if (aSize) {
mWindow->Resize(*aSize, aRepaint);
dirtyAttributes = {PersistentAttribute::Size};
} else if (aPosition) {
mWindow->Move(*aPosition);
dirtyAttributes = {PersistentAttribute::Position};
}
if (mSizingShellFromXUL) {
// If we're invoked for sizing from XUL, we want to neither ignore anything
// nor persist anything, since it's already the value in XUL.
return NS_OK;
}
if (!mChromeLoaded) {
// If we're called before the chrome is loaded someone obviously wants this
// window at this size & in the normal size mode (since it is the only mode
// in which setting dimensions makes sense). We don't persist this one-time
// position/size.
if (aPosition) {
mIgnoreXULPosition = true;
}
if (aSize) {
mIgnoreXULSize = true;
mIgnoreXULSizeMode = true;
}
return NS_OK;
}
PersistentAttributesDirty(dirtyAttributes, Sync);
return NS_OK;
}
nsresult AppWindow::CenterImpl(nsIAppWindow* aRelative, bool aScreen,
bool aAlert, bool aAllowCenteringForSizeChange) {
DesktopIntRect rect;
bool screenCoordinates = false, windowCoordinates = false;
nsresult result;
if (!mChromeLoaded) {
// note we lose the parameters. at time of writing, this isn't a problem.
mCenterAfterLoad = true;
return NS_OK;
}
if (!aScreen && !aRelative) {
return NS_ERROR_INVALID_ARG;
}
nsCOMPtr<nsIScreenManager> screenmgr =
do_GetService("@mozilla.org/gfx/screenmanager;1", &result);
if (NS_FAILED(result)) {
return result;
}
nsCOMPtr<nsIScreen> screen;
if (aRelative) {
nsCOMPtr<nsIBaseWindow> base(do_QueryInterface(aRelative));
if (base) {
rect = RoundedToInt(base->GetPositionAndSize() /
base->DevicePixelsPerDesktopPixel());
// if centering on screen, convert that to the corresponding screen
if (aScreen) {
screen = screenmgr->ScreenForRect(rect);
} else {
windowCoordinates = true;
}
}
}
if (!aRelative) {
if (!mOpenerScreenRect.IsEmpty()) {
screen = screenmgr->ScreenForRect(mOpenerScreenRect);
} else {
screenmgr->GetPrimaryScreen(getter_AddRefs(screen));
}
}
if (aScreen && screen) {
rect = screen->GetAvailRectDisplayPix();
screenCoordinates = true;
}
if (!screenCoordinates && !windowCoordinates) {
return NS_ERROR_FAILURE;
}
NS_ASSERTION(mWindow, "what, no window?");
const LayoutDeviceIntSize ourDevSize = GetSize();
const DesktopIntSize ourSize =
RoundedToInt(ourDevSize / DevicePixelsPerDesktopPixel());
auto newPos =
rect.TopLeft() +
DesktopIntPoint((rect.width - ourSize.width) / 2,
(rect.height - ourSize.height) / (aAlert ? 3 : 2));
if (windowCoordinates) {
mWindow->ConstrainPosition(newPos);
}
SetPositionDesktopPix(newPos.x, newPos.y);
// If moving the window caused it to change size, re-do the centering.
// Allow only one recursion here.
if (GetSize() != ourDevSize && aAllowCenteringForSizeChange) {
return CenterImpl(aRelative, aScreen, aAlert,
/* aAllowCenteringForSizeChange */ false);
}
return NS_OK;
}
NS_IMETHODIMP AppWindow::Center(nsIAppWindow* aRelative, bool aScreen,
bool aAlert) {
return CenterImpl(aRelative, aScreen, aAlert,
/* aAllowCenteringForSizeChange */ true);
}
NS_IMETHODIMP AppWindow::GetParentWidget(nsIWidget** aParentWidget) {
NS_ENSURE_ARG_POINTER(aParentWidget);
NS_ENSURE_STATE(mWindow);
NS_IF_ADDREF(*aParentWidget = mWindow->GetParent());
return NS_OK;
}
NS_IMETHODIMP AppWindow::SetParentWidget(nsIWidget* aParentWidget) {
// XXX First Check In
NS_ASSERTION(false, "Not Yet Implemented");
return NS_OK;
}
NS_IMETHODIMP AppWindow::GetNativeHandle(nsAString& aNativeHandle) {
if (mWindow) {
nativeWindow nativeWindowPtr = mWindow->GetNativeData(NS_NATIVE_WINDOW);
/* the nativeWindow pointer is converted to and exposed as a string. This
is a more reliable way not to lose information (as opposed to JS
|Number| for instance) */
aNativeHandle =
NS_ConvertASCIItoUTF16(nsPrintfCString("0x%p", nativeWindowPtr));
}
return NS_OK;
}
NS_IMETHODIMP AppWindow::GetVisibility(bool* aVisibility) {
NS_ENSURE_ARG_POINTER(aVisibility);
// Always claim to be visible for now. See bug
// https://bugzilla.mozilla.org/show_bug.cgi?id=306245.
*aVisibility = true;
return NS_OK;
}
NS_IMETHODIMP AppWindow::SetVisibility(bool aVisibility) {
if (!mChromeLoaded) {
mShowAfterLoad = aVisibility;
return NS_OK;
}
if (mDebuting) {
return NS_OK;
}
NS_ENSURE_STATE(mDocShell);
mDebuting = true; // (Show / Focus is recursive)
// XXXTAB Do we really need to show docshell and the window? Isn't
// the window good enough?
mDocShell->SetVisibility(aVisibility);
// Store locally so it doesn't die on us. 'Show' can result in the window
// being closed with AppWindow::Destroy being called. That would set
// mWindow to null and possibly destroy the nsIWidget while its Show method
// is on the stack. We need to keep it alive until Show finishes.
nsCOMPtr<nsIWidget> window = mWindow;
window->Show(aVisibility);
// NOTE(emilio): A bit hacky, but we need to synchronously trigger resizes
// for remote frames here if we're a sized popup (mDominantClientSize=true).
//
// This is because what we do to show a popup window with a specified size is
// to wait until the chrome loads (and gets sized, and thus laid out at a
// particular pre-size), then size the window, and call Show(), which ends up
// here.
//
// After bug 1917458, that remote browser resize would happen asynchronously,
// which means content might be able to observe the old size unexpectedly.
if (aVisibility && mDominantClientSize) {
if (RefPtr doc = mDocShell->GetDocument()) {
doc->SynchronouslyUpdateRemoteBrowserDimensions();
}
}
nsCOMPtr<nsIWindowMediator> windowMediator(
do_GetService(NS_WINDOWMEDIATOR_CONTRACTID));
if (windowMediator)
windowMediator->UpdateWindowTimeStamp(static_cast<nsIAppWindow*>(this));
// notify observers so that we can hide the splash screen if possible
nsCOMPtr<nsIObserverService> obssvc = services::GetObserverService();
NS_ASSERTION(obssvc, "Couldn't get observer service.");
if (obssvc) {
obssvc->NotifyObservers(static_cast<nsIAppWindow*>(this),
"xul-window-visible", nullptr);
}
mDebuting = false;
return NS_OK;
}
NS_IMETHODIMP AppWindow::GetEnabled(bool* aEnabled) {
NS_ENSURE_ARG_POINTER(aEnabled);
if (mWindow) {
*aEnabled = mWindow->IsEnabled();
return NS_OK;
}
*aEnabled = true; // better guess than most
return NS_ERROR_FAILURE;
}
NS_IMETHODIMP AppWindow::SetEnabled(bool aEnable) {
if (mWindow) {
mWindow->Enable(aEnable);
return NS_OK;
}
return NS_ERROR_FAILURE;
}
NS_IMETHODIMP AppWindow::GetMainWidget(nsIWidget** aMainWidget) {
NS_ENSURE_ARG_POINTER(aMainWidget);
NS_IF_ADDREF(*aMainWidget = mWindow);
return NS_OK;
}
NS_IMETHODIMP AppWindow::GetTitle(nsAString& aTitle) {
aTitle = mTitle;
return NS_OK;
}
NS_IMETHODIMP AppWindow::SetTitle(const nsAString& aTitle) {
NS_ENSURE_STATE(mWindow);
mTitle.Assign(aTitle);
mTitle.StripCRLF();
NS_ENSURE_SUCCESS(mWindow->SetTitle(mTitle), NS_ERROR_FAILURE);
return NS_OK;
}
//*****************************************************************************
// AppWindow: Helpers
//*****************************************************************************
NS_IMETHODIMP AppWindow::EnsureChromeTreeOwner() {
if (mChromeTreeOwner) return NS_OK;
mChromeTreeOwner = new nsChromeTreeOwner();
NS_ADDREF(mChromeTreeOwner);
mChromeTreeOwner->AppWindow(this);
return NS_OK;
}
NS_IMETHODIMP AppWindow::EnsureContentTreeOwner() {
if (mContentTreeOwner) return NS_OK;
mContentTreeOwner = new nsContentTreeOwner(false);
NS_ADDREF(mContentTreeOwner);
mContentTreeOwner->AppWindow(this);
return NS_OK;
}
NS_IMETHODIMP AppWindow::EnsurePrimaryContentTreeOwner() {
if (mPrimaryContentTreeOwner) return NS_OK;
mPrimaryContentTreeOwner = new nsContentTreeOwner(true);
NS_ADDREF(mPrimaryContentTreeOwner);
mPrimaryContentTreeOwner->AppWindow(this);
return NS_OK;
}
NS_IMETHODIMP AppWindow::EnsurePrompter() {
if (mPrompter) return NS_OK;
nsCOMPtr<mozIDOMWindowProxy> ourWindow;
nsresult rv = GetWindowDOMWindow(getter_AddRefs(ourWindow));
if (NS_SUCCEEDED(rv)) {
nsCOMPtr<nsIWindowWatcher> wwatch =
do_GetService(NS_WINDOWWATCHER_CONTRACTID);
if (wwatch) wwatch->GetNewPrompter(ourWindow, getter_AddRefs(mPrompter));
}
return mPrompter ? NS_OK : NS_ERROR_FAILURE;
}
NS_IMETHODIMP AppWindow::EnsureAuthPrompter() {
if (mAuthPrompter) return NS_OK;
nsCOMPtr<mozIDOMWindowProxy> ourWindow;
nsresult rv = GetWindowDOMWindow(getter_AddRefs(ourWindow));
if (NS_SUCCEEDED(rv)) {
nsCOMPtr<nsIWindowWatcher> wwatch(
do_GetService(NS_WINDOWWATCHER_CONTRACTID));
if (wwatch)
wwatch->GetNewAuthPrompter(ourWindow, getter_AddRefs(mAuthPrompter));
}
return mAuthPrompter ? NS_OK : NS_ERROR_FAILURE;
}
NS_IMETHODIMP AppWindow::GetAvailScreenSize(int32_t* aAvailWidth,
int32_t* aAvailHeight) {
nsCOMPtr<mozIDOMWindowProxy> domWindow;
GetWindowDOMWindow(getter_AddRefs(domWindow));
NS_ENSURE_STATE(domWindow);
auto* window = nsGlobalWindowOuter::Cast(domWindow);
RefPtr<nsScreen> screen = window->GetScreen();
NS_ENSURE_STATE(screen);
*aAvailWidth = screen->AvailWidth();
*aAvailHeight = screen->AvailHeight();
return NS_OK;
}
// Rounds window size to 1000x1000, or, if there isn't enough available
// screen space, to a multiple of 200x100.
NS_IMETHODIMP AppWindow::ForceRoundedDimensions() {
if (mIsHiddenWindow) {
return NS_OK;
}
CSSToLayoutDeviceScale scale = UnscaledDevicePixelsPerCSSPixel();
CSSIntSize availSizeCSS;
GetAvailScreenSize(&availSizeCSS.width, &availSizeCSS.height);
// To get correct chrome size, we have to resize the window to a proper
// size first. So, here, we size it to its available size.
SetSpecifiedSize(availSizeCSS.width, availSizeCSS.height);
// Get the current window size for calculating chrome UI size.
CSSIntSize windowSizeCSS = RoundedToInt(GetSize() / scale);
// Get the content size for calculating chrome UI size.
LayoutDeviceIntSize contentSizeDev;
GetPrimaryContentSize(&contentSizeDev.width, &contentSizeDev.height);
CSSIntSize contentSizeCSS = RoundedToInt(contentSizeDev / scale);
// Calculate the chrome UI size.
CSSIntSize chromeSizeCSS = windowSizeCSS - contentSizeCSS;
CSSIntSize targetSizeCSS;
// Here, we use the available screen dimensions as the input dimensions to
// force the window to be rounded as the maximum available content size.
nsContentUtils::CalcRoundedWindowSizeForResistingFingerprinting(
chromeSizeCSS.width, chromeSizeCSS.height, availSizeCSS.width,
availSizeCSS.height, availSizeCSS.width, availSizeCSS.height,
false, // aSetOuterWidth
false, // aSetOuterHeight
&targetSizeCSS.width, &targetSizeCSS.height);
LayoutDeviceIntSize targetSizeDev = RoundedToInt(targetSizeCSS * scale);
SetPrimaryContentSize(targetSizeDev.width, targetSizeDev.height);
return NS_OK;
}
void AppWindow::OnChromeLoaded() {
nsresult rv = EnsureContentTreeOwner();
if (NS_SUCCEEDED(rv)) {
mChromeLoaded = true;
ApplyChromeFlags();
SyncAttributesToWidget();
if (mWindow) {
SizeShell();
if (mShowAfterLoad) {
SetVisibility(true);
}
AddTooltipSupport();
}
// At this point the window may have been closed already during Show() or
// SyncAttributesToWidget(), so AppWindow::Destroy may already have been
// called. Take care!
}
mPersistentAttributesMask += AllPersistentAttributes();
}
bool AppWindow::NeedsTooltipListener() {
nsCOMPtr<dom::Element> docShellElement = GetWindowDOMElement();
if (!docShellElement || docShellElement->IsXULElement()) {
// Tooltips in XUL are handled by each element.
return false;
}
// All other non-XUL document types need a tooltip listener.
return true;
}
void AppWindow::AddTooltipSupport() {
if (!NeedsTooltipListener()) {
return;
}
nsXULTooltipListener* listener = nsXULTooltipListener::GetInstance();
if (!listener) {
return;
}
nsCOMPtr<dom::Element> docShellElement = GetWindowDOMElement();
MOZ_ASSERT(docShellElement);
listener->AddTooltipSupport(docShellElement);
}
void AppWindow::RemoveTooltipSupport() {
if (!NeedsTooltipListener()) {
return;
}
nsXULTooltipListener* listener = nsXULTooltipListener::GetInstance();
if (!listener) {
return;
}
nsCOMPtr<dom::Element> docShellElement = GetWindowDOMElement();
MOZ_ASSERT(docShellElement);
listener->RemoveTooltipSupport(docShellElement);
}
static Maybe<int32_t> ReadIntAttribute(const Element& aElement,
nsAtom* aPrimary,
nsAtom* aSecondary = nullptr) {
nsAutoString attrString;
if (!aElement.GetAttr(aPrimary, attrString)) {
if (aSecondary) {
return ReadIntAttribute(aElement, aSecondary);
}
return Nothing();
}
nsresult res = NS_OK;
int32_t ret = attrString.ToInteger(&res);
return NS_SUCCEEDED(res) ? Some(ret) : Nothing();
}
// If aSpecWidth and/or aSpecHeight are > 0, we will use these CSS px sizes
// to fit to the screen when staggering windows; if they're negative,
// we use the window's current size instead.
bool AppWindow::LoadPositionFromXUL(int32_t aSpecWidth, int32_t aSpecHeight) {
// if we're the hidden window, don't try to validate our size/position. We're
// special.
if (mIsHiddenWindow) {
return false;
}
// If we're not in the normal sizemode, don't move the window around.
if (mWindow->SizeMode() != nsSizeMode_Normal) {
return false;
}
RefPtr<dom::Element> root = GetWindowDOMElement();
NS_ENSURE_TRUE(root, false);
const LayoutDeviceIntRect devRect = GetPositionAndSize();
// Convert to global display pixels for consistent window management across
// screens with diverse resolutions
const DesktopIntPoint curPoint =
RoundedToInt(devRect.TopLeft() / DevicePixelsPerDesktopPixel());
// For size, use specified value if > 0, else current value
CSSIntSize cssSize(aSpecWidth, aSpecHeight);
{
CSSIntSize currentSize =
RoundedToInt(devRect.Size() / UnscaledDevicePixelsPerCSSPixel());
if (aSpecHeight <= 0) {
cssSize.height = currentSize.height;
}
if (aSpecWidth <= 0) {
cssSize.width = currentSize.width;
}
}
// Obtain the position information from the <xul:window> element.
DesktopIntPoint specPoint = curPoint;
bool gotPosition = false;
// Also read lowercase screenx/y because the front-end sometimes sets these
// via setAttribute on HTML documents like about:blank, and stuff gets
// lowercased.
//
// TODO(emilio): We should probably rename screenX/Y to screen-x/y to
// prevent this impedance mismatch.
if (auto attr =
ReadIntAttribute(*root, nsGkAtoms::screenX, nsGkAtoms::screenx)) {
specPoint.x = *attr;
gotPosition = true;
}
if (auto attr =
ReadIntAttribute(*root, nsGkAtoms::screenY, nsGkAtoms::screeny)) {
specPoint.y = *attr;
gotPosition = true;
}
if (gotPosition) {
// Our position will be relative to our parent, if any
nsCOMPtr<nsIBaseWindow> parent(do_QueryReferent(mParentWindow));
if (parent) {
const DesktopIntPoint parentPos = RoundedToInt(
parent->GetPosition() / parent->DevicePixelsPerDesktopPixel());
specPoint += parentPos;
} else {
StaggerPosition(specPoint.x.value, specPoint.y.value, cssSize.width,
cssSize.height);
}
}
mWindow->ConstrainPosition(specPoint);
if (specPoint != curPoint) {
SetPositionDesktopPix(specPoint.x, specPoint.y);
}
return gotPosition;
}
static Maybe<int32_t> ReadSize(const Element& aElement, nsAtom* aAttr,
nsAtom* aMinAttr, nsAtom* aMaxAttr) {
Maybe<int32_t> attr = ReadIntAttribute(aElement, aAttr);
if (!attr) {
return Nothing();
}
int32_t min =
std::max(100, ReadIntAttribute(aElement, aMinAttr).valueOr(100));
int32_t max = ReadIntAttribute(aElement, aMaxAttr)
.valueOr(std::numeric_limits<int32_t>::max());
return Some(std::clamp(*attr, min, max));
}
bool AppWindow::LoadSizeFromXUL(int32_t& aSpecWidth, int32_t& aSpecHeight) {
bool gotSize = false;
// if we're the hidden window, don't try to validate our size/position. We're
// special.
if (mIsHiddenWindow) {
return false;
}
nsCOMPtr<dom::Element> windowElement = GetWindowDOMElement();
NS_ENSURE_TRUE(windowElement, false);
// Obtain the sizing information from the <xul:window> element.
aSpecWidth = 100;
aSpecHeight = 100;
if (auto width = ReadSize(*windowElement, nsGkAtoms::width,
nsGkAtoms::minwidth, nsGkAtoms::maxwidth)) {
aSpecWidth = *width;
gotSize = true;
}
if (auto height = ReadSize(*windowElement, nsGkAtoms::height,
nsGkAtoms::minheight, nsGkAtoms::maxheight)) {
aSpecHeight = *height;
gotSize = true;
}
return gotSize;
}
void AppWindow::SetSpecifiedSize(int32_t aSpecWidth, int32_t aSpecHeight) {
// These are in CSS pixels of the main window.
// TODO(emilio): In my testing we usually have a pres context around, can we
// just use it? That'd simplify the coordinate calculations.
{
int32_t screenWidth;
int32_t screenHeight;
if (NS_SUCCEEDED(GetAvailScreenSize(&screenWidth, &screenHeight))) {
if (aSpecWidth > screenWidth) {
aSpecWidth = screenWidth;
}
if (aSpecHeight > screenHeight) {
aSpecHeight = screenHeight;
}
}
}
NS_ASSERTION(mWindow, "we expected to have a window already");
mIntrinsicallySized = false;
// Convert specified values to device pixels, and resize
auto newSize = RoundedToInt(CSSIntSize(aSpecWidth, aSpecHeight) *
UnscaledDevicePixelsPerCSSPixel());
// Note: Because of the asynchronous resizing on Linux we have to call
// SetSize even when the size doesn't appear to change. A previous call that
// has yet to complete can still change the size. We want the latest call to
// define the final size.
SetSize(newSize.width, newSize.height, false);
}
/* Miscellaneous persistent attributes are attributes named in the
|persist| attribute, other than size and position. Those are special
because it's important to load those before one of the misc
attributes (sizemode) and they require extra processing. */
bool AppWindow::UpdateWindowStateFromMiscXULAttributes() {
/* There are no misc attributes of interest to the hidden window.
It's especially important not to try to validate that window's
size or position, because some platforms (Mac OS X) need to
make it visible and offscreen. */
if (mIsHiddenWindow) {
return false;
}
nsCOMPtr<dom::Element> windowElement = GetWindowDOMElement();
NS_ENSURE_TRUE(windowElement, false);
nsAutoString stateString;
nsSizeMode sizeMode = nsSizeMode_Normal;
// If we are told to ignore the size mode attribute, force
// normal sizemode.
if (mIgnoreXULSizeMode) {
windowElement->SetAttr(nsGkAtoms::sizemode, SIZEMODE_NORMAL,
IgnoreErrors());
} else {
// Otherwise, read sizemode from DOM and, if the window is resizable,
// set it later.
windowElement->GetAttr(nsGkAtoms::sizemode, stateString);
if ((stateString.Equals(SIZEMODE_MAXIMIZED) ||
stateString.Equals(SIZEMODE_FULLSCREEN))) {
/* Honor request to maximize only if the window is sizable.
An unsizable, unmaximizable, yet maximized window confuses
Windows OS and is something of a travesty, anyway. */
if (mChromeFlags & nsIWebBrowserChrome::CHROME_WINDOW_RESIZE) {
mIntrinsicallySized = false;
sizeMode = stateString.Equals(SIZEMODE_MAXIMIZED)
? nsSizeMode_Maximized
: nsSizeMode_Fullscreen;
}
}
}
if (sizeMode == nsSizeMode_Fullscreen) {
nsCOMPtr<mozIDOMWindowProxy> ourWindow;
GetWindowDOMWindow(getter_AddRefs(ourWindow));
auto* piWindow = nsPIDOMWindowOuter::From(ourWindow);
piWindow->SetFullScreen(true);
} else {
// For maximized windows, ignore the XUL size and position attributes,
// as setting them would set the window back to normal sizemode.
if (sizeMode == nsSizeMode_Maximized) {
mIgnoreXULSize = true;
mIgnoreXULPosition = true;
}
mWindow->SetSizeMode(sizeMode);
}
return true;
}
/* Stagger windows of the same type so they don't appear on top of each other.
This code does have a scary double loop -- it'll keep passing through
the entire list of open windows until it finds a non-collision. Doesn't
seem to be a problem, but it deserves watching.
The aRequested{X,Y} parameters here are in desktop pixels;
the aSpec{Width,Height} parameters are CSS pixel dimensions.
*/
void AppWindow::StaggerPosition(int32_t& aRequestedX, int32_t& aRequestedY,
int32_t aSpecWidth, int32_t aSpecHeight) {
// These "constants" will be converted from CSS to desktop pixels
// for the appropriate screen, assuming we find a screen to use...
// hence they're not actually declared const here.
int32_t kOffset = 22;
uint32_t kSlop = 4;
bool keepTrying;
int bouncedX = 0, // bounced off vertical edge of screen
bouncedY = 0; // bounced off horizontal edge
// look for any other windows of this type
nsCOMPtr<nsIWindowMediator> wm(do_GetService(NS_WINDOWMEDIATOR_CONTRACTID));
if (!wm) return;
nsCOMPtr<dom::Element> windowElement = GetWindowDOMElement();
if (!windowElement) return;
nsCOMPtr<nsIAppWindow> ourAppWindow(this);
nsAutoString windowType;
windowElement->GetAttr(nsGkAtoms::windowtype, windowType);
DesktopIntRect screenRect;
bool gotScreen = false;
{ // fetch screen coordinates
nsCOMPtr<nsIScreenManager> screenMgr(
do_GetService("@mozilla.org/gfx/screenmanager;1"));
if (screenMgr) {
nsCOMPtr<nsIScreen> ourScreen;
// The coordinates here are already display pixels
// XXX aSpecWidth and aSpecHeight are CSS pixels!
screenMgr->ScreenForRect(aRequestedX, aRequestedY, aSpecWidth,
aSpecHeight, getter_AddRefs(ourScreen));
if (ourScreen) {
screenRect = ourScreen->GetAvailRectDisplayPix();
// Get the screen's scaling factors and convert staggering constants
// from CSS px to desktop pixel units
auto scale = ourScreen->GetCSSToDesktopScale();
kOffset = (CSSCoord(kOffset) * scale).Rounded();
kSlop = (CSSCoord(kSlop) * scale).Rounded();
// Convert dimensions from CSS to desktop pixels
aSpecWidth = (CSSCoord(aSpecWidth) * scale).Rounded();
aSpecHeight = (CSSCoord(aSpecHeight) * scale).Rounded();
gotScreen = true;
}
}
}
// One full pass through all windows of this type, repeat until no collisions.
do {
keepTrying = false;
nsCOMPtr<nsISimpleEnumerator> windowList;
wm->GetAppWindowEnumerator(windowType.get(), getter_AddRefs(windowList));
if (!windowList) break;
// One full pass through all windows of this type, offset and stop on
// collision.
do {
bool more;
windowList->HasMoreElements(&more);
if (!more) break;
nsCOMPtr<nsISupports> supportsWindow;
windowList->GetNext(getter_AddRefs(supportsWindow));
nsCOMPtr<nsIAppWindow> listAppWindow(do_QueryInterface(supportsWindow));
if (listAppWindow != ourAppWindow) {
int32_t listX, listY;
nsCOMPtr<nsIBaseWindow> listBaseWindow(
do_QueryInterface(supportsWindow));
listBaseWindow->GetPosition(&listX, &listY);
double scale;
if (NS_SUCCEEDED(
listBaseWindow->GetDevicePixelsPerDesktopPixel(&scale))) {
listX = NSToIntRound(listX / scale);
listY = NSToIntRound(listY / scale);
}
if (Abs(listX - aRequestedX) <= kSlop &&
Abs(listY - aRequestedY) <= kSlop) {
// collision! offset and start over
if (bouncedX & 0x1)
aRequestedX -= kOffset;
else
aRequestedX += kOffset;
aRequestedY += kOffset;
if (gotScreen) {
// if we're moving to the right and we need to bounce...
if (!(bouncedX & 0x1) &&
((aRequestedX + aSpecWidth) > screenRect.XMost())) {
aRequestedX = screenRect.XMost() - aSpecWidth;
++bouncedX;
}
// if we're moving to the left and we need to bounce...
if ((bouncedX & 0x1) && aRequestedX < screenRect.X()) {
aRequestedX = screenRect.X();
++bouncedX;
}
// if we hit the bottom then bounce to the top
if (aRequestedY + aSpecHeight > screenRect.YMost()) {
aRequestedY = screenRect.Y();
++bouncedY;
}
}
/* loop around again,
but it's time to give up once we've covered the screen.
there's a potential infinite loop with lots of windows. */
keepTrying = bouncedX < 2 || bouncedY == 0;
break;
}
}
} while (true);
} while (keepTrying);
}
void AppWindow::SyncAttributesToWidget() {
nsCOMPtr<dom::Element> windowElement = GetWindowDOMElement();
if (!windowElement) return;
MOZ_DIAGNOSTIC_ASSERT(mWindow, "No widget on SyncAttributesToWidget?");
nsAutoString attr;
// Some attributes can change the client size (e.g. customtitlebar on Windows
// and MacOS). But we might want to keep it.
const LayoutDeviceIntSize oldClientSize = mWindow->GetClientSize();
// We have to check now whether we want to restore the client size, as any
// change in size will reset its state.
bool maintainClientSize = mDominantClientSize;
// "hidechrome" attribute
// FIXME(emilio): This should arguably be
// HideWindowChrome(windowElement->GetBoolAttr(...)), but that has
// side-effects in some platforms.
if (windowElement->GetBoolAttr(nsGkAtoms::hidechrome)) {
mWindow->HideWindowChrome(true);
}
NS_ENSURE_TRUE_VOID(mWindow);
// "customtitlebar" attribute
// FIXME(emilio): This should arguably be
// SetCustomTitlebar(windowElement->GetBoolAttr(...)), but that breaks with
// the early blank window which sets the custom titlebar via
// nsIDOMWindowUtils...
if (windowElement->GetBoolAttr(nsGkAtoms::customtitlebar)) {
mWindow->SetCustomTitlebar(true);
}
NS_ENSURE_TRUE_VOID(mWindow);
mWindow->SetMicaBackdrop(windowElement->GetBoolAttr(nsGkAtoms::windowsmica));
NS_ENSURE_TRUE_VOID(mWindow);
// "windowtype", "windowclass", "windowname" attributes
nsAutoString windowClassAttr, windowNameAttr;
windowElement->GetAttr(nsGkAtoms::windowtype, attr);
windowElement->GetAttribute(u"windowclass"_ns, windowClassAttr);
windowElement->GetAttribute(u"windowname"_ns, windowNameAttr);
mWindow->SetWindowClass(attr, windowClassAttr, windowNameAttr);
NS_ENSURE_TRUE_VOID(mWindow);
// Only change blank window status once we're loaded, so that a
// partially-loaded browser window doesn't start painting early.
if (mChromeLoaded) {
mWindow->SetIsEarlyBlankWindow(attr.EqualsLiteral("navigator:blank"));
NS_ENSURE_TRUE_VOID(mWindow);
}
// "icon" attribute
windowElement->GetAttribute(u"icon"_ns, attr);
if (!attr.IsEmpty()) {
mWindow->SetIcon(attr);
NS_ENSURE_TRUE_VOID(mWindow);
}
// "hidetitlebarseparator" attribute
mWindow->SetHideTitlebarSeparator(
windowElement->GetBoolAttr(nsGkAtoms::hidetitlebarseparator));
NS_ENSURE_TRUE_VOID(mWindow);
// "toggletoolbar" attribute
mWindow->SetShowsToolbarButton(
windowElement->HasAttribute(u"toggletoolbar"_ns));
NS_ENSURE_TRUE_VOID(mWindow);
// "macnativefullscreen" attribute
mWindow->SetSupportsNativeFullscreen(
windowElement->HasAttribute(u"macnativefullscreen"_ns));
NS_ENSURE_TRUE_VOID(mWindow);
// "macanimationtype" attribute
windowElement->GetAttribute(u"macanimationtype"_ns, attr);
if (attr.EqualsLiteral("document")) {
mWindow->SetWindowAnimationType(nsIWidget::eDocumentWindowAnimation);
}
// Check if the client size did change and if we want to restore it.
if (maintainClientSize && mWindow->SizeMode() == nsSizeMode_Normal &&
oldClientSize != mWindow->GetClientSize()) {
mWindow->ResizeClient(oldClientSize / mWindow->GetDesktopToDeviceScale(),
true);
mDominantClientSize = true;
}
}
enum class ConversionDirection {
InnerToOuter,
OuterToInner,
};
static void ConvertWindowSize(nsIAppWindow* aWin, const nsAtom* aAttr,
ConversionDirection aDirection,
nsAString& aInOutString) {
MOZ_ASSERT(aWin);
MOZ_ASSERT(aAttr == nsGkAtoms::width || aAttr == nsGkAtoms::height);
nsresult rv;
int32_t size = aInOutString.ToInteger(&rv);
if (NS_FAILED(rv)) {
return;
}
int32_t sizeDiff = aAttr == nsGkAtoms::width
? aWin->GetOuterToInnerWidthDifferenceInCSSPixels()
: aWin->GetOuterToInnerHeightDifferenceInCSSPixels();
if (!sizeDiff) {
return;
}
int32_t multiplier = aDirection == ConversionDirection::InnerToOuter ? 1 : -1;
CopyASCIItoUTF16(nsPrintfCString("%d", size + multiplier * sizeDiff),
aInOutString);
}
nsresult AppWindow::GetPersistentValue(const nsAtom* aAttr, nsAString& aValue) {
if (!XRE_IsParentProcess()) {
// The XULStore is only available in the parent process.
return NS_ERROR_UNEXPECTED;
}
nsCOMPtr<dom::Element> docShellElement = GetWindowDOMElement();
if (!docShellElement) {
return NS_ERROR_FAILURE;
}
nsAutoString windowElementId;
docShellElement->GetId(windowElementId);
// Elements must have an ID to be persisted.
if (windowElementId.IsEmpty()) {
return NS_OK;
}
RefPtr<dom::Document> ownerDoc = docShellElement->OwnerDoc();
nsIURI* docURI = ownerDoc->GetDocumentURI();
if (!docURI) {
return NS_ERROR_FAILURE;
}
nsAutoCString utf8uri;
nsresult rv = docURI->GetSpec(utf8uri);
NS_ENSURE_SUCCESS(rv, rv);
NS_ConvertUTF8toUTF16 uri(utf8uri);
if (!mLocalStore) {
mLocalStore = do_GetService("@mozilla.org/xul/xulstore;1");
if (NS_WARN_IF(!mLocalStore)) {
return NS_ERROR_NOT_INITIALIZED;
}
}
rv = mLocalStore->GetValue(uri, windowElementId, nsDependentAtomString(aAttr),
aValue);
if (NS_WARN_IF(NS_FAILED(rv))) {
return rv;
}
if (aAttr == nsGkAtoms::width || aAttr == nsGkAtoms::height) {
// Convert attributes from outer size to inner size for top-level
// windows, see bug 1444525 & co.
ConvertWindowSize(this, aAttr, ConversionDirection::OuterToInner, aValue);
}
return NS_OK;
}
nsresult AppWindow::GetDocXulStoreKeys(nsString& aUriSpec,
nsString& aWindowElementId) {
nsCOMPtr<dom::Element> docShellElement = GetWindowDOMElement();
if (!docShellElement) {
return NS_ERROR_FAILURE;
}
docShellElement->GetId(aWindowElementId);
// Match the behavior of XULPersist and only persist values if the element
// has an ID.
if (aWindowElementId.IsEmpty()) {
return NS_OK;
}
RefPtr<dom::Document> ownerDoc = docShellElement->OwnerDoc();
nsIURI* docURI = ownerDoc->GetDocumentURI();
if (!docURI) {
return NS_ERROR_FAILURE;
}
nsAutoCString utf8uri;
nsresult rv = docURI->GetSpec(utf8uri);
if (NS_WARN_IF(NS_FAILED(rv))) {
return rv;
}
aUriSpec = NS_ConvertUTF8toUTF16(utf8uri);
return NS_OK;
}
nsresult AppWindow::MaybeSaveEarlyWindowPersistentValues(
const LayoutDeviceIntRect& aRect) {
#ifdef XP_WIN
nsAutoString uri;
nsAutoString windowElementId;
nsresult rv = GetDocXulStoreKeys(uri, windowElementId);
if (NS_WARN_IF(NS_FAILED(rv))) {
return rv;
}
if (!windowElementId.EqualsLiteral("main-window") ||
!uri.EqualsLiteral("chrome://browser/content/browser.xhtml")) {
return NS_OK;
}
SkeletonUISettings settings;
settings.screenX = aRect.X();
settings.screenY = aRect.Y();
settings.width = aRect.Width();
settings.height = aRect.Height();
settings.maximized = mWindow->SizeMode() == nsSizeMode_Maximized;
settings.cssToDevPixelScaling = UnscaledDevicePixelsPerCSSPixel().scale;
nsCOMPtr<dom::Element> windowElement = GetWindowDOMElement();
Document* doc = windowElement->GetComposedDoc();
Element* urlbarEl = doc->GetElementById(u"urlbar"_ns);
nsCOMPtr<nsPIDOMWindowOuter> window = mDocShell->GetWindow();
nsCOMPtr<nsIDOMWindowUtils> utils =
nsGlobalWindowOuter::Cast(window)->WindowUtils();
RefPtr<dom::DOMRect> urlbarRect;
rv = utils->GetBoundsWithoutFlushing(urlbarEl, getter_AddRefs(urlbarRect));
if (NS_WARN_IF(NS_FAILED(rv))) {
return rv;
}
double urlbarX = urlbarRect->X();
double urlbarWidth = urlbarRect->Width();
// Hard-coding the following values and this behavior in general is rather
// fragile, and can easily get out of sync with the actual front-end values.
// This is not intended as a long-term solution, but only as the relatively
// straightforward implementation of an experimental feature. If we want to
// ship the skeleton UI to all users, we should strongly consider a more
// robust solution than this. The vertical position of the urlbar will be
// fixed.
nsAutoString attributeValue;
urlbarEl->GetAttribute(u"breakout-extend"_ns, attributeValue);
// Scale down the urlbar if it is focused
if (attributeValue.EqualsLiteral("true")) {
// defined in browser.inc.css as 2px
int urlbarBreakoutExtend = 2;
// defined in urlbar-searchbar.inc.css as 5px
int urlbarMarginInline = 5;
// breakout-extend measurements are defined in urlbar-searchbar.inc.css
urlbarX += (double)(urlbarBreakoutExtend + urlbarMarginInline);
urlbarWidth -= (double)(2 * (urlbarBreakoutExtend + urlbarMarginInline));
}
CSSPixelSpan urlbar;
urlbar.start = urlbarX;
urlbar.end = urlbar.start + urlbarWidth;
settings.urlbarSpan = urlbar;
Element* navbar = doc->GetElementById(u"nav-bar"_ns);
Element* searchbarEl = doc->GetElementById(u"searchbar"_ns);
CSSPixelSpan searchbar;
if (navbar->Contains(searchbarEl)) {
RefPtr<dom::DOMRect> searchbarRect;
rv = utils->GetBoundsWithoutFlushing(searchbarEl,
getter_AddRefs(searchbarRect));
if (NS_WARN_IF(NS_FAILED(rv))) {
return rv;
}
searchbar.start = searchbarRect->X();
searchbar.end = searchbar.start + searchbarRect->Width();
} else {
// There is no searchbar in the UI
searchbar.start = 0;
searchbar.end = 0;
}
settings.searchbarSpan = searchbar;
nsAutoString bookmarksVisibility;
Preferences::GetString("browser.toolbars.bookmarks.visibility",
bookmarksVisibility);
settings.bookmarksToolbarShown =
bookmarksVisibility.EqualsLiteral("always") ||
bookmarksVisibility.EqualsLiteral("newtab");
Element* menubar = doc->GetElementById(u"toolbar-menubar"_ns);
menubar->GetAttribute(u"autohide"_ns, attributeValue);
settings.menubarShown = attributeValue.EqualsLiteral("false");
ErrorResult err;
nsCOMPtr<nsIHTMLCollection> toolbarSprings = navbar->GetElementsByTagNameNS(
u"http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"_ns,
u"toolbarspring"_ns, err);
if (err.Failed()) {
return NS_ERROR_FAILURE;
}
mozilla::Vector<CSSPixelSpan> springs;
for (size_t i = 0; i < toolbarSprings->Length(); i++) {
RefPtr<Element> springEl = toolbarSprings->Item(i);
RefPtr<dom::DOMRect> springRect;
rv = utils->GetBoundsWithoutFlushing(springEl, getter_AddRefs(springRect));
if (NS_WARN_IF(NS_FAILED(rv))) {
return rv;
}
CSSPixelSpan spring;
spring.start = springRect->X();
spring.end = spring.start + springRect->Width();
if (!settings.springs.append(spring)) {
return NS_ERROR_FAILURE;
}
}
settings.rtlEnabled = intl::LocaleService::GetInstance()->IsAppLocaleRTL();
bool isInTabletMode = false;
bool const autoTouchModePref =
Preferences::GetBool("browser.touchmode.auto", false);
if (autoTouchModePref) {
nsCOMPtr<nsIWindowsUIUtils> uiUtils(
do_GetService("@mozilla.org/windows-ui-utils;1"));
if (!NS_WARN_IF(!uiUtils)) {
// We switch to the touch-optimized layout in both Win10 and Win11 tablet-
// modes, since only the input mechanism is relevant. (See bug 1819421.)
if (IsWin11OrLater()) {
uiUtils->GetInWin11TabletMode(&isInTabletMode);
} else {
uiUtils->GetInWin10TabletMode(&isInTabletMode);
}
}
}
if (isInTabletMode) {
settings.uiDensity = SkeletonUIDensity::Touch;
} else {
int uiDensityPref = Preferences::GetInt("browser.uidensity", 0);
switch (uiDensityPref) {
case 0: {
settings.uiDensity = SkeletonUIDensity::Default;
break;
}
case 1: {
settings.uiDensity = SkeletonUIDensity::Compact;
break;
}
case 2: {
settings.uiDensity = SkeletonUIDensity::Touch;
break;
}
}
}
settings.verticalTabs = Preferences::GetBool("sidebar.verticalTabs", false);
(void)PersistPreXULSkeletonUIValues(settings);
#endif
return NS_OK;
}
nsresult AppWindow::SetPersistentValue(const nsAtom* aAttr,
const nsAString& aValue) {
if (!XRE_IsParentProcess()) {
// The XULStore is only available in the parent process.
return NS_ERROR_UNEXPECTED;
}
nsAutoString uri;
nsAutoString windowElementId;
nsresult rv = GetDocXulStoreKeys(uri, windowElementId);
if (NS_FAILED(rv) || windowElementId.IsEmpty()) {
return rv;
}
nsAutoString maybeConvertedValue(aValue);
if (aAttr == nsGkAtoms::width || aAttr == nsGkAtoms::height) {
// Make sure we store the <window> attributes as outer window size, see
// bug 1444525 & co.
ConvertWindowSize(this, aAttr, ConversionDirection::InnerToOuter,
maybeConvertedValue);
}
if (!mLocalStore) {
mLocalStore = do_GetService("@mozilla.org/xul/xulstore;1");
if (NS_WARN_IF(!mLocalStore)) {
return NS_ERROR_NOT_INITIALIZED;
}
}
return mLocalStore->SetValue(
uri, windowElementId, nsDependentAtomString(aAttr), maybeConvertedValue);
}
void AppWindow::MaybeSavePersistentPositionAndSize(
PersistentAttributes aAttributes, Element& aRootElement,
const nsAString& aPersistString, bool aShouldPersist) {
if ((aAttributes & PersistentAttributes{PersistentAttribute::Position,
PersistentAttribute::Size})
.isEmpty()) {
return;
}
// get our size, position and mode to persist
LayoutDeviceIntRect rect;
if (NS_FAILED(mWindow->GetRestoredBounds(rect))) {
return;
}
const bool isClient = mWindow->PersistClientBounds();
// we use CSS pixels for size, but desktop pixels for position
CSSToLayoutDeviceScale sizeScale = UnscaledDevicePixelsPerCSSPixel();
DesktopToLayoutDeviceScale posScale = DevicePixelsPerDesktopPixel();
// make our position relative to our parent, if any
nsCOMPtr<nsIBaseWindow> parent(do_QueryReferent(mParentWindow));
if (parent) {
int32_t parentX, parentY;
if (NS_SUCCEEDED(parent->GetPosition(&parentX, &parentY))) {
rect.MoveBy(-parentX, -parentY);
}
}
nsAutoString sizeString;
// (only for size elements which are persisted)
if (aAttributes.contains(PersistentAttribute::Position)) {
if (aPersistString.Find(u"screenX") >= 0) {
sizeString.Truncate();
sizeString.AppendInt(NSToIntRound(rect.X() / posScale.scale));
aRootElement.SetAttr(nsGkAtoms::screenX, sizeString, IgnoreErrors());
if (aShouldPersist) {
(void)SetPersistentValue(nsGkAtoms::screenX, sizeString);
}
}
if (aPersistString.Find(u"screenY") >= 0) {
sizeString.Truncate();
sizeString.AppendInt(NSToIntRound(rect.Y() / posScale.scale));
aRootElement.SetAttr(nsGkAtoms::screenY, sizeString, IgnoreErrors());
if (aShouldPersist) {
(void)SetPersistentValue(nsGkAtoms::screenY, sizeString);
}
}
}
if (aAttributes.contains(PersistentAttribute::Size)) {
const LayoutDeviceIntRect innerRect =
isClient ? rect : rect - GetOuterToInnerSizeDifference(mWindow);
if (aPersistString.Find(u"width") >= 0) {
sizeString.Truncate();
sizeString.AppendInt(NSToIntRound(innerRect.Width() / sizeScale.scale));
aRootElement.SetAttr(nsGkAtoms::width, sizeString, IgnoreErrors());
if (aShouldPersist) {
(void)SetPersistentValue(nsGkAtoms::width, sizeString);
}
}
if (aPersistString.Find(u"height") >= 0) {
sizeString.Truncate();
sizeString.AppendInt(NSToIntRound(innerRect.Height() / sizeScale.scale));
aRootElement.SetAttr(nsGkAtoms::height, sizeString, IgnoreErrors());
if (aShouldPersist) {
(void)SetPersistentValue(nsGkAtoms::height, sizeString);
}
}
}
(void)MaybeSaveEarlyWindowPersistentValues(rect);
}
void AppWindow::MaybeSavePersistentMiscAttributes(
PersistentAttributes aAttributes, Element& aRootElement,
const nsAString& aPersistString, bool aShouldPersist) {
if (!aAttributes.contains(PersistentAttribute::Misc)) {
return;
}
nsSizeMode sizeMode = mWindow->SizeMode();
nsAutoString sizeString;
if (sizeMode != nsSizeMode_Minimized) {
if (sizeMode == nsSizeMode_Maximized) {
sizeString.Assign(SIZEMODE_MAXIMIZED);
} else if (sizeMode == nsSizeMode_Fullscreen) {
sizeString.Assign(SIZEMODE_FULLSCREEN);
} else {
sizeString.Assign(SIZEMODE_NORMAL);
}
aRootElement.SetAttr(nsGkAtoms::sizemode, sizeString, IgnoreErrors());
if (aShouldPersist && aPersistString.Find(u"sizemode") >= 0) {
(void)SetPersistentValue(nsGkAtoms::sizemode, sizeString);
}
}
aRootElement.SetAttribute(u"gtktiledwindow"_ns,
mWindow->IsTiled() ? u"true"_ns : u"false"_ns,
IgnoreErrors());
}
void AppWindow::SavePersistentAttributes(
const PersistentAttributes aAttributes) {
// can happen when the persistence timer fires at an inopportune time
// during window shutdown
if (!mDocShell) {
return;
}
nsCOMPtr<dom::Element> docShellElement = GetWindowDOMElement();
if (!docShellElement) {
return;
}
nsAutoString persistString;
docShellElement->GetAttr(nsGkAtoms::persist, persistString);
if (persistString.IsEmpty()) { // quick check which sometimes helps
mPersistentAttributesDirty.clear();
return;
}
bool shouldPersist = mWindow->SizeMode() != nsSizeMode_Fullscreen;
MaybeSavePersistentPositionAndSize(aAttributes, *docShellElement,
persistString, shouldPersist);
MaybeSavePersistentMiscAttributes(aAttributes, *docShellElement,
persistString, shouldPersist);
mPersistentAttributesDirty -= aAttributes;
}
NS_IMETHODIMP AppWindow::GetWindowDOMWindow(mozIDOMWindowProxy** aDOMWindow) {
NS_ENSURE_STATE(mDocShell);
if (!mDOMWindow) mDOMWindow = mDocShell->GetWindow();
NS_ENSURE_TRUE(mDOMWindow, NS_ERROR_FAILURE);
*aDOMWindow = mDOMWindow;
NS_ADDREF(*aDOMWindow);
return NS_OK;
}
dom::Element* AppWindow::GetWindowDOMElement() const {
NS_ENSURE_TRUE(mDocShell, nullptr);
nsCOMPtr<nsIDocumentViewer> viewer;
mDocShell->GetDocViewer(getter_AddRefs(viewer));
NS_ENSURE_TRUE(viewer, nullptr);
const dom::Document* document = viewer->GetDocument();
NS_ENSURE_TRUE(document, nullptr);
return document->GetRootElement();
}
nsresult AppWindow::ContentShellAdded(nsIDocShellTreeItem* aContentShell,
bool aPrimary) {
// Set the default content tree owner
if (aPrimary) {
NS_ENSURE_SUCCESS(EnsurePrimaryContentTreeOwner(), NS_ERROR_FAILURE);
aContentShell->SetTreeOwner(mPrimaryContentTreeOwner);
mPrimaryContentShell = aContentShell;
mPrimaryBrowserParent = nullptr;
} else {
NS_ENSURE_SUCCESS(EnsureContentTreeOwner(), NS_ERROR_FAILURE);
aContentShell->SetTreeOwner(mContentTreeOwner);
if (mPrimaryContentShell == aContentShell) mPrimaryContentShell = nullptr;
}
return NS_OK;
}
nsresult AppWindow::ContentShellRemoved(nsIDocShellTreeItem* aContentShell) {
if (mPrimaryContentShell == aContentShell) {
mPrimaryContentShell = nullptr;
}
return NS_OK;
}
NS_IMETHODIMP
AppWindow::GetPrimaryContentSize(int32_t* aWidth, int32_t* aHeight) {
if (mPrimaryBrowserParent) {
return GetPrimaryRemoteTabSize(aWidth, aHeight);
}
if (mPrimaryContentShell) {
return GetPrimaryContentShellSize(aWidth, aHeight);
}
return NS_ERROR_UNEXPECTED;
}
nsresult AppWindow::GetPrimaryRemoteTabSize(int32_t* aWidth, int32_t* aHeight) {
BrowserHost* host = BrowserHost::GetFrom(mPrimaryBrowserParent.get());
// Need strong ref, since Client* can run script.
RefPtr<dom::Element> element = host->GetOwnerElement();
NS_ENSURE_STATE(element);
CSSIntSize size(element->ClientWidth(), element->ClientHeight());
LayoutDeviceIntSize sizeDev =
RoundedToInt(size * UnscaledDevicePixelsPerCSSPixel());
if (aWidth) {
*aWidth = sizeDev.width;
}
if (aHeight) {
*aHeight = sizeDev.height;
}
return NS_OK;
}
nsresult AppWindow::GetPrimaryContentShellSize(int32_t* aWidth,
int32_t* aHeight) {
NS_ENSURE_STATE(mPrimaryContentShell);
nsCOMPtr<nsIBaseWindow> shellWindow(do_QueryInterface(mPrimaryContentShell));
NS_ENSURE_STATE(shellWindow);
LayoutDeviceIntSize sizeDev = shellWindow->GetSize();
if (aWidth) {
*aWidth = sizeDev.width;
}
if (aHeight) {
*aHeight = sizeDev.height;
}
return NS_OK;
}
NS_IMETHODIMP
AppWindow::SetPrimaryContentSize(int32_t aWidth, int32_t aHeight) {
if (mPrimaryBrowserParent) {
return SetPrimaryRemoteTabSize(aWidth, aHeight);
}
if (mPrimaryContentShell) {
return SizeShellTo(mPrimaryContentShell, aWidth, aHeight);
}
return NS_ERROR_UNEXPECTED;
}
nsresult AppWindow::SetPrimaryRemoteTabSize(int32_t aWidth, int32_t aHeight) {
int32_t shellWidth, shellHeight;
GetPrimaryRemoteTabSize(&shellWidth, &shellHeight);
SizeShellToWithLimit(aWidth, aHeight, shellWidth, shellHeight);
return NS_OK;
}
nsresult AppWindow::GetRootShellSize(int32_t* aWidth, int32_t* aHeight) {
NS_ENSURE_TRUE(mDocShell, NS_ERROR_FAILURE);
return mDocShell->GetSize(aWidth, aHeight);
}
nsresult AppWindow::SetRootShellSize(int32_t aWidth, int32_t aHeight) {
return SizeShellTo(mDocShell, aWidth, aHeight);
}
NS_IMETHODIMP AppWindow::SizeShellTo(nsIDocShellTreeItem* aShellItem,
int32_t aCX, int32_t aCY) {
MOZ_ASSERT(aShellItem == mDocShell || aShellItem == mPrimaryContentShell);
if (aShellItem == mDocShell) {
auto newSize =
LayoutDeviceIntSize(aCX, aCY) + GetOuterToInnerSizeDifference(mWindow);
SetSize(newSize.width, newSize.height, /* aRepaint = */ true);
mDominantClientSize = true;
return NS_OK;
}
// XXXTAB This is wrong, we should actually reflow based on the passed in
// shell. For now we are hacking and doing delta sizing. This is bad
// because it assumes all size we add will go to the shell which probably
// won't happen.
nsCOMPtr<nsIBaseWindow> shellAsWin(do_QueryInterface(aShellItem));
NS_ENSURE_TRUE(shellAsWin, NS_ERROR_FAILURE);
int32_t width = 0;
int32_t height = 0;
shellAsWin->GetSize(&width, &height);
SizeShellToWithLimit(aCX, aCY, width, height);
return NS_OK;
}
NS_IMETHODIMP AppWindow::ExitModalLoop(nsresult aStatus) {
if (mContinueModalLoop) EnableParent(true);
mContinueModalLoop = false;
mModalStatus = aStatus;
return NS_OK;
}
// top-level function to create a new window
NS_IMETHODIMP AppWindow::CreateNewWindow(int32_t aChromeFlags,
nsIOpenWindowInfo* aOpenWindowInfo,
nsIAppWindow** _retval) {
NS_ENSURE_ARG_POINTER(_retval);
if (aChromeFlags & nsIWebBrowserChrome::CHROME_OPENAS_CHROME) {
MOZ_RELEASE_ASSERT(
!aOpenWindowInfo,
"Unexpected nsOpenWindowInfo when creating a new chrome window");
return CreateNewChromeWindow(aChromeFlags, _retval);
}
return CreateNewContentWindow(aChromeFlags, aOpenWindowInfo, _retval);
}
NS_IMETHODIMP AppWindow::CreateNewChromeWindow(int32_t aChromeFlags,
nsIAppWindow** _retval) {
nsCOMPtr<nsIAppShellService> appShell(
do_GetService(NS_APPSHELLSERVICE_CONTRACTID));
NS_ENSURE_TRUE(appShell, NS_ERROR_FAILURE);
// Just do a normal create of a window and return.
nsCOMPtr<nsIAppWindow> newWindow;
appShell->CreateTopLevelWindow(
this, nullptr, aChromeFlags, nsIAppShellService::SIZE_TO_CONTENT,
nsIAppShellService::SIZE_TO_CONTENT, getter_AddRefs(newWindow));
NS_ENSURE_TRUE(newWindow, NS_ERROR_FAILURE);
newWindow.forget(_retval);
return NS_OK;
}
NS_IMETHODIMP AppWindow::CreateNewContentWindow(
int32_t aChromeFlags, nsIOpenWindowInfo* aOpenWindowInfo,
nsIAppWindow** _retval) {
nsCOMPtr<nsIAppShellService> appShell(
do_GetService(NS_APPSHELLSERVICE_CONTRACTID));
NS_ENSURE_TRUE(appShell, NS_ERROR_FAILURE);
// We need to create a new top level window and then enter a nested
// loop. Eventually the new window will be told that it has loaded,
// at which time we know it is safe to spin out of the nested loop
// and allow the opening code to proceed.
nsCOMPtr<nsIURI> uri;
nsAutoCString urlStr;
urlStr.AssignLiteral(BROWSER_CHROME_URL_QUOTED);
nsCOMPtr<nsIIOService> service(do_GetService(NS_IOSERVICE_CONTRACTID));
if (service) {
service->NewURI(urlStr, nullptr, nullptr, getter_AddRefs(uri));
}
NS_ENSURE_TRUE(uri, NS_ERROR_FAILURE);
// We need to create a chrome window to contain the content window we're about
// to pass back. The subject principal needs to be system while we're creating
// it to make things work right, so force a system caller. See bug 799348
// comment 13 for a description of what happens when we don't.
nsCOMPtr<nsIAppWindow> newWindow;
{
AutoNoJSAPI nojsapi;
appShell->CreateTopLevelWindow(this, uri, aChromeFlags, 615, 480,
getter_AddRefs(newWindow));
NS_ENSURE_TRUE(newWindow, NS_ERROR_FAILURE);
}
AppWindow* appWin =
static_cast<AppWindow*>(static_cast<nsIAppWindow*>(newWindow));
// Specify which flags should be used by browser.xhtml to create the initial
// content browser window.
appWin->mInitialOpenWindowInfo = aOpenWindowInfo;
// Specify that we want the window to remain locked until the chrome has
// loaded.
appWin->LockUntilChromeLoad();
{
AutoNoJSAPI nojsapi;
SpinEventLoopUntil("AppWindow::CreateNewContentWindow"_ns,
[&]() { return !appWin->IsLocked(); });
}
NS_ENSURE_STATE(appWin->mPrimaryContentShell ||
appWin->mPrimaryBrowserParent);
MOZ_ASSERT_IF(appWin->mPrimaryContentShell,
!aOpenWindowInfo->GetNextRemoteBrowser());
newWindow.forget(_retval);
return NS_OK;
}
NS_IMETHODIMP AppWindow::GetHasPrimaryContent(bool* aResult) {
*aResult = mPrimaryBrowserParent || mPrimaryContentShell;
return NS_OK;
}
void AppWindow::EnableParent(bool aEnable) {
if (nsCOMPtr<nsIBaseWindow> parentWindow = do_QueryReferent(mParentWindow)) {
if (nsCOMPtr<nsIWidget> parentWidget = parentWindow->GetMainWidget()) {
parentWidget->Enable(aEnable);
}
}
}
void AppWindow::SetContentScrollbarVisibility(bool aVisible) {
nsCOMPtr<nsPIDOMWindowOuter> contentWin(
do_GetInterface(mPrimaryContentShell));
if (!contentWin) {
return;
}
nsContentUtils::SetScrollbarsVisibility(contentWin->GetDocShell(), aVisible);
}
void AppWindow::ApplyChromeFlags() {
nsCOMPtr<dom::Element> window = GetWindowDOMElement();
if (!window) {
return;
}
if (mChromeLoaded) {
// The two calls in this block don't need to happen early because they
// don't cause a global restyle on the document. Not only that, but the
// scrollbar stuff needs a content area to toggle the scrollbars on anyway.
// So just don't do these until mChromeLoaded is true.
// Scrollbars have their own special treatment.
SetContentScrollbarVisibility(mChromeFlags &
nsIWebBrowserChrome::CHROME_SCROLLBARS);
}
/* the other flags are handled together. we have style rules
in navigator.css that trigger visibility based on
the 'chromehidden' attribute of the <window> tag. */
nsAutoString newvalue;
if (!(mChromeFlags & nsIWebBrowserChrome::CHROME_MENUBAR))
newvalue.AppendLiteral("menubar ");
if (!(mChromeFlags & nsIWebBrowserChrome::CHROME_TOOLBAR))
newvalue.AppendLiteral("toolbar ");
if (!(mChromeFlags & nsIWebBrowserChrome::CHROME_LOCATIONBAR))
newvalue.AppendLiteral("location ");
if (!(mChromeFlags & nsIWebBrowserChrome::CHROME_PERSONAL_TOOLBAR))
newvalue.AppendLiteral("directories ");
if (!(mChromeFlags & nsIWebBrowserChrome::CHROME_STATUSBAR))
newvalue.AppendLiteral("status ");
if (!(mChromeFlags & nsIWebBrowserChrome::CHROME_EXTRA))
newvalue.AppendLiteral("extrachrome ");
// Note that if we're not actually changing the value this will be a no-op,
// so no need to compare to the old value.
IgnoredErrorResult rv;
window->SetAttribute(u"chromehidden"_ns, newvalue, rv);
}
NS_IMETHODIMP
AppWindow::BeforeStartLayout() {
ApplyChromeFlags();
// Ordering here is important, loading width/height values in
// LoadPersistentWindowState() depends on the customtitlebar attribute (since
// we need to translate outer to inner sizes).
SyncAttributesToWidget();
LoadPersistentWindowState();
if (mWindow) {
SizeShell();
}
return NS_OK;
}
NS_IMETHODIMP
AppWindow::LockAspectRatio(bool aShouldLock) {
mWindow->LockAspectRatio(aShouldLock);
return NS_OK;
}
NS_IMETHODIMP
AppWindow::NeedFastSnaphot() {
MOZ_ASSERT(mWindow);
if (!mWindow) {
return NS_ERROR_FAILURE;
}
mWindow->SetNeedFastSnaphot();
return NS_OK;
}
void AppWindow::LoadPersistentWindowState() {
nsCOMPtr<dom::Element> docShellElement = GetWindowDOMElement();
if (!docShellElement) {
return;
}
// Disable state restoration, allowing the kiosk desktop environment
// to manage state and position.
if (StaticPrefs::browser_restoreWindowState_disabled()) {
return;
}
// Check if the window wants to persist anything.
nsAutoString persist;
docShellElement->GetAttr(nsGkAtoms::persist, persist);
if (persist.IsEmpty()) {
return;
}
auto loadValue = [&](nsAtom* aAttr) {
nsDependentAtomString attrString(aAttr);
if (persist.Find(attrString) >= 0) {
nsAutoString value;
nsresult rv = GetPersistentValue(aAttr, value);
NS_WARNING_ASSERTION(NS_SUCCEEDED(rv), "Failed to get persistent state.");
if (NS_SUCCEEDED(rv) && !value.IsEmpty()) {
docShellElement->SetAttr(aAttr, value, IgnoreErrors());
}
}
};
loadValue(nsGkAtoms::screenX);
loadValue(nsGkAtoms::screenY);
loadValue(nsGkAtoms::width);
loadValue(nsGkAtoms::height);
loadValue(nsGkAtoms::sizemode);
}
void AppWindow::IntrinsicallySizeShell(const CSSIntSize& aWindowDiff,
int32_t& aSpecWidth,
int32_t& aSpecHeight) {
nsCOMPtr<nsIDocumentViewer> viewer;
mDocShell->GetDocViewer(getter_AddRefs(viewer));
if (!viewer) {
return;
}
RefPtr<nsDocShell> docShell = mDocShell;
CSSIntCoord maxWidth = 0;
CSSIntCoord maxHeight = 0;
CSSIntCoord prefWidth = 0;
if (RefPtr element = GetWindowDOMElement()) {
nsAutoString prefWidthAttr;
if (element->GetAttr(nsGkAtoms::prefwidth, prefWidthAttr)) {
// TODO: Make this more generic perhaps?
if (prefWidthAttr.EqualsLiteral("min-width")) {
if (auto* f = element->GetPrimaryFrame(FlushType::Frames)) {
const auto coord = f->StylePosition()->GetMinWidth(
AnchorPosResolutionParams::From(f));
if (coord->ConvertsToLength()) {
prefWidth = CSSPixel::FromAppUnitsRounded(coord->ToLength());
}
}
}
}
}
Maybe<CSSIntSize> size =
viewer->GetContentSize(maxWidth, maxHeight, prefWidth);
if (!size) {
return;
}
nsPresContext* pc = viewer->GetPresContext();
MOZ_ASSERT(pc, "Should have pres context");
int32_t width = pc->CSSPixelsToDevPixels(size->width);
int32_t height = pc->CSSPixelsToDevPixels(size->height);
SizeShellTo(docShell, width, height);
// Update specified size for the final LoadPositionFromXUL call.
aSpecWidth = size->width + aWindowDiff.width;
aSpecHeight = size->height + aWindowDiff.height;
}
void AppWindow::SizeShell() {
AutoRestore<bool> sizingShellFromXUL(mSizingShellFromXUL);
mSizingShellFromXUL = true;
int32_t specWidth = -1, specHeight = -1;
bool gotSize = false;
nsAutoString windowType;
if (nsCOMPtr<dom::Element> windowElement = GetWindowDOMElement()) {
windowElement->GetAttr(nsGkAtoms::windowtype, windowType);
}
const CSSIntSize windowDiff = GetOuterToInnerSizeDifferenceInCSSPixels(
mWindow, UnscaledDevicePixelsPerCSSPixel());
// If we're using fingerprint resistance, we're going to resize the window
// once we have primary content.
if (nsContentUtils::ShouldResistFingerprinting(
"if RFP is enabled we want to round the dimensions of the new"
"new pop up window regardless of their origin",
RFPTarget::RoundWindowSize) &&
windowType.EqualsLiteral("navigator:browser")) {
// Once we've got primary content, force dimensions.
if (mPrimaryContentShell || mPrimaryBrowserParent) {
ForceRoundedDimensions();
}
// Always avoid setting size/sizemode on this window.
mIgnoreXULSize = true;
mIgnoreXULSizeMode = true;
} else if (!mIgnoreXULSize) {
gotSize = LoadSizeFromXUL(specWidth, specHeight);
specWidth += windowDiff.width;
specHeight += windowDiff.height;
}
bool positionSet = !mIgnoreXULPosition;
nsCOMPtr<nsIAppWindow> parentWindow(do_QueryReferent(mParentWindow));
#if defined(XP_UNIX) && !defined(XP_MACOSX)
// don't override WM placement on unix for independent, top-level windows
// (however, we think the benefits of intelligent dependent window placement
// trump that override.)
if (!parentWindow) positionSet = false;
#endif
if (positionSet) {
// We have to do this before sizing the window, because sizing depends
// on the resolution of the screen we're on. But positioning needs to
// know the size so that it can constrain to screen bounds.... as an
// initial guess here, we'll use the specified size (if any).
positionSet = LoadPositionFromXUL(specWidth, specHeight);
}
if (gotSize) {
SetSpecifiedSize(specWidth, specHeight);
}
// If LoadSizeFromXUL set the size, mIntrinsicallySized will be false.
if (mIntrinsicallySized) {
IntrinsicallySizeShell(windowDiff, specWidth, specHeight);
}
// Now that we have set the window's final size, we can re-do its
// positioning so that it is properly constrained to the screen.
if (positionSet) {
LoadPositionFromXUL(specWidth, specHeight);
}
UpdateWindowStateFromMiscXULAttributes();
if (mChromeLoaded && mCenterAfterLoad && !positionSet &&
mWindow->SizeMode() == nsSizeMode_Normal) {
Center(parentWindow, !parentWindow, false);
}
}
NS_IMETHODIMP AppWindow::GetXULBrowserWindow(
nsIXULBrowserWindow** aXULBrowserWindow) {
NS_IF_ADDREF(*aXULBrowserWindow = mXULBrowserWindow);
return NS_OK;
}
NS_IMETHODIMP AppWindow::SetXULBrowserWindow(
nsIXULBrowserWindow* aXULBrowserWindow) {
mXULBrowserWindow = aXULBrowserWindow;
return NS_OK;
}
// Given the dimensions of some content area held within this XUL window, and
// assuming that that content area will change its dimensions in linear
// proportion to the dimensions of this XUL window, changes the size of the XUL
// window so that the content area reaches a particular size.
void AppWindow::SizeShellToWithLimit(int32_t aDesiredWidth,
int32_t aDesiredHeight,
int32_t shellItemWidth,
int32_t shellItemHeight) {
int32_t widthDelta = aDesiredWidth - shellItemWidth;
int32_t heightDelta = aDesiredHeight - shellItemHeight;
int32_t winWidth = 0;
int32_t winHeight = 0;
GetSize(&winWidth, &winHeight);
// There's no point in trying to make the window smaller than the
// desired content area size --- that's not likely to work. This whole
// function assumes that the outer docshell is adding some constant
// "border" chrome to the content area.
winWidth = std::max(winWidth + widthDelta, aDesiredWidth);
winHeight = std::max(winHeight + heightDelta, aDesiredHeight);
// Note: Because of the asynchronous resizing on Linux we have to call
// SetSize even when the size doesn't appear to change. A previous call that
// has yet to complete can still change the size. We want the latest call to
// define the final size.
SetSize(winWidth, winHeight, true);
mDominantClientSize = true;
}
nsresult AppWindow::GetInitialOpenWindowInfo(
nsIOpenWindowInfo** aOpenWindowInfo) {
NS_ENSURE_ARG_POINTER(aOpenWindowInfo);
*aOpenWindowInfo = do_AddRef(mInitialOpenWindowInfo).take();
return NS_OK;
}
PresShell* AppWindow::GetPresShell() {
if (!mDocShell) {
return nullptr;
}
return mDocShell->GetPresShell();
}
bool AppWindow::WindowMoved(nsIWidget* aWidget, int32_t x, int32_t y) {
nsXULPopupManager* pm = nsXULPopupManager::GetInstance();
if (pm) {
nsCOMPtr<nsPIDOMWindowOuter> window =
mDocShell ? mDocShell->GetWindow() : nullptr;
pm->AdjustPopupsOnWindowChange(window);
}
// Notify all tabs that the widget moved.
if (mDocShell && mDocShell->GetWindow()) {
nsCOMPtr<EventTarget> eventTarget =
mDocShell->GetWindow()->GetTopWindowRoot();
nsContentUtils::DispatchChromeEvent(
mDocShell->GetDocument(), eventTarget, u"MozUpdateWindowPos"_ns,
CanBubble::eNo, Cancelable::eNo, nullptr);
}
// Persist position, but not immediately, in case this OS is firing
// repeated move events as the user drags the window
PersistentAttributesDirty(PersistentAttribute::Position, Async);
return false;
}
bool AppWindow::WindowResized(nsIWidget* aWidget, int32_t aWidth,
int32_t aHeight) {
mDominantClientSize = false;
if (mDocShell) {
mDocShell->SetPositionAndSize(0, 0, aWidth, aHeight, 0);
}
// Persist size, but not immediately, in case this OS is firing
// repeated size events as the user drags the sizing handle
if (!IsLocked()) {
PersistentAttributesDirty(AllPersistentAttributes(), Async);
}
// Check if we need to continue a fullscreen change.
switch (mFullscreenChangeState) {
case FullscreenChangeState::WillChange:
mFullscreenChangeState = FullscreenChangeState::WidgetResized;
break;
case FullscreenChangeState::WidgetEnteredFullscreen:
FinishFullscreenChange(true);
break;
case FullscreenChangeState::WidgetExitedFullscreen:
FinishFullscreenChange(false);
break;
case FullscreenChangeState::WidgetResized:
case FullscreenChangeState::NotChanging:
break;
}
return true;
}
bool AppWindow::RequestWindowClose(nsIWidget* aWidget) {
// Maintain a reference to this as it is about to get destroyed.
nsCOMPtr<nsIAppWindow> appWindow(this);
nsCOMPtr<nsPIDOMWindowOuter> window(mDocShell ? mDocShell->GetWindow()
: nullptr);
nsCOMPtr<EventTarget> eventTarget = do_QueryInterface(window);
RefPtr<PresShell> presShell = mDocShell->GetPresShell();
if (!presShell) {
mozilla::DebugOnly<bool> dying;
MOZ_ASSERT(NS_SUCCEEDED(mDocShell->IsBeingDestroyed(&dying)) && dying,
"No presShell, but window is not being destroyed");
} else if (eventTarget) {
RefPtr<nsPresContext> presContext = presShell->GetPresContext();
nsEventStatus status = nsEventStatus_eIgnore;
WidgetMouseEvent event(true, eClose, nullptr, WidgetMouseEvent::eReal);
if (NS_SUCCEEDED(EventDispatcher::Dispatch(eventTarget, presContext, &event,
nullptr, &status)) &&
status == nsEventStatus_eConsumeNoDefault)
return false;
}
Destroy();
return false;
}
void AppWindow::SizeModeChanged(nsSizeMode aSizeMode) {
const bool wasWidgetInFullscreen = mIsWidgetInFullscreen;
// Fullscreen and minimized states are usually compatible, and the widget
// typically returns to fullscreen after restoration. By not updating the
// widget's fullscreen state while it is minimized, we can avoid unnecessary
// fullscreen exits, such as those encountered in bug 1823284.
if (aSizeMode != nsSizeMode_Minimized) {
mIsWidgetInFullscreen = aSizeMode == nsSizeMode_Fullscreen;
}
const bool fullscreenChanged = wasWidgetInFullscreen != mIsWidgetInFullscreen;
if (fullscreenChanged) {
FullscreenWillChange(mIsWidgetInFullscreen);
}
RecomputeBrowsingContextVisibility();
PersistentAttributesDirty(PersistentAttribute::Misc, Sync);
nsCOMPtr<nsPIDOMWindowOuter> ourWindow =
mDocShell ? mDocShell->GetWindow() : nullptr;
if (ourWindow) {
// Always fire a user-defined sizemodechange event on the window
ourWindow->DispatchCustomEvent(u"sizemodechange"_ns);
}
if (PresShell* presShell = GetPresShell()) {
presShell->GetPresContext()->SizeModeChanged(aSizeMode);
}
if (fullscreenChanged) {
FullscreenChanged(mIsWidgetInFullscreen);
}
// Note the current implementation of SetSizeMode just stores
// the new state; it doesn't actually resize. So here we store
// the state and pass the event on to the OS. The day is coming
// when we'll handle the event here, and the return result will
// then need to be different.
}
void AppWindow::FullscreenWillChange(bool aInFullscreen) {
if (mDocShell) {
if (nsCOMPtr<nsPIDOMWindowOuter> ourWindow = mDocShell->GetWindow()) {
ourWindow->FullscreenWillChange(aInFullscreen);
}
}
MOZ_ASSERT(mFullscreenChangeState == FullscreenChangeState::NotChanging);
CSSToLayoutDeviceScale scale = UnscaledDevicePixelsPerCSSPixel();
CSSIntSize windowSizeCSS = RoundedToInt(GetSize() / scale);
CSSIntSize screenSizeCSS;
GetAvailScreenSize(&screenSizeCSS.width, &screenSizeCSS.height);
// Check if the window is already at the expected dimensions. If it is, set
// the fullscreen change state to WidgetResized to avoid waiting for a resize
// event. On macOS, a fullscreen window could be slightly higher than
// available screen size because of the OS menu bar isn't yet hidden.
mFullscreenChangeState =
(aInFullscreen == (windowSizeCSS.width == screenSizeCSS.width &&
windowSizeCSS.height >= screenSizeCSS.height))
? FullscreenChangeState::WidgetResized
: FullscreenChangeState::WillChange;
}
void AppWindow::FullscreenChanged(bool aInFullscreen) {
if (mFullscreenChangeState == FullscreenChangeState::WidgetResized) {
FinishFullscreenChange(aInFullscreen);
} else {
NS_WARNING_ASSERTION(
mFullscreenChangeState == FullscreenChangeState::WillChange,
"Unexpected fullscreen change state");
FullscreenChangeState newState =
aInFullscreen ? FullscreenChangeState::WidgetEnteredFullscreen
: FullscreenChangeState::WidgetExitedFullscreen;
mFullscreenChangeState = newState;
nsCOMPtr<nsIAppWindow> kungFuDeathGrip(this);
// Wait for resize for a small amount of time.
// 80ms is actually picked arbitrarily. But it shouldn't be too large
// in case the widget resize is not going to happen at all, which can
// be the case for some Linux window managers and possibly Android.
NS_DelayedDispatchToCurrentThread(
NS_NewRunnableFunction(
"AppWindow::FullscreenChanged",
[this, kungFuDeathGrip, newState, aInFullscreen]() {
if (mFullscreenChangeState == newState) {
FinishFullscreenChange(aInFullscreen);
}
}),
80);
}
}
void AppWindow::FinishFullscreenChange(bool aInFullscreen) {
mFullscreenChangeState = FullscreenChangeState::NotChanging;
if (nsXULPopupManager* pm = nsXULPopupManager::GetInstance()) {
pm->Rollup({});
}
if (mDocShell) {
if (nsCOMPtr<nsPIDOMWindowOuter> ourWindow = mDocShell->GetWindow()) {
ourWindow->FinishFullscreenChange(aInFullscreen);
}
}
}
void AppWindow::MacFullscreenMenubarOverlapChanged(
mozilla::DesktopCoord aOverlapAmount) {
if (mDocShell) {
if (nsCOMPtr<nsPIDOMWindowOuter> ourWindow = mDocShell->GetWindow()) {
ourWindow->MacFullscreenMenubarOverlapChanged(aOverlapAmount);
}
}
}
void AppWindow::RecomputeBrowsingContextVisibility() {
if (!mDocShell) {
return;
}
RefPtr bc = mDocShell->GetBrowsingContext();
if (!bc) {
return;
}
bc->Canonical()->RecomputeAppWindowVisibility();
}
void AppWindow::OcclusionStateChanged(bool aIsFullyOccluded) {
if (!mDocShell) {
return;
}
RecomputeBrowsingContextVisibility();
if (RefPtr win = mDocShell->GetWindow()) {
// And always fire a user-defined occlusionstatechange event on the window
win->DispatchCustomEvent(u"occlusionstatechange"_ns,
ChromeOnlyDispatch::eYes);
}
}
void AppWindow::OSToolbarButtonPressed() {
// Keep a reference as setting the chrome flags can fire events.
nsCOMPtr<nsIAppWindow> appWindow(this);
// rjc: don't use "nsIWebBrowserChrome::CHROME_EXTRA"
// due to components with multiple sidebar components
// (such as Mail/News, Addressbook, etc)... and frankly,
// Mac IE, OmniWeb, and other Mac OS X apps all work this way
uint32_t chromeMask = (nsIWebBrowserChrome::CHROME_TOOLBAR |
nsIWebBrowserChrome::CHROME_LOCATIONBAR |
nsIWebBrowserChrome::CHROME_PERSONAL_TOOLBAR);
nsCOMPtr<nsIWebBrowserChrome> wbc(do_GetInterface(appWindow));
if (!wbc) return;
uint32_t chromeFlags, newChromeFlags = 0;
wbc->GetChromeFlags(&chromeFlags);
newChromeFlags = chromeFlags & chromeMask;
if (!newChromeFlags)
chromeFlags |= chromeMask;
else
chromeFlags &= (~newChromeFlags);
wbc->SetChromeFlags(chromeFlags);
}
void AppWindow::WindowActivated() {
nsCOMPtr<nsIAppWindow> appWindow(this);
// focusing the window could cause it to close, so keep a reference to it
if (mDocShell) {
if (nsCOMPtr<nsPIDOMWindowOuter> window = mDocShell->GetWindow()) {
if (RefPtr<nsFocusManager> fm = nsFocusManager::GetFocusManager()) {
fm->WindowRaised(window, nsFocusManager::GenerateFocusActionId());
}
}
}
if (mChromeLoaded) {
PersistentAttributesDirty(AllPersistentAttributes(), Sync);
}
}
void AppWindow::WindowDeactivated() {
if (mDocShell) {
if (nsCOMPtr<nsPIDOMWindowOuter> window = mDocShell->GetWindow()) {
if (RefPtr<nsFocusManager> fm = nsFocusManager::GetFocusManager()) {
if (!fm->IsTestMode()) {
fm->WindowLowered(window, nsFocusManager::GenerateFocusActionId());
}
}
}
}
}
#ifdef USE_NATIVE_MENUS
struct LoadNativeMenusListener {
LoadNativeMenusListener(Document* aDoc, nsIWidget* aParentWindow)
: mDocument(aDoc), mParentWindow(aParentWindow) {}
RefPtr<Document> mDocument;
nsCOMPtr<nsIWidget> mParentWindow;
};
// On macOS the hidden window is created eagerly, and we want to wait for it to
// load the native menus.
static bool sWaitingForHiddenWindowToLoadNativeMenus =
# ifdef XP_MACOSX
true
# else
false
# endif
;
MOZ_CONSTINIT static nsTArray<LoadNativeMenusListener>
sLoadNativeMenusListeners;
static void BeginLoadNativeMenus(Document* aDoc, nsIWidget* aParentWindow);
static void LoadNativeMenus(Document* aDoc, nsIWidget* aParentWindow) {
MOZ_ASSERT(!gfxPlatform::IsHeadless());
// Find the menubar tag (if there is more than one, we ignore all but
// the first).
RefPtr<Element> menubar =
aDoc->QuerySelector("menubar:not([nonnative])"_ns, IgnoreErrors());
widget::NativeMenuSupport::CreateNativeMenuBar(aParentWindow, menubar);
if (sWaitingForHiddenWindowToLoadNativeMenus) {
sWaitingForHiddenWindowToLoadNativeMenus = false;
for (auto& listener : sLoadNativeMenusListeners) {
BeginLoadNativeMenus(listener.mDocument, listener.mParentWindow);
}
sLoadNativeMenusListeners.Clear();
}
}
class L10nReadyPromiseHandler final : public dom::PromiseNativeHandler {
public:
NS_DECL_ISUPPORTS
L10nReadyPromiseHandler(Document* aDoc, nsIWidget* aParentWindow)
: mDocument(aDoc), mWindow(aParentWindow) {}
void ResolvedCallback(JSContext* aCx, JS::Handle<JS::Value> aValue,
ErrorResult& aRv) override {
LoadNativeMenus(mDocument, mWindow);
}
void RejectedCallback(JSContext* aCx, JS::Handle<JS::Value> aValue,
ErrorResult& aRv) override {
// Again, this shouldn't happen, but fallback to loading the menus as is.
NS_WARNING(
"L10nReadyPromiseHandler rejected - loading fallback native "
"menu.");
LoadNativeMenus(mDocument, mWindow);
}
private:
~L10nReadyPromiseHandler() = default;
RefPtr<Document> mDocument;
nsCOMPtr<nsIWidget> mWindow;
};
NS_IMPL_ISUPPORTS0(L10nReadyPromiseHandler)
static void BeginLoadNativeMenus(Document* aDoc, nsIWidget* aParentWindow) {
if (RefPtr<DocumentL10n> l10n = aDoc->GetL10n()) {
// Wait for l10n to be ready so the menus are localized.
RefPtr<Promise> promise = l10n->Ready();
MOZ_ASSERT(promise);
RefPtr handler = new L10nReadyPromiseHandler(aDoc, aParentWindow);
promise->AppendNativeHandler(handler);
} else {
// Something went wrong loading the doc and l10n wasn't created. This
// shouldn't really happen, but if it does fallback to trying to load
// the menus as is.
LoadNativeMenus(aDoc, aParentWindow);
}
}
#endif
class AppWindowTimerCallback final : public nsITimerCallback, public nsINamed {
public:
explicit AppWindowTimerCallback(AppWindow* aWindow) : mWindow(aWindow) {}
NS_DECL_THREADSAFE_ISUPPORTS
NS_IMETHOD Notify(nsITimer* aTimer) override {
// Although this object participates in a refcount cycle (this -> mWindow
// -> mSPTimer -> this), mSPTimer is a one-shot timer and releases this
// after it fires. So we don't need to release mWindow here.
mWindow->FirePersistenceTimer();
return NS_OK;
}
NS_IMETHOD GetName(nsACString& aName) override {
aName.AssignLiteral("AppWindowTimerCallback");
return NS_OK;
}
private:
~AppWindowTimerCallback() {}
RefPtr<AppWindow> mWindow;
};
NS_IMPL_ISUPPORTS(AppWindowTimerCallback, nsITimerCallback, nsINamed)
void AppWindow::PersistentAttributesDirty(PersistentAttributes aAttributes,
PersistentAttributeUpdate aUpdate) {
aAttributes = aAttributes & mPersistentAttributesMask;
if (aAttributes.isEmpty()) {
return;
}
mPersistentAttributesDirty += aAttributes;
if (aUpdate == Sync) {
// Only apply the attributes we've been requested to apply sync, not other
// potentially dirty attributes that have been requested asynchronously.
SavePersistentAttributes(aAttributes);
return;
}
if (!mSPTimer) {
mSPTimer = NS_NewTimer();
if (!mSPTimer) {
NS_WARNING("Couldn't create timer instance?");
return;
}
}
RefPtr<AppWindowTimerCallback> callback = new AppWindowTimerCallback(this);
mSPTimer->InitWithCallback(callback, SIZE_PERSISTENCE_TIMEOUT,
nsITimer::TYPE_ONE_SHOT);
}
void AppWindow::FirePersistenceTimer() { SavePersistentAttributes(); }
//----------------------------------------
// nsIWebProgessListener implementation
//----------------------------------------
NS_IMETHODIMP
AppWindow::OnProgressChange(nsIWebProgress* aProgress, nsIRequest* aRequest,
int32_t aCurSelfProgress, int32_t aMaxSelfProgress,
int32_t aCurTotalProgress,
int32_t aMaxTotalProgress) {
MOZ_ASSERT_UNREACHABLE("notification excluded in AddProgressListener(...)");
return NS_OK;
}
NS_IMETHODIMP
AppWindow::OnStateChange(nsIWebProgress* aProgress, nsIRequest* aRequest,
uint32_t aStateFlags, nsresult aStatus) {
// If the notification is not about a document finishing, then just
// ignore it...
if (!(aStateFlags & nsIWebProgressListener::STATE_STOP) ||
!(aStateFlags & nsIWebProgressListener::STATE_IS_NETWORK)) {
return NS_OK;
}
if (mChromeLoaded) return NS_OK;
// If this document notification is for a frame then ignore it...
nsCOMPtr<mozIDOMWindowProxy> eventWin;
aProgress->GetDOMWindow(getter_AddRefs(eventWin));
auto* eventPWin = nsPIDOMWindowOuter::From(eventWin);
if (eventPWin) {
nsPIDOMWindowOuter* rootPWin = eventPWin->GetPrivateRoot();
if (eventPWin != rootPWin) return NS_OK;
}
mChromeLoaded = true;
mLockedUntilChromeLoad = false;
#ifdef USE_NATIVE_MENUS
///////////////////////////////
// Find the Menubar DOM and Load the menus, hooking them up to the loaded
// commands
///////////////////////////////
if (!gfxPlatform::IsHeadless()) {
if (RefPtr<Document> menubarDoc = mDocShell->GetExtantDocument()) {
if (mIsHiddenWindow || !sWaitingForHiddenWindowToLoadNativeMenus) {
BeginLoadNativeMenus(menubarDoc, mWindow);
} else {
sLoadNativeMenusListeners.EmplaceBack(menubarDoc, mWindow);
}
}
}
#endif // USE_NATIVE_MENUS
OnChromeLoaded();
return NS_OK;
}
NS_IMETHODIMP
AppWindow::OnLocationChange(nsIWebProgress* aProgress, nsIRequest* aRequest,
nsIURI* aURI, uint32_t aFlags) {
MOZ_ASSERT_UNREACHABLE("notification excluded in AddProgressListener(...)");
return NS_OK;
}
NS_IMETHODIMP
AppWindow::OnStatusChange(nsIWebProgress* aWebProgress, nsIRequest* aRequest,
nsresult aStatus, const char16_t* aMessage) {
MOZ_ASSERT_UNREACHABLE("notification excluded in AddProgressListener(...)");
return NS_OK;
}
NS_IMETHODIMP
AppWindow::OnSecurityChange(nsIWebProgress* aWebProgress, nsIRequest* aRequest,
uint32_t aState) {
MOZ_ASSERT_UNREACHABLE("notification excluded in AddProgressListener(...)");
return NS_OK;
}
NS_IMETHODIMP
AppWindow::OnContentBlockingEvent(nsIWebProgress* aWebProgress,
nsIRequest* aRequest, uint32_t aEvent) {
MOZ_ASSERT_UNREACHABLE("notification excluded in AddProgressListener(...)");
return NS_OK;
}
/**
* ExecuteCloseHandler - Run the close handler, if any.
* @return true iff we found a close handler to run.
*/
bool AppWindow::ExecuteCloseHandler() {
/* If the event handler closes this window -- a likely scenario --
things get deleted out of order without this death grip.
(The problem may be the death grip in nsWindow::windowProc,
which forces this window's widget to remain alive longer
than it otherwise would.) */
nsCOMPtr<nsIAppWindow> kungFuDeathGrip(this);
nsCOMPtr<EventTarget> eventTarget;
if (mDocShell) {
eventTarget = do_QueryInterface(mDocShell->GetWindow());
}
if (eventTarget) {
nsCOMPtr<nsIDocumentViewer> viewer;
mDocShell->GetDocViewer(getter_AddRefs(viewer));
if (viewer) {
RefPtr<nsPresContext> presContext = viewer->GetPresContext();
nsEventStatus status = nsEventStatus_eIgnore;
WidgetMouseEvent event(true, eClose, nullptr, WidgetMouseEvent::eReal);
nsresult rv = EventDispatcher::Dispatch(eventTarget, presContext, &event,
nullptr, &status);
if (NS_SUCCEEDED(rv) && status == nsEventStatus_eConsumeNoDefault)
return true;
// else fall through and return false
}
}
return false;
} // ExecuteCloseHandler
void AppWindow::ConstrainToOpenerScreen(int32_t* aX, int32_t* aY) {
if (mOpenerScreenRect.IsEmpty()) {
*aX = *aY = 0;
return;
}
int32_t left, top, width, height;
// Constrain initial positions to the same screen as opener
nsCOMPtr<nsIScreenManager> screenmgr =
do_GetService("@mozilla.org/gfx/screenmanager;1");
if (screenmgr) {
nsCOMPtr<nsIScreen> screen = screenmgr->ScreenForRect(mOpenerScreenRect);
if (screen) {
screen->GetAvailRectDisplayPix(&left, &top, &width, &height);
if (*aX < left || *aX > left + width) {
*aX = left;
}
if (*aY < top || *aY > top + height) {
*aY = top;
}
}
}
}
nsIAppWindow* AppWindow::WidgetListenerDelegate::GetAppWindow() {
return mAppWindow->GetAppWindow();
}
PresShell* AppWindow::WidgetListenerDelegate::GetPresShell() {
return mAppWindow->GetPresShell();
}
bool AppWindow::WidgetListenerDelegate::WindowMoved(nsIWidget* aWidget,
int32_t aX, int32_t aY,
ByMoveToRect) {
RefPtr<AppWindow> holder = mAppWindow;
return holder->WindowMoved(aWidget, aX, aY);
}
bool AppWindow::WidgetListenerDelegate::WindowResized(nsIWidget* aWidget,
int32_t aWidth,
int32_t aHeight) {
RefPtr<AppWindow> holder = mAppWindow;
return holder->WindowResized(aWidget, aWidth, aHeight);
}
bool AppWindow::WidgetListenerDelegate::RequestWindowClose(nsIWidget* aWidget) {
RefPtr<AppWindow> holder = mAppWindow;
return holder->RequestWindowClose(aWidget);
}
void AppWindow::WidgetListenerDelegate::SizeModeChanged(nsSizeMode aSizeMode) {
RefPtr<AppWindow> holder = mAppWindow;
holder->SizeModeChanged(aSizeMode);
}
void AppWindow::WidgetListenerDelegate::MacFullscreenMenubarOverlapChanged(
DesktopCoord aOverlapAmount) {
RefPtr<AppWindow> holder = mAppWindow;
return holder->MacFullscreenMenubarOverlapChanged(aOverlapAmount);
}
void AppWindow::WidgetListenerDelegate::OcclusionStateChanged(
bool aIsFullyOccluded) {
RefPtr<AppWindow> holder = mAppWindow;
holder->OcclusionStateChanged(aIsFullyOccluded);
}
void AppWindow::WidgetListenerDelegate::OSToolbarButtonPressed() {
RefPtr<AppWindow> holder = mAppWindow;
holder->OSToolbarButtonPressed();
}
void AppWindow::WidgetListenerDelegate::WindowActivated() {
RefPtr<AppWindow> holder = mAppWindow;
holder->WindowActivated();
}
void AppWindow::WidgetListenerDelegate::WindowDeactivated() {
RefPtr<AppWindow> holder = mAppWindow;
holder->WindowDeactivated();
}
} // namespace mozilla
|