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
|
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#define UNICODE
#include "nsWindowsShellService.h"
#include "nsWindowsShellServiceInternal.h"
#include "BinaryPath.h"
#include "gfxUtils.h"
#include "imgIContainer.h"
#include "imgIRequest.h"
#include "imgITools.h"
#include "mozilla/dom/Element.h"
#include "mozilla/dom/Promise.h"
#include "mozilla/ErrorResult.h"
#include "mozilla/FileUtils.h"
#include "mozilla/gfx/2D.h"
#include "mozilla/intl/Localization.h"
#include "mozilla/RefPtr.h"
#include "mozilla/UniquePtrExtensions.h"
#include "mozilla/widget/WinTaskbar.h"
#include "mozilla/WindowsVersion.h"
#include "mozilla/WinHeaderOnlyUtils.h"
#include "nsAppDirectoryServiceDefs.h"
#include "nsComponentManagerUtils.h"
#include "nsDirectoryServiceDefs.h"
#include "nsDirectoryServiceUtils.h"
#include "nsIContent.h"
#include "nsIFile.h"
#include "nsIFileStreams.h"
#include "nsIImageLoadingContent.h"
#include "nsIMIMEService.h"
#include "nsINIParser.h"
#include "nsIOutputStream.h"
#include "nsIPrefService.h"
#include "nsIStringBundle.h"
#include "nsIWindowsRegKey.h"
#include "nsIXULAppInfo.h"
#include "nsLocalFile.h"
#include "nsNativeAppSupportWin.h"
#include "nsNetUtil.h"
#include "nsProxyRelease.h"
#include "nsServiceManagerUtils.h"
#include "nsShellService.h"
#include "nsUnicharUtils.h"
#include "nsWindowsHelpers.h"
#include "nsXULAppAPI.h"
#include "Windows11TaskbarPinning.h"
#include "WindowsDefaultBrowser.h"
#include "WindowsUserChoice.h"
#include "WinUtils.h"
#include <comutil.h>
#include <knownfolders.h>
#include <mbstring.h>
#include <objbase.h>
#include <propkey.h>
#include <propvarutil.h>
#include <shellapi.h>
#include <strsafe.h>
#include <windows.h>
#include <windows.foundation.h>
#include <wrl.h>
#include <wrl/wrappers/corewrappers.h>
using namespace ABI::Windows;
using namespace ABI::Windows::Foundation;
using namespace ABI::Windows::Foundation::Collections;
using namespace Microsoft::WRL;
using namespace Microsoft::WRL::Wrappers;
#ifndef __MINGW32__
# include <windows.applicationmodel.h>
# include <windows.applicationmodel.activation.h>
# include <windows.applicationmodel.core.h>
# include <windows.ui.startscreen.h>
using namespace ABI::Windows::ApplicationModel;
using namespace ABI::Windows::ApplicationModel::Core;
using namespace ABI::Windows::UI::StartScreen;
#endif
#define PRIVATE_BROWSING_BINARY L"private_browsing.exe"
#undef ACCESS_READ
#ifndef MAX_BUF
# define MAX_BUF 4096
#endif
#define REG_SUCCEEDED(val) (val == ERROR_SUCCESS)
#define REG_FAILED(val) (val != ERROR_SUCCESS)
#ifdef DEBUG
# define NS_ENSURE_HRESULT(hres, ret) \
do { \
HRESULT result = hres; \
if (MOZ_UNLIKELY(FAILED(result))) { \
mozilla::SmprintfPointer msg = mozilla::Smprintf( \
"NS_ENSURE_HRESULT(%s, %s) failed with " \
"result 0x%" PRIX32, \
#hres, #ret, static_cast<uint32_t>(result)); \
NS_WARNING(msg.get()); \
return ret; \
} \
} while (false)
#else
# define NS_ENSURE_HRESULT(hres, ret) \
if (MOZ_UNLIKELY(FAILED(hres))) return ret
#endif
using namespace mozilla;
using mozilla::intl::Localization;
struct SysFreeStringDeleter {
void operator()(BSTR aPtr) { ::SysFreeString(aPtr); }
};
using BStrPtr = mozilla::UniquePtr<OLECHAR, SysFreeStringDeleter>;
NS_IMPL_ISUPPORTS(nsWindowsShellService, nsIToolkitShellService,
nsIShellService, nsIWindowsShellService)
/* Enable logging by setting MOZ_LOG to "nsWindowsShellService:5" for debugging
* purposes. */
static LazyLogModule sLog("nsWindowsShellService");
static bool PollAppsFolderForShortcut(const nsAString& aAppUserModelId,
const TimeDuration aTimeout);
static nsresult PinCurrentAppToTaskbarWin10(bool aCheckOnly,
const nsAString& aAppUserModelId,
const nsAString& aShortcutPath);
static nsresult WriteBitmap(nsIFile* aFile, imgIContainer* aImage);
static nsresult WriteIcon(nsIFile* aIcoFile, gfx::DataSourceSurface* aSurface);
static nsresult OpenKeyForReading(HKEY aKeyRoot, const nsAString& aKeyName,
HKEY* aKey) {
const nsString& flatName = PromiseFlatString(aKeyName);
DWORD res = ::RegOpenKeyExW(aKeyRoot, flatName.get(), 0, KEY_READ, aKey);
switch (res) {
case ERROR_SUCCESS:
break;
case ERROR_ACCESS_DENIED:
return NS_ERROR_FILE_ACCESS_DENIED;
case ERROR_FILE_NOT_FOUND:
return NS_ERROR_NOT_AVAILABLE;
}
return NS_OK;
}
nsresult GetHelperPath(nsAutoString& aPath) {
nsresult rv;
nsCOMPtr<nsIProperties> directoryService =
do_GetService(NS_DIRECTORY_SERVICE_CONTRACTID, &rv);
NS_ENSURE_SUCCESS(rv, rv);
nsCOMPtr<nsIFile> appHelper;
rv = directoryService->Get(XRE_EXECUTABLE_FILE, NS_GET_IID(nsIFile),
getter_AddRefs(appHelper));
NS_ENSURE_SUCCESS(rv, rv);
rv = appHelper->SetNativeLeafName("uninstall"_ns);
NS_ENSURE_SUCCESS(rv, rv);
rv = appHelper->AppendNative("helper.exe"_ns);
NS_ENSURE_SUCCESS(rv, rv);
rv = appHelper->GetPath(aPath);
aPath.Insert(L'"', 0);
aPath.Append(L'"');
return rv;
}
nsresult LaunchHelper(nsAutoString& aPath) {
STARTUPINFOW si = {sizeof(si), 0};
PROCESS_INFORMATION pi = {0};
if (!CreateProcessW(nullptr, (LPWSTR)aPath.get(), nullptr, nullptr, FALSE, 0,
nullptr, nullptr, &si, &pi)) {
return NS_ERROR_FAILURE;
}
CloseHandle(pi.hProcess);
CloseHandle(pi.hThread);
return NS_OK;
}
static bool IsPathDefaultForClass(
const RefPtr<IApplicationAssociationRegistration>& pAAR, wchar_t* exePath,
LPCWSTR aClassName) {
LPWSTR registeredApp;
bool isProtocol = *aClassName != L'.';
ASSOCIATIONTYPE queryType = isProtocol ? AT_URLPROTOCOL : AT_FILEEXTENSION;
HRESULT hr = pAAR->QueryCurrentDefault(aClassName, queryType, AL_EFFECTIVE,
®isteredApp);
if (FAILED(hr)) {
return false;
}
nsAutoString regAppName(registeredApp);
CoTaskMemFree(registeredApp);
// Make sure the application path for this progID is this installation.
regAppName.AppendLiteral("\\shell\\open\\command");
HKEY theKey;
nsresult rv = OpenKeyForReading(HKEY_CLASSES_ROOT, regAppName, &theKey);
if (NS_FAILED(rv)) {
return false;
}
wchar_t cmdFromReg[MAX_BUF] = L"";
DWORD len = sizeof(cmdFromReg);
DWORD res = ::RegQueryValueExW(theKey, nullptr, nullptr, nullptr,
(LPBYTE)cmdFromReg, &len);
::RegCloseKey(theKey);
if (REG_FAILED(res)) {
return false;
}
nsAutoString pathFromReg(cmdFromReg);
nsLocalFile::CleanupCmdHandlerPath(pathFromReg);
return _wcsicmp(exePath, pathFromReg.Data()) == 0;
}
NS_IMETHODIMP
nsWindowsShellService::IsDefaultBrowser(bool aForAllTypes,
bool* aIsDefaultBrowser) {
*aIsDefaultBrowser = false;
RefPtr<IApplicationAssociationRegistration> pAAR;
HRESULT hr = CoCreateInstance(
CLSID_ApplicationAssociationRegistration, nullptr, CLSCTX_INPROC,
IID_IApplicationAssociationRegistration, getter_AddRefs(pAAR));
if (FAILED(hr)) {
return NS_OK;
}
wchar_t exePath[MAXPATHLEN] = L"";
nsresult rv = BinaryPath::GetLong(exePath);
if (NS_FAILED(rv)) {
return NS_OK;
}
*aIsDefaultBrowser = IsPathDefaultForClass(pAAR, exePath, L"http");
if (*aIsDefaultBrowser && aForAllTypes) {
*aIsDefaultBrowser = IsPathDefaultForClass(pAAR, exePath, L".html");
}
return NS_OK;
}
NS_IMETHODIMP
nsWindowsShellService::IsDefaultHandlerFor(
const nsAString& aFileExtensionOrProtocol, bool* aIsDefaultHandlerFor) {
*aIsDefaultHandlerFor = false;
RefPtr<IApplicationAssociationRegistration> pAAR;
HRESULT hr = CoCreateInstance(
CLSID_ApplicationAssociationRegistration, nullptr, CLSCTX_INPROC,
IID_IApplicationAssociationRegistration, getter_AddRefs(pAAR));
if (FAILED(hr)) {
return NS_OK;
}
wchar_t exePath[MAXPATHLEN] = L"";
nsresult rv = BinaryPath::GetLong(exePath);
if (NS_FAILED(rv)) {
return NS_OK;
}
const nsString& flatClass = PromiseFlatString(aFileExtensionOrProtocol);
*aIsDefaultHandlerFor = IsPathDefaultForClass(pAAR, exePath, flatClass.get());
return NS_OK;
}
NS_IMETHODIMP
nsWindowsShellService::QueryCurrentDefaultHandlerFor(
const nsAString& aFileExtensionOrProtocol, nsAString& aResult) {
aResult.Truncate();
RefPtr<IApplicationAssociationRegistration> pAAR;
HRESULT hr = CoCreateInstance(
CLSID_ApplicationAssociationRegistration, nullptr, CLSCTX_INPROC,
IID_IApplicationAssociationRegistration, getter_AddRefs(pAAR));
if (FAILED(hr)) {
return NS_OK;
}
const nsString& flatClass = PromiseFlatString(aFileExtensionOrProtocol);
LPWSTR registeredApp;
bool isProtocol = flatClass.First() != L'.';
ASSOCIATIONTYPE queryType = isProtocol ? AT_URLPROTOCOL : AT_FILEEXTENSION;
hr = pAAR->QueryCurrentDefault(flatClass.get(), queryType, AL_EFFECTIVE,
®isteredApp);
if (hr == HRESULT_FROM_WIN32(ERROR_NO_ASSOCIATION)) {
return NS_OK;
}
NS_ENSURE_HRESULT(hr, NS_ERROR_FAILURE);
aResult = registeredApp;
CoTaskMemFree(registeredApp);
return NS_OK;
}
nsresult nsWindowsShellService::LaunchControlPanelDefaultsSelectionUI() {
IApplicationAssociationRegistrationUI* pAARUI;
HRESULT hr = CoCreateInstance(
CLSID_ApplicationAssociationRegistrationUI, NULL, CLSCTX_INPROC,
IID_IApplicationAssociationRegistrationUI, (void**)&pAARUI);
if (SUCCEEDED(hr)) {
mozilla::UniquePtr<wchar_t[]> appRegName;
GetAppRegName(appRegName);
hr = pAARUI->LaunchAdvancedAssociationUI(appRegName.get());
pAARUI->Release();
}
return SUCCEEDED(hr) ? NS_OK : NS_ERROR_FAILURE;
}
NS_IMETHODIMP
nsWindowsShellService::CheckAllProgIDsExist(bool* aResult) {
*aResult = false;
nsAutoString aumid;
if (!mozilla::widget::WinTaskbar::GetAppUserModelID(aumid)) {
return NS_OK;
}
if (widget::WinUtils::HasPackageIdentity()) {
UniquePtr<wchar_t[]> extraProgID;
nsresult rv;
bool result = true;
// "FirefoxURL".
rv = GetMsixProgId(L"https", extraProgID);
if (NS_WARN_IF(NS_FAILED(rv))) {
return rv;
}
result = result && CheckProgIDExists(extraProgID.get());
// "FirefoxHTML".
rv = GetMsixProgId(L".htm", extraProgID);
if (NS_WARN_IF(NS_FAILED(rv))) {
return rv;
}
result = result && CheckProgIDExists(extraProgID.get());
// "FirefoxPDF".
rv = GetMsixProgId(L".pdf", extraProgID);
if (NS_WARN_IF(NS_FAILED(rv))) {
return rv;
}
result = result && CheckProgIDExists(extraProgID.get());
*aResult = result;
} else {
*aResult =
CheckProgIDExists(FormatProgID(L"FirefoxURL", aumid.get()).get()) &&
CheckProgIDExists(FormatProgID(L"FirefoxHTML", aumid.get()).get()) &&
CheckProgIDExists(FormatProgID(L"FirefoxPDF", aumid.get()).get());
}
return NS_OK;
}
NS_IMETHODIMP
nsWindowsShellService::CheckBrowserUserChoiceHashes(bool* aResult) {
*aResult = ::CheckBrowserUserChoiceHashes();
return NS_OK;
}
NS_IMETHODIMP
nsWindowsShellService::CheckCurrentProcessAUMIDForTesting(
nsAString& aRetAumid) {
PWSTR id;
HRESULT hr = GetCurrentProcessExplicitAppUserModelID(&id);
if (FAILED(hr)) {
// Process AUMID may not be set on MSIX builds,
// if so we should return a dummy value
if (widget::WinUtils::HasPackageIdentity()) {
aRetAumid.Assign(u"MSIXAumidTestValue"_ns);
return NS_OK;
}
return NS_ERROR_FAILURE;
}
aRetAumid.Assign(id);
CoTaskMemFree(id);
return NS_OK;
}
NS_IMETHODIMP
nsWindowsShellService::CanSetDefaultBrowserUserChoice(bool* aResult) {
*aResult = false;
// If the WDBA is not available, this could never succeed.
#ifdef MOZ_DEFAULT_BROWSER_AGENT
bool progIDsExist = false;
bool hashOk = false;
*aResult = NS_SUCCEEDED(CheckAllProgIDsExist(&progIDsExist)) &&
progIDsExist &&
NS_SUCCEEDED(CheckBrowserUserChoiceHashes(&hashOk)) && hashOk;
#endif
return NS_OK;
}
nsresult nsWindowsShellService::LaunchModernSettingsDialogDefaultApps() {
return ::LaunchModernSettingsDialogDefaultApps() ? NS_OK : NS_ERROR_FAILURE;
}
NS_IMETHODIMP
nsWindowsShellService::SetDefaultBrowser(bool aForAllUsers) {
// If running from within a package, don't attempt to set default with
// the helper, as it will not work and will only confuse our package's
// virtualized registry.
nsresult rv = NS_OK;
if (!widget::WinUtils::HasPackageIdentity()) {
nsAutoString appHelperPath;
if (NS_FAILED(GetHelperPath(appHelperPath))) return NS_ERROR_FAILURE;
if (aForAllUsers) {
appHelperPath.AppendLiteral(" /SetAsDefaultAppGlobal");
} else {
appHelperPath.AppendLiteral(" /SetAsDefaultAppUser");
}
rv = LaunchHelper(appHelperPath);
}
if (NS_SUCCEEDED(rv)) {
rv = LaunchModernSettingsDialogDefaultApps();
// The above call should never really fail, but just in case
// fall back to showing control panel for all defaults
if (NS_FAILED(rv)) {
rv = LaunchControlPanelDefaultsSelectionUI();
}
}
nsCOMPtr<nsIPrefBranch> prefs(do_GetService(NS_PREFSERVICE_CONTRACTID));
if (prefs) {
(void)prefs->SetBoolPref(PREF_CHECKDEFAULTBROWSER, true);
// Reset the number of times the dialog should be shown
// before it is silenced.
(void)prefs->SetIntPref(PREF_DEFAULTBROWSERCHECKCOUNT, 0);
}
return rv;
}
/*
* Asynchronous function to Write an ico file to the disk / in a nsIFile.
* Limitation: Only square images are supported as of now.
*/
NS_IMETHODIMP
nsWindowsShellService::CreateWindowsIcon(nsIFile* aIcoFile,
imgIContainer* aImage, JSContext* aCx,
dom::Promise** aPromise) {
NS_ENSURE_ARG_POINTER(aIcoFile);
NS_ENSURE_ARG_POINTER(aImage);
NS_ENSURE_ARG_POINTER(aCx);
NS_ENSURE_ARG_POINTER(aPromise);
if (!NS_IsMainThread()) {
return NS_ERROR_NOT_SAME_THREAD;
}
ErrorResult rv;
RefPtr<dom::Promise> promise =
dom::Promise::Create(xpc::CurrentNativeGlobal(aCx), rv);
if (MOZ_UNLIKELY(rv.Failed())) {
return rv.StealNSResult();
}
auto promiseHolder = MakeRefPtr<nsMainThreadPtrHolder<dom::Promise>>(
"CreateWindowsIcon promise", promise);
MOZ_LOG(sLog, LogLevel::Debug,
("%s:%d - Reading input image...\n", __FILE__, __LINE__));
RefPtr<gfx::SourceSurface> surface = aImage->GetFrame(
imgIContainer::FRAME_FIRST, imgIContainer::FLAG_SYNC_DECODE);
NS_ENSURE_TRUE(surface, NS_ERROR_FAILURE);
// At time of writing only `DataSourceSurface` was guaranteed thread safe. We
// need this guarantee to write the icon file off the main thread.
RefPtr<gfx::DataSourceSurface> dataSurface = surface->GetDataSurface();
NS_ENSURE_TRUE(dataSurface, NS_ERROR_FAILURE);
MOZ_LOG(sLog, LogLevel::Debug,
("%s:%d - Surface found, writing icon... \n", __FILE__, __LINE__));
NS_DispatchBackgroundTask(
NS_NewRunnableFunction(
"CreateWindowsIcon",
[icoFile = nsCOMPtr<nsIFile>(aIcoFile), dataSurface, promiseHolder] {
nsresult rv = WriteIcon(icoFile, dataSurface);
NS_DispatchToMainThread(NS_NewRunnableFunction(
"CreateWindowsIcon callback", [rv, promiseHolder] {
dom::Promise* promise = promiseHolder.get()->get();
if (NS_SUCCEEDED(rv)) {
promise->MaybeResolveWithUndefined();
} else {
promise->MaybeReject(rv);
}
}));
}),
NS_DISPATCH_EVENT_MAY_BLOCK);
promise.forget(aPromise);
return NS_OK;
}
static nsresult WriteIcon(nsIFile* aIcoFile, gfx::DataSourceSurface* aSurface) {
NS_ENSURE_ARG(aIcoFile);
NS_ENSURE_ARG(aSurface);
const gfx::IntSize size = aSurface->GetSize();
if (size.IsEmpty()) {
MOZ_LOG(sLog, LogLevel::Debug,
("%s:%d - The input image looks empty :(\n", __FILE__, __LINE__));
return NS_ERROR_FAILURE;
}
int32_t width = aSurface->GetSize().width;
int32_t height = aSurface->GetSize().height;
MOZ_LOG(sLog, LogLevel::Debug,
("%s:%d - Input image dimensions are: %dx%d pixels\n", __FILE__,
__LINE__, width, height));
NS_ENSURE_TRUE(height > 0, NS_ERROR_FAILURE);
NS_ENSURE_TRUE(width > 0, NS_ERROR_FAILURE);
NS_ENSURE_TRUE(width == height, NS_ERROR_FAILURE);
MOZ_LOG(sLog, LogLevel::Debug,
("%s:%d - Opening file for writing...\n", __FILE__, __LINE__));
ScopedCloseFile file;
nsresult rv = aIcoFile->OpenANSIFileDesc("wb", getter_Transfers(file));
NS_ENSURE_SUCCESS(rv, rv);
MOZ_LOG(sLog, LogLevel::Debug,
("%s:%d - Writing icon...\n", __FILE__, __LINE__));
rv = gfxUtils::EncodeSourceSurface(aSurface, ImageType::ICO, u""_ns,
gfxUtils::eBinaryEncode, file.get());
if (NS_FAILED(rv)) {
MOZ_LOG(sLog, LogLevel::Debug,
("%s:%d - Could not write the icon!\n", __FILE__, __LINE__));
return rv;
}
MOZ_LOG(sLog, LogLevel::Debug,
("%s:%d - Icon written!\n", __FILE__, __LINE__));
return NS_OK;
}
static nsresult WriteBitmap(nsIFile* aFile, imgIContainer* aImage) {
nsresult rv;
RefPtr<gfx::SourceSurface> surface = aImage->GetFrame(
imgIContainer::FRAME_FIRST, imgIContainer::FLAG_SYNC_DECODE);
NS_ENSURE_TRUE(surface, NS_ERROR_FAILURE);
// For either of the following formats we want to set the biBitCount member
// of the BITMAPINFOHEADER struct to 32, below. For that value the bitmap
// format defines that the A8/X8 WORDs in the bitmap byte stream be ignored
// for the BI_RGB value we use for the biCompression member.
MOZ_ASSERT(surface->GetFormat() == gfx::SurfaceFormat::B8G8R8A8 ||
surface->GetFormat() == gfx::SurfaceFormat::B8G8R8X8);
RefPtr<gfx::DataSourceSurface> dataSurface = surface->GetDataSurface();
NS_ENSURE_TRUE(dataSurface, NS_ERROR_FAILURE);
int32_t width = dataSurface->GetSize().width;
int32_t height = dataSurface->GetSize().height;
int32_t bytesPerPixel = 4 * sizeof(uint8_t);
uint32_t bytesPerRow = bytesPerPixel * width;
// initialize these bitmap structs which we will later
// serialize directly to the head of the bitmap file
BITMAPINFOHEADER bmi;
bmi.biSize = sizeof(BITMAPINFOHEADER);
bmi.biWidth = width;
bmi.biHeight = height;
bmi.biPlanes = 1;
bmi.biBitCount = (WORD)bytesPerPixel * 8;
bmi.biCompression = BI_RGB;
bmi.biSizeImage = bytesPerRow * height;
bmi.biXPelsPerMeter = 0;
bmi.biYPelsPerMeter = 0;
bmi.biClrUsed = 0;
bmi.biClrImportant = 0;
BITMAPFILEHEADER bf;
bf.bfType = 0x4D42; // 'BM'
bf.bfReserved1 = 0;
bf.bfReserved2 = 0;
bf.bfOffBits = sizeof(BITMAPFILEHEADER) + sizeof(BITMAPINFOHEADER);
bf.bfSize = bf.bfOffBits + bmi.biSizeImage;
// get a file output stream
nsCOMPtr<nsIOutputStream> stream;
rv = NS_NewLocalFileOutputStream(getter_AddRefs(stream), aFile);
NS_ENSURE_SUCCESS(rv, rv);
// (redundant) guard clause to assert stream is initialized
if (NS_WARN_IF(!stream)) {
MOZ_ASSERT(stream, "rv should have failed when stream is not initialized.");
return NS_ERROR_FAILURE;
}
gfx::DataSourceSurface::MappedSurface map;
if (!dataSurface->Map(gfx::DataSourceSurface::MapType::READ, &map)) {
// removal of file created handled later
rv = NS_ERROR_FAILURE;
}
// enter only if datasurface mapping succeeded
if (NS_SUCCEEDED(rv)) {
// write the bitmap headers and rgb pixel data to the file
uint32_t written;
rv = stream->Write((const char*)&bf, sizeof(BITMAPFILEHEADER), &written);
if (NS_SUCCEEDED(rv)) {
rv = stream->Write((const char*)&bmi, sizeof(BITMAPINFOHEADER), &written);
if (NS_SUCCEEDED(rv)) {
// write out the image data backwards because the desktop won't
// show bitmaps with negative heights for top-to-bottom
uint32_t i = map.mStride * height;
do {
i -= map.mStride;
rv = stream->Write(((const char*)map.mData) + i, bytesPerRow,
&written);
if (NS_FAILED(rv)) {
break;
}
} while (i != 0);
}
}
dataSurface->Unmap();
}
stream->Close();
// Obtaining the file output stream results in a newly created file or
// truncates the file if it already exists. As such, it is necessary to
// remove the file if the write fails for some reason.
if (NS_FAILED(rv)) {
if (NS_WARN_IF(NS_FAILED(aFile->Remove(PR_FALSE)))) {
MOZ_LOG(sLog, LogLevel::Warning,
("Failed to remove empty bitmap file : %s",
aFile->HumanReadablePath().get()));
}
}
return rv;
}
NS_IMETHODIMP
nsWindowsShellService::SetDesktopBackground(dom::Element* aElement,
int32_t aPosition,
const nsACString& aImageName) {
if (!aElement || !aElement->IsHTMLElement(nsGkAtoms::img)) {
// XXX write background loading stuff!
return NS_ERROR_NOT_AVAILABLE;
}
nsresult rv;
nsCOMPtr<nsIImageLoadingContent> imageContent =
do_QueryInterface(aElement, &rv);
if (!imageContent) return rv;
// get the image container
nsCOMPtr<imgIRequest> request;
rv = imageContent->GetRequest(nsIImageLoadingContent::CURRENT_REQUEST,
getter_AddRefs(request));
if (!request) return rv;
nsCOMPtr<imgIContainer> container;
rv = request->GetImage(getter_AddRefs(container));
if (!container) return NS_ERROR_FAILURE;
// get the file name from localized strings, e.g. "Desktop Background", then
// append the extension (".bmp").
nsTArray<nsCString> resIds = {
"browser/setDesktopBackground.ftl"_ns,
};
RefPtr<Localization> l10n = Localization::Create(resIds, true);
nsAutoCString fileLeafNameUtf8;
IgnoredErrorResult locRv;
l10n->FormatValueSync("set-desktop-background-filename"_ns, {},
fileLeafNameUtf8, locRv);
nsAutoString fileLeafName = NS_ConvertUTF8toUTF16(fileLeafNameUtf8);
fileLeafName.AppendLiteral(".bmp");
// get the profile root directory
nsCOMPtr<nsIFile> file;
rv = NS_GetSpecialDirectory(NS_APP_APPLICATION_REGISTRY_DIR,
getter_AddRefs(file));
NS_ENSURE_SUCCESS(rv, rv);
// eventually, the path is "%APPDATA%\Mozilla\Firefox\Desktop Background.bmp"
rv = file->Append(fileLeafName);
NS_ENSURE_SUCCESS(rv, rv);
nsAutoString path;
rv = file->GetPath(path);
NS_ENSURE_SUCCESS(rv, rv);
// write the bitmap to a file in the profile directory.
// We have to write old bitmap format for Windows 7 wallpaper support.
rv = WriteBitmap(file, container);
// if the file was written successfully, set it as the system wallpaper
if (NS_SUCCEEDED(rv)) {
nsCOMPtr<nsIWindowsRegKey> regKey =
do_CreateInstance("@mozilla.org/windows-registry-key;1", &rv);
NS_ENSURE_SUCCESS(rv, rv);
rv = regKey->Create(nsIWindowsRegKey::ROOT_KEY_CURRENT_USER,
u"Control Panel\\Desktop"_ns,
nsIWindowsRegKey::ACCESS_SET_VALUE);
NS_ENSURE_SUCCESS(rv, rv);
nsAutoString tile;
nsAutoString style;
switch (aPosition) {
case BACKGROUND_TILE:
style.Assign('0');
tile.Assign('1');
break;
case BACKGROUND_CENTER:
style.Assign('0');
tile.Assign('0');
break;
case BACKGROUND_STRETCH:
style.Assign('2');
tile.Assign('0');
break;
case BACKGROUND_FILL:
style.AssignLiteral("10");
tile.Assign('0');
break;
case BACKGROUND_FIT:
style.Assign('6');
tile.Assign('0');
break;
case BACKGROUND_SPAN:
style.AssignLiteral("22");
tile.Assign('0');
break;
}
rv = regKey->WriteStringValue(u"TileWallpaper"_ns, tile);
NS_ENSURE_SUCCESS(rv, rv);
rv = regKey->WriteStringValue(u"WallpaperStyle"_ns, style);
NS_ENSURE_SUCCESS(rv, rv);
rv = regKey->Close();
NS_ENSURE_SUCCESS(rv, rv);
::SystemParametersInfoW(SPI_SETDESKWALLPAPER, 0, (PVOID)path.get(),
SPIF_UPDATEINIFILE | SPIF_SENDCHANGE);
}
return rv;
}
NS_IMETHODIMP
nsWindowsShellService::GetDesktopBackgroundColor(uint32_t* aColor) {
uint32_t color = ::GetSysColor(COLOR_DESKTOP);
*aColor =
(GetRValue(color) << 16) | (GetGValue(color) << 8) | GetBValue(color);
return NS_OK;
}
NS_IMETHODIMP
nsWindowsShellService::SetDesktopBackgroundColor(uint32_t aColor) {
int aParameters[2] = {COLOR_BACKGROUND, COLOR_DESKTOP};
BYTE r = (aColor >> 16);
BYTE g = (aColor << 16) >> 24;
BYTE b = (aColor << 24) >> 24;
COLORREF colors[2] = {RGB(r, g, b), RGB(r, g, b)};
::SetSysColors(sizeof(aParameters) / sizeof(int), aParameters, colors);
nsresult rv;
nsCOMPtr<nsIWindowsRegKey> regKey =
do_CreateInstance("@mozilla.org/windows-registry-key;1", &rv);
NS_ENSURE_SUCCESS(rv, rv);
rv = regKey->Create(nsIWindowsRegKey::ROOT_KEY_CURRENT_USER,
u"Control Panel\\Colors"_ns,
nsIWindowsRegKey::ACCESS_SET_VALUE);
NS_ENSURE_SUCCESS(rv, rv);
wchar_t rgb[12];
_snwprintf(rgb, 12, L"%u %u %u", r, g, b);
rv = regKey->WriteStringValue(u"Background"_ns, nsDependentString(rgb));
NS_ENSURE_SUCCESS(rv, rv);
return regKey->Close();
}
/*
* Writes information about a shortcut to a shortcuts log in
* %PROGRAMDATA%\Mozilla-1de4eec8-1241-4177-a864-e594e8d1fb38.
* (This is the same directory used for update staging.)
* For more on the shortcuts log format and purpose, consult
* /toolkit/mozapps/installer/windows/nsis/common.nsh.
*
* The shortcuts log created or appended here is named after
* the currently running application and current user SID.
* For example: Firefox_$SID_shortcuts.ini.
*
* If it does not exist, it will be created. If it exists
* and a matching shortcut named already exists in the file,
* a new one will not be appended.
*
* In an ideal world this function would not need aShortcutsLogDir
* passed to it, but it is called by at least one function that runs
* asynchronously, and is therefore unable to use nsDirectoryService
* to look it up itself.
*/
static nsresult WriteShortcutToLog(nsIFile* aShortcutsLogDir,
KNOWNFOLDERID aFolderId,
const nsAString& aShortcutName) {
// the section inside the shortcuts log
nsAutoCString section;
// the shortcuts log wants "Programs" shortcuts in its "STARTMENU" section
if (aFolderId == FOLDERID_CommonPrograms || aFolderId == FOLDERID_Programs) {
section.Assign("STARTMENU");
} else if (aFolderId == FOLDERID_PublicDesktop ||
aFolderId == FOLDERID_Desktop) {
section.Assign("DESKTOP");
} else {
return NS_ERROR_INVALID_ARG;
}
nsCOMPtr<nsIFile> shortcutsLog;
nsresult rv = aShortcutsLogDir->GetParent(getter_AddRefs(shortcutsLog));
NS_ENSURE_SUCCESS(rv, rv);
nsAutoCString appName;
nsCOMPtr<nsIXULAppInfo> appInfo =
do_GetService("@mozilla.org/xre/app-info;1");
rv = appInfo->GetName(appName);
NS_ENSURE_SUCCESS(rv, rv);
auto userSid = GetCurrentUserStringSid();
if (!userSid) {
return NS_ERROR_FILE_NOT_FOUND;
}
nsAutoString filename;
filename.AppendPrintf("%s_%ls_shortcuts.ini", appName.get(), userSid.get());
rv = shortcutsLog->Append(filename);
NS_ENSURE_SUCCESS(rv, rv);
nsINIParser parser;
bool fileExists = false;
bool shortcutsLogEntryExists = false;
nsAutoCString keyName, shortcutName;
shortcutName = NS_ConvertUTF16toUTF8(aShortcutName);
shortcutsLog->IsFile(&fileExists);
// if the shortcuts log exists, find either an existing matching
// entry, or the next available shortcut index
if (fileExists) {
rv = parser.Init(shortcutsLog);
NS_ENSURE_SUCCESS(rv, rv);
nsCString iniShortcut;
// surely we'll never need more than 10 shortcuts in one section...
for (int i = 0; i < 10; i++) {
keyName.AssignLiteral("Shortcut");
keyName.AppendInt(i);
rv = parser.GetString(section.get(), keyName.get(), iniShortcut);
if (NS_FAILED(rv)) {
// we found an unused index
break;
} else if (iniShortcut.Equals(shortcutName)) {
shortcutsLogEntryExists = true;
}
}
// otherwise, this is safe to use
} else {
keyName.AssignLiteral("Shortcut0");
}
if (!shortcutsLogEntryExists) {
parser.SetString(section.get(), keyName.get(), shortcutName.get());
// We write this ourselves instead of using parser->WriteToFile because
// the INI parser in our uninstaller needs to read this, and only supports
// UTF-16LE encoding. nsINIParser does not support UTF-16.
nsAutoCString formatted;
parser.WriteToString(formatted);
FILE* writeFile;
rv = shortcutsLog->OpenANSIFileDesc("w,ccs=UTF-16LE", &writeFile);
NS_ENSURE_SUCCESS(rv, rv);
NS_ConvertUTF8toUTF16 formattedUTF16(formatted);
if (fwrite(formattedUTF16.get(), sizeof(wchar_t), formattedUTF16.Length(),
writeFile) != formattedUTF16.Length()) {
fclose(writeFile);
return NS_ERROR_FAILURE;
}
fclose(writeFile);
}
return NS_OK;
}
nsresult CreateShellLinkObject(nsIFile* aBinary,
const CopyableTArray<nsString>& aArguments,
const nsAString& aDescription,
nsIFile* aIconFile, uint16_t aIconIndex,
const nsAString& aAppUserModelId,
IShellLinkW** aLink) {
RefPtr<IShellLinkW> link;
HRESULT hr = CoCreateInstance(CLSID_ShellLink, nullptr, CLSCTX_INPROC_SERVER,
IID_IShellLinkW, getter_AddRefs(link));
NS_ENSURE_HRESULT(hr, NS_ERROR_FAILURE);
nsString path(aBinary->NativePath());
link->SetPath(path.get());
wchar_t workingDir[MAX_PATH + 1];
wcscpy_s(workingDir, MAX_PATH + 1, aBinary->NativePath().get());
PathRemoveFileSpecW(workingDir);
link->SetWorkingDirectory(workingDir);
if (!aDescription.IsEmpty()) {
link->SetDescription(PromiseFlatString(aDescription).get());
}
// TODO: Properly escape quotes in the string, see bug 1604287.
nsString arguments;
for (const auto& arg : aArguments) {
arguments += u"\""_ns + arg + u"\" "_ns;
}
link->SetArguments(arguments.get());
if (aIconFile) {
nsString icon(aIconFile->NativePath());
link->SetIconLocation(icon.get(), aIconIndex);
}
if (!aAppUserModelId.IsEmpty()) {
RefPtr<IPropertyStore> propStore;
hr = link->QueryInterface(IID_IPropertyStore, getter_AddRefs(propStore));
NS_ENSURE_HRESULT(hr, NS_ERROR_FAILURE);
PROPVARIANT pv;
if (FAILED(InitPropVariantFromString(
PromiseFlatString(aAppUserModelId).get(), &pv))) {
return NS_ERROR_FAILURE;
}
hr = propStore->SetValue(PKEY_AppUserModel_ID, pv);
PropVariantClear(&pv);
NS_ENSURE_HRESULT(hr, NS_ERROR_FAILURE);
hr = propStore->Commit();
NS_ENSURE_HRESULT(hr, NS_ERROR_FAILURE);
}
link.forget(aLink);
return NS_OK;
}
static nsresult CreateShortcutImpl(
nsIFile* aBinary, const CopyableTArray<nsString>& aArguments,
const nsAString& aDescription, nsIFile* aIconFile, uint16_t aIconIndex,
const nsAString& aAppUserModelId, KNOWNFOLDERID aShortcutFolder,
const nsAString& aShortcutName, const nsString& aShortcutFile,
nsIFile* aShortcutsLogDir) {
NS_ENSURE_ARG(aBinary);
NS_ENSURE_ARG(aIconFile);
nsresult rv =
WriteShortcutToLog(aShortcutsLogDir, aShortcutFolder, aShortcutName);
NS_ENSURE_SUCCESS(rv, rv);
RefPtr<IShellLinkW> link;
rv = CreateShellLinkObject(aBinary, aArguments, aDescription, aIconFile,
aIconIndex, aAppUserModelId, getter_AddRefs(link));
NS_ENSURE_SUCCESS(rv, rv);
RefPtr<IPersistFile> persist;
HRESULT hr = link->QueryInterface(IID_IPersistFile, getter_AddRefs(persist));
NS_ENSURE_HRESULT(hr, NS_ERROR_FAILURE);
hr = persist->Save(aShortcutFile.get(), TRUE);
NS_ENSURE_HRESULT(hr, NS_ERROR_FAILURE);
return NS_OK;
}
NS_IMETHODIMP
nsWindowsShellService::CreateShortcut(
nsIFile* aBinary, const nsTArray<nsString>& aArguments,
const nsAString& aDescription, nsIFile* aIconFile, uint16_t aIconIndex,
const nsAString& aAppUserModelId, const nsAString& aShortcutFolder,
const nsAString& aShortcutName, JSContext* aCx, dom::Promise** aPromise) {
if (!NS_IsMainThread()) {
return NS_ERROR_NOT_SAME_THREAD;
}
ErrorResult rv;
RefPtr<dom::Promise> promise =
dom::Promise::Create(xpc::CurrentNativeGlobal(aCx), rv);
if (MOZ_UNLIKELY(rv.Failed())) {
return rv.StealNSResult();
}
// In an ideal world we'd probably send along nsIFile pointers
// here, but it's easier to determine the needed shortcuts log
// entry with a KNOWNFOLDERID - so we pass this along instead
// and let CreateShortcutImpl take care of converting it to
// an nsIFile.
KNOWNFOLDERID folderId;
if (aShortcutFolder.Equals(L"Programs")) {
folderId = FOLDERID_Programs;
} else if (aShortcutFolder.Equals(L"Desktop")) {
folderId = FOLDERID_Desktop;
} else {
return NS_ERROR_INVALID_ARG;
}
nsCOMPtr<nsIFile> updRoot, shortcutsLogDir;
nsresult nsrv =
NS_GetSpecialDirectory(XRE_UPDATE_ROOT_DIR, getter_AddRefs(updRoot));
NS_ENSURE_SUCCESS(nsrv, nsrv);
nsrv = updRoot->GetParent(getter_AddRefs(shortcutsLogDir));
NS_ENSURE_SUCCESS(nsrv, nsrv);
nsCOMPtr<nsIFile> shortcutFile;
if (folderId == FOLDERID_Programs) {
nsrv = NS_GetSpecialDirectory(NS_WIN_PROGRAMS_DIR,
getter_AddRefs(shortcutFile));
} else if (folderId == FOLDERID_Desktop) {
nsrv =
NS_GetSpecialDirectory(NS_OS_DESKTOP_DIR, getter_AddRefs(shortcutFile));
} else {
return NS_ERROR_FILE_NOT_FOUND;
}
if (NS_FAILED(nsrv)) {
return NS_ERROR_FILE_NOT_FOUND;
}
shortcutFile->Append(aShortcutName);
auto promiseHolder = MakeRefPtr<nsMainThreadPtrHolder<dom::Promise>>(
"CreateShortcut promise", promise);
nsCOMPtr<nsIFile> binary(aBinary);
nsCOMPtr<nsIFile> iconFile(aIconFile);
NS_DispatchBackgroundTask(
NS_NewRunnableFunction(
"CreateShortcut",
[binary, aArguments = CopyableTArray<nsString>(aArguments),
aDescription = nsString{aDescription}, iconFile, aIconIndex,
aAppUserModelId = nsString{aAppUserModelId}, folderId,
aShortcutFolder = nsString{aShortcutFolder},
aShortcutName = nsString{aShortcutName}, shortcutsLogDir,
shortcutFile, promiseHolder = std::move(promiseHolder)] {
nsresult rv = CreateShortcutImpl(
binary.get(), aArguments, aDescription, iconFile.get(),
aIconIndex, aAppUserModelId, folderId, aShortcutName,
shortcutFile->NativePath(), shortcutsLogDir.get());
NS_DispatchToMainThread(NS_NewRunnableFunction(
"CreateShortcut callback",
[rv, shortcutFile, promiseHolder = std::move(promiseHolder)] {
dom::Promise* promise = promiseHolder.get()->get();
if (NS_SUCCEEDED(rv)) {
promise->MaybeResolve(shortcutFile->NativePath());
} else {
promise->MaybeReject(rv);
}
}));
}),
NS_DISPATCH_EVENT_MAY_BLOCK);
promise.forget(aPromise);
return NS_OK;
}
NS_IMETHODIMP
nsWindowsShellService::GetLaunchOnLoginShortcuts(
nsTArray<nsString>& aShortcutPaths) {
aShortcutPaths.Clear();
// Get AppData\\Roaming folder using a known folder ID
RefPtr<IKnownFolderManager> fManager;
RefPtr<IKnownFolder> roamingAppData;
LPWSTR roamingAppDataW;
nsString roamingAppDataNS;
HRESULT hr =
CoCreateInstance(CLSID_KnownFolderManager, nullptr, CLSCTX_INPROC_SERVER,
IID_IKnownFolderManager, getter_AddRefs(fManager));
if (FAILED(hr)) {
return NS_ERROR_ABORT;
}
fManager->GetFolder(FOLDERID_RoamingAppData,
roamingAppData.StartAssignment());
hr = roamingAppData->GetPath(0, &roamingAppDataW);
if (FAILED(hr)) {
return NS_ERROR_FILE_NOT_FOUND;
}
// Append startup folder to AppData\\Roaming
roamingAppDataNS.Assign(roamingAppDataW);
CoTaskMemFree(roamingAppDataW);
nsString startupFolder =
roamingAppDataNS +
u"\\Microsoft\\Windows\\Start Menu\\Programs\\Startup"_ns;
nsString startupFolderWildcard = startupFolder + u"\\*.lnk"_ns;
// Get known path for binary file for later comparison with shortcuts.
// Returns lowercase file path which should be fine for Windows as all
// directories and files are case-insensitive by default.
RefPtr<nsIFile> binFile;
nsString binPath;
nsresult rv = XRE_GetBinaryPath(binFile.StartAssignment());
if (FAILED(rv)) {
return NS_ERROR_FAILURE;
}
rv = binFile->GetPath(binPath);
if (FAILED(rv)) {
return NS_ERROR_FILE_UNRECOGNIZED_PATH;
}
// Check for if first file exists with a shortcut extension (.lnk)
WIN32_FIND_DATAW ffd;
HANDLE fileHandle = INVALID_HANDLE_VALUE;
fileHandle = FindFirstFileW(startupFolderWildcard.get(), &ffd);
if (fileHandle == INVALID_HANDLE_VALUE) {
// This means that no files were found in the folder which
// doesn't imply an error. Most of the time the user won't
// have any shortcuts here.
return NS_OK;
}
do {
// Extract shortcut target path from every
// shortcut in the startup folder.
nsString fileName(ffd.cFileName);
RefPtr<IShellLinkW> link;
RefPtr<IPersistFile> ppf;
nsString target;
target.SetLength(MAX_PATH);
CoCreateInstance(CLSID_ShellLink, nullptr, CLSCTX_INPROC_SERVER,
IID_IShellLinkW, getter_AddRefs(link));
hr = link->QueryInterface(IID_IPersistFile, getter_AddRefs(ppf));
if (NS_WARN_IF(FAILED(hr))) {
continue;
}
nsString filePath = startupFolder + u"\\"_ns + fileName;
hr = ppf->Load(filePath.get(), STGM_READ);
if (NS_WARN_IF(FAILED(hr))) {
continue;
}
hr = link->GetPath(target.get(), MAX_PATH, nullptr, 0);
if (NS_WARN_IF(FAILED(hr))) {
continue;
}
// If shortcut target matches known binary file value
// then add the path to the shortcut as a valid
// startup shortcut. This has to be a substring search as
// the user could have added unknown command line arguments
// to the shortcut.
if (_wcsnicmp(target.get(), binPath.get(), binPath.Length()) == 0) {
aShortcutPaths.AppendElement(filePath);
}
} while (FindNextFile(fileHandle, &ffd) != 0);
FindClose(fileHandle);
return NS_OK;
}
// Look for any installer-created shortcuts in the given location that match
// the given AUMID and EXE Path. If one is found, output its path.
//
// NOTE: DO NOT USE if a false negative (mismatch) is unacceptable.
// aExePath is compared directly to the path retrieved from the shortcut.
// Due to the presence of symlinks or other filesystem issues, it's possible
// for different paths to refer to the same file, which would cause the check
// to fail.
// This should rarely be an issue as we are most likely to be run from a path
// written by the installer (shortcut, association, launch from installer),
// which also wrote the shortcuts. But it is possible.
//
// aCSIDL the CSIDL of the directory to look for matching shortcuts in
// aAUMID the AUMID to check for
// aExePath the target exe path to check for, should be a long path where
// possible
// aShortcutSubstring a substring to limit which shortcuts in aCSIDL are
// inspected for a match. Only shortcuts whose filename
// contains this substring will be considered
// aShortcutPath outparam, set to matching shortcut path if NS_OK is returned.
//
// Returns
// NS_ERROR_FAILURE on errors before any shortcuts were loaded
// NS_ERROR_FILE_NOT_FOUND if no shortcuts matching aShortcutSubstring exist
// NS_ERROR_FILE_ALREADY_EXISTS if shortcuts were found but did not match
// aAUMID or aExePath
// NS_OK if a matching shortcut is found
static nsresult GetMatchingShortcut(int aCSIDL, const nsAString& aAUMID,
const wchar_t aExePath[MAXPATHLEN],
const nsAString& aShortcutSubstring,
/* out */ nsAutoString& aShortcutPath) {
nsresult result = NS_ERROR_FAILURE;
wchar_t folderPath[MAX_PATH] = {};
HRESULT hr = SHGetFolderPathW(nullptr, aCSIDL, nullptr, SHGFP_TYPE_CURRENT,
folderPath);
if (NS_WARN_IF(FAILED(hr))) {
return NS_ERROR_FAILURE;
}
if (wcscat_s(folderPath, MAX_PATH, L"\\") != 0) {
return NS_ERROR_FAILURE;
}
// Get list of shortcuts in aCSIDL
nsAutoString pattern(folderPath);
pattern.AppendLiteral("*.lnk");
WIN32_FIND_DATAW findData = {};
HANDLE hFindFile = FindFirstFileW(pattern.get(), &findData);
if (hFindFile == INVALID_HANDLE_VALUE) {
Unused << NS_WARN_IF(GetLastError() != ERROR_FILE_NOT_FOUND);
return NS_ERROR_FILE_NOT_FOUND;
}
// Past this point we don't return until the end of the function,
// when FindClose() is called.
// todo: improve return values here
do {
// Skip any that don't contain aShortcutSubstring
// This is a case sensitive comparison, but that's probably fine for
// the vast majority of cases -- and certainly for all the ones where
// a shortcut was created by the installer.
if (StrStrIW(findData.cFileName, aShortcutSubstring.Data()) == NULL) {
continue;
}
nsAutoString path(folderPath);
path.Append(findData.cFileName);
// Create a shell link object for loading the shortcut
RefPtr<IShellLinkW> link;
HRESULT hr =
CoCreateInstance(CLSID_ShellLink, nullptr, CLSCTX_INPROC_SERVER,
IID_IShellLinkW, getter_AddRefs(link));
if (NS_WARN_IF(FAILED(hr))) {
continue;
}
// Load
RefPtr<IPersistFile> persist;
hr = link->QueryInterface(IID_IPersistFile, getter_AddRefs(persist));
if (NS_WARN_IF(FAILED(hr))) {
continue;
}
hr = persist->Load(path.get(), STGM_READ);
if (FAILED(hr)) {
if (NS_WARN_IF(hr != HRESULT_FROM_WIN32(ERROR_FILE_NOT_FOUND))) {
// empty branch, result unchanged but warning issued
} else {
// If we've ever gotten past this block, result will already be
// NS_ERROR_FILE_ALREADY_EXISTS, which is a more accurate error
// than NS_ERROR_FILE_NOT_FOUND.
if (result != NS_ERROR_FILE_ALREADY_EXISTS) {
result = NS_ERROR_FILE_NOT_FOUND;
}
}
continue;
}
result = NS_ERROR_FILE_ALREADY_EXISTS;
// Check the AUMID
RefPtr<IPropertyStore> propStore;
hr = link->QueryInterface(IID_IPropertyStore, getter_AddRefs(propStore));
if (NS_WARN_IF(FAILED(hr))) {
continue;
}
PROPVARIANT pv;
hr = propStore->GetValue(PKEY_AppUserModel_ID, &pv);
if (NS_WARN_IF(FAILED(hr))) {
continue;
}
wchar_t storedAUMID[MAX_PATH];
hr = PropVariantToString(pv, storedAUMID, MAX_PATH);
PropVariantClear(&pv);
if (NS_WARN_IF(FAILED(hr))) {
continue;
}
if (!aAUMID.Equals(storedAUMID)) {
continue;
}
// Check the exe path
static_assert(MAXPATHLEN == MAX_PATH);
wchar_t storedExePath[MAX_PATH] = {};
// With no flags GetPath gets a long path
hr = link->GetPath(storedExePath, std::size(storedExePath), nullptr, 0);
if (FAILED(hr) || hr == S_FALSE) {
continue;
}
// Case insensitive path comparison
if (wcsnicmp(storedExePath, aExePath, MAXPATHLEN) == 0) {
aShortcutPath.Assign(path);
result = NS_OK;
break;
}
} while (FindNextFileW(hFindFile, &findData));
FindClose(hFindFile);
return result;
}
static nsresult FindPinnableShortcut(const nsAString& aAppUserModelId,
const nsAString& aShortcutSubstring,
const bool aPrivateBrowsing,
nsAutoString& aShortcutPath) {
wchar_t exePath[MAXPATHLEN] = {};
if (NS_WARN_IF(NS_FAILED(BinaryPath::GetLong(exePath)))) {
return NS_ERROR_FAILURE;
}
if (aPrivateBrowsing) {
if (!PathRemoveFileSpecW(exePath)) {
return NS_ERROR_FAILURE;
}
if (!PathAppendW(exePath, L"private_browsing.exe")) {
return NS_ERROR_FAILURE;
}
}
int shortcutCSIDLs[] = {CSIDL_COMMON_PROGRAMS, CSIDL_PROGRAMS};
for (int shortcutCSIDL : shortcutCSIDLs) {
// GetMatchingShortcut may fail when the exe path doesn't match, even
// if it refers to the same file. This should be rare, and the worst
// outcome would be failure to pin, so the risk is acceptable.
nsresult rv = GetMatchingShortcut(shortcutCSIDL, aAppUserModelId, exePath,
aShortcutSubstring, aShortcutPath);
if (NS_SUCCEEDED(rv)) {
return NS_OK;
}
}
return NS_ERROR_FILE_NOT_FOUND;
}
static bool HasPinnableShortcutImpl(const nsAString& aAppUserModelId,
const bool aPrivateBrowsing,
const nsAutoString& aShortcutSubstring) {
// unused by us, but required
nsAutoString shortcutPath;
nsresult rv = FindPinnableShortcut(aAppUserModelId, aShortcutSubstring,
aPrivateBrowsing, shortcutPath);
if (SUCCEEDED(rv)) {
return true;
}
return false;
}
NS_IMETHODIMP nsWindowsShellService::HasPinnableShortcut(
const nsAString& aAppUserModelId, const bool aPrivateBrowsing,
JSContext* aCx, dom::Promise** aPromise) {
if (!NS_IsMainThread()) {
return NS_ERROR_NOT_SAME_THREAD;
}
ErrorResult rv;
RefPtr<dom::Promise> promise =
dom::Promise::Create(xpc::CurrentNativeGlobal(aCx), rv);
if (MOZ_UNLIKELY(rv.Failed())) {
return rv.StealNSResult();
}
auto promiseHolder = MakeRefPtr<nsMainThreadPtrHolder<dom::Promise>>(
"HasPinnableShortcut promise", promise);
NS_DispatchBackgroundTask(
NS_NewRunnableFunction(
"HasPinnableShortcut",
[aAppUserModelId = nsString{aAppUserModelId}, aPrivateBrowsing,
promiseHolder = std::move(promiseHolder)] {
bool rv = false;
HRESULT hr = CoInitialize(nullptr);
if (SUCCEEDED(hr)) {
nsAutoString shortcutSubstring;
shortcutSubstring.AssignLiteral(MOZ_APP_DISPLAYNAME);
rv = HasPinnableShortcutImpl(aAppUserModelId, aPrivateBrowsing,
shortcutSubstring);
CoUninitialize();
}
NS_DispatchToMainThread(NS_NewRunnableFunction(
"HasPinnableShortcut callback",
[rv, promiseHolder = std::move(promiseHolder)] {
dom::Promise* promise = promiseHolder.get()->get();
promise->MaybeResolve(rv);
}));
}),
NS_DISPATCH_EVENT_MAY_BLOCK);
promise.forget(aPromise);
return NS_OK;
}
static bool IsCurrentAppPinnedToTaskbarSync(const nsAString& aumid) {
// Use new Windows pinning APIs to determine whether or not we're pinned.
// If these fail we can safely fall back to the old method for regular
// installs however MSIX will always return false.
// Bug 1911343: Add a check for whether we're looking for a regular pin
// or PB pin based on the AUMID value once private browser pinning
// is supported on MSIX.
// Right now only run this check on MSIX to avoid
// false positives when only private browsing is pinned.
if (widget::WinUtils::HasPackageIdentity()) {
auto pinWithWin11TaskbarAPIResults =
IsCurrentAppPinnedToTaskbarWin11(false);
switch (pinWithWin11TaskbarAPIResults.result) {
case Win11PinToTaskBarResultStatus::NotPinned:
return false;
break;
case Win11PinToTaskBarResultStatus::AlreadyPinned:
return true;
break;
default:
// Fall through to the old mechanism.
// The old mechanism should continue working for non-MSIX
// builds.
break;
}
}
// There are two shortcut targets that we created. One always matches the
// binary we're running as (eg: firefox.exe). The other is the wrapper
// for launching in Private Browsing mode. We need to inspect shortcuts
// that point at either of these to accurately judge whether or not
// the app is pinned with the given AUMID.
wchar_t exePath[MAXPATHLEN] = {};
wchar_t pbExePath[MAXPATHLEN] = {};
if (NS_WARN_IF(NS_FAILED(BinaryPath::GetLong(exePath)))) {
return false;
}
wcscpy_s(pbExePath, MAXPATHLEN, exePath);
if (!PathRemoveFileSpecW(pbExePath)) {
return false;
}
if (!PathAppendW(pbExePath, L"private_browsing.exe")) {
return false;
}
wchar_t folderChars[MAX_PATH] = {};
HRESULT hr = SHGetFolderPathW(nullptr, CSIDL_APPDATA, nullptr,
SHGFP_TYPE_CURRENT, folderChars);
if (NS_WARN_IF(FAILED(hr))) {
return false;
}
nsAutoString folder;
folder.Assign(folderChars);
if (NS_WARN_IF(folder.IsEmpty())) {
return false;
}
if (folder[folder.Length() - 1] != '\\') {
folder.AppendLiteral("\\");
}
folder.AppendLiteral(
"Microsoft\\Internet Explorer\\Quick Launch\\User Pinned\\TaskBar");
nsAutoString pattern;
pattern.Assign(folder);
pattern.AppendLiteral("\\*.lnk");
WIN32_FIND_DATAW findData = {};
HANDLE hFindFile = FindFirstFileW(pattern.get(), &findData);
if (hFindFile == INVALID_HANDLE_VALUE) {
Unused << NS_WARN_IF(GetLastError() != ERROR_FILE_NOT_FOUND);
return false;
}
// Past this point we don't return until the end of the function,
// when FindClose() is called.
// Check all shortcuts until a match is found
bool isPinned = false;
do {
nsAutoString fileName;
fileName.Assign(folder);
fileName.AppendLiteral("\\");
fileName.Append(findData.cFileName);
// Create a shell link object for loading the shortcut
RefPtr<IShellLinkW> link;
HRESULT hr =
CoCreateInstance(CLSID_ShellLink, nullptr, CLSCTX_INPROC_SERVER,
IID_IShellLinkW, getter_AddRefs(link));
if (NS_WARN_IF(FAILED(hr))) {
continue;
}
// Load
RefPtr<IPersistFile> persist;
hr = link->QueryInterface(IID_IPersistFile, getter_AddRefs(persist));
if (NS_WARN_IF(FAILED(hr))) {
continue;
}
hr = persist->Load(fileName.get(), STGM_READ);
if (NS_WARN_IF(FAILED(hr))) {
continue;
}
// Check the exe path
static_assert(MAXPATHLEN == MAX_PATH);
wchar_t storedExePath[MAX_PATH] = {};
// With no flags GetPath gets a long path
hr = link->GetPath(storedExePath, std::size(storedExePath), nullptr, 0);
if (FAILED(hr) || hr == S_FALSE) {
continue;
}
// Case insensitive path comparison
// NOTE: Because this compares the path directly, it is possible to
// have a false negative mismatch.
if (wcsnicmp(storedExePath, exePath, MAXPATHLEN) == 0 ||
wcsnicmp(storedExePath, pbExePath, MAXPATHLEN) == 0) {
RefPtr<IPropertyStore> propStore;
hr = link->QueryInterface(IID_IPropertyStore, getter_AddRefs(propStore));
if (NS_WARN_IF(FAILED(hr))) {
continue;
}
PROPVARIANT pv;
hr = propStore->GetValue(PKEY_AppUserModel_ID, &pv);
if (NS_WARN_IF(FAILED(hr))) {
continue;
}
wchar_t storedAUMID[MAX_PATH];
hr = PropVariantToString(pv, storedAUMID, MAX_PATH);
PropVariantClear(&pv);
if (NS_WARN_IF(FAILED(hr))) {
continue;
}
if (aumid.Equals(storedAUMID)) {
isPinned = true;
break;
}
}
} while (FindNextFileW(hFindFile, &findData));
FindClose(hFindFile);
return isPinned;
}
static nsresult ManageShortcutTaskbarPins(bool aCheckOnly, bool aPinType,
const nsAString& aShortcutPath) {
// This enum is likely only used for Windows telemetry, INT_MAX is chosen to
// avoid confusion with existing uses.
enum PINNEDLISTMODIFYCALLER { PLMC_INT_MAX = INT_MAX };
// The types below, and the idea of using IPinnedList3::Modify,
// are thanks to Gee Law <https://geelaw.blog/entries/msedge-pins/>
static constexpr GUID CLSID_TaskbandPin = {
0x90aa3a4e,
0x1cba,
0x4233,
{0xb8, 0xbb, 0x53, 0x57, 0x73, 0xd4, 0x84, 0x49}};
static constexpr GUID IID_IPinnedList3 = {
0x0dd79ae2,
0xd156,
0x45d4,
{0x9e, 0xeb, 0x3b, 0x54, 0x97, 0x69, 0xe9, 0x40}};
struct IPinnedList3Vtbl;
struct IPinnedList3 {
IPinnedList3Vtbl* vtbl;
};
typedef ULONG STDMETHODCALLTYPE ReleaseFunc(IPinnedList3 * that);
typedef HRESULT STDMETHODCALLTYPE ModifyFunc(
IPinnedList3 * that, PCIDLIST_ABSOLUTE unpin, PCIDLIST_ABSOLUTE pin,
PINNEDLISTMODIFYCALLER caller);
struct IPinnedList3Vtbl {
void* QueryInterface; // 0
void* AddRef; // 1
ReleaseFunc* Release; // 2
void* Other[13]; // 3-15
ModifyFunc* Modify; // 16
};
struct ILFreeDeleter {
void operator()(LPITEMIDLIST aPtr) {
if (aPtr) {
ILFree(aPtr);
}
}
};
mozilla::UniquePtr<__unaligned ITEMIDLIST, ILFreeDeleter> path(
ILCreateFromPathW(nsString(aShortcutPath).get()));
if (NS_WARN_IF(!path)) {
return NS_ERROR_FILE_NOT_FOUND;
}
IPinnedList3* pinnedList = nullptr;
HRESULT hr = CoCreateInstance(CLSID_TaskbandPin, NULL, CLSCTX_INPROC_SERVER,
IID_IPinnedList3, (void**)&pinnedList);
if (FAILED(hr) || !pinnedList) {
return NS_ERROR_NOT_AVAILABLE;
}
if (!aCheckOnly) {
hr = pinnedList->vtbl->Modify(pinnedList, aPinType ? NULL : path.get(),
aPinType ? path.get() : NULL, PLMC_INT_MAX);
}
pinnedList->vtbl->Release(pinnedList);
if (FAILED(hr)) {
return NS_ERROR_FILE_ACCESS_DENIED;
}
return NS_OK;
}
static nsresult PinShortcutToTaskbarImpl(bool aCheckOnly,
const nsAString& aAppUserModelId,
const nsAString& aShortcutPath) {
// Verify shortcut is visible to `shell:appsfolder`. Shortcut creation -
// during install or runtime - causes a race between it propagating to the
// virtual `shell:appsfolder` and attempts to pin via `ITaskbarManager`,
// resulting in pin failures when the latter occurs before the former. We can
// skip this when we're in a MSIX build or only checking whether we're pinned.
if (!widget::WinUtils::HasPackageIdentity() && !aCheckOnly &&
!PollAppsFolderForShortcut(aAppUserModelId,
TimeDuration::FromSeconds(15))) {
return NS_ERROR_FILE_NOT_FOUND;
}
auto pinWithWin11TaskbarAPIResults =
PinCurrentAppToTaskbarWin11(aCheckOnly, aAppUserModelId);
switch (pinWithWin11TaskbarAPIResults.result) {
case Win11PinToTaskBarResultStatus::NotSupported:
// Fall through to the win 10 mechanism
break;
case Win11PinToTaskBarResultStatus::Success:
case Win11PinToTaskBarResultStatus::AlreadyPinned:
return NS_OK;
case Win11PinToTaskBarResultStatus::NotPinned:
case Win11PinToTaskBarResultStatus::NotCurrentlyAllowed:
case Win11PinToTaskBarResultStatus::Failed:
// return NS_ERROR_FAILURE;
// Fall through to the old mechanism for now
// In future, we should be sending telemetry for when
// an error occurs or for when pinning is not allowed
// with the Win 11 APIs.
break;
}
return PinCurrentAppToTaskbarWin10(aCheckOnly, aAppUserModelId,
aShortcutPath);
}
/* This function pins a shortcut to the taskbar based on its location. While
* Windows 11 only needs the `aAppUserModelId`, `aShortcutPath` is required
* for pinning in Windows 10.
* @param aAppUserModelId
* The same string used to create an lnk file.
* @param aShortcutPaths
* Path for existing shortcuts (e.g., start menu)
*/
NS_IMETHODIMP
nsWindowsShellService::PinShortcutToTaskbar(const nsAString& aAppUserModelId,
const nsAString& aShortcutPath,
JSContext* aCx,
dom::Promise** aPromise) {
NS_ENSURE_ARG_POINTER(aCx);
NS_ENSURE_ARG_POINTER(aPromise);
if (!NS_IsMainThread()) {
return NS_ERROR_NOT_SAME_THREAD;
}
// First available on 1809
if (!IsWin10Sep2018UpdateOrLater()) {
return NS_ERROR_NOT_AVAILABLE;
}
ErrorResult rv;
RefPtr<dom::Promise> promise =
dom::Promise::Create(xpc::CurrentNativeGlobal(aCx), rv);
if (MOZ_UNLIKELY(rv.Failed())) {
return rv.StealNSResult();
}
auto promiseHolder = MakeRefPtr<nsMainThreadPtrHolder<dom::Promise>>(
"pinShortcutToTaskbar promise", promise);
NS_DispatchBackgroundTask(
NS_NewRunnableFunction(
"pinShortcutToTaskbar",
[aumid = nsString{aAppUserModelId},
shortcutPath = nsString(aShortcutPath),
promiseHolder = std::move(promiseHolder)] {
nsresult rv = NS_ERROR_FAILURE;
HRESULT hr = CoInitialize(nullptr);
if (SUCCEEDED(hr)) {
rv = PinShortcutToTaskbarImpl(false, aumid, shortcutPath);
CoUninitialize();
}
NS_DispatchToMainThread(NS_NewRunnableFunction(
"pinShortcutToTaskbar callback",
[rv, promiseHolder = std::move(promiseHolder)] {
dom::Promise* promise = promiseHolder.get()->get();
if (NS_SUCCEEDED(rv)) {
promise->MaybeResolveWithUndefined();
} else {
promise->MaybeReject(rv);
}
}));
}),
NS_DISPATCH_EVENT_MAY_BLOCK);
promise.forget(aPromise);
return NS_OK;
}
NS_IMETHODIMP
nsWindowsShellService::UnpinShortcutFromTaskbar(
const nsAString& aShortcutPath) {
const bool pinType = false; // false means unpin
const bool runInTestMode = false;
return ManageShortcutTaskbarPins(runInTestMode, pinType, aShortcutPath);
}
// Ensure that the supplied name doesn't have invalid characters.
static void ValidateFilename(nsAString& aFilename) {
nsCOMPtr<nsIMIMEService> mimeService = do_GetService("@mozilla.org/mime;1");
if (NS_WARN_IF(!mimeService)) {
aFilename.Truncate();
return;
}
uint32_t flags = nsIMIMEService::VALIDATE_SANITIZE_ONLY |
nsIMIMEService::VALIDATE_DONT_COLLAPSE_WHITESPACE;
nsAutoString outFilename;
mimeService->ValidateFileNameForSaving(aFilename, EmptyCString(), flags,
outFilename);
aFilename = outFilename;
}
NS_IMETHODIMP
nsWindowsShellService::GetTaskbarTabShortcutPath(const nsAString& aShortcutName,
nsAString& aRetPath) {
nsAutoString sanitizedShortcutName(aShortcutName);
ValidateFilename(sanitizedShortcutName);
if (sanitizedShortcutName != aShortcutName) {
return NS_ERROR_FILE_INVALID_PATH;
}
// The taskbar tab shortcut will always be in
// %APPDATA%\Microsoft\Windows\Start Menu\Programs
RefPtr<IKnownFolderManager> fManager;
RefPtr<IKnownFolder> progFolder;
LPWSTR progFolderW;
nsString progFolderNS;
HRESULT hr =
CoCreateInstance(CLSID_KnownFolderManager, nullptr, CLSCTX_INPROC_SERVER,
IID_IKnownFolderManager, getter_AddRefs(fManager));
if (NS_WARN_IF(FAILED(hr))) {
return NS_ERROR_ABORT;
}
fManager->GetFolder(FOLDERID_Programs, progFolder.StartAssignment());
hr = progFolder->GetPath(0, &progFolderW);
if (FAILED(hr)) {
return NS_ERROR_FILE_NOT_FOUND;
}
progFolderNS.Assign(progFolderW);
aRetPath = progFolderNS + u"\\"_ns + aShortcutName + u".lnk"_ns;
return NS_OK;
}
NS_IMETHODIMP
nsWindowsShellService::GetTaskbarTabPins(nsTArray<nsString>& aShortcutPaths) {
#ifdef __MINGW32__
return NS_ERROR_NOT_IMPLEMENTED;
#else
aShortcutPaths.Clear();
// Get AppData\\Roaming folder using a known folder ID
RefPtr<IKnownFolderManager> fManager;
RefPtr<IKnownFolder> roamingAppData;
LPWSTR roamingAppDataW;
nsString roamingAppDataNS;
HRESULT hr =
CoCreateInstance(CLSID_KnownFolderManager, nullptr, CLSCTX_INPROC_SERVER,
IID_IKnownFolderManager, getter_AddRefs(fManager));
if (NS_WARN_IF(FAILED(hr))) {
return NS_ERROR_ABORT;
}
fManager->GetFolder(FOLDERID_RoamingAppData,
roamingAppData.StartAssignment());
hr = roamingAppData->GetPath(0, &roamingAppDataW);
if (FAILED(hr)) {
return NS_ERROR_FILE_NOT_FOUND;
}
// Append taskbar pins folder to AppData\\Roaming
roamingAppDataNS.Assign(roamingAppDataW);
CoTaskMemFree(roamingAppDataW);
nsString taskbarFolder =
roamingAppDataNS + u"\\Microsoft\\Windows\\Start Menu\\Programs"_ns;
nsString taskbarFolderWildcard = taskbarFolder + u"\\*.lnk"_ns;
// Get known path for binary file for later comparison with shortcuts.
// Returns lowercase file path which should be fine for Windows as all
// directories and files are case-insensitive by default.
RefPtr<nsIFile> binFile;
nsString binPath;
nsresult rv = XRE_GetBinaryPath(binFile.StartAssignment());
if (NS_WARN_IF(FAILED(rv))) {
return NS_ERROR_FAILURE;
}
rv = binFile->GetPath(binPath);
if (NS_WARN_IF(FAILED(rv))) {
return NS_ERROR_FILE_UNRECOGNIZED_PATH;
}
// Check for if first file exists with a shortcut extension (.lnk)
WIN32_FIND_DATAW ffd;
HANDLE fileHandle = INVALID_HANDLE_VALUE;
fileHandle = FindFirstFileW(taskbarFolderWildcard.get(), &ffd);
if (fileHandle == INVALID_HANDLE_VALUE) {
// This means that no files were found in the folder which
// doesn't imply an error.
return NS_OK;
}
do {
// Extract shortcut target path from every
// shortcut in the taskbar pins folder.
nsString fileName(ffd.cFileName);
RefPtr<IShellLinkW> link;
RefPtr<IPropertyStore> pps;
nsString target;
target.SetLength(MAX_PATH);
hr = CoCreateInstance(CLSID_ShellLink, nullptr, CLSCTX_INPROC_SERVER,
IID_IShellLinkW, getter_AddRefs(link));
if (NS_WARN_IF(FAILED(hr))) {
continue;
}
nsString filePath = taskbarFolder + u"\\"_ns + fileName;
if (NS_WARN_IF(FAILED(hr))) {
continue;
}
// After loading shortcut, search through arguments to find if
// it is a taskbar tab shortcut.
hr = SHGetPropertyStoreFromParsingName(filePath.get(), nullptr,
GPS_READWRITE, IID_IPropertyStore,
getter_AddRefs(pps));
if (NS_WARN_IF(FAILED(hr)) || pps == nullptr) {
continue;
}
PROPVARIANT propVar;
PropVariantInit(&propVar);
auto cleanupPropVariant =
MakeScopeExit([&] { PropVariantClear(&propVar); });
// Get the PKEY_Link_Arguments property
hr = pps->GetValue(PKEY_Link_Arguments, &propVar);
if (NS_WARN_IF(FAILED(hr))) {
continue;
}
// Check if the argument matches
if (!(propVar.vt == VT_LPWSTR && propVar.pwszVal != nullptr &&
wcsstr(propVar.pwszVal, L"-taskbar-tab") != nullptr)) {
continue;
}
hr = link->GetPath(target.get(), MAX_PATH, nullptr, 0);
if (NS_WARN_IF(FAILED(hr))) {
continue;
}
// If shortcut target matches known binary file value
// then add the path to the shortcut as a valid
// shortcut. This has to be a substring search as
// the user could have added unknown command line arguments
// to the shortcut.
if (_wcsnicmp(target.get(), binPath.get(), binPath.Length()) == 0) {
aShortcutPaths.AppendElement(filePath);
}
} while (FindNextFile(fileHandle, &ffd) != 0);
FindClose(fileHandle);
return NS_OK;
#endif
}
static nsresult PinCurrentAppToTaskbarWin10(bool aCheckOnly,
const nsAString& aAppUserModelId,
const nsAString& aShortcutPath) {
// The behavior here is identical if we're only checking or if we try to pin
// but the app is already pinned so we update the variable accordingly.
if (!aCheckOnly) {
aCheckOnly = IsCurrentAppPinnedToTaskbarSync(aAppUserModelId);
}
const bool pinType = true; // true means pin
return ManageShortcutTaskbarPins(aCheckOnly, pinType, aShortcutPath);
}
// There's a delay between shortcuts being created in locations visible to
// `shell:appsfolder` and that information being propogated to
// `shell:appsfolder`. APIs like `ITaskbarManager` pinning rely on said
// shortcuts being visible to `shell:appsfolder`, so we have to introduce a wait
// until they're visible when creating these shortcuts at runtime.
static bool PollAppsFolderForShortcut(const nsAString& aAppUserModelId,
const TimeDuration aTimeout) {
MOZ_DIAGNOSTIC_ASSERT(!NS_IsMainThread(),
"PollAppsFolderForShortcut blocks and should be called "
"off main thread only");
// Implementation note: it was taken into consideration at the time of writing
// to implement this with `SHChangeNotifyRegister` and a `HWND_MESSAGE`
// window. This added significant complexity in terms of resource management
// and control flow that was deemed excessive for a function that is rarely
// run. Absent evidence that we're consuming excessive system resources, this
// simple, poll-based approach seemed more appropriate.
//
// If in the future it seems appropriate to modify this to be event based,
// here are some of the lessons learned during the investigation:
// - `shell:appsfolder` is a virtual directory, composed of shortcut files
// with unique AUMIDs from
// `[%PROGRAMDATA%|%APPDATA%]\Microsoft\Windows\Start Menu\Programs`.
// - `shell:appsfolder` does not have a full path in the filesystem,
// therefore does not work with most file watching APIs.
// - `SHChangeNotifyRegister` should listen for `SHCNE_UPDATEDIR` on
// `FOLDERID_AppsFolder`. `SHCNE_CREATE` events are not issued for
// shortcuts added to `FOLDERID_AppsFolder` likely due to it's virtual
// nature.
// - The mechanism for inspecting the `shell:appsfolder` for a shortcut with
// matching AUMID is the same in an event-based implementation due to
// `SHCNE_UPDATEDIR` events include the modified folder, but not the
// modified file.
TimeStamp start = TimeStamp::Now();
ComPtr<IShellItem> appsFolder;
HRESULT hr = SHGetKnownFolderItem(FOLDERID_AppsFolder, KF_FLAG_DEFAULT,
nullptr, IID_PPV_ARGS(&appsFolder));
if (FAILED(hr)) {
return false;
}
do {
// It's possible to have identically named files in `shell:appsfolder` as
// it's disambiguated by AUMID instead of file name, so we have to iterate
// over all items instead of querying the specific shortcut.
ComPtr<IEnumShellItems> shortcutIter;
hr = appsFolder->BindToHandler(nullptr, BHID_EnumItems,
IID_PPV_ARGS(&shortcutIter));
if (FAILED(hr)) {
return false;
}
ComPtr<IShellItem> shortcut;
while (shortcutIter->Next(1, &shortcut, nullptr) == S_OK) {
ComPtr<IShellItem2> shortcut2;
hr = shortcut.As(&shortcut2);
if (FAILED(hr)) {
return false;
}
mozilla::UniquePtr<WCHAR, mozilla::CoTaskMemFreeDeleter> shortcutAumid;
hr = shortcut2->GetString(PKEY_AppUserModel_ID,
getter_Transfers(shortcutAumid));
if (FAILED(hr)) {
// `shell:appsfolder` is populated by unique shortcut AUMID; if this is
// absent something has gone wrong and we should exit.
return false;
}
if (aAppUserModelId == nsDependentString(shortcutAumid.get())) {
return true;
}
}
// Sleep for a quarter of a second to avoid pinning the CPU while waiting.
::Sleep(250);
} while ((TimeStamp::Now() - start) < aTimeout);
return false;
}
static nsresult PinCurrentAppToTaskbarImpl(
bool aCheckOnly, bool aPrivateBrowsing, const nsAString& aAppUserModelId,
const nsAString& aShortcutName, const nsAString& aShortcutSubstring,
nsIFile* aShortcutsLogDir, nsIFile* aGreDir, nsIFile* aProgramsDir) {
MOZ_DIAGNOSTIC_ASSERT(
!NS_IsMainThread(),
"PinCurrentAppToTaskbarImpl should be called off main thread only");
nsAutoString shortcutPath;
nsresult rv = FindPinnableShortcut(aAppUserModelId, aShortcutSubstring,
aPrivateBrowsing, shortcutPath);
if (NS_FAILED(rv)) {
shortcutPath.Truncate();
}
if (shortcutPath.IsEmpty()) {
if (aCheckOnly) {
// Later checks rely on a shortcut already existing.
// We don't want to create a shortcut in check only mode
// so the best we can do is assume those parts will work.
return NS_OK;
}
nsAutoString linkName(aShortcutName);
nsCOMPtr<nsIFile> exeFile(aGreDir);
if (aPrivateBrowsing) {
nsAutoString pbExeStr(PRIVATE_BROWSING_BINARY);
nsresult rv = exeFile->Append(pbExeStr);
if (!NS_SUCCEEDED(rv)) {
return NS_ERROR_FAILURE;
}
} else {
wchar_t exePath[MAXPATHLEN] = {};
if (NS_WARN_IF(NS_FAILED(BinaryPath::GetLong(exePath)))) {
return NS_ERROR_FAILURE;
}
nsAutoString exeStr(exePath);
nsresult rv = NS_NewLocalFile(exeStr, getter_AddRefs(exeFile));
if (!NS_SUCCEEDED(rv)) {
return NS_ERROR_FILE_NOT_FOUND;
}
}
nsCOMPtr<nsIFile> shortcutFile(aProgramsDir);
shortcutFile->Append(aShortcutName);
shortcutPath.Assign(shortcutFile->NativePath());
nsTArray<nsString> arguments;
rv = CreateShortcutImpl(exeFile, arguments, aShortcutName, exeFile,
// Icon indexes are defined as Resource IDs, but
// CreateShortcutImpl needs an index.
IDI_APPICON - 1, aAppUserModelId, FOLDERID_Programs,
linkName, shortcutFile->NativePath(),
aShortcutsLogDir);
if (!NS_SUCCEEDED(rv)) {
return NS_ERROR_FILE_NOT_FOUND;
}
}
return PinShortcutToTaskbarImpl(aCheckOnly, aAppUserModelId, shortcutPath);
}
static nsresult PinCurrentAppToTaskbarAsyncImpl(bool aCheckOnly,
bool aPrivateBrowsing,
JSContext* aCx,
dom::Promise** aPromise) {
if (!NS_IsMainThread()) {
return NS_ERROR_NOT_SAME_THREAD;
}
// First available on 1809
if (!IsWin10Sep2018UpdateOrLater()) {
return NS_ERROR_NOT_AVAILABLE;
}
ErrorResult rv;
RefPtr<dom::Promise> promise =
dom::Promise::Create(xpc::CurrentNativeGlobal(aCx), rv);
if (MOZ_UNLIKELY(rv.Failed())) {
return rv.StealNSResult();
}
nsAutoString aumid;
if (NS_WARN_IF(!mozilla::widget::WinTaskbar::GetAppUserModelID(
aumid, aPrivateBrowsing))) {
return NS_ERROR_FAILURE;
}
// NOTE: In the installer, non-private shortcuts are named
// "${BrandShortName}.lnk". This is set from MOZ_APP_DISPLAYNAME in
// defines.nsi.in. (Except in dev edition where it's explicitly set to
// "Firefox Developer Edition" in branding.nsi, which matches
// MOZ_APP_DISPLAYNAME in aurora/configure.sh.)
//
// If this changes, we could expand this to check shortcuts_log.ini,
// which records the name of the shortcuts as created by the installer.
//
// Private shortcuts are not created by the installer (they're created
// upon user request, ultimately by CreateShortcutImpl, and recorded in
// a separate shortcuts log. As with non-private shortcuts they have a known
// name - so there's no need to look through logs to find them.
nsAutoString shortcutName;
if (aPrivateBrowsing) {
nsTArray<nsCString> resIds = {
"branding/brand.ftl"_ns,
"browser/browser.ftl"_ns,
};
RefPtr<Localization> l10n = Localization::Create(resIds, true);
nsAutoCString pbStr;
IgnoredErrorResult rv;
l10n->FormatValueSync("private-browsing-shortcut-text-2"_ns, {}, pbStr, rv);
shortcutName.Append(NS_ConvertUTF8toUTF16(pbStr));
shortcutName.AppendLiteral(".lnk");
} else {
shortcutName.AppendLiteral(MOZ_APP_DISPLAYNAME ".lnk");
}
nsCOMPtr<nsIFile> greDir, updRoot, programsDir, shortcutsLogDir;
nsresult nsrv = NS_GetSpecialDirectory(NS_GRE_DIR, getter_AddRefs(greDir));
NS_ENSURE_SUCCESS(nsrv, nsrv);
nsrv = NS_GetSpecialDirectory(XRE_UPDATE_ROOT_DIR, getter_AddRefs(updRoot));
NS_ENSURE_SUCCESS(nsrv, nsrv);
rv = NS_GetSpecialDirectory(NS_WIN_PROGRAMS_DIR, getter_AddRefs(programsDir));
NS_ENSURE_SUCCESS(nsrv, nsrv);
nsrv = updRoot->GetParent(getter_AddRefs(shortcutsLogDir));
NS_ENSURE_SUCCESS(nsrv, nsrv);
auto promiseHolder = MakeRefPtr<nsMainThreadPtrHolder<dom::Promise>>(
"CheckPinCurrentAppToTaskbarAsync promise", promise);
NS_DispatchBackgroundTask(
NS_NewRunnableFunction(
"CheckPinCurrentAppToTaskbarAsync",
[aCheckOnly, aPrivateBrowsing, shortcutName, aumid = nsString{aumid},
shortcutsLogDir, greDir, programsDir,
promiseHolder = std::move(promiseHolder)] {
nsresult rv = NS_ERROR_FAILURE;
HRESULT hr = CoInitialize(nullptr);
if (SUCCEEDED(hr)) {
nsAutoString shortcutSubstring;
shortcutSubstring.AssignLiteral(MOZ_APP_DISPLAYNAME);
rv = PinCurrentAppToTaskbarImpl(
aCheckOnly, aPrivateBrowsing, aumid, shortcutName,
shortcutSubstring, shortcutsLogDir.get(), greDir.get(),
programsDir.get());
CoUninitialize();
}
NS_DispatchToMainThread(NS_NewRunnableFunction(
"CheckPinCurrentAppToTaskbarAsync callback",
[rv, promiseHolder = std::move(promiseHolder)] {
dom::Promise* promise = promiseHolder.get()->get();
if (NS_SUCCEEDED(rv)) {
promise->MaybeResolveWithUndefined();
} else {
promise->MaybeReject(rv);
}
}));
}),
NS_DISPATCH_EVENT_MAY_BLOCK);
promise.forget(aPromise);
return NS_OK;
}
NS_IMETHODIMP
nsWindowsShellService::PinCurrentAppToTaskbarAsync(bool aPrivateBrowsing,
JSContext* aCx,
dom::Promise** aPromise) {
return PinCurrentAppToTaskbarAsyncImpl(
/* aCheckOnly */ false, aPrivateBrowsing, aCx, aPromise);
}
NS_IMETHODIMP
nsWindowsShellService::CheckPinCurrentAppToTaskbarAsync(
bool aPrivateBrowsing, JSContext* aCx, dom::Promise** aPromise) {
return PinCurrentAppToTaskbarAsyncImpl(
/* aCheckOnly = */ true, aPrivateBrowsing, aCx, aPromise);
}
NS_IMETHODIMP
nsWindowsShellService::IsCurrentAppPinnedToTaskbarAsync(
const nsAString& aumid, JSContext* aCx, /* out */ dom::Promise** aPromise) {
if (!NS_IsMainThread()) {
return NS_ERROR_NOT_SAME_THREAD;
}
ErrorResult rv;
RefPtr<dom::Promise> promise =
dom::Promise::Create(xpc::CurrentNativeGlobal(aCx), rv);
if (MOZ_UNLIKELY(rv.Failed())) {
return rv.StealNSResult();
}
// A holder to pass the promise through the background task and back to
// the main thread when finished.
auto promiseHolder = MakeRefPtr<nsMainThreadPtrHolder<dom::Promise>>(
"IsCurrentAppPinnedToTaskbarAsync promise", promise);
// nsAString can't be captured by a lambda because it does not have a
// public copy constructor
nsAutoString capturedAumid(aumid);
NS_DispatchBackgroundTask(
NS_NewRunnableFunction(
"IsCurrentAppPinnedToTaskbarAsync",
[capturedAumid, promiseHolder = std::move(promiseHolder)] {
bool isPinned = false;
HRESULT hr = CoInitialize(nullptr);
if (SUCCEEDED(hr)) {
isPinned = IsCurrentAppPinnedToTaskbarSync(capturedAumid);
CoUninitialize();
}
// Dispatch back to the main thread to resolve the promise.
NS_DispatchToMainThread(NS_NewRunnableFunction(
"IsCurrentAppPinnedToTaskbarAsync callback",
[isPinned, promiseHolder = std::move(promiseHolder)] {
promiseHolder.get()->get()->MaybeResolve(isPinned);
}));
}),
NS_DISPATCH_EVENT_MAY_BLOCK);
promise.forget(aPromise);
return NS_OK;
}
#ifndef __MINGW32__
# define RESOLVE_AND_RETURN(HOLDER, RESOLVE, RETURN) \
NS_DispatchToMainThread(NS_NewRunnableFunction( \
__func__, [resolveVal = (RESOLVE), promiseHolder = HOLDER] { \
promiseHolder.get()->get()->MaybeResolve(resolveVal); \
})); \
return RETURN
# define REJECT_AND_RETURN(HOLDER, REJECT, RETURN) \
NS_DispatchToMainThread( \
NS_NewRunnableFunction(__func__, [promiseHolder = HOLDER] { \
promiseHolder.get()->get()->MaybeReject(REJECT); \
})); \
return RETURN
static void EnableLaunchOnLoginMSIXAsyncImpl(
const nsString& capturedTaskId,
const RefPtr<nsMainThreadPtrHolder<dom::Promise>> promiseHolder) {
ComPtr<IStartupTaskStatics> startupTaskStatics;
HRESULT hr = GetActivationFactory(
HStringReference(RuntimeClass_Windows_ApplicationModel_StartupTask).Get(),
&startupTaskStatics);
if (FAILED(hr)) {
REJECT_AND_RETURN(promiseHolder, NS_ERROR_FAILURE, /* void */);
}
ComPtr<IAsyncOperation<StartupTask*>> getTaskOperation = nullptr;
hr = startupTaskStatics->GetAsync(
HStringReference(capturedTaskId.get()).Get(), &getTaskOperation);
if (FAILED(hr)) {
REJECT_AND_RETURN(promiseHolder, NS_ERROR_FAILURE, /* void */);
}
auto getTaskCallback =
Callback<IAsyncOperationCompletedHandler<StartupTask*>>(
[promiseHolder](IAsyncOperation<StartupTask*>* operation,
AsyncStatus status) -> HRESULT {
if (status != AsyncStatus::Completed) {
REJECT_AND_RETURN(promiseHolder, NS_ERROR_FAILURE, E_FAIL);
}
ComPtr<IStartupTask> startupTask;
HRESULT hr = operation->GetResults(&startupTask);
if (FAILED(hr)) {
REJECT_AND_RETURN(promiseHolder, NS_ERROR_FAILURE, E_FAIL);
}
ComPtr<IAsyncOperation<StartupTaskState>> enableOperation;
hr = startupTask->RequestEnableAsync(&enableOperation);
if (FAILED(hr)) {
REJECT_AND_RETURN(promiseHolder, NS_ERROR_FAILURE, E_FAIL);
}
// Set another callback for enabling the startup task
auto enableHandler =
Callback<IAsyncOperationCompletedHandler<StartupTaskState>>(
[promiseHolder](
IAsyncOperation<StartupTaskState>* operation,
AsyncStatus status) -> HRESULT {
StartupTaskState resultState;
HRESULT hr = operation->GetResults(&resultState);
if (SUCCEEDED(hr) && status == AsyncStatus::Completed) {
RESOLVE_AND_RETURN(promiseHolder, true, S_OK);
}
RESOLVE_AND_RETURN(promiseHolder, false, S_OK);
});
hr = enableOperation->put_Completed(enableHandler.Get());
if (FAILED(hr)) {
REJECT_AND_RETURN(promiseHolder, NS_ERROR_FAILURE, hr);
}
return hr;
});
hr = getTaskOperation->put_Completed(getTaskCallback.Get());
if (FAILED(hr)) {
REJECT_AND_RETURN(promiseHolder, NS_ERROR_FAILURE, /* void */);
}
}
static void DisableLaunchOnLoginMSIXAsyncImpl(
const nsString& capturedTaskId,
const RefPtr<nsMainThreadPtrHolder<dom::Promise>> promiseHolder) {
ComPtr<IStartupTaskStatics> startupTaskStatics;
HRESULT hr = GetActivationFactory(
HStringReference(RuntimeClass_Windows_ApplicationModel_StartupTask).Get(),
&startupTaskStatics);
if (FAILED(hr)) {
REJECT_AND_RETURN(promiseHolder, NS_ERROR_FAILURE, /* void */);
}
ComPtr<IAsyncOperation<StartupTask*>> getTaskOperation = nullptr;
hr = startupTaskStatics->GetAsync(
HStringReference(capturedTaskId.get()).Get(), &getTaskOperation);
if (FAILED(hr)) {
REJECT_AND_RETURN(promiseHolder, NS_ERROR_FAILURE, /* void */);
}
auto getTaskCallback =
Callback<IAsyncOperationCompletedHandler<StartupTask*>>(
[promiseHolder](IAsyncOperation<StartupTask*>* operation,
AsyncStatus status) -> HRESULT {
if (status != AsyncStatus::Completed) {
REJECT_AND_RETURN(promiseHolder, NS_ERROR_FAILURE, E_FAIL);
}
ComPtr<IStartupTask> startupTask;
HRESULT hr = operation->GetResults(&startupTask);
if (FAILED(hr)) {
REJECT_AND_RETURN(promiseHolder, NS_ERROR_FAILURE, E_FAIL);
}
hr = startupTask->Disable();
if (FAILED(hr)) {
REJECT_AND_RETURN(promiseHolder, NS_ERROR_FAILURE, E_FAIL);
}
RESOLVE_AND_RETURN(promiseHolder, true, S_OK);
});
hr = getTaskOperation->put_Completed(getTaskCallback.Get());
if (FAILED(hr)) {
REJECT_AND_RETURN(promiseHolder, NS_ERROR_FAILURE, /* void */);
}
}
static void GetLaunchOnLoginEnabledMSIXAsyncImpl(
const nsString& capturedTaskId,
const RefPtr<nsMainThreadPtrHolder<dom::Promise>> promiseHolder) {
ComPtr<IStartupTaskStatics> startupTaskStatics;
HRESULT hr = GetActivationFactory(
HStringReference(RuntimeClass_Windows_ApplicationModel_StartupTask).Get(),
&startupTaskStatics);
if (FAILED(hr)) {
REJECT_AND_RETURN(promiseHolder, NS_ERROR_FAILURE, /* void */);
}
ComPtr<IAsyncOperation<StartupTask*>> getTaskOperation = nullptr;
hr = startupTaskStatics->GetAsync(
HStringReference(capturedTaskId.get()).Get(), &getTaskOperation);
if (FAILED(hr)) {
REJECT_AND_RETURN(promiseHolder, NS_ERROR_FAILURE, /* void */);
}
auto getTaskCallback =
Callback<IAsyncOperationCompletedHandler<StartupTask*>>(
[promiseHolder](IAsyncOperation<StartupTask*>* operation,
AsyncStatus status) -> HRESULT {
if (status != AsyncStatus::Completed) {
REJECT_AND_RETURN(promiseHolder, NS_ERROR_FAILURE, E_FAIL);
}
ComPtr<IStartupTask> startupTask;
HRESULT hr = operation->GetResults(&startupTask);
if (FAILED(hr)) {
REJECT_AND_RETURN(promiseHolder, NS_ERROR_FAILURE, E_FAIL);
}
StartupTaskState state;
hr = startupTask->get_State(&state);
if (FAILED(hr)) {
REJECT_AND_RETURN(promiseHolder, NS_ERROR_FAILURE, E_FAIL);
}
switch (state) {
case StartupTaskState_EnabledByPolicy:
RESOLVE_AND_RETURN(
promiseHolder,
nsIWindowsShellService::LaunchOnLoginEnabledEnumerator::
LAUNCH_ON_LOGIN_ENABLED_BY_POLICY,
S_OK);
break;
case StartupTaskState_Enabled:
RESOLVE_AND_RETURN(
promiseHolder,
nsIWindowsShellService::LaunchOnLoginEnabledEnumerator::
LAUNCH_ON_LOGIN_ENABLED,
S_OK);
break;
case StartupTaskState_DisabledByUser:
case StartupTaskState_DisabledByPolicy:
RESOLVE_AND_RETURN(
promiseHolder,
nsIWindowsShellService::LaunchOnLoginEnabledEnumerator::
LAUNCH_ON_LOGIN_DISABLED_BY_SETTINGS,
S_OK);
break;
default:
RESOLVE_AND_RETURN(
promiseHolder,
nsIWindowsShellService::LaunchOnLoginEnabledEnumerator::
LAUNCH_ON_LOGIN_DISABLED,
S_OK);
}
});
hr = getTaskOperation->put_Completed(getTaskCallback.Get());
if (FAILED(hr)) {
REJECT_AND_RETURN(promiseHolder, NS_ERROR_FAILURE, /* void */);
}
}
NS_IMETHODIMP
nsWindowsShellService::EnableLaunchOnLoginMSIXAsync(
const nsAString& aTaskId, JSContext* aCx,
/* out */ dom::Promise** aPromise) {
if (!widget::WinUtils::HasPackageIdentity()) {
return NS_ERROR_NOT_AVAILABLE;
}
if (!NS_IsMainThread()) {
return NS_ERROR_NOT_SAME_THREAD;
}
ErrorResult rv;
RefPtr<dom::Promise> promise =
dom::Promise::Create(xpc::CurrentNativeGlobal(aCx), rv);
if (MOZ_UNLIKELY(rv.Failed())) {
return rv.StealNSResult();
}
// A holder to pass the promise through the background task and back to
// the main thread when finished.
auto promiseHolder = MakeRefPtr<nsMainThreadPtrHolder<dom::Promise>>(
"EnableLaunchOnLoginMSIXAsync promise", promise);
NS_DispatchBackgroundTask(NS_NewRunnableFunction(
"EnableLaunchOnLoginMSIXAsync",
[taskId = nsString(aTaskId), promiseHolder] {
EnableLaunchOnLoginMSIXAsyncImpl(taskId, promiseHolder);
}));
promise.forget(aPromise);
return NS_OK;
}
NS_IMETHODIMP
nsWindowsShellService::DisableLaunchOnLoginMSIXAsync(
const nsAString& aTaskId, JSContext* aCx,
/* out */ dom::Promise** aPromise) {
if (!widget::WinUtils::HasPackageIdentity()) {
return NS_ERROR_NOT_AVAILABLE;
}
if (!NS_IsMainThread()) {
return NS_ERROR_NOT_SAME_THREAD;
}
ErrorResult rv;
RefPtr<dom::Promise> promise =
dom::Promise::Create(xpc::CurrentNativeGlobal(aCx), rv);
if (MOZ_UNLIKELY(rv.Failed())) {
return rv.StealNSResult();
}
// A holder to pass the promise through the background task and back to
// the main thread when finished.
auto promiseHolder = MakeRefPtr<nsMainThreadPtrHolder<dom::Promise>>(
"DisableLaunchOnLoginMSIXAsync promise", promise);
NS_DispatchBackgroundTask(NS_NewRunnableFunction(
"DisableLaunchOnLoginMSIXAsync",
[taskId = nsString(aTaskId), promiseHolder] {
DisableLaunchOnLoginMSIXAsyncImpl(taskId, promiseHolder);
}));
promise.forget(aPromise);
return NS_OK;
}
NS_IMETHODIMP
nsWindowsShellService::GetLaunchOnLoginEnabledMSIXAsync(
const nsAString& aTaskId, JSContext* aCx,
/* out */ dom::Promise** aPromise) {
if (!widget::WinUtils::HasPackageIdentity()) {
return NS_ERROR_NOT_AVAILABLE;
}
if (!NS_IsMainThread()) {
return NS_ERROR_NOT_SAME_THREAD;
}
ErrorResult rv;
RefPtr<dom::Promise> promise =
dom::Promise::Create(xpc::CurrentNativeGlobal(aCx), rv);
if (MOZ_UNLIKELY(rv.Failed())) {
return rv.StealNSResult();
}
// A holder to pass the promise through the background task and back to
// the main thread when finished.
auto promiseHolder = MakeRefPtr<nsMainThreadPtrHolder<dom::Promise>>(
"GetLaunchOnLoginEnabledMSIXAsync promise", promise);
NS_DispatchBackgroundTask(NS_NewRunnableFunction(
"GetLaunchOnLoginEnabledMSIXAsync",
[taskId = nsString(aTaskId), promiseHolder] {
GetLaunchOnLoginEnabledMSIXAsyncImpl(taskId, promiseHolder);
}));
promise.forget(aPromise);
return NS_OK;
}
static HRESULT GetPackage3(ComPtr<IPackage3>& package3) {
// Get the current package and cast it to IPackage3 so we can
// check for AppListEntries
ComPtr<IPackageStatics> packageStatics;
HRESULT hr = GetActivationFactory(
HStringReference(RuntimeClass_Windows_ApplicationModel_Package).Get(),
&packageStatics);
if (FAILED(hr)) {
return hr;
}
ComPtr<IPackage> package;
hr = packageStatics->get_Current(&package);
if (FAILED(hr)) {
return hr;
}
hr = package.As(&package3);
return hr;
}
static HRESULT GetStartScreenManager(
ComPtr<IVectorView<AppListEntry*>>& appListEntries,
ComPtr<IAppListEntry>& entry,
ComPtr<IStartScreenManager>& startScreenManager) {
unsigned int numEntries = 0;
HRESULT hr = appListEntries->get_Size(&numEntries);
if (FAILED(hr) || numEntries == 0) {
return E_FAIL;
}
// There's only one AppListEntry in the Firefox package and by
// convention our main executable should be the first in the
// list.
hr = appListEntries->GetAt(0, &entry);
// Create and init a StartScreenManager and check if we're already
// pinned.
ComPtr<IStartScreenManagerStatics> startScreenManagerStatics;
hr = GetActivationFactory(
HStringReference(RuntimeClass_Windows_UI_StartScreen_StartScreenManager)
.Get(),
&startScreenManagerStatics);
if (FAILED(hr)) {
return hr;
}
hr = startScreenManagerStatics->GetDefault(&startScreenManager);
return hr;
}
static void PinCurrentAppToStartMenuAsyncImpl(
bool aCheckOnly,
const RefPtr<nsMainThreadPtrHolder<dom::Promise>> promiseHolder) {
ComPtr<IPackage3> package3;
HRESULT hr = GetPackage3(package3);
if (FAILED(hr)) {
REJECT_AND_RETURN(promiseHolder, NS_ERROR_FAILURE, /* void */);
}
// Get the AppList entries
ComPtr<IVectorView<AppListEntry*>> appListEntries;
ComPtr<IAsyncOperation<IVectorView<AppListEntry*>*>>
getAppListEntriesOperation;
hr = package3->GetAppListEntriesAsync(&getAppListEntriesOperation);
if (FAILED(hr)) {
REJECT_AND_RETURN(promiseHolder, NS_ERROR_FAILURE, /* void */);
}
auto getAppListEntriesCallback =
Callback<IAsyncOperationCompletedHandler<IVectorView<AppListEntry*>*>>(
[promiseHolder, aCheckOnly](
IAsyncOperation<IVectorView<AppListEntry*>*>* operation,
AsyncStatus status) -> HRESULT {
if (status != AsyncStatus::Completed) {
REJECT_AND_RETURN(promiseHolder, NS_ERROR_FAILURE, E_FAIL);
}
ComPtr<IVectorView<AppListEntry*>> appListEntries;
HRESULT hr = operation->GetResults(&appListEntries);
if (FAILED(hr)) {
REJECT_AND_RETURN(promiseHolder, NS_ERROR_FAILURE, E_FAIL);
}
ComPtr<IStartScreenManager> startScreenManager;
ComPtr<IAppListEntry> entry;
hr = GetStartScreenManager(appListEntries, entry,
startScreenManager);
if (FAILED(hr)) {
REJECT_AND_RETURN(promiseHolder, NS_ERROR_FAILURE, E_FAIL);
}
ComPtr<IAsyncOperation<bool>> getPinnedOperation;
hr = startScreenManager->ContainsAppListEntryAsync(
entry.Get(), &getPinnedOperation);
if (FAILED(hr)) {
REJECT_AND_RETURN(promiseHolder, NS_ERROR_FAILURE, E_FAIL);
}
auto getPinnedCallback =
Callback<IAsyncOperationCompletedHandler<bool>>(
[promiseHolder, entry, startScreenManager, aCheckOnly](
IAsyncOperation<bool>* operation,
AsyncStatus status) -> HRESULT {
if (status != AsyncStatus::Completed) {
REJECT_AND_RETURN(promiseHolder, NS_ERROR_FAILURE,
E_FAIL);
}
boolean isAlreadyPinned;
HRESULT hr = operation->GetResults(&isAlreadyPinned);
if (FAILED(hr)) {
REJECT_AND_RETURN(promiseHolder, NS_ERROR_FAILURE,
E_FAIL);
}
// If we're already pinned we can return early
// Ditto if we're just checking whether we *can* pin
if (isAlreadyPinned || aCheckOnly) {
RESOLVE_AND_RETURN(promiseHolder, true, S_OK);
}
ComPtr<IAsyncOperation<bool>> pinOperation;
startScreenManager->RequestAddAppListEntryAsync(
entry.Get(), &pinOperation);
// Set another callback for pinning to the start menu
auto pinOperationCallback =
Callback<IAsyncOperationCompletedHandler<bool>>(
[promiseHolder](IAsyncOperation<bool>* operation,
AsyncStatus status) -> HRESULT {
if (status != AsyncStatus::Completed) {
REJECT_AND_RETURN(promiseHolder,
NS_ERROR_FAILURE, E_FAIL);
};
boolean pinSuccess;
HRESULT hr = operation->GetResults(&pinSuccess);
if (FAILED(hr)) {
REJECT_AND_RETURN(promiseHolder,
NS_ERROR_FAILURE, E_FAIL);
}
RESOLVE_AND_RETURN(promiseHolder,
pinSuccess ? true : false,
S_OK);
});
hr = pinOperation->put_Completed(
pinOperationCallback.Get());
if (FAILED(hr)) {
REJECT_AND_RETURN(promiseHolder, NS_ERROR_FAILURE, hr);
}
return hr;
});
hr = getPinnedOperation->put_Completed(getPinnedCallback.Get());
if (FAILED(hr)) {
REJECT_AND_RETURN(promiseHolder, NS_ERROR_FAILURE, hr);
}
return hr;
});
hr = getAppListEntriesOperation->put_Completed(
getAppListEntriesCallback.Get());
if (FAILED(hr)) {
REJECT_AND_RETURN(promiseHolder, NS_ERROR_FAILURE, /* void */);
}
}
NS_IMETHODIMP
nsWindowsShellService::PinCurrentAppToStartMenuAsync(bool aCheckOnly,
JSContext* aCx,
dom::Promise** aPromise) {
if (!NS_IsMainThread()) {
return NS_ERROR_NOT_SAME_THREAD;
}
// Unfortunately pinning to the Start Menu requires IAppListEntry
// which is only implemented for packaged applications.
if (!widget::WinUtils::HasPackageIdentity()) {
return NS_ERROR_NOT_AVAILABLE;
}
ErrorResult rv;
RefPtr<dom::Promise> promise =
dom::Promise::Create(xpc::CurrentNativeGlobal(aCx), rv);
if (MOZ_UNLIKELY(rv.Failed())) {
return rv.StealNSResult();
}
// A holder to pass the promise through the background task and back to
// the main thread when finished.
auto promiseHolder = MakeRefPtr<nsMainThreadPtrHolder<dom::Promise>>(
"PinCurrentAppToStartMenuAsync promise", promise);
NS_DispatchBackgroundTask(NS_NewRunnableFunction(
"PinCurrentAppToStartMenuAsync", [aCheckOnly, promiseHolder] {
PinCurrentAppToStartMenuAsyncImpl(aCheckOnly, promiseHolder);
}));
promise.forget(aPromise);
return NS_OK;
}
static void IsCurrentAppPinnedToStartMenuAsyncImpl(
const RefPtr<nsMainThreadPtrHolder<dom::Promise>> promiseHolder) {
ComPtr<IPackage3> package3;
HRESULT hr = GetPackage3(package3);
if (FAILED(hr)) {
REJECT_AND_RETURN(promiseHolder, NS_ERROR_FAILURE, /* void */);
}
// Get the AppList entries
ComPtr<IVectorView<AppListEntry*>> appListEntries;
ComPtr<IAsyncOperation<IVectorView<AppListEntry*>*>>
getAppListEntriesOperation;
hr = package3->GetAppListEntriesAsync(&getAppListEntriesOperation);
if (FAILED(hr)) {
REJECT_AND_RETURN(promiseHolder, NS_ERROR_FAILURE, /* void */);
}
auto getAppListEntriesCallback =
Callback<IAsyncOperationCompletedHandler<IVectorView<AppListEntry*>*>>(
[promiseHolder](
IAsyncOperation<IVectorView<AppListEntry*>*>* operation,
AsyncStatus status) -> HRESULT {
if (status != AsyncStatus::Completed) {
REJECT_AND_RETURN(promiseHolder, NS_ERROR_FAILURE, E_FAIL);
}
ComPtr<IVectorView<AppListEntry*>> appListEntries;
HRESULT hr = operation->GetResults(&appListEntries);
if (FAILED(hr)) {
REJECT_AND_RETURN(promiseHolder, NS_ERROR_FAILURE, E_FAIL);
}
ComPtr<IStartScreenManager> startScreenManager;
ComPtr<IAppListEntry> entry;
hr = GetStartScreenManager(appListEntries, entry,
startScreenManager);
if (FAILED(hr)) {
REJECT_AND_RETURN(promiseHolder, NS_ERROR_FAILURE, E_FAIL);
}
ComPtr<IAsyncOperation<bool>> getPinnedOperation;
hr = startScreenManager->ContainsAppListEntryAsync(
entry.Get(), &getPinnedOperation);
if (FAILED(hr)) {
REJECT_AND_RETURN(promiseHolder, NS_ERROR_FAILURE, E_FAIL);
}
auto getPinnedCallback =
Callback<IAsyncOperationCompletedHandler<bool>>(
[promiseHolder, entry, startScreenManager](
IAsyncOperation<bool>* operation,
AsyncStatus status) -> HRESULT {
if (status != AsyncStatus::Completed) {
REJECT_AND_RETURN(promiseHolder, NS_ERROR_FAILURE,
E_FAIL);
}
boolean isAlreadyPinned;
HRESULT hr = operation->GetResults(&isAlreadyPinned);
if (FAILED(hr)) {
REJECT_AND_RETURN(promiseHolder, NS_ERROR_FAILURE,
E_FAIL);
}
RESOLVE_AND_RETURN(promiseHolder,
isAlreadyPinned ? true : false, S_OK);
});
hr = getPinnedOperation->put_Completed(getPinnedCallback.Get());
if (FAILED(hr)) {
REJECT_AND_RETURN(promiseHolder, NS_ERROR_FAILURE, hr);
}
return hr;
});
hr = getAppListEntriesOperation->put_Completed(
getAppListEntriesCallback.Get());
if (FAILED(hr)) {
REJECT_AND_RETURN(promiseHolder, NS_ERROR_FAILURE, /* void */);
}
}
NS_IMETHODIMP
nsWindowsShellService::IsCurrentAppPinnedToStartMenuAsync(
JSContext* aCx, dom::Promise** aPromise) {
if (!NS_IsMainThread()) {
return NS_ERROR_NOT_SAME_THREAD;
}
// Unfortunately pinning to the Start Menu requires IAppListEntry
// which is only implemented for packaged applications.
if (!widget::WinUtils::HasPackageIdentity()) {
return NS_ERROR_NOT_AVAILABLE;
}
ErrorResult rv;
RefPtr<dom::Promise> promise =
dom::Promise::Create(xpc::CurrentNativeGlobal(aCx), rv);
if (MOZ_UNLIKELY(rv.Failed())) {
return rv.StealNSResult();
}
// A holder to pass the promise through the background task and back to
// the main thread when finished.
auto promiseHolder = MakeRefPtr<nsMainThreadPtrHolder<dom::Promise>>(
"IsCurrentAppPinnedToStartMenuAsync promise", promise);
NS_DispatchBackgroundTask(NS_NewRunnableFunction(
"IsCurrentAppPinnedToStartMenuAsync", [promiseHolder] {
IsCurrentAppPinnedToStartMenuAsyncImpl(promiseHolder);
}));
promise.forget(aPromise);
return NS_OK;
}
#else
NS_IMETHODIMP
nsWindowsShellService::EnableLaunchOnLoginMSIXAsync(
const nsAString& aTaskId, JSContext* aCx,
/* out */ dom::Promise** aPromise) {
return NS_ERROR_NOT_IMPLEMENTED;
}
NS_IMETHODIMP
nsWindowsShellService::DisableLaunchOnLoginMSIXAsync(
const nsAString& aTaskId, JSContext* aCx,
/* out */ dom::Promise** aPromise) {
return NS_ERROR_NOT_IMPLEMENTED;
}
NS_IMETHODIMP
nsWindowsShellService::GetLaunchOnLoginEnabledMSIXAsync(
const nsAString& aTaskId, JSContext* aCx,
/* out */ dom::Promise** aPromise) {
return NS_ERROR_NOT_IMPLEMENTED;
}
NS_IMETHODIMP
nsWindowsShellService::PinCurrentAppToStartMenuAsync(bool aCheckOnly,
JSContext* aCx,
dom::Promise** aPromise) {
return NS_ERROR_NOT_IMPLEMENTED;
}
NS_IMETHODIMP
nsWindowsShellService::IsCurrentAppPinnedToStartMenuAsync(
JSContext* aCx, dom::Promise** aPromise) {
return NS_ERROR_NOT_IMPLEMENTED;
}
#endif
NS_IMETHODIMP
nsWindowsShellService::ClassifyShortcut(const nsAString& aPath,
nsAString& aResult) {
aResult.Truncate();
nsAutoString shortcutPath(PromiseFlatString(aPath));
// NOTE: On Windows 7, Start Menu pin shortcuts are stored under
// "<FOLDERID_User Pinned>\StartMenu", but on Windows 10 they are just normal
// Start Menu shortcuts. These both map to "StartMenu" for consistency,
// rather than having a separate "StartMenuPins" which would only apply on
// Win7.
struct {
KNOWNFOLDERID folderId;
const char16_t* postfix;
const char16_t* classification;
} folders[] = {{FOLDERID_CommonStartMenu, u"\\", u"StartMenu"},
{FOLDERID_StartMenu, u"\\", u"StartMenu"},
{FOLDERID_PublicDesktop, u"\\", u"Desktop"},
{FOLDERID_Desktop, u"\\", u"Desktop"},
{FOLDERID_UserPinned, u"\\TaskBar\\", u"Taskbar"},
{FOLDERID_UserPinned, u"\\StartMenu\\", u"StartMenu"}};
for (size_t i = 0; i < std::size(folders); ++i) {
nsAutoString knownPath;
// These flags are chosen to avoid I/O, see bug 1363398.
DWORD flags =
KF_FLAG_SIMPLE_IDLIST | KF_FLAG_DONT_VERIFY | KF_FLAG_NO_ALIAS;
PWSTR rawPath = nullptr;
if (FAILED(SHGetKnownFolderPath(folders[i].folderId, flags, nullptr,
&rawPath))) {
continue;
}
knownPath = nsDependentString(rawPath);
CoTaskMemFree(rawPath);
knownPath.Append(folders[i].postfix);
// Check if the shortcut path starts with the shell folder path.
if (wcsnicmp(shortcutPath.get(), knownPath.get(), knownPath.Length()) ==
0) {
aResult.Assign(folders[i].classification);
nsTArray<nsCString> resIds = {
"branding/brand.ftl"_ns,
"browser/browser.ftl"_ns,
};
RefPtr<Localization> l10n = Localization::Create(resIds, true);
nsAutoCString pbStr;
IgnoredErrorResult rv;
l10n->FormatValueSync("private-browsing-shortcut-text-2"_ns, {}, pbStr,
rv);
NS_ConvertUTF8toUTF16 widePbStr(pbStr);
if (wcsstr(shortcutPath.get(), widePbStr.get())) {
aResult.AppendLiteral("Private");
}
return NS_OK;
}
}
// Nothing found, aResult is already "".
return NS_OK;
}
nsWindowsShellService::nsWindowsShellService() {}
nsWindowsShellService::~nsWindowsShellService() {}
|