1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332 4333 4334 4335 4336 4337 4338 4339 4340 4341 4342 4343 4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 4359 4360 4361 4362 4363 4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397 4398 4399 4400 4401 4402 4403 4404 4405 4406 4407 4408 4409 4410 4411 4412 4413 4414 4415 4416 4417 4418 4419 4420 4421 4422 4423 4424 4425 4426 4427 4428 4429 4430 4431 4432 4433 4434 4435 4436 4437 4438 4439 4440 4441 4442 4443 4444 4445 4446 4447 4448 4449 4450 4451 4452 4453 4454 4455 4456 4457 4458 4459 4460 4461 4462 4463 4464 4465 4466 4467 4468 4469 4470 4471 4472 4473 4474 4475 4476 4477 4478 4479 4480 4481 4482 4483 4484 4485 4486 4487 4488 4489 4490 4491 4492 4493 4494 4495 4496 4497 4498 4499 4500 4501 4502 4503 4504 4505 4506 4507 4508 4509 4510 4511 4512 4513 4514 4515 4516 4517 4518 4519 4520 4521 4522 4523 4524 4525 4526 4527 4528 4529 4530 4531 4532 4533 4534 4535 4536 4537 4538 4539 4540 4541 4542 4543 4544 4545 4546 4547 4548 4549 4550 4551 4552 4553 4554 4555 4556 4557 4558 4559 4560 4561 4562 4563 4564 4565 4566 4567 4568 4569 4570 4571 4572 4573 4574 4575 4576 4577 4578 4579 4580 4581 4582 4583 4584 4585 4586 4587 4588 4589 4590 4591 4592 4593 4594 4595 4596 4597 4598 4599 4600 4601 4602 4603 4604 4605 4606 4607 4608 4609 4610 4611 4612 4613 4614 4615 4616 4617 4618 4619 4620 4621 4622 4623 4624 4625 4626 4627 4628 4629 4630 4631 4632 4633 4634 4635 4636 4637 4638 4639 4640 4641 4642 4643 4644 4645 4646 4647 4648 4649 4650 4651 4652 4653 4654 4655 4656 4657 4658 4659 4660 4661 4662 4663 4664 4665 4666 4667 4668 4669 4670 4671 4672 4673 4674 4675 4676 4677 4678 4679 4680 4681 4682 4683 4684 4685 4686 4687 4688 4689 4690 4691 4692 4693 4694 4695 4696 4697 4698 4699 4700 4701 4702 4703 4704 4705 4706 4707 4708 4709 4710 4711 4712 4713 4714 4715 4716 4717 4718 4719 4720 4721 4722 4723 4724 4725 4726 4727 4728 4729 4730 4731 4732 4733 4734 4735 4736 4737 4738 4739 4740 4741 4742 4743 4744 4745 4746 4747 4748 4749 4750 4751 4752 4753 4754 4755 4756 4757 4758 4759 4760 4761 4762 4763 4764 4765 4766 4767 4768 4769 4770 4771 4772 4773 4774 4775 4776 4777 4778 4779 4780 4781 4782 4783 4784 4785 4786 4787 4788 4789 4790 4791 4792 4793 4794 4795 4796 4797 4798 4799 4800 4801 4802 4803 4804 4805 4806 4807 4808 4809 4810 4811 4812 4813 4814 4815 4816 4817 4818 4819 4820 4821 4822 4823 4824 4825 4826 4827 4828 4829 4830 4831 4832 4833 4834 4835 4836 4837 4838 4839 4840 4841 4842 4843 4844 4845 4846 4847 4848 4849 4850 4851 4852 4853 4854 4855 4856 4857 4858 4859 4860 4861 4862 4863 4864 4865 4866 4867 4868 4869 4870 4871 4872 4873 4874 4875 4876 4877 4878 4879 4880 4881 4882 4883 4884 4885 4886 4887 4888 4889 4890 4891 4892 4893 4894 4895 4896 4897 4898 4899 4900 4901 4902 4903 4904 4905 4906 4907 4908 4909 4910 4911 4912 4913 4914 4915 4916 4917 4918 4919 4920 4921 4922 4923 4924 4925 4926 4927 4928 4929 4930 4931 4932 4933 4934 4935 4936 4937 4938 4939 4940 4941 4942 4943 4944 4945 4946 4947 4948 4949 4950 4951 4952 4953 4954 4955 4956 4957 4958 4959 4960 4961 4962 4963 4964 4965 4966 4967 4968 4969 4970 4971 4972 4973 4974 4975 4976 4977 4978 4979 4980 4981 4982 4983 4984 4985 4986 4987 4988 4989 4990 4991 4992 4993 4994 4995 4996 4997 4998 4999 5000 5001 5002 5003 5004 5005 5006 5007 5008 5009 5010 5011 5012 5013 5014 5015 5016 5017 5018 5019 5020 5021 5022 5023 5024 5025 5026 5027 5028 5029 5030 5031 5032 5033 5034 5035 5036 5037 5038 5039 5040 5041 5042 5043 5044 5045 5046 5047 5048 5049 5050 5051 5052 5053 5054 5055 5056 5057 5058 5059 5060 5061 5062 5063 5064 5065 5066 5067 5068 5069 5070 5071 5072 5073 5074 5075 5076 5077 5078 5079 5080 5081 5082 5083 5084 5085 5086 5087 5088 5089 5090 5091 5092 5093 5094 5095 5096 5097 5098 5099 5100 5101 5102 5103 5104 5105 5106 5107 5108 5109 5110 5111 5112 5113 5114 5115 5116 5117 5118 5119 5120 5121 5122 5123 5124 5125 5126 5127 5128 5129 5130 5131 5132 5133 5134 5135 5136 5137 5138 5139 5140 5141 5142 5143 5144 5145 5146 5147 5148 5149 5150 5151 5152 5153 5154 5155 5156 5157 5158 5159 5160 5161 5162 5163 5164 5165 5166 5167 5168 5169 5170 5171 5172 5173 5174 5175 5176 5177 5178 5179 5180 5181 5182 5183 5184 5185 5186 5187 5188 5189 5190 5191 5192 5193 5194 5195 5196 5197 5198 5199 5200 5201 5202 5203 5204 5205 5206 5207 5208 5209 5210 5211 5212 5213 5214 5215 5216 5217 5218 5219 5220 5221 5222 5223 5224 5225 5226 5227 5228 5229 5230 5231 5232 5233 5234 5235 5236 5237 5238 5239 5240 5241 5242 5243 5244 5245 5246 5247 5248 5249 5250 5251 5252 5253 5254 5255 5256 5257 5258 5259 5260 5261 5262 5263 5264 5265 5266 5267 5268 5269 5270 5271 5272 5273 5274 5275 5276 5277 5278 5279 5280 5281 5282 5283 5284 5285 5286 5287 5288 5289 5290 5291 5292 5293 5294 5295 5296 5297 5298 5299 5300 5301 5302 5303 5304 5305 5306 5307 5308 5309 5310 5311 5312 5313 5314 5315 5316 5317 5318 5319 5320 5321 5322 5323 5324 5325 5326 5327 5328 5329 5330 5331 5332 5333 5334 5335 5336 5337 5338 5339 5340 5341 5342 5343 5344 5345 5346 5347 5348 5349 5350 5351 5352 5353 5354 5355 5356 5357 5358 5359 5360 5361 5362 5363 5364 5365 5366 5367 5368 5369 5370 5371 5372 5373 5374 5375 5376 5377 5378 5379 5380 5381 5382 5383 5384 5385 5386 5387 5388 5389 5390 5391 5392 5393 5394 5395 5396 5397 5398 5399 5400 5401 5402 5403 5404 5405 5406 5407 5408 5409 5410 5411 5412 5413 5414 5415 5416 5417 5418 5419 5420 5421 5422 5423 5424 5425 5426 5427 5428 5429 5430 5431 5432 5433 5434 5435 5436 5437 5438 5439 5440 5441 5442 5443 5444 5445 5446 5447 5448 5449 5450 5451 5452 5453 5454 5455 5456 5457 5458 5459 5460 5461 5462 5463 5464 5465 5466 5467 5468 5469 5470 5471 5472 5473 5474 5475 5476 5477 5478 5479 5480 5481 5482 5483 5484 5485 5486 5487 5488 5489 5490 5491 5492 5493 5494 5495 5496 5497 5498 5499 5500 5501 5502 5503 5504 5505 5506 5507 5508 5509 5510 5511 5512 5513 5514 5515 5516 5517 5518 5519 5520 5521 5522 5523 5524 5525 5526 5527 5528 5529 5530 5531 5532 5533 5534 5535 5536 5537 5538 5539 5540 5541 5542 5543 5544 5545 5546 5547 5548 5549 5550 5551 5552 5553 5554 5555 5556 5557 5558 5559 5560 5561 5562 5563 5564 5565 5566 5567 5568 5569 5570 5571 5572 5573 5574 5575 5576 5577 5578 5579 5580 5581 5582 5583 5584 5585 5586 5587 5588 5589 5590 5591 5592 5593 5594 5595 5596 5597 5598 5599 5600 5601 5602 5603 5604 5605 5606 5607 5608 5609 5610 5611 5612 5613 5614 5615 5616 5617 5618 5619 5620 5621 5622 5623 5624 5625 5626 5627 5628 5629 5630 5631 5632 5633 5634 5635 5636 5637 5638 5639 5640 5641 5642 5643 5644 5645 5646 5647 5648 5649 5650 5651 5652 5653 5654 5655 5656 5657 5658 5659 5660 5661 5662 5663 5664 5665 5666 5667 5668 5669 5670 5671 5672 5673 5674 5675 5676 5677 5678 5679 5680 5681 5682 5683 5684 5685 5686 5687 5688 5689 5690 5691 5692 5693 5694 5695 5696 5697 5698 5699 5700 5701 5702 5703 5704 5705 5706 5707 5708 5709 5710 5711 5712 5713 5714 5715 5716 5717 5718 5719 5720 5721 5722 5723 5724 5725 5726 5727 5728 5729 5730 5731 5732 5733 5734 5735 5736 5737 5738 5739 5740 5741 5742 5743 5744 5745 5746 5747 5748 5749 5750 5751 5752 5753 5754 5755 5756 5757 5758 5759 5760 5761 5762 5763 5764 5765 5766 5767 5768 5769 5770 5771 5772 5773 5774 5775 5776 5777 5778 5779 5780 5781 5782 5783 5784 5785 5786 5787 5788 5789 5790 5791 5792 5793 5794 5795 5796 5797 5798 5799 5800 5801 5802 5803 5804 5805 5806 5807 5808 5809 5810 5811 5812 5813 5814 5815 5816 5817 5818 5819 5820 5821 5822 5823 5824 5825 5826 5827 5828 5829 5830 5831 5832 5833 5834 5835 5836 5837 5838 5839 5840 5841 5842 5843 5844 5845 5846 5847 5848 5849 5850 5851 5852 5853 5854 5855 5856 5857 5858 5859 5860 5861 5862 5863 5864 5865 5866 5867 5868 5869 5870 5871 5872 5873 5874 5875 5876 5877 5878 5879 5880 5881 5882 5883 5884 5885 5886 5887 5888 5889 5890 5891 5892 5893 5894 5895 5896 5897 5898 5899 5900 5901 5902 5903 5904 5905 5906 5907 5908 5909 5910 5911 5912 5913 5914 5915 5916 5917 5918 5919 5920 5921 5922 5923 5924 5925 5926 5927 5928 5929 5930 5931 5932 5933 5934 5935 5936 5937 5938 5939 5940 5941 5942 5943 5944 5945 5946 5947 5948 5949 5950 5951 5952 5953 5954 5955 5956 5957 5958 5959 5960 5961 5962 5963 5964 5965 5966 5967 5968 5969 5970 5971 5972 5973 5974 5975 5976 5977 5978 5979 5980 5981 5982 5983 5984 5985 5986 5987 5988 5989 5990 5991 5992 5993 5994 5995 5996 5997 5998 5999 6000 6001 6002 6003 6004 6005 6006 6007 6008 6009 6010 6011 6012 6013 6014 6015 6016 6017 6018 6019 6020 6021 6022 6023 6024 6025 6026 6027 6028 6029 6030 6031 6032 6033 6034 6035 6036 6037 6038 6039 6040 6041 6042 6043 6044 6045 6046 6047 6048 6049 6050 6051 6052 6053 6054 6055 6056 6057 6058 6059 6060 6061 6062 6063 6064 6065 6066 6067 6068 6069 6070 6071 6072 6073 6074 6075 6076 6077 6078 6079 6080 6081 6082 6083 6084 6085 6086 6087 6088 6089 6090 6091 6092 6093 6094 6095 6096 6097 6098 6099 6100 6101 6102 6103 6104 6105 6106 6107 6108 6109 6110 6111 6112 6113 6114 6115 6116 6117 6118 6119 6120 6121 6122 6123 6124 6125 6126 6127 6128 6129 6130 6131 6132 6133 6134 6135 6136 6137 6138 6139 6140 6141 6142 6143 6144 6145 6146 6147 6148 6149 6150 6151 6152 6153 6154 6155 6156 6157 6158 6159 6160 6161 6162 6163 6164 6165 6166 6167 6168 6169 6170 6171 6172 6173 6174 6175 6176 6177 6178 6179 6180 6181 6182 6183 6184 6185 6186 6187 6188 6189 6190 6191 6192 6193 6194 6195 6196 6197 6198 6199 6200 6201 6202 6203 6204 6205 6206 6207 6208 6209 6210 6211 6212 6213 6214 6215 6216 6217 6218 6219 6220 6221 6222 6223 6224 6225 6226 6227 6228 6229 6230 6231 6232 6233 6234 6235 6236 6237 6238 6239 6240 6241 6242 6243 6244 6245 6246 6247 6248 6249 6250 6251 6252 6253 6254 6255 6256 6257 6258 6259 6260 6261 6262 6263 6264 6265 6266 6267 6268 6269 6270 6271 6272 6273 6274 6275 6276 6277 6278 6279 6280 6281 6282 6283 6284 6285 6286 6287 6288 6289 6290 6291 6292 6293 6294 6295 6296 6297 6298 6299 6300 6301 6302 6303 6304 6305 6306 6307 6308 6309 6310 6311 6312 6313 6314 6315 6316 6317 6318 6319 6320 6321 6322 6323 6324 6325 6326 6327 6328 6329 6330 6331 6332 6333 6334 6335 6336 6337 6338 6339 6340 6341 6342 6343 6344 6345 6346 6347 6348 6349 6350 6351 6352 6353 6354 6355 6356 6357 6358 6359 6360 6361 6362 6363 6364 6365 6366 6367 6368
|
/*
==============================================================================
This file is part of the JUCE framework.
Copyright (c) Raw Material Software Limited
JUCE is an open source framework subject to commercial or open source
licensing.
By downloading, installing, or using the JUCE framework, or combining the
JUCE framework with any other source code, object code, content or any other
copyrightable work, you agree to the terms of the JUCE End User Licence
Agreement, and all incorporated terms including the JUCE Privacy Policy and
the JUCE Website Terms of Service, as applicable, which will bind you. If you
do not agree to the terms of these agreements, we will not license the JUCE
framework to you, and you must discontinue the installation or download
process and cease use of the JUCE framework.
JUCE End User Licence Agreement: https://juce.com/legal/juce-8-licence/
JUCE Privacy Policy: https://juce.com/juce-privacy-policy
JUCE Website Terms of Service: https://juce.com/juce-website-terms-of-service/
Or:
You may also use this code under the terms of the AGPLv3:
https://www.gnu.org/licenses/agpl-3.0.en.html
THE JUCE FRAMEWORK IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL
WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING WARRANTY OF
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, ARE DISCLAIMED.
==============================================================================
*/
#if JUCE_MODULE_AVAILABLE_juce_audio_plugin_client
#include <juce_audio_plugin_client/AAX/juce_AAX_Modifier_Injector.h>
#endif
namespace juce
{
JUCE_BEGIN_IGNORE_WARNINGS_GCC_LIKE ("-Wcast-function-type")
#undef GetSystemMetrics // multimon overrides this for some reason and causes a mess..
// these are in the windows SDK, but need to be repeated here for GCC..
#ifndef GET_APPCOMMAND_LPARAM
#define GET_APPCOMMAND_LPARAM(lParam) ((short) (HIWORD (lParam) & ~FAPPCOMMAND_MASK))
#define FAPPCOMMAND_MASK 0xF000
#define APPCOMMAND_MEDIA_NEXTTRACK 11
#define APPCOMMAND_MEDIA_PREVIOUSTRACK 12
#define APPCOMMAND_MEDIA_STOP 13
#define APPCOMMAND_MEDIA_PLAY_PAUSE 14
#endif
#ifndef WM_APPCOMMAND
#define WM_APPCOMMAND 0x0319
#endif
void juce_repeatLastProcessPriority();
using CheckEventBlockedByModalComps = bool (*) (const MSG&);
extern CheckEventBlockedByModalComps isEventBlockedByModalComps;
static bool shouldDeactivateTitleBar = true;
void* getUser32Function (const char*);
#if JUCE_DEBUG
int numActiveScopedDpiAwarenessDisablers = 0;
extern HWND juce_messageWindowHandle;
#endif
struct ScopedDeviceContext
{
explicit ScopedDeviceContext (HWND h)
: hwnd (h), dc (GetDC (hwnd))
{
}
~ScopedDeviceContext()
{
ReleaseDC (hwnd, dc);
}
HWND hwnd;
HDC dc;
JUCE_DECLARE_NON_COPYABLE (ScopedDeviceContext)
JUCE_DECLARE_NON_MOVEABLE (ScopedDeviceContext)
};
//==============================================================================
#ifndef WM_TOUCH
enum
{
WM_TOUCH = 0x0240,
TOUCHEVENTF_MOVE = 0x0001,
TOUCHEVENTF_DOWN = 0x0002,
TOUCHEVENTF_UP = 0x0004
};
typedef HANDLE HTOUCHINPUT;
typedef HANDLE HGESTUREINFO;
struct TOUCHINPUT
{
LONG x;
LONG y;
HANDLE hSource;
DWORD dwID;
DWORD dwFlags;
DWORD dwMask;
DWORD dwTime;
ULONG_PTR dwExtraInfo;
DWORD cxContact;
DWORD cyContact;
};
struct GESTUREINFO
{
UINT cbSize;
DWORD dwFlags;
DWORD dwID;
HWND hwndTarget;
POINTS ptsLocation;
DWORD dwInstanceID;
DWORD dwSequenceID;
ULONGLONG ullArguments;
UINT cbExtraArgs;
};
#endif
#ifndef WM_NCPOINTERUPDATE
enum
{
WM_NCPOINTERUPDATE = 0x241,
WM_NCPOINTERDOWN = 0x242,
WM_NCPOINTERUP = 0x243,
WM_POINTERUPDATE = 0x245,
WM_POINTERDOWN = 0x246,
WM_POINTERUP = 0x247,
WM_POINTERENTER = 0x249,
WM_POINTERLEAVE = 0x24A,
WM_POINTERACTIVATE = 0x24B,
WM_POINTERCAPTURECHANGED = 0x24C,
WM_TOUCHHITTESTING = 0x24D,
WM_POINTERWHEEL = 0x24E,
WM_POINTERHWHEEL = 0x24F,
WM_POINTERHITTEST = 0x250
};
enum
{
PT_TOUCH = 0x00000002,
PT_PEN = 0x00000003
};
enum POINTER_BUTTON_CHANGE_TYPE
{
POINTER_CHANGE_NONE,
POINTER_CHANGE_FIRSTBUTTON_DOWN,
POINTER_CHANGE_FIRSTBUTTON_UP,
POINTER_CHANGE_SECONDBUTTON_DOWN,
POINTER_CHANGE_SECONDBUTTON_UP,
POINTER_CHANGE_THIRDBUTTON_DOWN,
POINTER_CHANGE_THIRDBUTTON_UP,
POINTER_CHANGE_FOURTHBUTTON_DOWN,
POINTER_CHANGE_FOURTHBUTTON_UP,
POINTER_CHANGE_FIFTHBUTTON_DOWN,
POINTER_CHANGE_FIFTHBUTTON_UP
};
enum
{
PEN_MASK_NONE = 0x00000000,
PEN_MASK_PRESSURE = 0x00000001,
PEN_MASK_ROTATION = 0x00000002,
PEN_MASK_TILT_X = 0x00000004,
PEN_MASK_TILT_Y = 0x00000008
};
enum
{
TOUCH_MASK_NONE = 0x00000000,
TOUCH_MASK_CONTACTAREA = 0x00000001,
TOUCH_MASK_ORIENTATION = 0x00000002,
TOUCH_MASK_PRESSURE = 0x00000004
};
enum
{
POINTER_FLAG_NONE = 0x00000000,
POINTER_FLAG_NEW = 0x00000001,
POINTER_FLAG_INRANGE = 0x00000002,
POINTER_FLAG_INCONTACT = 0x00000004,
POINTER_FLAG_FIRSTBUTTON = 0x00000010,
POINTER_FLAG_SECONDBUTTON = 0x00000020,
POINTER_FLAG_THIRDBUTTON = 0x00000040,
POINTER_FLAG_FOURTHBUTTON = 0x00000080,
POINTER_FLAG_FIFTHBUTTON = 0x00000100,
POINTER_FLAG_PRIMARY = 0x00002000,
POINTER_FLAG_CONFIDENCE = 0x00004000,
POINTER_FLAG_CANCELED = 0x00008000,
POINTER_FLAG_DOWN = 0x00010000,
POINTER_FLAG_UPDATE = 0x00020000,
POINTER_FLAG_UP = 0x00040000,
POINTER_FLAG_WHEEL = 0x00080000,
POINTER_FLAG_HWHEEL = 0x00100000,
POINTER_FLAG_CAPTURECHANGED = 0x00200000,
POINTER_FLAG_HASTRANSFORM = 0x00400000
};
typedef DWORD POINTER_INPUT_TYPE;
typedef UINT32 POINTER_FLAGS;
typedef UINT32 PEN_FLAGS;
typedef UINT32 PEN_MASK;
typedef UINT32 TOUCH_FLAGS;
typedef UINT32 TOUCH_MASK;
struct POINTER_INFO
{
POINTER_INPUT_TYPE pointerType;
UINT32 pointerId;
UINT32 frameId;
POINTER_FLAGS pointerFlags;
HANDLE sourceDevice;
HWND hwndTarget;
POINT ptPixelLocation;
POINT ptHimetricLocation;
POINT ptPixelLocationRaw;
POINT ptHimetricLocationRaw;
DWORD dwTime;
UINT32 historyCount;
INT32 InputData;
DWORD dwKeyStates;
UINT64 PerformanceCount;
POINTER_BUTTON_CHANGE_TYPE ButtonChangeType;
};
struct POINTER_TOUCH_INFO
{
POINTER_INFO pointerInfo;
TOUCH_FLAGS touchFlags;
TOUCH_MASK touchMask;
RECT rcContact;
RECT rcContactRaw;
UINT32 orientation;
UINT32 pressure;
};
struct POINTER_PEN_INFO
{
POINTER_INFO pointerInfo;
PEN_FLAGS penFlags;
PEN_MASK penMask;
UINT32 pressure;
UINT32 rotation;
INT32 tiltX;
INT32 tiltY;
};
#define GET_POINTERID_WPARAM(wParam) (LOWORD(wParam))
#endif
#ifndef MONITOR_DPI_TYPE
enum Monitor_DPI_Type
{
MDT_Effective_DPI = 0,
MDT_Angular_DPI = 1,
MDT_Raw_DPI = 2,
MDT_Default = MDT_Effective_DPI
};
#endif
#ifndef DPI_AWARENESS
enum DPI_Awareness
{
DPI_Awareness_Invalid = -1,
DPI_Awareness_Unaware = 0,
DPI_Awareness_System_Aware = 1,
DPI_Awareness_Per_Monitor_Aware = 2
};
#endif
#ifndef USER_DEFAULT_SCREEN_DPI
#define USER_DEFAULT_SCREEN_DPI 96
#endif
#ifndef _DPI_AWARENESS_CONTEXTS_
typedef HANDLE DPI_AWARENESS_CONTEXT;
#define DPI_AWARENESS_CONTEXT_UNAWARE ((DPI_AWARENESS_CONTEXT) - 1)
#define DPI_AWARENESS_CONTEXT_SYSTEM_AWARE ((DPI_AWARENESS_CONTEXT) - 2)
#define DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE ((DPI_AWARENESS_CONTEXT) - 3)
#define DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2 ((DPI_AWARENESS_CONTEXT) - 4)
#endif
// Some versions of the Windows 10 SDK define _DPI_AWARENESS_CONTEXTS_ but not
// DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2
#ifndef DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2
#define DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2 ((DPI_AWARENESS_CONTEXT) - 4)
#endif
//==============================================================================
using RegisterTouchWindowFunc = BOOL (WINAPI*) (HWND, ULONG);
using GetTouchInputInfoFunc = BOOL (WINAPI*) (HTOUCHINPUT, UINT, TOUCHINPUT*, int);
using CloseTouchInputHandleFunc = BOOL (WINAPI*) (HTOUCHINPUT);
using GetGestureInfoFunc = BOOL (WINAPI*) (HGESTUREINFO, GESTUREINFO*);
static RegisterTouchWindowFunc registerTouchWindow = nullptr;
static GetTouchInputInfoFunc getTouchInputInfo = nullptr;
static CloseTouchInputHandleFunc closeTouchInputHandle = nullptr;
static GetGestureInfoFunc getGestureInfo = nullptr;
static bool hasCheckedForMultiTouch = false;
static bool canUseMultiTouch()
{
if (registerTouchWindow == nullptr && ! hasCheckedForMultiTouch)
{
hasCheckedForMultiTouch = true;
registerTouchWindow = (RegisterTouchWindowFunc) getUser32Function ("RegisterTouchWindow");
getTouchInputInfo = (GetTouchInputInfoFunc) getUser32Function ("GetTouchInputInfo");
closeTouchInputHandle = (CloseTouchInputHandleFunc) getUser32Function ("CloseTouchInputHandle");
getGestureInfo = (GetGestureInfoFunc) getUser32Function ("GetGestureInfo");
}
return registerTouchWindow != nullptr;
}
//==============================================================================
using GetPointerTypeFunc = BOOL (WINAPI*) (UINT32, POINTER_INPUT_TYPE*);
using GetPointerTouchInfoFunc = BOOL (WINAPI*) (UINT32, POINTER_TOUCH_INFO*);
using GetPointerPenInfoFunc = BOOL (WINAPI*) (UINT32, POINTER_PEN_INFO*);
static GetPointerTypeFunc getPointerTypeFunction = nullptr;
static GetPointerTouchInfoFunc getPointerTouchInfo = nullptr;
static GetPointerPenInfoFunc getPointerPenInfo = nullptr;
static bool canUsePointerAPI = false;
static void checkForPointerAPI()
{
getPointerTypeFunction = (GetPointerTypeFunc) getUser32Function ("GetPointerType");
getPointerTouchInfo = (GetPointerTouchInfoFunc) getUser32Function ("GetPointerTouchInfo");
getPointerPenInfo = (GetPointerPenInfoFunc) getUser32Function ("GetPointerPenInfo");
canUsePointerAPI = (getPointerTypeFunction != nullptr
&& getPointerTouchInfo != nullptr
&& getPointerPenInfo != nullptr);
}
//==============================================================================
using SetProcessDPIAwareFunc = BOOL (WINAPI*) ();
using SetProcessDPIAwarenessContextFunc = BOOL (WINAPI*) (DPI_AWARENESS_CONTEXT);
using SetProcessDPIAwarenessFunc = HRESULT (WINAPI*) (DPI_Awareness);
using SetThreadDPIAwarenessContextFunc = DPI_AWARENESS_CONTEXT (WINAPI*) (DPI_AWARENESS_CONTEXT);
using GetDPIForWindowFunc = UINT (WINAPI*) (HWND);
using GetDPIForMonitorFunc = HRESULT (WINAPI*) (HMONITOR, Monitor_DPI_Type, UINT*, UINT*);
using GetSystemMetricsForDpiFunc = int (WINAPI*) (int, UINT);
using GetProcessDPIAwarenessFunc = HRESULT (WINAPI*) (HANDLE, DPI_Awareness*);
using GetWindowDPIAwarenessContextFunc = DPI_AWARENESS_CONTEXT (WINAPI*) (HWND);
using GetThreadDPIAwarenessContextFunc = DPI_AWARENESS_CONTEXT (WINAPI*) ();
using GetAwarenessFromDpiAwarenessContextFunc = DPI_Awareness (WINAPI*) (DPI_AWARENESS_CONTEXT);
using EnableNonClientDPIScalingFunc = BOOL (WINAPI*) (HWND);
static SetProcessDPIAwareFunc setProcessDPIAware = nullptr;
static SetProcessDPIAwarenessContextFunc setProcessDPIAwarenessContext = nullptr;
static SetProcessDPIAwarenessFunc setProcessDPIAwareness = nullptr;
static SetThreadDPIAwarenessContextFunc setThreadDPIAwarenessContext = nullptr;
static GetDPIForMonitorFunc getDPIForMonitor = nullptr;
static GetDPIForWindowFunc getDPIForWindow = nullptr;
static GetProcessDPIAwarenessFunc getProcessDPIAwareness = nullptr;
static GetWindowDPIAwarenessContextFunc getWindowDPIAwarenessContext = nullptr;
static GetThreadDPIAwarenessContextFunc getThreadDPIAwarenessContext = nullptr;
static GetAwarenessFromDpiAwarenessContextFunc getAwarenessFromDPIAwarenessContext = nullptr;
static EnableNonClientDPIScalingFunc enableNonClientDPIScaling = nullptr;
static bool hasCheckedForDPIAwareness = false;
static void loadDPIAwarenessFunctions()
{
setProcessDPIAware = (SetProcessDPIAwareFunc) getUser32Function ("SetProcessDPIAware");
constexpr auto shcore = "SHCore.dll";
LoadLibraryA (shcore);
const auto shcoreModule = GetModuleHandleA (shcore);
if (shcoreModule == nullptr)
return;
getDPIForMonitor = (GetDPIForMonitorFunc) GetProcAddress (shcoreModule, "GetDpiForMonitor");
setProcessDPIAwareness = (SetProcessDPIAwarenessFunc) GetProcAddress (shcoreModule, "SetProcessDpiAwareness");
#if JUCE_WIN_PER_MONITOR_DPI_AWARE
getDPIForWindow = (GetDPIForWindowFunc) getUser32Function ("GetDpiForWindow");
getProcessDPIAwareness = (GetProcessDPIAwarenessFunc) GetProcAddress (shcoreModule, "GetProcessDpiAwareness");
getWindowDPIAwarenessContext = (GetWindowDPIAwarenessContextFunc) getUser32Function ("GetWindowDpiAwarenessContext");
setThreadDPIAwarenessContext = (SetThreadDPIAwarenessContextFunc) getUser32Function ("SetThreadDpiAwarenessContext");
getThreadDPIAwarenessContext = (GetThreadDPIAwarenessContextFunc) getUser32Function ("GetThreadDpiAwarenessContext");
getAwarenessFromDPIAwarenessContext = (GetAwarenessFromDpiAwarenessContextFunc) getUser32Function ("GetAwarenessFromDpiAwarenessContext");
setProcessDPIAwarenessContext = (SetProcessDPIAwarenessContextFunc) getUser32Function ("SetProcessDpiAwarenessContext");
enableNonClientDPIScaling = (EnableNonClientDPIScalingFunc) getUser32Function ("EnableNonClientDpiScaling");
#endif
}
static void setDPIAwareness()
{
if (hasCheckedForDPIAwareness)
return;
hasCheckedForDPIAwareness = true;
if (! JUCEApplicationBase::isStandaloneApp())
return;
loadDPIAwarenessFunctions();
if (setProcessDPIAwarenessContext != nullptr
&& setProcessDPIAwarenessContext (DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2))
return;
if (setProcessDPIAwareness != nullptr && enableNonClientDPIScaling != nullptr
&& SUCCEEDED (setProcessDPIAwareness (DPI_Awareness::DPI_Awareness_Per_Monitor_Aware)))
return;
if (setProcessDPIAwareness != nullptr && getDPIForMonitor != nullptr
&& SUCCEEDED (setProcessDPIAwareness (DPI_Awareness::DPI_Awareness_System_Aware)))
return;
NullCheckedInvocation::invoke (setProcessDPIAware);
}
static bool isPerMonitorDPIAwareProcess()
{
#if ! JUCE_WIN_PER_MONITOR_DPI_AWARE
return false;
#else
static bool dpiAware = []() -> bool
{
setDPIAwareness();
if (! JUCEApplication::isStandaloneApp())
return false;
if (getProcessDPIAwareness == nullptr)
return false;
DPI_Awareness context;
getProcessDPIAwareness (nullptr, &context);
return context == DPI_Awareness::DPI_Awareness_Per_Monitor_Aware;
}();
return dpiAware;
#endif
}
static bool isPerMonitorDPIAwareWindow ([[maybe_unused]] HWND nativeWindow)
{
#if ! JUCE_WIN_PER_MONITOR_DPI_AWARE
return false;
#else
setDPIAwareness();
if (getWindowDPIAwarenessContext != nullptr
&& getAwarenessFromDPIAwarenessContext != nullptr)
{
return (getAwarenessFromDPIAwarenessContext (getWindowDPIAwarenessContext (nativeWindow))
== DPI_Awareness::DPI_Awareness_Per_Monitor_Aware);
}
return isPerMonitorDPIAwareProcess();
#endif
}
static bool isPerMonitorDPIAwareThread (GetThreadDPIAwarenessContextFunc getThreadDPIAwarenessContextIn = getThreadDPIAwarenessContext,
GetAwarenessFromDpiAwarenessContextFunc getAwarenessFromDPIAwarenessContextIn = getAwarenessFromDPIAwarenessContext)
{
#if ! JUCE_WIN_PER_MONITOR_DPI_AWARE
return false;
#else
setDPIAwareness();
if (getThreadDPIAwarenessContextIn != nullptr
&& getAwarenessFromDPIAwarenessContextIn != nullptr)
{
return (getAwarenessFromDPIAwarenessContextIn (getThreadDPIAwarenessContextIn())
== DPI_Awareness::DPI_Awareness_Per_Monitor_Aware);
}
return isPerMonitorDPIAwareProcess();
#endif
}
static double getGlobalDPI()
{
setDPIAwareness();
ScopedDeviceContext deviceContext { nullptr };
return (GetDeviceCaps (deviceContext.dc, LOGPIXELSX) + GetDeviceCaps (deviceContext.dc, LOGPIXELSY)) / 2.0;
}
//==============================================================================
class ScopedSuspendResumeNotificationRegistration
{
static auto& getFunctions()
{
struct Functions
{
using Register = HPOWERNOTIFY (WINAPI*) (HANDLE, DWORD);
using Unregister = BOOL (WINAPI*) (HPOWERNOTIFY);
Register registerNotification = (Register) getUser32Function ("RegisterSuspendResumeNotification");
Unregister unregisterNotification = (Unregister) getUser32Function ("UnregisterSuspendResumeNotification");
bool isValid() const { return registerNotification != nullptr && unregisterNotification != nullptr; }
Functions() = default;
JUCE_DECLARE_NON_COPYABLE (Functions)
JUCE_DECLARE_NON_MOVEABLE (Functions)
};
static const Functions functions;
return functions;
}
public:
ScopedSuspendResumeNotificationRegistration() = default;
explicit ScopedSuspendResumeNotificationRegistration (HWND window)
: handle (getFunctions().isValid()
? getFunctions().registerNotification (window, DEVICE_NOTIFY_WINDOW_HANDLE)
: nullptr)
{}
private:
struct Destructor
{
void operator() (HPOWERNOTIFY ptr) const
{
if (ptr != nullptr)
getFunctions().unregisterNotification (ptr);
}
};
std::unique_ptr<std::remove_pointer_t<HPOWERNOTIFY>, Destructor> handle;
};
//==============================================================================
class ScopedThreadDPIAwarenessSetter::NativeImpl
{
public:
static auto& getFunctions()
{
struct Functions
{
SetThreadDPIAwarenessContextFunc setThreadAwareness = (SetThreadDPIAwarenessContextFunc) getUser32Function ("SetThreadDpiAwarenessContext");
GetWindowDPIAwarenessContextFunc getWindowAwareness = (GetWindowDPIAwarenessContextFunc) getUser32Function ("GetWindowDpiAwarenessContext");
GetThreadDPIAwarenessContextFunc getThreadAwareness = (GetThreadDPIAwarenessContextFunc) getUser32Function ("GetThreadDpiAwarenessContext");
GetAwarenessFromDpiAwarenessContextFunc getAwarenessFromContext = (GetAwarenessFromDpiAwarenessContextFunc) getUser32Function ("GetAwarenessFromDpiAwarenessContext");
bool isLoaded() const noexcept
{
return setThreadAwareness != nullptr
&& getWindowAwareness != nullptr
&& getThreadAwareness != nullptr
&& getAwarenessFromContext != nullptr;
}
Functions() = default;
JUCE_DECLARE_NON_COPYABLE (Functions)
JUCE_DECLARE_NON_MOVEABLE (Functions)
};
static const Functions functions;
return functions;
}
explicit NativeImpl (HWND nativeWindow [[maybe_unused]])
{
#if JUCE_WIN_PER_MONITOR_DPI_AWARE
if (const auto& functions = getFunctions(); functions.isLoaded())
{
auto dpiAwareWindow = (functions.getAwarenessFromContext (functions.getWindowAwareness (nativeWindow))
== DPI_Awareness::DPI_Awareness_Per_Monitor_Aware);
auto dpiAwareThread = (functions.getAwarenessFromContext (functions.getThreadAwareness())
== DPI_Awareness::DPI_Awareness_Per_Monitor_Aware);
if (dpiAwareWindow && ! dpiAwareThread)
oldContext = functions.setThreadAwareness (DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE);
else if (! dpiAwareWindow && dpiAwareThread)
oldContext = functions.setThreadAwareness (DPI_AWARENESS_CONTEXT_UNAWARE);
}
#endif
}
~NativeImpl()
{
if (oldContext != nullptr)
getFunctions().setThreadAwareness (oldContext);
}
private:
DPI_AWARENESS_CONTEXT oldContext = nullptr;
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (NativeImpl)
JUCE_DECLARE_NON_MOVEABLE (NativeImpl)
};
ScopedThreadDPIAwarenessSetter::ScopedThreadDPIAwarenessSetter (void* nativeWindow)
{
pimpl = std::make_unique<NativeImpl> ((HWND) nativeWindow);
}
ScopedThreadDPIAwarenessSetter::~ScopedThreadDPIAwarenessSetter() = default;
ScopedThreadDPIAwarenessSetter::ScopedThreadDPIAwarenessSetter (ScopedThreadDPIAwarenessSetter&&) noexcept = default;
ScopedThreadDPIAwarenessSetter& ScopedThreadDPIAwarenessSetter::operator= (ScopedThreadDPIAwarenessSetter&&) noexcept = default;
static auto& getScopedDPIAwarenessDisablerFunctions()
{
struct Functions
{
GetThreadDPIAwarenessContextFunc localGetThreadDpiAwarenessContext = (GetThreadDPIAwarenessContextFunc) getUser32Function ("GetThreadDpiAwarenessContext");
GetAwarenessFromDpiAwarenessContextFunc localGetAwarenessFromDpiAwarenessContextFunc = (GetAwarenessFromDpiAwarenessContextFunc) getUser32Function ("GetAwarenessFromDpiAwarenessContext");
SetThreadDPIAwarenessContextFunc localSetThreadDPIAwarenessContext = (SetThreadDPIAwarenessContextFunc) getUser32Function ("SetThreadDpiAwarenessContext");
Functions() = default;
JUCE_DECLARE_NON_COPYABLE (Functions)
JUCE_DECLARE_NON_MOVEABLE (Functions)
};
static const Functions functions;
return functions;
}
ScopedDPIAwarenessDisabler::ScopedDPIAwarenessDisabler()
{
const auto& functions = getScopedDPIAwarenessDisablerFunctions();
if (! isPerMonitorDPIAwareThread (functions.localGetThreadDpiAwarenessContext, functions.localGetAwarenessFromDpiAwarenessContextFunc))
return;
if (auto* localSetThreadDPIAwarenessContext = functions.localSetThreadDPIAwarenessContext)
{
previousContext = localSetThreadDPIAwarenessContext (DPI_AWARENESS_CONTEXT_UNAWARE);
#if JUCE_DEBUG
++numActiveScopedDpiAwarenessDisablers;
#endif
}
}
ScopedDPIAwarenessDisabler::~ScopedDPIAwarenessDisabler()
{
if (previousContext != nullptr)
{
if (auto* localSetThreadDPIAwarenessContext = getScopedDPIAwarenessDisablerFunctions().localSetThreadDPIAwarenessContext)
localSetThreadDPIAwarenessContext ((DPI_AWARENESS_CONTEXT) previousContext);
#if JUCE_DEBUG
--numActiveScopedDpiAwarenessDisablers;
#endif
}
}
//==============================================================================
using SettingChangeCallbackFunc = void (*)(void);
extern SettingChangeCallbackFunc settingChangeCallback;
//==============================================================================
static const Displays::Display* getCurrentDisplayFromScaleFactor (HWND hwnd);
template <typename ValueType>
static Rectangle<ValueType> convertPhysicalScreenRectangleToLogical (Rectangle<ValueType> r, HWND h) noexcept
{
if (isPerMonitorDPIAwareWindow (h))
return Desktop::getInstance().getDisplays().physicalToLogical (r, getCurrentDisplayFromScaleFactor (h));
return r;
}
template <typename ValueType>
static Rectangle<ValueType> convertLogicalScreenRectangleToPhysical (Rectangle<ValueType> r, HWND h) noexcept
{
if (isPerMonitorDPIAwareWindow (h))
return Desktop::getInstance().getDisplays().logicalToPhysical (r, getCurrentDisplayFromScaleFactor (h));
return r;
}
static Point<int> convertPhysicalScreenPointToLogical (Point<int> p, HWND h) noexcept
{
if (isPerMonitorDPIAwareWindow (h))
return Desktop::getInstance().getDisplays().physicalToLogical (p, getCurrentDisplayFromScaleFactor (h));
return p;
}
static Point<int> convertLogicalScreenPointToPhysical (Point<int> p, HWND h) noexcept
{
if (isPerMonitorDPIAwareWindow (h))
return Desktop::getInstance().getDisplays().logicalToPhysical (p, getCurrentDisplayFromScaleFactor (h));
return p;
}
JUCE_API double getScaleFactorForWindow (HWND h);
JUCE_API double getScaleFactorForWindow (HWND h)
{
// NB. Using a local function here because we need to call this method from the plug-in wrappers
// which don't load the DPI-awareness functions on startup
static auto localGetDPIForWindow = (GetDPIForWindowFunc) getUser32Function ("GetDpiForWindow");
if (localGetDPIForWindow != nullptr)
return (double) localGetDPIForWindow (h) / USER_DEFAULT_SCREEN_DPI;
return 1.0;
}
static RECT getWindowScreenRect (HWND hwnd)
{
ScopedThreadDPIAwarenessSetter setter { hwnd };
RECT rect;
GetWindowRect (hwnd, &rect);
return rect;
}
static RECT getWindowClientRect (HWND hwnd)
{
auto rect = getWindowScreenRect (hwnd);
if (auto parentH = GetParent (hwnd))
{
ScopedThreadDPIAwarenessSetter setter { hwnd };
MapWindowPoints (HWND_DESKTOP, parentH, (LPPOINT) &rect, 2);
}
return rect;
}
static void setWindowZOrder (HWND hwnd, HWND insertAfter)
{
SetWindowPos (hwnd, insertAfter, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE | SWP_NOSENDCHANGING);
}
//==============================================================================
RTL_OSVERSIONINFOW getWindowsVersionInfo();
double Desktop::getDefaultMasterScale()
{
if (! JUCEApplicationBase::isStandaloneApp() || isPerMonitorDPIAwareProcess())
return 1.0;
return getGlobalDPI() / USER_DEFAULT_SCREEN_DPI;
}
bool Desktop::canUseSemiTransparentWindows() noexcept
{
return true;
}
class Desktop::NativeDarkModeChangeDetectorImpl
{
public:
NativeDarkModeChangeDetectorImpl()
{
const auto winVer = getWindowsVersionInfo();
if (winVer.dwMajorVersion >= 10 && winVer.dwBuildNumber >= 17763)
{
const auto uxtheme = "uxtheme.dll";
LoadLibraryA (uxtheme);
const auto uxthemeModule = GetModuleHandleA (uxtheme);
if (uxthemeModule != nullptr)
{
shouldAppsUseDarkMode = (ShouldAppsUseDarkModeFunc) GetProcAddress (uxthemeModule, MAKEINTRESOURCEA (132));
if (shouldAppsUseDarkMode != nullptr)
darkModeEnabled = shouldAppsUseDarkMode() && ! isHighContrast();
}
}
}
~NativeDarkModeChangeDetectorImpl()
{
UnhookWindowsHookEx (hook);
}
bool isDarkModeEnabled() const noexcept { return darkModeEnabled; }
private:
static bool isHighContrast()
{
HIGHCONTRASTW highContrast {};
if (SystemParametersInfoW (SPI_GETHIGHCONTRAST, sizeof (highContrast), &highContrast, false))
return highContrast.dwFlags & HCF_HIGHCONTRASTON;
return false;
}
static LRESULT CALLBACK callWndProc (int nCode, WPARAM wParam, LPARAM lParam)
{
auto* params = reinterpret_cast<CWPSTRUCT*> (lParam);
if (nCode >= 0
&& params != nullptr
&& params->message == WM_SETTINGCHANGE
&& params->lParam != 0
&& CompareStringOrdinal (reinterpret_cast<LPWCH> (params->lParam), -1, L"ImmersiveColorSet", -1, true) == CSTR_EQUAL)
{
Desktop::getInstance().nativeDarkModeChangeDetectorImpl->colourSetChanged();
}
return CallNextHookEx ({}, nCode, wParam, lParam);
}
void colourSetChanged()
{
if (shouldAppsUseDarkMode != nullptr)
{
const auto wasDarkModeEnabled = std::exchange (darkModeEnabled, shouldAppsUseDarkMode() && ! isHighContrast());
if (darkModeEnabled != wasDarkModeEnabled)
Desktop::getInstance().darkModeChanged();
}
}
using ShouldAppsUseDarkModeFunc = bool (WINAPI*)();
ShouldAppsUseDarkModeFunc shouldAppsUseDarkMode = nullptr;
bool darkModeEnabled = false;
HHOOK hook { SetWindowsHookEx (WH_CALLWNDPROC,
callWndProc,
(HINSTANCE) juce::Process::getCurrentModuleInstanceHandle(),
GetCurrentThreadId()) };
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (NativeDarkModeChangeDetectorImpl)
};
std::unique_ptr<Desktop::NativeDarkModeChangeDetectorImpl> Desktop::createNativeDarkModeChangeDetectorImpl()
{
return std::make_unique<NativeDarkModeChangeDetectorImpl>();
}
bool Desktop::isDarkModeActive() const
{
return nativeDarkModeChangeDetectorImpl->isDarkModeEnabled();
}
Desktop::DisplayOrientation Desktop::getCurrentOrientation() const
{
return upright;
}
int64 getMouseEventTime();
int64 getMouseEventTime()
{
static int64 eventTimeOffset = 0;
static LONG lastMessageTime = 0;
const LONG thisMessageTime = GetMessageTime();
if (thisMessageTime < lastMessageTime || lastMessageTime == 0)
{
lastMessageTime = thisMessageTime;
eventTimeOffset = Time::currentTimeMillis() - thisMessageTime;
}
return eventTimeOffset + thisMessageTime;
}
//==============================================================================
const int extendedKeyModifier = 0x10000;
const int KeyPress::spaceKey = VK_SPACE;
const int KeyPress::returnKey = VK_RETURN;
const int KeyPress::escapeKey = VK_ESCAPE;
const int KeyPress::backspaceKey = VK_BACK;
const int KeyPress::deleteKey = VK_DELETE | extendedKeyModifier;
const int KeyPress::insertKey = VK_INSERT | extendedKeyModifier;
const int KeyPress::tabKey = VK_TAB;
const int KeyPress::leftKey = VK_LEFT | extendedKeyModifier;
const int KeyPress::rightKey = VK_RIGHT | extendedKeyModifier;
const int KeyPress::upKey = VK_UP | extendedKeyModifier;
const int KeyPress::downKey = VK_DOWN | extendedKeyModifier;
const int KeyPress::homeKey = VK_HOME | extendedKeyModifier;
const int KeyPress::endKey = VK_END | extendedKeyModifier;
const int KeyPress::pageUpKey = VK_PRIOR | extendedKeyModifier;
const int KeyPress::pageDownKey = VK_NEXT | extendedKeyModifier;
const int KeyPress::F1Key = VK_F1 | extendedKeyModifier;
const int KeyPress::F2Key = VK_F2 | extendedKeyModifier;
const int KeyPress::F3Key = VK_F3 | extendedKeyModifier;
const int KeyPress::F4Key = VK_F4 | extendedKeyModifier;
const int KeyPress::F5Key = VK_F5 | extendedKeyModifier;
const int KeyPress::F6Key = VK_F6 | extendedKeyModifier;
const int KeyPress::F7Key = VK_F7 | extendedKeyModifier;
const int KeyPress::F8Key = VK_F8 | extendedKeyModifier;
const int KeyPress::F9Key = VK_F9 | extendedKeyModifier;
const int KeyPress::F10Key = VK_F10 | extendedKeyModifier;
const int KeyPress::F11Key = VK_F11 | extendedKeyModifier;
const int KeyPress::F12Key = VK_F12 | extendedKeyModifier;
const int KeyPress::F13Key = VK_F13 | extendedKeyModifier;
const int KeyPress::F14Key = VK_F14 | extendedKeyModifier;
const int KeyPress::F15Key = VK_F15 | extendedKeyModifier;
const int KeyPress::F16Key = VK_F16 | extendedKeyModifier;
const int KeyPress::F17Key = VK_F17 | extendedKeyModifier;
const int KeyPress::F18Key = VK_F18 | extendedKeyModifier;
const int KeyPress::F19Key = VK_F19 | extendedKeyModifier;
const int KeyPress::F20Key = VK_F20 | extendedKeyModifier;
const int KeyPress::F21Key = VK_F21 | extendedKeyModifier;
const int KeyPress::F22Key = VK_F22 | extendedKeyModifier;
const int KeyPress::F23Key = VK_F23 | extendedKeyModifier;
const int KeyPress::F24Key = VK_F24 | extendedKeyModifier;
const int KeyPress::F25Key = 0x31000; // Windows doesn't support F-keys 25 or higher
const int KeyPress::F26Key = 0x31001;
const int KeyPress::F27Key = 0x31002;
const int KeyPress::F28Key = 0x31003;
const int KeyPress::F29Key = 0x31004;
const int KeyPress::F30Key = 0x31005;
const int KeyPress::F31Key = 0x31006;
const int KeyPress::F32Key = 0x31007;
const int KeyPress::F33Key = 0x31008;
const int KeyPress::F34Key = 0x31009;
const int KeyPress::F35Key = 0x3100a;
const int KeyPress::numberPad0 = VK_NUMPAD0 | extendedKeyModifier;
const int KeyPress::numberPad1 = VK_NUMPAD1 | extendedKeyModifier;
const int KeyPress::numberPad2 = VK_NUMPAD2 | extendedKeyModifier;
const int KeyPress::numberPad3 = VK_NUMPAD3 | extendedKeyModifier;
const int KeyPress::numberPad4 = VK_NUMPAD4 | extendedKeyModifier;
const int KeyPress::numberPad5 = VK_NUMPAD5 | extendedKeyModifier;
const int KeyPress::numberPad6 = VK_NUMPAD6 | extendedKeyModifier;
const int KeyPress::numberPad7 = VK_NUMPAD7 | extendedKeyModifier;
const int KeyPress::numberPad8 = VK_NUMPAD8 | extendedKeyModifier;
const int KeyPress::numberPad9 = VK_NUMPAD9 | extendedKeyModifier;
const int KeyPress::numberPadAdd = VK_ADD | extendedKeyModifier;
const int KeyPress::numberPadSubtract = VK_SUBTRACT | extendedKeyModifier;
const int KeyPress::numberPadMultiply = VK_MULTIPLY | extendedKeyModifier;
const int KeyPress::numberPadDivide = VK_DIVIDE | extendedKeyModifier;
const int KeyPress::numberPadSeparator = VK_SEPARATOR | extendedKeyModifier;
const int KeyPress::numberPadDecimalPoint = VK_DECIMAL | extendedKeyModifier;
const int KeyPress::numberPadEquals = 0x92 /*VK_OEM_NEC_EQUAL*/ | extendedKeyModifier;
const int KeyPress::numberPadDelete = VK_DELETE | extendedKeyModifier;
const int KeyPress::playKey = 0x30000;
const int KeyPress::stopKey = 0x30001;
const int KeyPress::fastForwardKey = 0x30002;
const int KeyPress::rewindKey = 0x30003;
//==============================================================================
class WindowsBitmapImage final : public ImagePixelData
{
public:
using Ptr = ReferenceCountedObjectPtr<WindowsBitmapImage>;
WindowsBitmapImage (const Image::PixelFormat format,
const int w, const int h, const bool clearImage)
: ImagePixelData (format, w, h)
{
jassert (format == Image::RGB || format == Image::ARGB);
static bool alwaysUse32Bits = isGraphicsCard32Bit(); // NB: for 32-bit cards, it's faster to use a 32-bit image.
pixelStride = (alwaysUse32Bits || format == Image::ARGB) ? 4 : 3;
lineStride = -((w * pixelStride + 3) & ~3);
zerostruct (bitmapInfo);
bitmapInfo.bV4Size = sizeof (BITMAPV4HEADER);
bitmapInfo.bV4Width = w;
bitmapInfo.bV4Height = h;
bitmapInfo.bV4Planes = 1;
bitmapInfo.bV4CSType = 1;
bitmapInfo.bV4BitCount = (unsigned short) (pixelStride * 8);
if (format == Image::ARGB)
{
bitmapInfo.bV4AlphaMask = 0xff000000;
bitmapInfo.bV4RedMask = 0xff0000;
bitmapInfo.bV4GreenMask = 0xff00;
bitmapInfo.bV4BlueMask = 0xff;
bitmapInfo.bV4V4Compression = BI_BITFIELDS;
}
else
{
bitmapInfo.bV4V4Compression = BI_RGB;
}
{
ScopedDeviceContext deviceContext { nullptr };
hdc = CreateCompatibleDC (deviceContext.dc);
}
SetMapMode (hdc, MM_TEXT);
hBitmap = CreateDIBSection (hdc, (BITMAPINFO*) &(bitmapInfo), DIB_RGB_COLORS,
(void**) &bitmapData, nullptr, 0);
if (hBitmap != nullptr)
previousBitmap = SelectObject (hdc, hBitmap);
if (format == Image::ARGB && clearImage)
zeromem (bitmapData, (size_t) std::abs (h * lineStride));
imageData = bitmapData - (lineStride * (h - 1));
}
~WindowsBitmapImage() override
{
SelectObject (hdc, previousBitmap); // Selecting the previous bitmap before deleting the DC avoids a warning in BoundsChecker
DeleteDC (hdc);
DeleteObject (hBitmap);
}
std::unique_ptr<ImageType> createType() const override
{
// This type only exists to return a type ID that's different to the SoftwareImageType's ID,
// so that `SoftwareImageType{}.convert (windowsBitmapImage)` works.
// If we return SoftwareImageType here, then SoftwareImageType{}.convert() will compare the
// type IDs and assume the source image is already of the correct type.
struct Type : public ImageType
{
int getTypeID() const override { return ByteOrder::makeInt ('w', 'b', 'i', 't'); }
ImagePixelData::Ptr create (Image::PixelFormat, int, int, bool) const override { return {}; }
Image convert (const Image&) const override { return {}; }
};
return std::make_unique<Type>();
}
std::unique_ptr<LowLevelGraphicsContext> createLowLevelContext() override
{
sendDataChangeMessage();
return std::make_unique<LowLevelGraphicsSoftwareRenderer> (Image (this));
}
void initialiseBitmapData (Image::BitmapData& bitmap, int x, int y, Image::BitmapData::ReadWriteMode mode) override
{
const auto offset = (size_t) (x * pixelStride + y * lineStride);
bitmap.data = imageData + offset;
bitmap.size = (size_t) (lineStride * height) - offset;
bitmap.pixelFormat = pixelFormat;
bitmap.lineStride = lineStride;
bitmap.pixelStride = pixelStride;
if (mode != Image::BitmapData::readOnly)
sendDataChangeMessage();
}
ImagePixelData::Ptr clone() override
{
Image newImage { SoftwareImageType{}.create (pixelFormat, width, height, pixelFormat != Image::RGB) };
{
Graphics g (newImage);
g.drawImageAt (Image { *this }, 0, 0);
}
return newImage.getPixelData();
}
static void updateLayeredWindow (HDC sourceHdc, HWND hwnd, Point<int> pt, float constantAlpha)
{
const auto windowBounds = getWindowScreenRect (hwnd);
auto p = D2DUtilities::toPOINT (pt);
POINT pos = { windowBounds.left, windowBounds.top };
SIZE size = { windowBounds.right - windowBounds.left,
windowBounds.bottom - windowBounds.top };
BLENDFUNCTION bf { AC_SRC_OVER, 0, (BYTE) (255.0f * constantAlpha), AC_SRC_ALPHA };
UpdateLayeredWindow (hwnd, nullptr, &pos, &size, sourceHdc, &p, 0, &bf, ULW_ALPHA);
}
void updateLayeredWindow (HWND hwnd, Point<int> pt, float constantAlpha) const noexcept
{
updateLayeredWindow (hdc, hwnd, pt, constantAlpha);
}
void blitToDC (HDC dc, int x, int y) const noexcept
{
SetMapMode (dc, MM_TEXT);
StretchDIBits (dc,
x, y, width, height,
0, 0, width, height,
bitmapData, (const BITMAPINFO*) &bitmapInfo,
DIB_RGB_COLORS, SRCCOPY);
}
HBITMAP getHBITMAP() const { return hBitmap; }
HDC getHDC() const { return hdc; }
private:
HBITMAP hBitmap;
HGDIOBJ previousBitmap;
BITMAPV4HEADER bitmapInfo;
HDC hdc;
uint8* bitmapData;
int pixelStride, lineStride;
uint8* imageData;
static bool isGraphicsCard32Bit()
{
ScopedDeviceContext deviceContext { nullptr };
return GetDeviceCaps (deviceContext.dc, BITSPIXEL) > 24;
}
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WindowsBitmapImage)
};
//==============================================================================
namespace IconConverters
{
struct IconDestructor
{
void operator() (HICON ptr) const { if (ptr != nullptr) DestroyIcon (ptr); }
};
using IconPtr = std::unique_ptr<std::remove_pointer_t<HICON>, IconDestructor>;
static Image createImageFromHICON (HICON icon)
{
if (icon == nullptr)
return {};
struct ScopedICONINFO final : public ICONINFO
{
ScopedICONINFO()
{
hbmColor = nullptr;
hbmMask = nullptr;
}
~ScopedICONINFO()
{
if (hbmColor != nullptr)
::DeleteObject (hbmColor);
if (hbmMask != nullptr)
::DeleteObject (hbmMask);
}
};
ScopedICONINFO info;
if (! ::GetIconInfo (icon, &info))
return {};
BITMAP bm;
if (! (::GetObject (info.hbmColor, sizeof (BITMAP), &bm)
&& bm.bmWidth > 0 && bm.bmHeight > 0))
return {};
ScopedDeviceContext deviceContext { nullptr };
if (auto* dc = ::CreateCompatibleDC (deviceContext.dc))
{
BITMAPV5HEADER header = {};
header.bV5Size = sizeof (BITMAPV5HEADER);
header.bV5Width = bm.bmWidth;
header.bV5Height = -bm.bmHeight;
header.bV5Planes = 1;
header.bV5Compression = BI_RGB;
header.bV5BitCount = 32;
header.bV5RedMask = 0x00FF0000;
header.bV5GreenMask = 0x0000FF00;
header.bV5BlueMask = 0x000000FF;
header.bV5AlphaMask = 0xFF000000;
header.bV5CSType = 0x57696E20; // 'Win '
header.bV5Intent = LCS_GM_IMAGES;
uint32* bitmapImageData = nullptr;
if (auto* dib = ::CreateDIBSection (deviceContext.dc, (BITMAPINFO*) &header, DIB_RGB_COLORS,
(void**) &bitmapImageData, nullptr, 0))
{
auto oldObject = ::SelectObject (dc, dib);
auto numPixels = bm.bmWidth * bm.bmHeight;
auto numColourComponents = (size_t) numPixels * 4;
// Windows icon data comes as two layers, an XOR mask which contains the bulk
// of the image data and an AND mask which provides the transparency. Annoyingly
// the XOR mask can also contain an alpha channel, in which case the transparency
// mask should not be applied, but there's no way to find out a priori if the XOR
// mask contains an alpha channel.
HeapBlock<bool> opacityMask (numPixels);
memset (bitmapImageData, 0, numColourComponents);
::DrawIconEx (dc, 0, 0, icon, bm.bmWidth, bm.bmHeight, 0, nullptr, DI_MASK);
for (int i = 0; i < numPixels; ++i)
opacityMask[i] = (bitmapImageData[i] == 0);
Image result = Image (Image::ARGB, bm.bmWidth, bm.bmHeight, true, SoftwareImageType{});
Image::BitmapData imageData (result, Image::BitmapData::readWrite);
memset (bitmapImageData, 0, numColourComponents);
::DrawIconEx (dc, 0, 0, icon, bm.bmWidth, bm.bmHeight, 0, nullptr, DI_NORMAL);
memcpy (imageData.data, bitmapImageData, numColourComponents);
auto imageHasAlphaChannel = [&imageData, numPixels]()
{
for (int i = 0; i < numPixels; ++i)
if (imageData.data[i * 4] != 0)
return true;
return false;
};
if (! imageHasAlphaChannel())
for (int i = 0; i < numPixels; ++i)
imageData.data[i * 4] = opacityMask[i] ? 0xff : 0x00;
::SelectObject (dc, oldObject);
::DeleteObject (dib);
::DeleteDC (dc);
return result;
}
::DeleteDC (dc);
}
return {};
}
HICON createHICONFromImage (const Image& image, const BOOL isIcon, int hotspotX, int hotspotY);
HICON createHICONFromImage (const Image& image, const BOOL isIcon, int hotspotX, int hotspotY)
{
auto nativeBitmap = new WindowsBitmapImage (Image::ARGB, image.getWidth(), image.getHeight(), true);
Image bitmap (nativeBitmap);
{
Graphics g (bitmap);
g.drawImageAt (image, 0, 0);
}
auto mask = CreateBitmap (image.getWidth(), image.getHeight(), 1, 1, nullptr);
ICONINFO info;
info.fIcon = isIcon;
info.xHotspot = (DWORD) hotspotX;
info.yHotspot = (DWORD) hotspotY;
info.hbmMask = mask;
info.hbmColor = nativeBitmap->getHBITMAP();
auto hi = CreateIconIndirect (&info);
DeleteObject (mask);
return hi;
}
} // namespace IconConverters
//==============================================================================
JUCE_IUNKNOWNCLASS (ITipInvocation, "37c994e7-432b-4834-a2f7-dce1f13b834b")
{
static CLSID getCLSID() noexcept { return { 0x4ce576fa, 0x83dc, 0x4f88, { 0x95, 0x1c, 0x9d, 0x07, 0x82, 0xb4, 0xe3, 0x76 } }; }
JUCE_COMCALL Toggle (HWND) = 0;
};
} // namespace juce
#ifdef __CRT_UUID_DECL
__CRT_UUID_DECL (juce::ITipInvocation, 0x37c994e7, 0x432b, 0x4834, 0xa2, 0xf7, 0xdc, 0xe1, 0xf1, 0x3b, 0x83, 0x4b)
#endif
namespace juce
{
//==============================================================================
struct HSTRING_PRIVATE;
typedef HSTRING_PRIVATE* HSTRING;
struct IInspectable : public IUnknown
{
JUCE_COMCALL GetIids (ULONG* ,IID**) = 0;
JUCE_COMCALL GetRuntimeClassName (HSTRING*) = 0;
JUCE_COMCALL GetTrustLevel (void*) = 0;
};
JUCE_COMCLASS (IUIViewSettingsInterop, "3694dbf9-8f68-44be-8ff5-195c98ede8a6") : public IInspectable
{
JUCE_COMCALL GetForWindow (HWND, REFIID, void**) = 0;
};
JUCE_COMCLASS (IUIViewSettings, "c63657f6-8850-470d-88f8-455e16ea2c26") : public IInspectable
{
enum UserInteractionMode
{
Mouse = 0,
Touch = 1
};
JUCE_COMCALL GetUserInteractionMode (UserInteractionMode*) = 0;
};
} // namespace juce
#ifdef __CRT_UUID_DECL
__CRT_UUID_DECL (juce::IUIViewSettingsInterop, 0x3694dbf9, 0x8f68, 0x44be, 0x8f, 0xf5, 0x19, 0x5c, 0x98, 0xed, 0xe8, 0xa6)
__CRT_UUID_DECL (juce::IUIViewSettings, 0xc63657f6, 0x8850, 0x470d, 0x88, 0xf8, 0x45, 0x5e, 0x16, 0xea, 0x2c, 0x26)
#endif
namespace juce
{
struct UWPUIViewSettings
{
UWPUIViewSettings()
{
ComBaseModule dll (L"api-ms-win-core-winrt-l1-1-0");
if (dll.h != nullptr)
{
roInitialize = (RoInitializeFuncPtr) ::GetProcAddress (dll.h, "RoInitialize");
roGetActivationFactory = (RoGetActivationFactoryFuncPtr) ::GetProcAddress (dll.h, "RoGetActivationFactory");
createHString = (WindowsCreateStringFuncPtr) ::GetProcAddress (dll.h, "WindowsCreateString");
deleteHString = (WindowsDeleteStringFuncPtr) ::GetProcAddress (dll.h, "WindowsDeleteString");
if (roInitialize == nullptr || roGetActivationFactory == nullptr
|| createHString == nullptr || deleteHString == nullptr)
return;
auto status = roInitialize (1);
if (status != S_OK && status != S_FALSE && (unsigned) status != 0x80010106L)
return;
LPCWSTR uwpClassName = L"Windows.UI.ViewManagement.UIViewSettings";
HSTRING uwpClassId = nullptr;
if (createHString (uwpClassName, (::UINT32) wcslen (uwpClassName), &uwpClassId) != S_OK
|| uwpClassId == nullptr)
return;
JUCE_BEGIN_IGNORE_WARNINGS_GCC_LIKE ("-Wlanguage-extension-token")
status = roGetActivationFactory (uwpClassId, __uuidof (IUIViewSettingsInterop),
(void**) viewSettingsInterop.resetAndGetPointerAddress());
JUCE_END_IGNORE_WARNINGS_GCC_LIKE
deleteHString (uwpClassId);
if (status != S_OK || viewSettingsInterop == nullptr)
return;
// move dll into member var
comBaseDLL = std::move (dll);
}
}
private:
//==============================================================================
struct ComBaseModule
{
ComBaseModule() = default;
ComBaseModule (LPCWSTR libraryName) : h (::LoadLibrary (libraryName)) {}
ComBaseModule (ComBaseModule&& o) : h (o.h) { o.h = nullptr; }
~ComBaseModule() { release(); }
void release() { if (h != nullptr) ::FreeLibrary (h); h = nullptr; }
ComBaseModule& operator= (ComBaseModule&& o) { release(); h = o.h; o.h = nullptr; return *this; }
HMODULE h = {};
};
using RoInitializeFuncPtr = HRESULT (WINAPI*) (int);
using RoGetActivationFactoryFuncPtr = HRESULT (WINAPI*) (HSTRING, REFIID, void**);
using WindowsCreateStringFuncPtr = HRESULT (WINAPI*) (LPCWSTR,UINT32, HSTRING*);
using WindowsDeleteStringFuncPtr = HRESULT (WINAPI*) (HSTRING);
ComBaseModule comBaseDLL;
ComSmartPtr<IUIViewSettingsInterop> viewSettingsInterop;
RoInitializeFuncPtr roInitialize;
RoGetActivationFactoryFuncPtr roGetActivationFactory;
WindowsCreateStringFuncPtr createHString;
WindowsDeleteStringFuncPtr deleteHString;
};
//==============================================================================
/* This is an interface to functionality that is implemented differently depending on the rendering
backend, currently either GDI or Direct2D on Windows.
This isn't public, so feel free to add or remove functions if necessary.
In general, it's best to keep things consistent between renderers, so try to make changes
in the HWNDComponentPeer rather than in implementations of RenderContext wherever possible.
However, any behaviour that is only required in specific renderers should be added to the
RenderContext implementations of those renderers.
*/
struct RenderContext
{
virtual ~RenderContext() = default;
/* The name of the renderer backend.
This must be unique - no two backends may share the same name.
The name may be displayed to the user, so it should be descriptive.
*/
virtual const char* getName() const = 0;
/* The following functions will all be called by the peer to update the state of the renderer. */
virtual void updateConstantAlpha() = 0;
virtual void handlePaintMessage() = 0;
virtual void repaint (const Rectangle<int>& area) = 0;
virtual void dispatchDeferredRepaints() = 0;
virtual void performAnyPendingRepaintsNow() = 0;
virtual void onVBlank() = 0;
virtual void handleShowWindow() = 0;
/* Gets a snapshot of whatever the render context is currently showing. */
virtual Image createSnapshot() = 0;
};
//==============================================================================
class HWNDComponentPeer final : public ComponentPeer
, private ComponentPeer::VBlankListener
, private Timer
#if JUCE_MODULE_AVAILABLE_juce_audio_plugin_client
, public ModifierKeyReceiver
#endif
{
public:
//==============================================================================
HWNDComponentPeer (Component& comp,
int windowStyleFlags,
HWND parent,
bool nonRepainting,
int engine)
: ComponentPeer (comp, windowStyleFlags),
dontRepaint (nonRepainting),
parentToAddTo (parent)
{
getNativeRealtimeModifiers = getMouseModifiers;
// CreateWindowEx needs to be called from the message thread
callFunctionIfNotLocked (&createWindowCallback, this);
// Complete the window initialisation on the calling thread
setTitle (component.getName());
updateShadower();
updateCurrentMonitorAndRefreshVBlankDispatcher (ForceRefreshDispatcher::yes);
if (parentToAddTo != nullptr)
{
monitorUpdateTimer.emplace ([this]
{
updateCurrentMonitorAndRefreshVBlankDispatcher (ForceRefreshDispatcher::yes);
monitorUpdateTimer->startTimer (1000);
});
}
suspendResumeRegistration = ScopedSuspendResumeNotificationRegistration { hwnd };
setCurrentRenderingEngine (engine);
}
~HWNDComponentPeer() override
{
// Clean up that needs to happen on the calling thread
suspendResumeRegistration = {};
VBlankDispatcher::getInstance()->removeListener (*this);
// do this first to avoid messages arriving for this window before it's destroyed
JuceWindowIdentifier::setAsJUCEWindow (hwnd, false);
if (isAccessibilityActive)
WindowsAccessibility::revokeUIAMapEntriesForWindow (hwnd);
shadower = nullptr;
currentTouches.deleteAllTouchesForPeer (this);
// Destroy the window from the message thread
callFunctionIfNotLocked (&destroyWindowCallback, this);
// And one last little bit of cleanup
if (dropTarget != nullptr)
{
dropTarget->peerIsDeleted = true;
dropTarget->Release();
dropTarget = nullptr;
}
}
//==============================================================================
auto getHWND() const { return hwnd; }
void* getNativeHandle() const override { return hwnd; }
void setVisible (bool shouldBeVisible) override
{
const ScopedValueSetter<bool> scope (shouldIgnoreModalDismiss, true);
ShowWindow (hwnd, shouldBeVisible ? SW_SHOWNA : SW_HIDE);
if (shouldBeVisible)
InvalidateRect (hwnd, nullptr, 0);
else
lastPaintTime = 0;
}
void setTitle (const String& title) override
{
// Unfortunately some ancient bits of win32 mean you can only perform this operation from the message thread.
JUCE_ASSERT_MESSAGE_THREAD
SetWindowText (hwnd, title.toWideCharPointer());
}
void repaintNowIfTransparent()
{
if (getTransparencyKind() == TransparencyKind::perPixel
&& lastPaintTime > 0
&& Time::getMillisecondCounter() > lastPaintTime + 30)
{
handlePaintMessage();
}
}
std::optional<BorderSize<int>> getCustomBorderSize() const
{
if (hasTitleBar() || (styleFlags & windowIsTemporary) != 0 || isFullScreen())
return {};
return BorderSize<int> { 0, 0, 0, 0 };
}
std::optional<BorderSize<int>> findPhysicalBorderSize() const
{
if (const auto custom = getCustomBorderSize())
return *custom;
ScopedThreadDPIAwarenessSetter setter { hwnd };
WINDOWINFO info{};
info.cbSize = sizeof (info);
if (! GetWindowInfo (hwnd, &info))
return {};
// Sometimes GetWindowInfo returns bogus information when called in the middle of restoring
// the window
if (info.rcWindow.left <= -32000 && info.rcWindow.top <= -32000)
return {};
return BorderSize<int> { info.rcClient.top - info.rcWindow.top,
info.rcClient.left - info.rcWindow.left,
info.rcWindow.bottom - info.rcClient.bottom,
info.rcWindow.right - info.rcClient.right };
}
void setBounds (const Rectangle<int>& bounds, bool isNowFullScreen) override
{
// If we try to set new bounds while handling an existing position change,
// Windows may get confused about our current scale and size.
// This can happen when moving a window between displays, because the mouse-move
// generator in handlePositionChanged can cause the window to move again.
if (inHandlePositionChanged)
return;
if (isNowFullScreen != isFullScreen())
setFullScreen (isNowFullScreen);
const ScopedValueSetter<bool> scope (shouldIgnoreModalDismiss, true);
const auto borderSize = findPhysicalBorderSize().value_or (BorderSize<int>{});
auto newBounds = borderSize.addedTo ([&]
{
ScopedThreadDPIAwarenessSetter setter { hwnd };
if (! isPerMonitorDPIAwareWindow (hwnd))
return bounds;
if (inDpiChange)
return convertLogicalScreenRectangleToPhysical (bounds, hwnd);
return convertLogicalScreenRectangleToPhysical (bounds, hwnd)
.withPosition (Desktop::getInstance().getDisplays().logicalToPhysical (bounds.getTopLeft()));
}());
if (getTransparencyKind() == TransparencyKind::perPixel)
{
if (auto parentHwnd = GetParent (hwnd))
{
auto parentRect = convertPhysicalScreenRectangleToLogical (D2DUtilities::toRectangle (getWindowScreenRect (parentHwnd)), hwnd);
newBounds.translate (parentRect.getX(), parentRect.getY());
}
}
const auto oldBounds = [this]
{
ScopedThreadDPIAwarenessSetter setter { hwnd };
RECT result;
GetWindowRect (hwnd, &result);
return D2DUtilities::toRectangle (result);
}();
const bool hasMoved = (oldBounds.getPosition() != bounds.getPosition());
const bool hasResized = (oldBounds.getWidth() != bounds.getWidth()
|| oldBounds.getHeight() != bounds.getHeight());
DWORD flags = SWP_NOACTIVATE | SWP_NOZORDER | SWP_NOOWNERZORDER | SWP_FRAMECHANGED;
if (! hasMoved) flags |= SWP_NOMOVE;
if (! hasResized) flags |= SWP_NOSIZE;
SetWindowPos (hwnd,
nullptr,
newBounds.getX(),
newBounds.getY(),
newBounds.getWidth(),
newBounds.getHeight(),
flags);
if (hasResized && isValidPeer (this))
{
repaintNowIfTransparent();
}
}
Rectangle<int> getBounds() const override
{
if (parentToAddTo == nullptr)
{
if (hasTitleBar())
{
// Depending on the desktop scale factor, the physical size of the window may not map to
// an integral client-area size.
// In this case, we always round the width and height of the client area up to the next
// integer.
// This means that we may end up clipping off up to one logical pixel under the physical
// window border, but this is preferable to displaying an uninitialised/unpainted
// region of the client area.
const auto physicalBorder = findPhysicalBorderSize().value_or (BorderSize<int>{});
const auto physicalBounds = D2DUtilities::toRectangle (getWindowScreenRect (hwnd));
const auto physicalClient = physicalBorder.subtractedFrom (physicalBounds);
const auto logicalClient = convertPhysicalScreenRectangleToLogical (physicalClient.toFloat(), hwnd);
const auto snapped = logicalClient.withPosition (logicalClient.getPosition().roundToInt().toFloat()).getSmallestIntegerContainer();
return snapped;
}
const auto logicalClient = convertPhysicalScreenRectangleToLogical (getClientRectInScreen(), hwnd);
return logicalClient;
}
auto localBounds = D2DUtilities::toRectangle (getWindowClientRect (hwnd));
if (isPerMonitorDPIAwareWindow (hwnd))
return (localBounds.toDouble() / getPlatformScaleFactor()).toNearestInt();
return localBounds;
}
Point<int> getScreenPosition() const
{
return convertPhysicalScreenPointToLogical (getClientRectInScreen().getPosition(), hwnd);
}
Point<float> localToGlobal (Point<float> relativePosition) override { return relativePosition + getScreenPosition().toFloat(); }
Point<float> globalToLocal (Point<float> screenPosition) override { return screenPosition - getScreenPosition().toFloat(); }
using ComponentPeer::localToGlobal;
using ComponentPeer::globalToLocal;
enum class TransparencyKind
{
perPixel,
constant,
opaque,
};
TransparencyKind getTransparencyKind() const
{
return transparencyKind;
}
void setAlpha (float) override
{
setLayeredWindow();
if (renderContext != nullptr)
renderContext->updateConstantAlpha();
}
void setMinimised (bool shouldBeMinimised) override
{
const ScopedValueSetter<bool> scope (shouldIgnoreModalDismiss, true);
if (shouldBeMinimised != isMinimised())
ShowWindow (hwnd, shouldBeMinimised ? SW_MINIMIZE : SW_RESTORE);
}
bool isMinimised() const override
{
WINDOWPLACEMENT wp;
wp.length = sizeof (WINDOWPLACEMENT);
GetWindowPlacement (hwnd, &wp);
return wp.showCmd == SW_SHOWMINIMIZED;
}
bool isShowing() const override
{
return IsWindowVisible (hwnd) && ! isMinimised();
}
void setFullScreen (bool shouldBeFullScreen) override
{
const ScopedValueSetter<bool> scope (shouldIgnoreModalDismiss, true);
setMinimised (false);
if (isFullScreen() != shouldBeFullScreen)
{
if (constrainer != nullptr)
constrainer->resizeStart();
const WeakReference<Component> deletionChecker (&component);
if (shouldBeFullScreen)
{
ShowWindow (hwnd, SW_SHOWMAXIMIZED);
}
else
{
auto boundsCopy = lastNonFullscreenBounds;
ShowWindow (hwnd, SW_SHOWNORMAL);
if (! boundsCopy.isEmpty())
setBounds (detail::ScalingHelpers::scaledScreenPosToUnscaled (component, boundsCopy), false);
}
if (deletionChecker != nullptr)
handleMovedOrResized();
if (constrainer != nullptr)
constrainer->resizeEnd();
}
}
bool isFullScreen() const override
{
WINDOWPLACEMENT wp;
wp.length = sizeof (wp);
GetWindowPlacement (hwnd, &wp);
return wp.showCmd == SW_SHOWMAXIMIZED;
}
Rectangle<int> getClientRectInScreen() const
{
ScopedThreadDPIAwarenessSetter setter { hwnd };
RECT rect{};
GetClientRect (hwnd, &rect);
auto points = readUnaligned<std::array<POINT, 2>> (&rect);
MapWindowPoints (hwnd, nullptr, points.data(), (UINT) points.size());
const auto result = readUnaligned<RECT> (&points);
return D2DUtilities::toRectangle (result);
}
bool contains (Point<int> localPos, bool trueIfInAChildWindow) const override
{
auto r = convertPhysicalScreenRectangleToLogical (D2DUtilities::toRectangle (getWindowScreenRect (hwnd)), hwnd);
if (! r.withZeroOrigin().contains (localPos))
return false;
const auto screenPos = convertLogicalScreenPointToPhysical (localPos + getScreenPosition(), hwnd);
auto w = WindowFromPoint (D2DUtilities::toPOINT (screenPos));
return w == hwnd || (trueIfInAChildWindow && (IsChild (hwnd, w) != 0));
}
OptionalBorderSize getFrameSizeIfPresent() const override
{
return ComponentPeer::OptionalBorderSize { getFrameSize() };
}
BorderSize<int> getFrameSize() const override
{
return findPhysicalBorderSize().value_or (BorderSize<int>{}).multipliedBy (1.0 / scaleFactor);
}
bool setAlwaysOnTop (bool alwaysOnTop) override
{
const bool oldDeactivate = shouldDeactivateTitleBar;
shouldDeactivateTitleBar = ((styleFlags & windowIsTemporary) == 0);
setWindowZOrder (hwnd, alwaysOnTop ? HWND_TOPMOST : HWND_NOTOPMOST);
shouldDeactivateTitleBar = oldDeactivate;
if (shadower != nullptr)
handleBroughtToFront();
return true;
}
void toFront (bool makeActive) override
{
const ScopedValueSetter<bool> scope (shouldIgnoreModalDismiss, true);
setMinimised (false);
const bool oldDeactivate = shouldDeactivateTitleBar;
shouldDeactivateTitleBar = ((styleFlags & windowIsTemporary) == 0);
callFunctionIfNotLocked (makeActive ? &toFrontCallback1 : &toFrontCallback2, hwnd);
shouldDeactivateTitleBar = oldDeactivate;
if (! makeActive)
{
// in this case a broughttofront call won't have occurred, so do it now..
handleBroughtToFront();
}
}
void toBehind (ComponentPeer* other) override
{
const ScopedValueSetter<bool> scope (shouldIgnoreModalDismiss, true);
if (auto* otherPeer = dynamic_cast<HWNDComponentPeer*> (other))
{
setMinimised (false);
// Must be careful not to try to put a topmost window behind a normal one, or Windows
// promotes the normal one to be topmost!
if (component.isAlwaysOnTop() == otherPeer->getComponent().isAlwaysOnTop())
setWindowZOrder (hwnd, otherPeer->hwnd);
else if (otherPeer->getComponent().isAlwaysOnTop())
setWindowZOrder (hwnd, HWND_TOP);
}
else
{
jassertfalse; // wrong type of window?
}
}
bool isFocused() const override
{
return callFunctionIfNotLocked (&getFocusCallback, nullptr) == (void*) hwnd;
}
void grabFocus() override
{
const ScopedValueSetter ignoreDismissScope (shouldIgnoreModalDismiss, true);
const ScopedValueSetter titlebarScope (shouldDeactivateTitleBar, (styleFlags & windowIsTemporary) == 0);
callFunctionIfNotLocked (&setFocusCallback, hwnd);
}
void textInputRequired (Point<int>, TextInputTarget&) override
{
if (! hasCreatedCaret)
hasCreatedCaret = CreateCaret (hwnd, (HBITMAP) 1, 0, 0);
if (hasCreatedCaret)
{
SetCaretPos (0, 0);
ShowCaret (hwnd);
}
ImmAssociateContext (hwnd, nullptr);
// MSVC complains about the nullptr argument, but the docs for this
// function say that the second argument is ignored when the third
// argument is IACE_DEFAULT.
JUCE_BEGIN_IGNORE_WARNINGS_MSVC (6387)
ImmAssociateContextEx (hwnd, nullptr, IACE_DEFAULT);
JUCE_END_IGNORE_WARNINGS_MSVC
}
void closeInputMethodContext() override
{
imeHandler.handleSetContext (hwnd, false);
}
void dismissPendingTextInput() override
{
closeInputMethodContext();
ImmAssociateContext (hwnd, nullptr);
if (std::exchange (hasCreatedCaret, false))
DestroyCaret();
}
void repaint (const Rectangle<int>& area) override
{
if (renderContext != nullptr)
renderContext->repaint ((area.toDouble() * getPlatformScaleFactor()).getSmallestIntegerContainer());
}
void dispatchDeferredRepaints()
{
if (renderContext != nullptr)
renderContext->dispatchDeferredRepaints();
}
void performAnyPendingRepaintsNow() override
{
if (renderContext != nullptr)
renderContext->performAnyPendingRepaintsNow();
}
Image createSnapshot()
{
if (renderContext != nullptr)
return renderContext->createSnapshot();
return {};
}
//==============================================================================
void onVBlank (double timestampSec) override
{
callVBlankListeners (timestampSec);
dispatchDeferredRepaints();
if (renderContext != nullptr)
renderContext->onVBlank();
}
//==============================================================================
static HWNDComponentPeer* getOwnerOfWindow (HWND h) noexcept
{
if (h != nullptr && JuceWindowIdentifier::isJUCEWindow (h))
return (HWNDComponentPeer*) GetWindowLongPtr (h, 8);
return nullptr;
}
//==============================================================================
bool isInside (HWND h) const noexcept
{
return GetAncestor (hwnd, GA_ROOT) == h;
}
//==============================================================================
static bool isKeyDown (const int key) noexcept { return (GetAsyncKeyState (key) & 0x8000) != 0; }
static void updateKeyModifiers() noexcept
{
int keyMods = 0;
if (isKeyDown (VK_SHIFT)) keyMods |= ModifierKeys::shiftModifier;
if (isKeyDown (VK_CONTROL)) keyMods |= ModifierKeys::ctrlModifier;
if (isKeyDown (VK_MENU)) keyMods |= ModifierKeys::altModifier;
// workaround: Windows maps AltGr to left-Ctrl + right-Alt.
if (isKeyDown (VK_RMENU) && !isKeyDown (VK_RCONTROL))
{
keyMods = (keyMods & ~ModifierKeys::ctrlModifier) | ModifierKeys::altModifier;
}
ModifierKeys::currentModifiers = ModifierKeys::getCurrentModifiers().withOnlyMouseButtons().withFlags (keyMods);
}
static void updateModifiersFromWParam (const WPARAM wParam)
{
int mouseMods = 0;
if (wParam & MK_LBUTTON) mouseMods |= ModifierKeys::leftButtonModifier;
if (wParam & MK_RBUTTON) mouseMods |= ModifierKeys::rightButtonModifier;
if (wParam & MK_MBUTTON) mouseMods |= ModifierKeys::middleButtonModifier;
if (wParam & MK_XBUTTON1) mouseMods |= ModifierKeys::backButtonModifier;
if (wParam & MK_XBUTTON2) mouseMods |= ModifierKeys::forwardButtonModifier;
ModifierKeys::currentModifiers = ModifierKeys::getCurrentModifiers().withoutMouseButtons().withFlags (mouseMods);
updateKeyModifiers();
}
//==============================================================================
bool dontRepaint;
static inline ModifierKeys modifiersAtLastCallback;
//==============================================================================
struct FileDropTarget final : public ComBaseClassHelper<IDropTarget>
{
FileDropTarget (HWNDComponentPeer& p) : peer (p) {}
JUCE_COMRESULT DragEnter (IDataObject* pDataObject, DWORD grfKeyState, POINTL mousePos, DWORD* pdwEffect) override
{
auto hr = updateFileList (pDataObject);
if (FAILED (hr))
return hr;
return DragOver (grfKeyState, mousePos, pdwEffect);
}
JUCE_COMRESULT DragLeave() override
{
if (peerIsDeleted)
return S_FALSE;
peer.handleDragExit (dragInfo);
return S_OK;
}
JUCE_COMRESULT DragOver (DWORD /*grfKeyState*/, POINTL mousePos, DWORD* pdwEffect) override
{
if (peerIsDeleted)
return S_FALSE;
dragInfo.position = getMousePos (mousePos).roundToInt();
*pdwEffect = peer.handleDragMove (dragInfo) ? (DWORD) DROPEFFECT_COPY
: (DWORD) DROPEFFECT_NONE;
return S_OK;
}
JUCE_COMRESULT Drop (IDataObject* pDataObject, DWORD /*grfKeyState*/, POINTL mousePos, DWORD* pdwEffect) override
{
auto hr = updateFileList (pDataObject);
if (FAILED (hr))
return hr;
dragInfo.position = getMousePos (mousePos).roundToInt();
*pdwEffect = peer.handleDragDrop (dragInfo) ? (DWORD) DROPEFFECT_COPY
: (DWORD) DROPEFFECT_NONE;
return S_OK;
}
HWNDComponentPeer& peer;
DragInfo dragInfo;
bool peerIsDeleted = false;
private:
Point<float> getMousePos (POINTL mousePos) const
{
const auto originalPos = D2DUtilities::toPoint ({ mousePos.x, mousePos.y });
const auto logicalPos = convertPhysicalScreenPointToLogical (originalPos, peer.hwnd);
return detail::ScalingHelpers::screenPosToLocalPos (peer.component, logicalPos.toFloat());
}
struct DroppedData
{
DroppedData (IDataObject* dataObject, CLIPFORMAT type)
{
FORMATETC format = { type, nullptr, DVASPECT_CONTENT, -1, TYMED_HGLOBAL };
if (SUCCEEDED (error = dataObject->GetData (&format, &medium)) && medium.hGlobal != nullptr)
{
dataSize = GlobalSize (medium.hGlobal);
data = GlobalLock (medium.hGlobal);
}
}
~DroppedData()
{
if (data != nullptr && medium.hGlobal != nullptr)
GlobalUnlock (medium.hGlobal);
}
HRESULT error;
STGMEDIUM medium { TYMED_HGLOBAL, { nullptr }, nullptr };
void* data = {};
SIZE_T dataSize;
};
void parseFileList (HDROP dropFiles)
{
dragInfo.files.clearQuick();
std::vector<TCHAR> nameBuffer;
const auto numFiles = DragQueryFile (dropFiles, ~(UINT) 0, nullptr, 0);
for (UINT i = 0; i < numFiles; ++i)
{
const auto bufferSize = DragQueryFile (dropFiles, i, nullptr, 0);
nameBuffer.clear();
nameBuffer.resize (bufferSize + 1, 0); // + 1 for the null terminator
[[maybe_unused]] const auto readCharacters = DragQueryFile (dropFiles, i, nameBuffer.data(), (UINT) nameBuffer.size());
jassert (readCharacters == bufferSize);
dragInfo.files.add (String (nameBuffer.data()));
}
}
HRESULT updateFileList (IDataObject* const dataObject)
{
if (peerIsDeleted)
return S_FALSE;
dragInfo.clear();
{
DroppedData fileData (dataObject, CF_HDROP);
if (SUCCEEDED (fileData.error))
{
parseFileList (static_cast<HDROP> (fileData.data));
return S_OK;
}
}
DroppedData textData (dataObject, CF_UNICODETEXT);
if (SUCCEEDED (textData.error))
{
dragInfo.text = String (CharPointer_UTF16 ((const WCHAR*) textData.data),
CharPointer_UTF16 ((const WCHAR*) addBytesToPointer (textData.data, textData.dataSize)));
return S_OK;
}
return textData.error;
}
JUCE_DECLARE_NON_COPYABLE (FileDropTarget)
};
static bool offerKeyMessageToJUCEWindow (const MSG& msg)
{
// If this isn't a keyboard message, let the host deal with it.
constexpr UINT messages[] { WM_KEYDOWN, WM_SYSKEYDOWN, WM_KEYUP, WM_SYSKEYUP, WM_CHAR, WM_SYSCHAR };
if (std::find (std::begin (messages), std::end (messages), msg.message) == std::end (messages))
return false;
auto* peer = getOwnerOfWindow (msg.hwnd);
auto* focused = Component::getCurrentlyFocusedComponent();
if (focused == nullptr || peer == nullptr || focused->getPeer() != peer)
return false;
auto* hwnd = static_cast<HWND> (peer->getNativeHandle());
if (hwnd == nullptr)
return false;
ScopedThreadDPIAwarenessSetter threadDpiAwarenessSetter { hwnd };
// If we've been sent a text character, process it as text.
if (msg.message == WM_CHAR || msg.message == WM_SYSCHAR)
return peer->doKeyChar ((int) msg.wParam, msg.lParam);
// The event was a keypress, rather than a text character
if (peer->findCurrentTextInputTarget() != nullptr)
{
// If there's a focused text input target, we want to attempt "real" text input with an
// IME, and we want to prevent the host from eating keystrokes (spaces etc.).
TranslateMessage (&msg);
// TranslateMessage may post WM_CHAR back to the window, so we remove those messages
// from the queue before the host gets to see them.
// This will dispatch pending WM_CHAR messages, so we may end up reentering
// offerKeyMessageToJUCEWindow and hitting the WM_CHAR case above.
// We always return true if WM_CHAR is posted so that the keypress is not forwarded
// to the host. Otherwise, the host may call TranslateMessage again on this message,
// resulting in duplicate WM_CHAR messages being posted.
MSG peeked{};
if (PeekMessage (&peeked, hwnd, WM_CHAR, WM_DEADCHAR, PM_REMOVE)
|| PeekMessage (&peeked, hwnd, WM_SYSCHAR, WM_SYSDEADCHAR, PM_REMOVE))
{
return true;
}
// If TranslateMessage didn't add a WM_CHAR to the queue, fall back to processing the
// event as a plain keypress
}
// There's no text input target, or the key event wasn't translated, so we'll just see if we
// can use the plain keystroke event
if (msg.message == WM_KEYDOWN || msg.message == WM_SYSKEYDOWN)
return peer->doKeyDown (msg.wParam);
return peer->doKeyUp (msg.wParam);
}
double getPlatformScaleFactor() const noexcept override
{
#if ! JUCE_WIN_PER_MONITOR_DPI_AWARE
return 1.0;
#else
if (! isPerMonitorDPIAwareWindow (hwnd))
return 1.0;
if (auto* parentHWND = GetParent (hwnd))
{
if (auto* parentPeer = getOwnerOfWindow (parentHWND))
return parentPeer->getPlatformScaleFactor();
if (getDPIForWindow != nullptr)
return getScaleFactorForWindow (parentHWND);
}
return scaleFactor;
#endif
}
static void getLastError()
{
TCHAR messageBuffer[256] = {};
FormatMessage (FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
nullptr,
GetLastError(),
MAKELANGID (LANG_NEUTRAL, SUBLANG_DEFAULT),
messageBuffer,
(DWORD) numElementsInArray (messageBuffer) - 1,
nullptr);
DBG (messageBuffer);
jassertfalse;
}
DWORD computeNativeStyleFlags() const
{
const auto titled = ! isKioskMode() && (styleFlags & windowHasTitleBar) != 0;
const auto usesDropShadow = windowUsesNativeShadow();
const auto hasClose = (styleFlags & windowHasCloseButton) != 0;
const auto hasMin = (styleFlags & windowHasMinimiseButton) != 0;
const auto hasMax = (styleFlags & windowHasMaximiseButton) != 0;
const auto resizable = (styleFlags & windowIsResizable) != 0;
DWORD result = WS_CLIPSIBLINGS | WS_CLIPCHILDREN;
if (parentToAddTo != nullptr)
{
result |= WS_CHILD;
}
else if (titled || usesDropShadow)
{
result |= usesDropShadow ? WS_CAPTION : 0;
result |= titled ? (WS_OVERLAPPED | WS_CAPTION) : WS_POPUP;
result |= hasClose ? (WS_SYSMENU | WS_CAPTION) : 0;
result |= hasMin ? (WS_MINIMIZEBOX | WS_CAPTION | WS_SYSMENU) : 0;
result |= hasMax ? (WS_MAXIMIZEBOX | WS_CAPTION | WS_SYSMENU) : 0;
result |= resizable ? WS_THICKFRAME : 0;
}
else
{
// Transparent windows need WS_POPUP and not WS_OVERLAPPED | WS_CAPTION, otherwise
// the top corners of the window will get rounded unconditionally.
// Unfortunately, this disables nice mouse handling for the caption area.
result |= WS_POPUP;
}
return result;
}
bool hasTitleBar() const { return (styleFlags & windowHasTitleBar) != 0; }
double getScaleFactor() const { return scaleFactor; }
private:
HWND hwnd, parentToAddTo;
std::unique_ptr<DropShadower> shadower;
uint32 lastPaintTime = 0;
ULONGLONG lastMagnifySize = 0;
bool isDragging = false, isMouseOver = false,
hasCreatedCaret = false, constrainerIsResizing = false, sizing = false;
IconConverters::IconPtr currentWindowIcon;
FileDropTarget* dropTarget = nullptr;
UWPUIViewSettings uwpViewSettings;
TransparencyKind transparencyKind = TransparencyKind::opaque;
#if JUCE_MODULE_AVAILABLE_juce_audio_plugin_client
ModifierKeyProvider* modProvider = nullptr;
#endif
double scaleFactor = 1.0;
bool inDpiChange = 0, inHandlePositionChanged = 0;
HMONITOR currentMonitor = nullptr;
bool isAccessibilityActive = false;
//==============================================================================
static inline MultiTouchMapper<DWORD> currentTouches;
//==============================================================================
class WindowClassHolder final : private DeletedAtShutdown
{
public:
WindowClassHolder()
{
// this name has to be different for each app/dll instance because otherwise poor old Windows can
// get a bit confused (even despite it not being a process-global window class).
String windowClassName ("JUCE_");
windowClassName << String::toHexString (Time::currentTimeMillis());
auto moduleHandle = (HINSTANCE) Process::getCurrentModuleInstanceHandle();
TCHAR moduleFile[1024] = {};
GetModuleFileName (moduleHandle, moduleFile, 1024);
WNDCLASSEX wcex = {};
wcex.cbSize = sizeof (wcex);
wcex.lpfnWndProc = (WNDPROC) windowProc;
wcex.lpszClassName = windowClassName.toWideCharPointer();
wcex.cbWndExtra = 32;
wcex.hInstance = moduleHandle;
for (const auto& [index, field, ptr] : { std::tuple { 0, &wcex.hIcon, &iconBig },
std::tuple { 1, &wcex.hIconSm, &iconSmall } })
{
auto iconNum = static_cast<WORD> (index);
ptr->reset (*field = ExtractAssociatedIcon (moduleHandle, moduleFile, &iconNum));
}
atom = RegisterClassEx (&wcex);
jassert (atom != 0);
isEventBlockedByModalComps = checkEventBlockedByModalComps;
}
~WindowClassHolder()
{
if (ComponentPeer::getNumPeers() == 0)
UnregisterClass (getWindowClassName(), (HINSTANCE) Process::getCurrentModuleInstanceHandle());
clearSingletonInstance();
}
LPCTSTR getWindowClassName() const noexcept { return (LPCTSTR) (pointer_sized_uint) atom; }
JUCE_DECLARE_SINGLETON_SINGLETHREADED_MINIMAL_INLINE (WindowClassHolder)
private:
ATOM atom;
static bool isHWNDBlockedByModalComponents (HWND h)
{
for (int i = Desktop::getInstance().getNumComponents(); --i >= 0;)
if (auto* c = Desktop::getInstance().getComponent (i))
if ((! c->isCurrentlyBlockedByAnotherModalComponent())
&& IsChild ((HWND) c->getWindowHandle(), h))
return false;
return true;
}
static bool checkEventBlockedByModalComps (const MSG& m)
{
if (Component::getNumCurrentlyModalComponents() == 0 || JuceWindowIdentifier::isJUCEWindow (m.hwnd))
return false;
switch (m.message)
{
case WM_MOUSEMOVE:
case WM_NCMOUSEMOVE:
case 0x020A: /* WM_MOUSEWHEEL */
case 0x020E: /* WM_MOUSEHWHEEL */
case WM_KEYUP:
case WM_SYSKEYUP:
case WM_CHAR:
case WM_APPCOMMAND:
case WM_LBUTTONUP:
case WM_MBUTTONUP:
case WM_RBUTTONUP:
case WM_MOUSEACTIVATE:
case WM_NCMOUSEHOVER:
case WM_MOUSEHOVER:
case WM_TOUCH:
case WM_POINTERUPDATE:
case WM_NCPOINTERUPDATE:
case WM_POINTERWHEEL:
case WM_POINTERHWHEEL:
case WM_POINTERUP:
case WM_POINTERACTIVATE:
return isHWNDBlockedByModalComponents (m.hwnd);
case WM_NCLBUTTONDOWN:
case WM_NCLBUTTONDBLCLK:
case WM_NCRBUTTONDOWN:
case WM_NCRBUTTONDBLCLK:
case WM_NCMBUTTONDOWN:
case WM_NCMBUTTONDBLCLK:
case WM_LBUTTONDOWN:
case WM_LBUTTONDBLCLK:
case WM_MBUTTONDOWN:
case WM_MBUTTONDBLCLK:
case WM_RBUTTONDOWN:
case WM_RBUTTONDBLCLK:
case WM_KEYDOWN:
case WM_SYSKEYDOWN:
case WM_NCPOINTERDOWN:
case WM_POINTERDOWN:
if (isHWNDBlockedByModalComponents (m.hwnd))
{
if (auto* modal = Component::getCurrentlyModalComponent (0))
modal->inputAttemptWhenModal();
return true;
}
break;
default:
break;
}
return false;
}
IconConverters::IconPtr iconBig, iconSmall;
JUCE_DECLARE_NON_COPYABLE (WindowClassHolder)
};
//==============================================================================
static void* createWindowCallback (void* userData)
{
static_cast<HWNDComponentPeer*> (userData)->createWindowOnMessageThread();
return nullptr;
}
void createWindowOnMessageThread()
{
const auto type = computeNativeStyleFlags();
const auto exstyle = std::invoke ([&]() -> DWORD
{
if (parentToAddTo != nullptr)
return 0;
const auto appearsOnTaskbar = (styleFlags & windowAppearsOnTaskbar) != 0;
return appearsOnTaskbar ? WS_EX_APPWINDOW : WS_EX_TOOLWINDOW;
});
hwnd = CreateWindowEx (exstyle, WindowClassHolder::getInstance()->getWindowClassName(),
L"", type, 0, 0, 0, 0, parentToAddTo, nullptr,
(HINSTANCE) Process::getCurrentModuleInstanceHandle(), nullptr);
const auto titled = (styleFlags & windowHasTitleBar) != 0;
const auto usesDropShadow = windowUsesNativeShadow();
if (! titled && usesDropShadow)
{
// The choice of margins is very particular.
// - Using 0 for all values disables the system decoration (shadow etc.) completely.
// - Using -1 for all values breaks the software renderer, because the client content
// gets blended with the system-drawn controls.
// It looks OK most of the time with the D2D renderer, but can look very ugly during
// resize because the native window controls still get drawn under the client area.
// - Using 1 for all values looks the way we want for both renderers, but seems to
// prevent the Windows 11 maximize-button flyout from appearing (?).
// - Using 1 for left and right, and 0 for top and bottom shows the system shadow and
// maximize-button flyout.
static constexpr MARGINS margins { 1, 1, 0, 0 };
::DwmExtendFrameIntoClientArea (hwnd, &margins);
::SetWindowPos (hwnd, nullptr, 0, 0, 0, 0, SWP_FRAMECHANGED | SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER);
}
#if JUCE_DEBUG
// The DPI-awareness context of this window and JUCE's hidden message window are different.
// You normally want these to match otherwise timer events and async messages will happen
// in a different context to normal HWND messages which can cause issues with UI scaling.
jassert (isPerMonitorDPIAwareWindow (hwnd) == isPerMonitorDPIAwareWindow (juce_messageWindowHandle)
|| numActiveScopedDpiAwarenessDisablers > 0);
#endif
if (hwnd != nullptr)
{
SetWindowLongPtr (hwnd, 0, 0);
SetWindowLongPtr (hwnd, 8, (LONG_PTR) this);
JuceWindowIdentifier::setAsJUCEWindow (hwnd, true);
if (dropTarget == nullptr)
{
HWNDComponentPeer* peer = nullptr;
if (dontRepaint)
peer = getOwnerOfWindow (parentToAddTo);
if (peer == nullptr)
peer = this;
dropTarget = new FileDropTarget (*peer);
}
RegisterDragDrop (hwnd, dropTarget);
if (canUseMultiTouch())
registerTouchWindow (hwnd, 0);
setDPIAwareness();
if (isPerMonitorDPIAwareThread())
scaleFactor = getScaleFactorForWindow (hwnd);
setMessageFilter();
checkForPointerAPI();
// This is needed so that our plugin window gets notified of WM_SETTINGCHANGE messages
// and can respond to display scale changes
if (! JUCEApplication::isStandaloneApp())
settingChangeCallback = ComponentPeer::forceDisplayUpdate;
// Calling this function here is (for some reason) necessary to make Windows
// correctly enable the menu items that we specify in the wm_initmenu message.
GetSystemMenu (hwnd, false);
setAlpha (component.getAlpha());
}
else
{
getLastError();
}
}
static BOOL CALLBACK revokeChildDragDropCallback (HWND hwnd, LPARAM) { RevokeDragDrop (hwnd); return TRUE; }
static void* destroyWindowCallback (void* userData)
{
static_cast<HWNDComponentPeer*> (userData)->destroyWindowOnMessageThread();
return nullptr;
}
void destroyWindowOnMessageThread() noexcept
{
if (IsWindow (hwnd))
{
RevokeDragDrop (hwnd);
// NB: we need to do this before DestroyWindow() as child HWNDs will be invalid after
EnumChildWindows (hwnd, revokeChildDragDropCallback, 0);
DestroyWindow (hwnd);
}
}
static void* toFrontCallback1 (void* h)
{
BringWindowToTop ((HWND) h);
return nullptr;
}
static void* toFrontCallback2 (void* h)
{
setWindowZOrder ((HWND) h, HWND_TOP);
return nullptr;
}
static void* setFocusCallback (void* h)
{
SetFocus ((HWND) h);
return nullptr;
}
static void* getFocusCallback (void*)
{
return GetFocus();
}
bool isOpaque() const
{
return component.isOpaque();
}
bool windowUsesNativeShadow() const
{
return ! isKioskMode()
&& (hasTitleBar()
|| ( (0 != (styleFlags & windowHasDropShadow))
&& (0 == (styleFlags & windowIsSemiTransparent))
&& (0 == (styleFlags & windowIsTemporary))));
}
void updateShadower()
{
if (! component.isCurrentlyModal()
&& (styleFlags & windowHasDropShadow) != 0
&& ! windowUsesNativeShadow())
{
shadower = component.getLookAndFeel().createDropShadowerForComponent (component);
if (shadower != nullptr)
shadower->setOwner (&component);
}
}
void setIcon (const Image& newIcon) override
{
if (IconConverters::IconPtr hicon { IconConverters::createHICONFromImage (newIcon, TRUE, 0, 0) })
{
SendMessage (hwnd, WM_SETICON, ICON_BIG, reinterpret_cast<LPARAM> (hicon.get()));
SendMessage (hwnd, WM_SETICON, ICON_SMALL, reinterpret_cast<LPARAM> (hicon.get()));
currentWindowIcon = std::move (hicon);
}
}
void setMessageFilter()
{
using ChangeWindowMessageFilterExFunc = BOOL (WINAPI*) (HWND, UINT, DWORD, PVOID);
static auto changeMessageFilter = (ChangeWindowMessageFilterExFunc) getUser32Function ("ChangeWindowMessageFilterEx");
if (changeMessageFilter != nullptr)
{
changeMessageFilter (hwnd, WM_DROPFILES, 1 /*MSGFLT_ALLOW*/, nullptr);
changeMessageFilter (hwnd, WM_COPYDATA, 1 /*MSGFLT_ALLOW*/, nullptr);
changeMessageFilter (hwnd, 0x49, 1 /*MSGFLT_ALLOW*/, nullptr);
}
}
TransparencyKind computeTransparencyKind() const
{
if (! hasTitleBar() && ! component.isOpaque())
return TransparencyKind::perPixel;
// If you hit this assertion, you're trying to create a window with a native titlebar
// and per-pixel transparency. If you want a semi-transparent window, then remove the
// native title bar. Otherwise, ensure that the window's component is opaque.
jassert (! hasTitleBar() || component.isOpaque());
if (component.getAlpha() < 1.0f)
return TransparencyKind::constant;
return TransparencyKind::opaque;
}
void setLayeredWindow()
{
const auto old = std::exchange (transparencyKind, computeTransparencyKind());
if (old == getTransparencyKind())
return;
const auto prev = GetWindowLongPtr (hwnd, GWL_EXSTYLE);
// UpdateLayeredWindow will fail if SetLayeredWindowAttributes has previously been called
// without unsetting and resetting the layering style bit.
// UpdateLayeredWindow is used for perPixel windows; SetLayeredWindowAttributes is used for
// windows with a constant alpha but otherwise "opaque" contents (i.e. component.isOpaque()
// returns true but component.getAlpha() is less than 1.0f).
if (getTransparencyKind() == TransparencyKind::perPixel)
SetWindowLongPtr (hwnd, GWL_EXSTYLE, prev & ~WS_EX_LAYERED);
const auto newStyle = getTransparencyKind() == TransparencyKind::opaque
? (prev & ~WS_EX_LAYERED)
: (prev | WS_EX_LAYERED);
SetWindowLongPtr (hwnd, GWL_EXSTYLE, newStyle);
RedrawWindow (hwnd, nullptr, nullptr, RDW_ERASE | RDW_INVALIDATE | RDW_FRAME | RDW_ALLCHILDREN);
}
//==============================================================================
void handlePaintMessage()
{
if (renderContext != nullptr)
renderContext->handlePaintMessage();
lastPaintTime = Time::getMillisecondCounter();
}
//==============================================================================
void doMouseEvent (Point<float> position, float pressure, float orientation = 0.0f, ModifierKeys mods = ModifierKeys::currentModifiers)
{
handleMouseEvent (MouseInputSource::InputSourceType::mouse, position, mods, pressure, orientation, getMouseEventTime());
}
StringArray getAvailableRenderingEngines() override;
int getCurrentRenderingEngine() const override;
void setCurrentRenderingEngine (int e) override;
bool isTouchEvent() noexcept
{
if (registerTouchWindow == nullptr)
return false;
// Relevant info about touch/pen detection flags:
// https://msdn.microsoft.com/en-us/library/windows/desktop/ms703320(v=vs.85).aspx
// http://www.petertissen.de/?p=4
return ((uint32_t) GetMessageExtraInfo() & 0xFFFFFF80 /*SIGNATURE_MASK*/) == 0xFF515780 /*MI_WP_SIGNATURE*/;
}
static bool areOtherTouchSourcesActive()
{
for (auto& ms : Desktop::getInstance().getMouseSources())
if (ms.isDragging() && (ms.getType() == MouseInputSource::InputSourceType::touch
|| ms.getType() == MouseInputSource::InputSourceType::pen))
return true;
return false;
}
enum class WindowArea
{
nonclient,
client,
};
std::optional<LRESULT> doMouseMoveAtPoint (bool isMouseDownEvent, WindowArea area, Point<float> position)
{
auto modsToSend = ModifierKeys::getCurrentModifiers();
// this will be handled by WM_TOUCH
if (isTouchEvent() || areOtherTouchSourcesActive())
return {};
if (! isMouseOver)
{
isMouseOver = true;
// This avoids a rare stuck-button problem when focus is lost unexpectedly, but must
// not be called as part of a move, in case it's actually a mouse-drag from another
// app which ends up here when we get focus before the mouse is released..
if (isMouseDownEvent)
NullCheckedInvocation::invoke (getNativeRealtimeModifiers);
updateKeyModifiers();
updateModifiersFromModProvider();
TRACKMOUSEEVENT tme;
tme.cbSize = sizeof (tme);
tme.dwFlags = TME_LEAVE | (area == WindowArea::nonclient ? TME_NONCLIENT : 0);
tme.hwndTrack = hwnd;
tme.dwHoverTime = 0;
if (! TrackMouseEvent (&tme))
jassertfalse;
if (area == WindowArea::client)
Desktop::getInstance().getMainMouseSource().forceMouseCursorUpdate();
}
else if (! isDragging && ! contains (position.roundToInt(), false))
{
return {};
}
static uint32 lastMouseTime = 0;
auto now = Time::getMillisecondCounter();
if (! Desktop::getInstance().getMainMouseSource().isDragging())
modsToSend = modsToSend.withoutMouseButtons();
if (now >= lastMouseTime)
{
lastMouseTime = now;
doMouseEvent (position, MouseInputSource::defaultPressure,
MouseInputSource::defaultOrientation, modsToSend);
}
return {};
}
std::optional<LRESULT> doMouseMove (const LPARAM lParam, bool isMouseDownEvent, WindowArea area)
{
// Check if the mouse has moved since being pressed in the caption area.
// If it has, then we defer to DefWindowProc to handle the mouse movement.
// Allowing DefWindowProc to handle WM_NCLBUTTONDOWN directly will pause message
// processing (and therefore painting) when the mouse is clicked in the caption area,
// which is why we wait until the mouse is *moved* before asking the system to take over.
// Letting the system handle the move is important for things like Aero Snap to work.
if (area == WindowArea::nonclient && captionMouseDown.has_value() && *captionMouseDown != lParam)
{
captionMouseDown.reset();
return handleNcMouseEventThenFixModifiers (WM_NCLBUTTONDOWN, HTCAPTION, lParam);
}
const auto position = area == WindowArea::client ? getPointFromLocalLParam (lParam)
: getLocalPointFromScreenLParam (lParam);
return doMouseMoveAtPoint (isMouseDownEvent, area, position);
}
LRESULT handleNcMouseEventThenFixModifiers (UINT msg, WPARAM wParam, LPARAM lParam)
{
// When clicking and dragging on the caption area (including in the edge resize areas), a
// new modal loop is started inside DefWindowProc. This modal loop appears to consume some
// mouse events, without forwarding them back to our own window proc. In particular, we
// never get to see the WM_NCLBUTTONUP event with the HTCAPTION argument, or any other
// kind of mouse-up event to signal that the loop exited, so
// ModifierKeys::currentModifiers gets left in the wrong state. As a workaround, we
// manually update the modifier keys after DefWindowProc exits, and update the
// capture state if necessary.
const auto result = DefWindowProc (hwnd, msg, wParam, lParam);
getMouseModifiers();
releaseCaptureIfNecessary();
return result;
}
void updateModifiersFromModProvider() const
{
#if JUCE_MODULE_AVAILABLE_juce_audio_plugin_client
if (modProvider != nullptr)
ModifierKeys::currentModifiers = ModifierKeys::currentModifiers.withFlags (modProvider->getWin32Modifiers());
#endif
}
void updateModifiersWithMouseWParam (const WPARAM wParam) const
{
updateModifiersFromWParam (wParam);
updateModifiersFromModProvider();
}
void releaseCaptureIfNecessary() const
{
if (! ModifierKeys::getCurrentModifiers().isAnyMouseButtonDown() && hwnd == GetCapture())
ReleaseCapture();
}
void doMouseDown (LPARAM lParam, const WPARAM wParam)
{
// this will be handled by WM_TOUCH
if (isTouchEvent() || areOtherTouchSourcesActive())
return;
if (GetCapture() != hwnd)
SetCapture (hwnd);
doMouseMove (lParam, true, WindowArea::client);
if (isValidPeer (this))
{
updateModifiersWithMouseWParam (wParam);
isDragging = true;
doMouseEvent (getPointFromLocalLParam (lParam), MouseInputSource::defaultPressure);
}
// If this is the first event after receiving both a MOUSEACTIVATE and a SETFOCUS, then
// process the postponed focus update.
if (std::exchange (mouseActivateFlags, (uint8_t) 0) == (gotMouseActivate | gotSetFocus))
handleSetFocus();
}
void doMouseUp (Point<float> position, const WPARAM wParam, bool adjustCapture = true)
{
// this will be handled by WM_TOUCH
if (isTouchEvent() || areOtherTouchSourcesActive())
return;
updateModifiersWithMouseWParam (wParam);
const bool wasDragging = std::exchange (isDragging, false);
// release the mouse capture if the user has released all buttons
if (adjustCapture)
releaseCaptureIfNecessary();
// NB: under some circumstances (e.g. double-clicking a native title bar), a mouse-up can
// arrive without a mouse-down, so in that case we need to avoid sending a message.
if (wasDragging)
doMouseEvent (position, MouseInputSource::defaultPressure);
}
void doCaptureChanged()
{
if (constrainerIsResizing)
{
if (constrainer != nullptr)
constrainer->resizeEnd();
constrainerIsResizing = false;
}
if (isDragging)
doMouseUp (getCurrentMousePos(), (WPARAM) 0, false);
}
/* The parameter specifies the area the cursor just left. */
void doMouseExit (WindowArea area)
{
isMouseOver = false;
const auto messagePos = GetMessagePos();
// If the system tells us that the mouse left an area, but the cursor is still over that
// area, respect the system's decision and treat this as a mouse-leave event.
// Starting a native drag-n-drop or dragging the window caption may cause the system to send
// a mouse-leave event while the mouse is still within the window's bounds.
const auto shouldRestartTracking = std::invoke ([&]
{
auto* peer = getOwnerOfWindow (WindowFromPoint (getPOINTFromLParam (messagePos)));
if (peer != this)
return false;
const auto newAreaNative = peerWindowProc (hwnd, WM_NCHITTEST, 0, messagePos);
if (newAreaNative == HTNOWHERE || newAreaNative == HTTRANSPARENT)
return false;
if (newAreaNative == HTCLIENT)
return area == WindowArea::nonclient;
return area == WindowArea::client;
});
if (shouldRestartTracking)
{
doMouseMoveAtPoint (false,
area == WindowArea::client ? WindowArea::nonclient : WindowArea::client,
getLocalPointFromScreenLParam (messagePos));
}
else if (! areOtherTouchSourcesActive())
{
doMouseEvent (getCurrentMousePos(), MouseInputSource::defaultPressure);
}
}
std::tuple<ComponentPeer*, Point<float>> findPeerUnderMouse()
{
auto currentMousePos = getPOINTFromLParam (GetMessagePos());
auto* peer = getOwnerOfWindow (WindowFromPoint (currentMousePos));
if (peer == nullptr)
peer = this;
return std::tuple (peer, peer->globalToLocal (convertPhysicalScreenPointToLogical (D2DUtilities::toPoint (currentMousePos), hwnd).toFloat()));
}
static MouseInputSource::InputSourceType getPointerType (WPARAM wParam)
{
if (getPointerTypeFunction != nullptr)
{
POINTER_INPUT_TYPE pointerType;
if (getPointerTypeFunction (GET_POINTERID_WPARAM (wParam), &pointerType))
{
if (pointerType == 2)
return MouseInputSource::InputSourceType::touch;
if (pointerType == 3)
return MouseInputSource::InputSourceType::pen;
}
}
return MouseInputSource::InputSourceType::mouse;
}
bool doMouseWheel (const WPARAM wParam, const bool isVertical)
{
updateKeyModifiers();
const float amount = jlimit (-1000.0f, 1000.0f, 0.5f * (short) HIWORD (wParam));
MouseWheelDetails wheel;
wheel.deltaX = isVertical ? 0.0f : amount / -256.0f;
wheel.deltaY = isVertical ? amount / 256.0f : 0.0f;
wheel.isReversed = false;
wheel.isSmooth = false;
wheel.isInertial = false;
// From Windows 10 onwards, mouse events are sent first to the window under the mouse, not
// the window with focus, despite what the MSDN docs might say.
// This is the behaviour we want; if we're receiving a scroll event, we can assume it
// should be processed by the current peer.
const auto localPos = getLocalPointFromScreenLParam ((LPARAM) GetMessagePos());
handleMouseWheel (getPointerType (wParam), localPos, getMouseEventTime(), wheel);
return true;
}
bool doGestureEvent (LPARAM lParam)
{
GESTUREINFO gi;
zerostruct (gi);
gi.cbSize = sizeof (gi);
if (getGestureInfo != nullptr && getGestureInfo ((HGESTUREINFO) lParam, &gi))
{
updateKeyModifiers();
if (const auto [peer, localPos] = findPeerUnderMouse(); peer != nullptr)
{
switch (gi.dwID)
{
case 3: /*GID_ZOOM*/
if (gi.dwFlags != 1 /*GF_BEGIN*/ && lastMagnifySize > 0)
peer->handleMagnifyGesture (MouseInputSource::InputSourceType::touch, localPos, getMouseEventTime(),
(float) ((double) gi.ullArguments / (double) lastMagnifySize));
lastMagnifySize = gi.ullArguments;
return true;
case 4: /*GID_PAN*/
case 5: /*GID_ROTATE*/
case 6: /*GID_TWOFINGERTAP*/
case 7: /*GID_PRESSANDTAP*/
default:
break;
}
}
}
return false;
}
LRESULT doTouchEvent (const int numInputs, HTOUCHINPUT eventHandle)
{
if ((styleFlags & windowIgnoresMouseClicks) != 0)
if (auto* parent = getOwnerOfWindow (GetParent (hwnd)))
if (parent != this)
return parent->doTouchEvent (numInputs, eventHandle);
HeapBlock<TOUCHINPUT> inputInfo (numInputs);
if (getTouchInputInfo (eventHandle, (UINT) numInputs, inputInfo, sizeof (TOUCHINPUT)))
{
for (int i = 0; i < numInputs; ++i)
{
auto flags = inputInfo[i].dwFlags;
if ((flags & (TOUCHEVENTF_DOWN | TOUCHEVENTF_MOVE | TOUCHEVENTF_UP)) != 0)
if (! handleTouchInput (inputInfo[i], (flags & TOUCHEVENTF_DOWN) != 0, (flags & TOUCHEVENTF_UP) != 0))
return 0; // abandon method if this window was deleted by the callback
}
}
closeTouchInputHandle (eventHandle);
return 0;
}
bool handleTouchInput (const TOUCHINPUT& touch, const bool isDown, const bool isUp,
const float touchPressure = MouseInputSource::defaultPressure,
const float orientation = 0.0f)
{
auto isCancel = false;
const auto touchIndex = currentTouches.getIndexOfTouch (this, touch.dwID);
const auto time = getMouseEventTime();
const auto pos = globalToLocal (convertPhysicalScreenPointToLogical (D2DUtilities::toPoint ({ roundToInt (touch.x / 100.0f),
roundToInt (touch.y / 100.0f) }), hwnd).toFloat());
const auto pressure = touchPressure;
auto modsToSend = ModifierKeys::getCurrentModifiers();
if (isDown)
{
ModifierKeys::currentModifiers = ModifierKeys::getCurrentModifiers().withoutMouseButtons().withFlags (ModifierKeys::leftButtonModifier);
modsToSend = ModifierKeys::getCurrentModifiers();
// this forces a mouse-enter/up event, in case for some reason we didn't get a mouse-up before.
handleMouseEvent (MouseInputSource::InputSourceType::touch, pos, modsToSend.withoutMouseButtons(),
pressure, orientation, time, {}, touchIndex);
if (! isValidPeer (this)) // (in case this component was deleted by the event)
return false;
}
else if (isUp)
{
modsToSend = modsToSend.withoutMouseButtons();
ModifierKeys::currentModifiers = modsToSend;
currentTouches.clearTouch (touchIndex);
if (! currentTouches.areAnyTouchesActive())
isCancel = true;
}
else
{
modsToSend = ModifierKeys::getCurrentModifiers().withoutMouseButtons().withFlags (ModifierKeys::leftButtonModifier);
}
handleMouseEvent (MouseInputSource::InputSourceType::touch, pos, modsToSend,
pressure, orientation, time, {}, touchIndex);
if (! isValidPeer (this))
return false;
if (isUp)
{
handleMouseEvent (MouseInputSource::InputSourceType::touch, MouseInputSource::offscreenMousePos, ModifierKeys::getCurrentModifiers().withoutMouseButtons(),
pressure, orientation, time, {}, touchIndex);
if (! isValidPeer (this))
return false;
if (isCancel)
{
currentTouches.clear();
ModifierKeys::currentModifiers = ModifierKeys::getCurrentModifiers().withoutMouseButtons();
}
}
return true;
}
bool handlePointerInput (WPARAM wParam, LPARAM lParam, const bool isDown, const bool isUp)
{
if (! canUsePointerAPI)
return false;
auto pointerType = getPointerType (wParam);
if (pointerType == MouseInputSource::InputSourceType::touch)
{
POINTER_TOUCH_INFO touchInfo;
if (! getPointerTouchInfo (GET_POINTERID_WPARAM (wParam), &touchInfo))
return false;
const auto pressure = touchInfo.touchMask & TOUCH_MASK_PRESSURE ? static_cast<float> (touchInfo.pressure)
: MouseInputSource::defaultPressure;
const auto orientation = touchInfo.touchMask & TOUCH_MASK_ORIENTATION ? degreesToRadians (static_cast<float> (touchInfo.orientation))
: MouseInputSource::defaultOrientation;
if (! handleTouchInput (emulateTouchEventFromPointer (touchInfo.pointerInfo.ptPixelLocationRaw, wParam),
isDown, isUp, pressure, orientation))
return false;
}
else if (pointerType == MouseInputSource::InputSourceType::pen)
{
POINTER_PEN_INFO penInfo;
if (! getPointerPenInfo (GET_POINTERID_WPARAM (wParam), &penInfo))
return false;
const auto pressure = (penInfo.penMask & PEN_MASK_PRESSURE) ? (float) penInfo.pressure / 1024.0f : MouseInputSource::defaultPressure;
if (! handlePenInput (penInfo, globalToLocal (convertPhysicalScreenPointToLogical (D2DUtilities::toPoint (getPOINTFromLParam (lParam)), hwnd).toFloat()),
pressure, isDown, isUp))
return false;
}
else
{
return false;
}
return true;
}
TOUCHINPUT emulateTouchEventFromPointer (POINT p, WPARAM wParam)
{
TOUCHINPUT touchInput;
touchInput.dwID = GET_POINTERID_WPARAM (wParam);
touchInput.x = p.x * 100;
touchInput.y = p.y * 100;
return touchInput;
}
bool handlePenInput (POINTER_PEN_INFO penInfo, Point<float> pos, const float pressure, bool isDown, bool isUp)
{
const auto time = getMouseEventTime();
ModifierKeys modsToSend (ModifierKeys::currentModifiers);
PenDetails penDetails;
penDetails.rotation = (penInfo.penMask & PEN_MASK_ROTATION) ? degreesToRadians (static_cast<float> (penInfo.rotation)) : MouseInputSource::defaultRotation;
penDetails.tiltX = (penInfo.penMask & PEN_MASK_TILT_X) ? (float) penInfo.tiltX / 90.0f : MouseInputSource::defaultTiltX;
penDetails.tiltY = (penInfo.penMask & PEN_MASK_TILT_Y) ? (float) penInfo.tiltY / 90.0f : MouseInputSource::defaultTiltY;
auto pInfoFlags = penInfo.pointerInfo.pointerFlags;
if ((pInfoFlags & POINTER_FLAG_FIRSTBUTTON) != 0)
ModifierKeys::currentModifiers = ModifierKeys::getCurrentModifiers().withoutMouseButtons().withFlags (ModifierKeys::leftButtonModifier);
else if ((pInfoFlags & POINTER_FLAG_SECONDBUTTON) != 0)
ModifierKeys::currentModifiers = ModifierKeys::getCurrentModifiers().withoutMouseButtons().withFlags (ModifierKeys::rightButtonModifier);
if (isDown)
{
modsToSend = ModifierKeys::currentModifiers;
// this forces a mouse-enter/up event, in case for some reason we didn't get a mouse-up before.
handleMouseEvent (MouseInputSource::InputSourceType::pen, pos, modsToSend.withoutMouseButtons(),
pressure, MouseInputSource::defaultOrientation, time, penDetails);
if (! isValidPeer (this)) // (in case this component was deleted by the event)
return false;
}
else if (isUp || ! (pInfoFlags & POINTER_FLAG_INCONTACT))
{
modsToSend = modsToSend.withoutMouseButtons();
ModifierKeys::currentModifiers = ModifierKeys::getCurrentModifiers().withoutMouseButtons();
}
handleMouseEvent (MouseInputSource::InputSourceType::pen, pos, modsToSend, pressure,
MouseInputSource::defaultOrientation, time, penDetails);
if (! isValidPeer (this)) // (in case this component was deleted by the event)
return false;
if (isUp)
{
handleMouseEvent (MouseInputSource::InputSourceType::pen, MouseInputSource::offscreenMousePos, ModifierKeys::getCurrentModifiers(),
pressure, MouseInputSource::defaultOrientation, time, penDetails);
if (! isValidPeer (this))
return false;
}
return true;
}
//==============================================================================
void sendModifierKeyChangeIfNeeded()
{
if (modifiersAtLastCallback != ModifierKeys::currentModifiers)
{
modifiersAtLastCallback = ModifierKeys::currentModifiers;
handleModifierKeysChange();
}
}
bool doKeyUp (const WPARAM key)
{
updateKeyModifiers();
switch (key)
{
case VK_SHIFT:
case VK_CONTROL:
case VK_MENU:
case VK_CAPITAL:
case VK_LWIN:
case VK_RWIN:
case VK_APPS:
case VK_NUMLOCK:
case VK_SCROLL:
case VK_LSHIFT:
case VK_RSHIFT:
case VK_LCONTROL:
case VK_LMENU:
case VK_RCONTROL:
case VK_RMENU:
sendModifierKeyChangeIfNeeded();
}
return handleKeyUpOrDown (false)
|| Component::getCurrentlyModalComponent() != nullptr;
}
bool doKeyDown (const WPARAM key)
{
updateKeyModifiers();
bool used = false;
switch (key)
{
case VK_SHIFT:
case VK_LSHIFT:
case VK_RSHIFT:
case VK_CONTROL:
case VK_LCONTROL:
case VK_RCONTROL:
case VK_MENU:
case VK_LMENU:
case VK_RMENU:
case VK_LWIN:
case VK_RWIN:
case VK_CAPITAL:
case VK_NUMLOCK:
case VK_SCROLL:
case VK_APPS:
used = handleKeyUpOrDown (true);
sendModifierKeyChangeIfNeeded();
break;
case VK_LEFT:
case VK_RIGHT:
case VK_UP:
case VK_DOWN:
case VK_PRIOR:
case VK_NEXT:
case VK_HOME:
case VK_END:
case VK_DELETE:
case VK_INSERT:
case VK_F1:
case VK_F2:
case VK_F3:
case VK_F4:
case VK_F5:
case VK_F6:
case VK_F7:
case VK_F8:
case VK_F9:
case VK_F10:
case VK_F11:
case VK_F12:
case VK_F13:
case VK_F14:
case VK_F15:
case VK_F16:
case VK_F17:
case VK_F18:
case VK_F19:
case VK_F20:
case VK_F21:
case VK_F22:
case VK_F23:
case VK_F24:
used = handleKeyUpOrDown (true);
used = handleKeyPress (extendedKeyModifier | (int) key, 0) || used;
break;
default:
used = handleKeyUpOrDown (true);
{
MSG msg;
if (! PeekMessage (&msg, hwnd, WM_CHAR, WM_DEADCHAR, PM_NOREMOVE))
{
// if there isn't a WM_CHAR or WM_DEADCHAR message pending, we need to
// manually generate the key-press event that matches this key-down.
const UINT keyChar = MapVirtualKey ((UINT) key, 2);
const UINT scanCode = MapVirtualKey ((UINT) key, 0);
BYTE keyState[256];
[[maybe_unused]] const auto state = GetKeyboardState (keyState);
WCHAR text[16] = { 0 };
if (ToUnicode ((UINT) key, scanCode, keyState, text, 8, 0) != 1)
text[0] = 0;
used = handleKeyPress ((int) LOWORD (keyChar), (juce_wchar) text[0]) || used;
}
}
break;
}
return used || (Component::getCurrentlyModalComponent() != nullptr);
}
bool doKeyChar (int key, const LPARAM flags)
{
updateKeyModifiers();
auto textChar = (juce_wchar) key;
const int virtualScanCode = (flags >> 16) & 0xff;
if (key >= '0' && key <= '9')
{
switch (virtualScanCode) // check for a numeric keypad scan-code
{
case 0x52:
case 0x4f:
case 0x50:
case 0x51:
case 0x4b:
case 0x4c:
case 0x4d:
case 0x47:
case 0x48:
case 0x49:
key = (key - '0') + KeyPress::numberPad0;
break;
default:
break;
}
}
else
{
// convert the scan code to an unmodified character code..
const UINT virtualKey = MapVirtualKey ((UINT) virtualScanCode, 1);
UINT keyChar = MapVirtualKey (virtualKey, 2);
keyChar = LOWORD (keyChar);
if (keyChar != 0)
key = (int) keyChar;
// avoid sending junk text characters for some control-key combinations
if (textChar < ' ' && ModifierKeys::getCurrentModifiers().testFlags (ModifierKeys::ctrlModifier | ModifierKeys::altModifier))
textChar = 0;
}
return handleKeyPress (key, textChar);
}
void forwardMessageToParent (UINT message, WPARAM wParam, LPARAM lParam) const
{
if (HWND parentH = GetParent (hwnd))
PostMessage (parentH, message, wParam, lParam);
}
bool doAppCommand (const LPARAM lParam)
{
int key = 0;
switch (GET_APPCOMMAND_LPARAM (lParam))
{
case APPCOMMAND_MEDIA_PLAY_PAUSE: key = KeyPress::playKey; break;
case APPCOMMAND_MEDIA_STOP: key = KeyPress::stopKey; break;
case APPCOMMAND_MEDIA_NEXTTRACK: key = KeyPress::fastForwardKey; break;
case APPCOMMAND_MEDIA_PREVIOUSTRACK: key = KeyPress::rewindKey; break;
default: break;
}
if (key != 0)
{
updateKeyModifiers();
if (hwnd == GetActiveWindow())
return handleKeyPress (key, 0);
}
return false;
}
bool isConstrainedNativeWindow() const
{
return constrainer != nullptr && ! isKioskMode();
}
LRESULT handleSizeConstraining (RECT& r, const WPARAM wParam)
{
if (isConstrainedNativeWindow())
{
const auto movingTop = wParam == WMSZ_TOP || wParam == WMSZ_TOPLEFT || wParam == WMSZ_TOPRIGHT;
const auto movingLeft = wParam == WMSZ_LEFT || wParam == WMSZ_TOPLEFT || wParam == WMSZ_BOTTOMLEFT;
const auto movingBottom = wParam == WMSZ_BOTTOM || wParam == WMSZ_BOTTOMLEFT || wParam == WMSZ_BOTTOMRIGHT;
const auto movingRight = wParam == WMSZ_RIGHT || wParam == WMSZ_TOPRIGHT || wParam == WMSZ_BOTTOMRIGHT;
const auto requestedPhysicalBounds = D2DUtilities::toRectangle (r);
const auto modifiedPhysicalBounds = getConstrainedBounds (requestedPhysicalBounds,
movingTop,
movingLeft,
movingBottom,
movingRight);
if (! modifiedPhysicalBounds.has_value())
return TRUE;
r = D2DUtilities::toRECT (*modifiedPhysicalBounds);
}
return TRUE;
}
LRESULT handlePositionChanging (WINDOWPOS& wp)
{
if (isConstrainedNativeWindow() && ! isFullScreen())
{
if ((wp.flags & (SWP_NOMOVE | SWP_NOSIZE)) != (SWP_NOMOVE | SWP_NOSIZE)
&& (wp.x > -32000 && wp.y > -32000)
&& ! Component::isMouseButtonDownAnywhere())
{
const auto requestedPhysicalBounds = D2DUtilities::toRectangle ({ wp.x, wp.y, wp.x + wp.cx, wp.y + wp.cy });
if (const auto modifiedPhysicalBounds = getConstrainedBounds (requestedPhysicalBounds, false, false, false, false))
{
wp.x = modifiedPhysicalBounds->getX();
wp.y = modifiedPhysicalBounds->getY();
wp.cx = modifiedPhysicalBounds->getWidth();
wp.cy = modifiedPhysicalBounds->getHeight();
}
}
}
if (((wp.flags & SWP_SHOWWINDOW) != 0 && ! component.isVisible()))
component.setVisible (true);
else if (((wp.flags & SWP_HIDEWINDOW) != 0 && component.isVisible()))
component.setVisible (false);
return 0;
}
std::optional<Rectangle<int>> getConstrainedBounds (Rectangle<int> proposed,
bool top,
bool left,
bool bottom,
bool right) const
{
const auto physicalBorder = findPhysicalBorderSize();
if (! physicalBorder.has_value())
return {};
const auto logicalBorder = getFrameSize();
// The constrainer expects to operate in logical coordinate space.
// Additionally, the ComponentPeer can only report the current frame size as an integral
// number of logical pixels, but at fractional scale factors it may not be possible to
// express the logical frame size accurately as an integer.
// To work around this, we replace the physical borders with the currently-reported logical
// border size before invoking the constrainer.
// After the constrainer returns, we substitute in the other direction, replacing logical
// borders with physical.
const auto requestedPhysicalBounds = proposed;
const auto requestedPhysicalClient = physicalBorder->subtractedFrom (requestedPhysicalBounds);
const auto requestedLogicalClient = detail::ScalingHelpers::unscaledScreenPosToScaled (
component,
convertPhysicalScreenRectangleToLogical (requestedPhysicalClient, hwnd));
const auto requestedLogicalBounds = logicalBorder.addedTo (requestedLogicalClient);
const auto originalLogicalBounds = logicalBorder.addedTo (component.getBounds());
auto modifiedLogicalBounds = requestedLogicalBounds;
constrainer->checkBounds (modifiedLogicalBounds,
originalLogicalBounds,
Desktop::getInstance().getDisplays().getTotalBounds (true),
top,
left,
bottom,
right);
const auto modifiedLogicalClient = logicalBorder.subtractedFrom (modifiedLogicalBounds);
const auto modifiedPhysicalClient = convertLogicalScreenRectangleToPhysical (
detail::ScalingHelpers::scaledScreenPosToUnscaled (component, modifiedLogicalClient).toFloat(),
hwnd);
const auto closestIntegralSize = modifiedPhysicalClient
.withPosition (requestedPhysicalClient.getPosition().toFloat())
.getLargestIntegerWithin();
const auto withSnappedPosition = [&]
{
auto modified = closestIntegralSize;
if (left || right)
{
modified = left ? modified.withRightX (requestedPhysicalClient.getRight())
: modified.withX (requestedPhysicalClient.getX());
}
if (top || bottom)
{
modified = top ? modified.withBottomY (requestedPhysicalClient.getBottom())
: modified.withY (requestedPhysicalClient.getY());
}
return modified;
}();
return physicalBorder->addedTo (withSnappedPosition);
}
enum class ForceRefreshDispatcher
{
no,
yes
};
static void updateVBlankDispatcherForAllPeers (ForceRefreshDispatcher force = ForceRefreshDispatcher::no)
{
// There's an edge case where only top-level windows seem to get WM_SETTINGCHANGE
// messages, which means that if we have a plugin that opens its own top-level/desktop
// window, then the extra window might get a SETTINGCHANGE but the plugin window may not.
// If we only update the vblank dispatcher for windows that get a SETTINGCHANGE, we might
// miss child windows, and those windows won't be able to repaint.
for (auto i = getNumPeers(); --i >= 0;)
if (auto* peer = static_cast<HWNDComponentPeer*> (getPeer (i)))
peer->updateCurrentMonitorAndRefreshVBlankDispatcher (force);
}
void updateCurrentMonitorAndRefreshVBlankDispatcher (ForceRefreshDispatcher force = ForceRefreshDispatcher::no)
{
auto monitor = MonitorFromWindow (hwnd, MONITOR_DEFAULTTONULL);
if (std::exchange (currentMonitor, monitor) != monitor || force == ForceRefreshDispatcher::yes)
VBlankDispatcher::getInstance()->updateDisplay (*this, currentMonitor);
}
bool handlePositionChanged()
{
auto pos = getCurrentMousePos();
if (contains (pos.roundToInt(), false))
{
const ScopedValueSetter<bool> scope (inHandlePositionChanged, true);
if (! areOtherTouchSourcesActive())
{
auto modsToSend = ModifierKeys::getCurrentModifiers();
if (! Desktop::getInstance().getMainMouseSource().isDragging())
modsToSend = modsToSend.withoutMouseButtons();
doMouseEvent (pos, MouseInputSource::defaultPressure, 0.0f, modsToSend);
}
if (! isValidPeer (this))
return true;
}
handleMovedOrResized();
updateCurrentMonitorAndRefreshVBlankDispatcher();
return ! dontRepaint; // to allow non-accelerated openGL windows to draw themselves correctly.
}
//==============================================================================
LRESULT handleDPIChanging (int newDPI, RECT newRect)
{
// Sometimes, windows that should not be automatically scaled (secondary windows in plugins)
// are sent WM_DPICHANGED. The size suggested by the OS is incorrect for our unscaled
// window, so we should ignore it.
if (! isPerMonitorDPIAwareWindow (hwnd))
return 0;
const auto newScale = (double) newDPI / USER_DEFAULT_SCREEN_DPI;
if (approximatelyEqual (scaleFactor, newScale))
return 0;
scaleFactor = newScale;
{
const ScopedValueSetter<bool> setter (inDpiChange, true);
SetWindowPos (hwnd,
nullptr,
newRect.left,
newRect.top,
newRect.right - newRect.left,
newRect.bottom - newRect.top,
SWP_NOZORDER | SWP_NOACTIVATE);
}
// This is to handle reentrancy. If responding to a DPI change triggers further DPI changes,
// we should only notify listeners and resize windows once all of the DPI changes have
// resolved.
if (inDpiChange)
{
// Danger! Re-entrant call to handleDPIChanging.
// Please report this issue on the JUCE forum, along with instructions
// so that a JUCE developer can reproduce the issue.
jassertfalse;
return 0;
}
updateShadower();
InvalidateRect (hwnd, nullptr, FALSE);
scaleFactorListeners.call ([this] (ScaleFactorListener& l) { l.nativeScaleFactorChanged (scaleFactor); });
return 0;
}
//==============================================================================
void handleAppActivation (const WPARAM wParam)
{
modifiersAtLastCallback = -1;
updateKeyModifiers();
if (isMinimised())
{
component.repaint();
handleMovedOrResized();
if (! isValidPeer (this))
return;
}
auto* underMouse = component.getComponentAt (component.getMouseXYRelative());
if (underMouse == nullptr)
underMouse = &component;
if (underMouse->isCurrentlyBlockedByAnotherModalComponent())
{
if (LOWORD (wParam) == WA_CLICKACTIVE)
Component::getCurrentlyModalComponent()->inputAttemptWhenModal();
else
ModalComponentManager::getInstance()->bringModalComponentsToFront();
}
else
{
handleBroughtToFront();
}
}
void handlePowerBroadcast (WPARAM wParam)
{
if (auto* app = JUCEApplicationBase::getInstance())
{
switch (wParam)
{
case PBT_APMSUSPEND: app->suspended(); break;
case PBT_APMQUERYSUSPENDFAILED:
case PBT_APMRESUMECRITICAL:
case PBT_APMRESUMESUSPEND:
case PBT_APMRESUMEAUTOMATIC: app->resumed(); break;
default: break;
}
}
}
void handleLeftClickInNCArea (WPARAM wParam)
{
if (sendInputAttemptWhenModalMessage())
return;
switch (wParam)
{
case HTBOTTOM:
case HTBOTTOMLEFT:
case HTBOTTOMRIGHT:
case HTGROWBOX:
case HTLEFT:
case HTRIGHT:
case HTTOP:
case HTTOPLEFT:
case HTTOPRIGHT:
if (isConstrainedNativeWindow())
{
constrainerIsResizing = true;
constrainer->resizeStart();
}
return;
default:
break;
}
}
void initialiseSysMenu (HMENU menu) const
{
if (! hasTitleBar())
{
if (isFullScreen())
{
EnableMenuItem (menu, SC_RESTORE, MF_BYCOMMAND | MF_ENABLED);
EnableMenuItem (menu, SC_MOVE, MF_BYCOMMAND | MF_GRAYED);
}
else if (! isMinimised())
{
EnableMenuItem (menu, SC_MAXIMIZE, MF_BYCOMMAND | MF_GRAYED);
}
}
}
void doSettingChange()
{
forceDisplayUpdate();
auto* dispatcher = VBlankDispatcher::getInstance();
dispatcher->reconfigureDisplays();
updateVBlankDispatcherForAllPeers (ForceRefreshDispatcher::yes);
}
//==============================================================================
#if JUCE_MODULE_AVAILABLE_juce_audio_plugin_client
void setModifierKeyProvider (ModifierKeyProvider* provider) override
{
modProvider = provider;
}
void removeModifierKeyProvider() override
{
modProvider = nullptr;
}
#endif
static LRESULT CALLBACK windowProc (HWND h, UINT message, WPARAM wParam, LPARAM lParam)
{
// Ensure that non-client areas are scaled for per-monitor DPI awareness v1 - can't
// do this in peerWindowProc as we have no window at this point
if (message == WM_NCCREATE)
NullCheckedInvocation::invoke (enableNonClientDPIScaling, h);
if (auto* peer = getOwnerOfWindow (h))
{
jassert (isValidPeer (peer));
return peer->peerWindowProc (h, message, wParam, lParam);
}
return DefWindowProcW (h, message, wParam, lParam);
}
static void* callFunctionIfNotLocked (MessageCallbackFunction* callback, void* userData)
{
auto& mm = *MessageManager::getInstance();
if (mm.currentThreadHasLockedMessageManager())
return callback (userData);
return mm.callFunctionOnMessageThread (callback, userData);
}
static POINT getPOINTFromLParam (LPARAM lParam) noexcept
{
return { GET_X_LPARAM (lParam), GET_Y_LPARAM (lParam) };
}
Point<float> getLocalPointFromScreenLParam (LPARAM lParam)
{
const auto globalPos = D2DUtilities::toPoint (getPOINTFromLParam (lParam));
return globalToLocal (convertPhysicalScreenPointToLogical (globalPos, hwnd).toFloat());
}
Point<float> getPointFromLocalLParam (LPARAM lParam) noexcept
{
const auto p = D2DUtilities::toPoint (getPOINTFromLParam (lParam));
if (! isPerMonitorDPIAwareWindow (hwnd))
return p.toFloat();
// LPARAM is relative to this window's top-left but may be on a different monitor so we need to calculate the
// physical screen position and then convert this to local logical coordinates
auto r = getWindowScreenRect (hwnd);
const auto windowBorder = findPhysicalBorderSize().value_or (BorderSize<int>{});
const auto offset = p
+ Point { (int) r.left, (int) r.top }
+ Point { windowBorder.getLeft(), windowBorder.getTop() };
return globalToLocal (Desktop::getInstance().getDisplays().physicalToLogical (offset).toFloat());
}
Point<float> getCurrentMousePos() noexcept
{
return globalToLocal (convertPhysicalScreenPointToLogical (D2DUtilities::toPoint (getPOINTFromLParam ((LPARAM) GetMessagePos())), hwnd).toFloat());
}
static ModifierKeys getMouseModifiers()
{
updateKeyModifiers();
int mouseMods = 0;
if (isKeyDown (VK_LBUTTON)) mouseMods |= ModifierKeys::leftButtonModifier;
if (isKeyDown (VK_RBUTTON)) mouseMods |= ModifierKeys::rightButtonModifier;
if (isKeyDown (VK_MBUTTON)) mouseMods |= ModifierKeys::middleButtonModifier;
ModifierKeys::currentModifiers = ModifierKeys::getCurrentModifiers().withoutMouseButtons().withFlags (mouseMods);
return ModifierKeys::getCurrentModifiers();
}
std::optional<LRESULT> onNcLButtonDown (WPARAM wParam, LPARAM lParam)
{
handleLeftClickInNCArea (wParam);
switch (wParam)
{
case HTCLOSE:
case HTMAXBUTTON:
case HTMINBUTTON:
// The default implementation in DefWindowProc for these functions has some
// unwanted behaviour. Specifically, it seems to draw some ugly grey buttons over
// our custom nonclient area, just for one frame.
// To avoid this, we handle the message ourselves. The actual handling happens
// in WM_NCLBUTTONUP.
return 0;
case HTCAPTION:
// The default click-in-caption handler appears to block the message loop until a
// mouse move is detected, which prevents the view from repainting. We want to keep
// painting, so log the click ourselves and only defer to DefWindowProc once the
// mouse moves with the button held.
captionMouseDown = lParam;
return 0;
}
return {};
}
void handleSetFocus()
{
/* When the HWND receives Focus from the system it sends a
UIA_AutomationFocusChangedEventId notification redirecting the focus to the HWND
itself. This is a built-in behaviour of the HWND.
This means that whichever JUCE managed provider was active before the entire
window lost and then regained the focus, loses its focused state, and the
window's root element will become focused under which all JUCE managed providers
can be found.
This needs to be reflected on currentlyFocusedHandler so that the JUCE
accessibility mechanisms can detect that the root window got the focus, and send
another FocusChanged event to the system to redirect focus to a JUCE managed
provider if necessary.
*/
AccessibilityHandler::clearCurrentlyFocusedHandler();
updateKeyModifiers();
handleFocusGain();
}
LRESULT peerWindowProc (HWND h, UINT message, WPARAM wParam, LPARAM lParam)
{
switch (message)
{
//==============================================================================
case WM_NCHITTEST:
{
if ((styleFlags & windowIgnoresMouseClicks) != 0)
return HTTRANSPARENT;
if (! hasTitleBar() && (styleFlags & windowIsTemporary) == 0 && parentToAddTo == nullptr)
{
if ((styleFlags & windowIsResizable) != 0)
if (const auto result = DefWindowProc (h, message, wParam, lParam); HTSIZEFIRST <= result && result <= HTSIZELAST)
return result;
const auto physicalPoint = D2DUtilities::toPoint (getPOINTFromLParam (lParam));
const auto logicalPoint = convertPhysicalScreenPointToLogical (physicalPoint, hwnd);
const auto localPoint = globalToLocal (logicalPoint.toFloat());
const auto componentPoint = detail::ScalingHelpers::unscaledScreenPosToScaled (component, localPoint);
const auto kind = component.findControlAtPoint (componentPoint);
using Kind = Component::WindowControlKind;
switch (kind)
{
case Kind::caption: return HTCAPTION;
case Kind::minimise: return HTMINBUTTON;
case Kind::maximise: return HTMAXBUTTON;
case Kind::close: return HTCLOSE;
case Kind::sizeTop: return HTTOP;
case Kind::sizeLeft: return HTLEFT;
case Kind::sizeRight: return HTRIGHT;
case Kind::sizeBottom: return HTBOTTOM;
case Kind::sizeTopLeft: return HTTOPLEFT;
case Kind::sizeTopRight: return HTTOPRIGHT;
case Kind::sizeBottomLeft: return HTBOTTOMLEFT;
case Kind::sizeBottomRight: return HTBOTTOMRIGHT;
case Kind::client:
break;
}
// For a bordered window, Windows would normally let you resize by hovering just
// outside the client area (over the drop shadow).
// When we disable the border by doing nothing in WM_NCCALCSIZE, the client
// size will match the total window size.
// It seems that, when there's no nonclient area, Windows won't send us
// WM_NCHITTEST when hovering the window shadow.
// We only start getting NCHITTEST messages once the cursor is inside the client
// area.
// The upshot of all this is that we need to emulate the resizable border
// ourselves, but inside the window.
// Other borderless apps (1Password, Spotify, VS Code) seem to do the same thing,
// and if Microsoft's own VS Code doesn't have perfect mouse handling I don't
// think we can be expected to either!
if ((styleFlags & windowIsResizable) != 0 && ! isKioskMode())
{
const ScopedThreadDPIAwarenessSetter scope { hwnd };
const auto cursor = getPOINTFromLParam (lParam);
RECT client{};
::GetWindowRect (h, &client);
const auto dpi = GetDpiForWindow (hwnd);
const auto padding = GetSystemMetricsForDpi (SM_CXPADDEDBORDER, dpi);
const auto borderX = GetSystemMetricsForDpi (SM_CXFRAME, dpi) + padding;
const auto borderY = GetSystemMetricsForDpi (SM_CYFRAME, dpi) + padding;
const auto left = cursor.x < client.left + borderX;
const auto right = client.right - borderX < cursor.x;
const auto top = cursor.y < client.top + borderY;
const auto bottom = client.bottom - borderY < cursor.y;
enum Bits
{
bitL = 1 << 0,
bitR = 1 << 1,
bitT = 1 << 2,
bitB = 1 << 3,
};
const auto positionMask = (left ? bitL : 0)
| (right ? bitR : 0)
| (top ? bitT : 0)
| (bottom ? bitB : 0);
switch (positionMask)
{
case bitL: return HTLEFT;
case bitR: return HTRIGHT;
case bitT: return HTTOP;
case bitB: return HTBOTTOM;
case bitT | bitL: return HTTOPLEFT;
case bitT | bitR: return HTTOPRIGHT;
case bitB | bitL: return HTBOTTOMLEFT;
case bitB | bitR: return HTBOTTOMRIGHT;
}
}
return HTCLIENT;
}
break;
}
//==============================================================================
case WM_PAINT:
handlePaintMessage();
return 0;
case WM_NCPAINT:
// this must be done, even with native titlebars, or there are rendering artifacts.
handlePaintMessage();
// Even if we're *not* using a native titlebar (i.e. extending into the nonclient area)
// the system needs to handle the NCPAINT to draw rounded corners and shadows.
break;
case WM_ERASEBKGND:
if (hasTitleBar())
break;
return 1;
case WM_NCCALCSIZE:
{
// If we're using the native titlebar, then the default window proc behaviour will
// do the right thing.
if (hasTitleBar())
break;
auto* param = (RECT*) lParam;
// If we're not using a native titlebar, and the window is maximised, then the
// proposed window may be a bit bigger than the available space. Remove the padding
// so that the client area exactly fills the available space.
if (isFullScreen())
{
const auto monitor = MonitorFromWindow (hwnd, MONITOR_DEFAULTTONULL);
if (monitor == nullptr)
return 0;
MONITORINFOEX info{};
info.cbSize = sizeof (info);
GetMonitorInfo (monitor, &info);
const auto padX = info.rcMonitor.left - param->left;
const auto padY = info.rcMonitor.top - param->top;
param->left += padX;
param->right -= padX;
param->top += padY;
param->bottom -= padY;
}
return 0;
}
//==============================================================================
case WM_POINTERUPDATE:
if (handlePointerInput (wParam, lParam, false, false))
return 0;
break;
case WM_POINTERDOWN:
if (handlePointerInput (wParam, lParam, true, false))
return 0;
break;
case WM_POINTERUP:
if (handlePointerInput (wParam, lParam, false, true))
return 0;
break;
//==============================================================================
case WM_NCMOUSEMOVE:
case WM_MOUSEMOVE:
return doMouseMove (lParam, false, message == WM_MOUSEMOVE ? WindowArea::client : WindowArea::nonclient).value_or (0);
case WM_POINTERLEAVE:
case WM_NCMOUSELEAVE:
case WM_MOUSELEAVE:
doMouseExit (message == WM_NCMOUSELEAVE ? WindowArea::nonclient : WindowArea::client);
return 0;
case WM_LBUTTONDOWN:
case WM_MBUTTONDOWN:
case WM_RBUTTONDOWN:
case WM_XBUTTONDOWN:
doMouseDown (lParam, wParam);
return 0;
case WM_LBUTTONUP:
case WM_MBUTTONUP:
case WM_RBUTTONUP:
case WM_XBUTTONUP:
doMouseUp (getPointFromLocalLParam (lParam), wParam);
return 0;
case WM_POINTERWHEEL:
case WM_MOUSEWHEEL:
if (doMouseWheel (wParam, true))
return 0;
break;
case WM_POINTERHWHEEL:
case WM_MOUSEHWHEEL:
if (doMouseWheel (wParam, false))
return 0;
break;
case WM_CAPTURECHANGED:
doCaptureChanged();
return 0;
case WM_TOUCH:
if (getTouchInputInfo != nullptr)
return doTouchEvent ((int) wParam, (HTOUCHINPUT) lParam);
break;
case 0x119: /* WM_GESTURE */
if (doGestureEvent (lParam))
return 0;
break;
//==============================================================================
case WM_ENTERSIZEMOVE:
sizing = true;
break;
case WM_EXITSIZEMOVE:
sizing = false;
break;
case WM_SIZING:
sizing = true;
return handleSizeConstraining (*(RECT*) lParam, wParam);
case WM_MOVING:
return handleSizeConstraining (*(RECT*) lParam, 0);
case WM_WINDOWPOSCHANGING:
if (hasTitleBar() && sizing)
break;
return handlePositionChanging (*(WINDOWPOS*) lParam);
case 0x2e0: /* WM_DPICHANGED */ return handleDPIChanging ((int) HIWORD (wParam), *(RECT*) lParam);
case WM_WINDOWPOSCHANGED:
{
const WINDOWPOS& wPos = *reinterpret_cast<WINDOWPOS*> (lParam);
if ((wPos.flags & SWP_NOMOVE) != 0 && (wPos.flags & SWP_NOSIZE) != 0)
startTimer (100);
else if (handlePositionChanged())
return 0;
}
break;
//==============================================================================
case WM_KEYDOWN:
case WM_SYSKEYDOWN:
if (doKeyDown (wParam))
return 0;
forwardMessageToParent (message, wParam, lParam);
break;
case WM_KEYUP:
case WM_SYSKEYUP:
if (doKeyUp (wParam))
return 0;
forwardMessageToParent (message, wParam, lParam);
break;
case WM_CHAR:
if (doKeyChar ((int) wParam, lParam))
return 0;
forwardMessageToParent (message, wParam, lParam);
break;
case WM_APPCOMMAND:
if (doAppCommand (lParam))
return TRUE;
break;
case WM_MENUCHAR: // triggered when alt+something is pressed
return MNC_CLOSE << 16; // (avoids making the default system beep)
//==============================================================================
case WM_SETFOCUS:
mouseActivateFlags |= gotSetFocus;
// If we've received a MOUSEACTIVATE, wait until we've seen the relevant mouse event
// before updating the focus.
if ((mouseActivateFlags & gotMouseActivate) != 0)
break;
handleSetFocus();
break;
case WM_KILLFOCUS:
if (hasCreatedCaret)
{
hasCreatedCaret = false;
DestroyCaret();
}
handleFocusLoss();
if (auto* modal = Component::getCurrentlyModalComponent())
if (auto* peer = modal->getPeer())
if ((peer->getStyleFlags() & windowIsTemporary) != 0)
sendInputAttemptWhenModalMessage();
break;
case WM_ACTIVATEAPP:
// Windows does weird things to process priority when you swap apps,
// so this forces an update when the app is brought to the front
if (wParam != FALSE)
juce_repeatLastProcessPriority();
else
Desktop::getInstance().setKioskModeComponent (nullptr); // turn kiosk mode off if we lose focus
detail::TopLevelWindowManager::checkCurrentlyFocusedTopLevelWindow();
modifiersAtLastCallback = -1;
return 0;
case WM_ACTIVATE:
if (LOWORD (wParam) == WA_ACTIVE || LOWORD (wParam) == WA_CLICKACTIVE)
{
handleAppActivation (wParam);
return 0;
}
break;
case WM_NCACTIVATE:
// while a temporary window is being shown, prevent Windows from deactivating the
// title bars of our main windows.
if (wParam == 0 && ! shouldDeactivateTitleBar)
wParam = TRUE; // change this and let it get passed to the DefWindowProc.
break;
case WM_POINTERACTIVATE:
case WM_MOUSEACTIVATE:
{
mouseActivateFlags = 0;
if (! component.getMouseClickGrabsKeyboardFocus())
return MA_NOACTIVATE;
mouseActivateFlags |= gotMouseActivate;
break;
}
case WM_SHOWWINDOW:
if (wParam != 0)
{
component.setVisible (true);
handleBroughtToFront();
if (renderContext != nullptr)
renderContext->handleShowWindow();
}
break;
case WM_CLOSE:
if (! component.isCurrentlyBlockedByAnotherModalComponent())
handleUserClosingWindow();
return 0;
#if JUCE_REMOVE_COMPONENT_FROM_DESKTOP_ON_WM_DESTROY
case WM_DESTROY:
getComponent().removeFromDesktop();
return 0;
#endif
case WM_QUERYENDSESSION:
if (auto* app = JUCEApplicationBase::getInstance())
{
app->systemRequestedQuit();
return MessageManager::getInstance()->hasStopMessageBeenSent();
}
return TRUE;
case WM_POWERBROADCAST:
handlePowerBroadcast (wParam);
break;
case WM_SYNCPAINT:
return 0;
case WM_DISPLAYCHANGE:
InvalidateRect (h, nullptr, 0);
// intentional fall-through...
JUCE_FALLTHROUGH
case WM_SETTINGCHANGE: // note the fall-through in the previous case!
doSettingChange();
break;
case WM_INITMENU:
initialiseSysMenu ((HMENU) wParam);
break;
case WM_SYSCOMMAND:
switch (wParam & 0xfff0)
{
case SC_CLOSE:
if (sendInputAttemptWhenModalMessage())
return 0;
PostMessage (h, WM_CLOSE, 0, 0);
return 0;
case SC_KEYMENU:
#if ! JUCE_WINDOWS_ALT_KEY_TRIGGERS_MENU
// This test prevents a press of the ALT key from triggering the ancient top-left window menu.
// By default we suppress this behaviour because it's unlikely that more than a tiny subset of
// our users will actually want it, and it causes problems if you're trying to use the ALT key
// as a modifier for mouse actions. If you really need the old behaviour, then just define
// JUCE_WINDOWS_ALT_KEY_TRIGGERS_MENU=1 in your app.
if ((lParam >> 16) <= 0) // Values above zero indicate that a mouse-click triggered the menu
return 0;
#endif
// (NB mustn't call sendInputAttemptWhenModalMessage() here because of very obscure
// situations that can arise if a modal loop is started from an alt-key keypress).
if (h == GetCapture())
ReleaseCapture();
break;
case SC_MAXIMIZE:
if (sendInputAttemptWhenModalMessage())
return 0;
setFullScreen (true);
return 0;
case SC_MINIMIZE:
if (sendInputAttemptWhenModalMessage())
return 0;
setMinimised (true);
return 0;
case SC_RESTORE:
if (sendInputAttemptWhenModalMessage())
return 0;
if (hasTitleBar())
{
if (isFullScreen())
{
setFullScreen (false);
return 0;
}
}
else
{
if (isMinimised())
setMinimised (false);
else if (isFullScreen())
setFullScreen (false);
return 0;
}
break;
}
break;
case WM_NCPOINTERDOWN:
handleLeftClickInNCArea (HIWORD (wParam));
break;
case WM_NCLBUTTONDOWN:
{
if (auto result = onNcLButtonDown (wParam, lParam))
return *result;
return handleNcMouseEventThenFixModifiers (WM_NCLBUTTONDOWN, wParam, lParam);
}
case WM_NCLBUTTONUP:
switch (wParam)
{
case HTCLOSE:
if ((styleFlags & windowHasCloseButton) != 0 && ! sendInputAttemptWhenModalMessage())
{
if (hasTitleBar())
PostMessage (h, WM_CLOSE, 0, 0);
else
component.windowControlClickedClose();
}
return 0;
case HTMAXBUTTON:
if ((styleFlags & windowHasMaximiseButton) != 0 && ! sendInputAttemptWhenModalMessage())
{
if (hasTitleBar())
setFullScreen (! isFullScreen());
else
component.windowControlClickedMaximise();
}
return 0;
case HTMINBUTTON:
if ((styleFlags & windowHasMinimiseButton) != 0 && ! sendInputAttemptWhenModalMessage())
{
if (hasTitleBar())
setMinimised (true);
else
component.windowControlClickedMinimise();
}
return 0;
}
break;
case WM_NCRBUTTONDOWN:
case WM_NCMBUTTONDOWN:
sendInputAttemptWhenModalMessage();
return 0;
case WM_IME_SETCONTEXT:
imeHandler.handleSetContext (h, wParam == TRUE);
lParam &= ~(LPARAM) ISC_SHOWUICOMPOSITIONWINDOW;
break;
case WM_IME_STARTCOMPOSITION: imeHandler.handleStartComposition (*this); return 0;
case WM_IME_ENDCOMPOSITION: imeHandler.handleEndComposition (*this, h); return 0;
case WM_IME_COMPOSITION: imeHandler.handleComposition (*this, h, lParam); return 0;
case WM_GETDLGCODE:
return DLGC_WANTALLKEYS;
case WM_GETOBJECT:
{
if (static_cast<long> (lParam) == WindowsAccessibility::getUiaRootObjectId())
{
if (auto* handler = component.getAccessibilityHandler())
{
LRESULT res = 0;
if (WindowsAccessibility::handleWmGetObject (handler, wParam, lParam, &res))
{
isAccessibilityActive = true;
return res;
}
}
}
break;
}
default:
break;
}
return DefWindowProc (h, message, wParam, lParam);
}
bool sendInputAttemptWhenModalMessage()
{
if (! component.isCurrentlyBlockedByAnotherModalComponent())
return false;
if (auto* current = Component::getCurrentlyModalComponent())
if (auto* owner = getOwnerOfWindow ((HWND) current->getWindowHandle()))
if (! owner->shouldIgnoreModalDismiss)
current->inputAttemptWhenModal();
return true;
}
//==============================================================================
struct IMEHandler
{
IMEHandler()
{
reset();
}
void handleSetContext (HWND hWnd, const bool windowIsActive)
{
if (compositionInProgress && ! windowIsActive)
{
if (HIMC hImc = ImmGetContext (hWnd))
{
ImmNotifyIME (hImc, NI_COMPOSITIONSTR, CPS_COMPLETE, 0);
ImmReleaseContext (hWnd, hImc);
}
// If the composition is still in progress, calling ImmNotifyIME may call back
// into handleComposition to let us know that the composition has finished.
// We need to set compositionInProgress *after* calling handleComposition, so that
// the text replaces the current selection, rather than being inserted after the
// caret.
compositionInProgress = false;
}
}
void handleStartComposition (ComponentPeer& owner)
{
reset();
if (auto* target = owner.findCurrentTextInputTarget())
target->insertTextAtCaret (String());
}
void handleEndComposition (ComponentPeer& owner, HWND hWnd)
{
if (compositionInProgress)
{
// If this occurs, the user has cancelled the composition, so clear their changes..
if (auto* target = owner.findCurrentTextInputTarget())
{
target->setHighlightedRegion (compositionRange);
target->insertTextAtCaret (String());
compositionRange.setLength (0);
target->setHighlightedRegion (Range<int>::emptyRange (compositionRange.getEnd()));
target->setTemporaryUnderlining ({});
}
if (auto hImc = ImmGetContext (hWnd))
{
ImmNotifyIME (hImc, NI_CLOSECANDIDATE, 0, 0);
ImmReleaseContext (hWnd, hImc);
}
}
reset();
}
void handleComposition (ComponentPeer& owner, HWND hWnd, const LPARAM lParam)
{
if (auto* target = owner.findCurrentTextInputTarget())
{
if (auto hImc = ImmGetContext (hWnd))
{
if (compositionRange.getStart() < 0)
compositionRange = Range<int>::emptyRange (target->getHighlightedRegion().getStart());
if ((lParam & GCS_RESULTSTR) != 0) // (composition has finished)
{
replaceCurrentSelection (target, getCompositionString (hImc, GCS_RESULTSTR),
Range<int>::emptyRange (-1));
reset();
target->setTemporaryUnderlining ({});
}
else if ((lParam & GCS_COMPSTR) != 0) // (composition is still in-progress)
{
replaceCurrentSelection (target, getCompositionString (hImc, GCS_COMPSTR),
getCompositionSelection (hImc, lParam));
target->setTemporaryUnderlining (getCompositionUnderlines (hImc, lParam));
compositionInProgress = true;
}
moveCandidateWindowToLeftAlignWithSelection (hImc, owner, target);
ImmReleaseContext (hWnd, hImc);
}
}
}
private:
//==============================================================================
Range<int> compositionRange; // The range being modified in the TextInputTarget
bool compositionInProgress;
//==============================================================================
void reset()
{
compositionRange = Range<int>::emptyRange (-1);
compositionInProgress = false;
}
String getCompositionString (HIMC hImc, const DWORD type) const
{
jassert (hImc != HIMC{});
const auto stringSizeBytes = ImmGetCompositionString (hImc, type, nullptr, 0);
if (stringSizeBytes > 0)
{
HeapBlock<TCHAR> buffer;
buffer.calloc ((size_t) stringSizeBytes / sizeof (TCHAR) + 1);
ImmGetCompositionString (hImc, type, buffer, (DWORD) stringSizeBytes);
return String (buffer.get());
}
return {};
}
int getCompositionCaretPos (HIMC hImc, LPARAM lParam, const String& currentIMEString) const
{
jassert (hImc != HIMC{});
if ((lParam & CS_NOMOVECARET) != 0)
return compositionRange.getStart();
if ((lParam & GCS_CURSORPOS) != 0)
{
const int localCaretPos = ImmGetCompositionString (hImc, GCS_CURSORPOS, nullptr, 0);
return compositionRange.getStart() + jmax (0, localCaretPos);
}
return compositionRange.getStart() + currentIMEString.length();
}
// Get selected/highlighted range while doing composition:
// returned range is relative to beginning of TextInputTarget, not composition string
Range<int> getCompositionSelection (HIMC hImc, LPARAM lParam) const
{
jassert (hImc != HIMC{});
int selectionStart = 0;
int selectionEnd = 0;
if ((lParam & GCS_COMPATTR) != 0)
{
// Get size of attributes array:
const int attributeSizeBytes = ImmGetCompositionString (hImc, GCS_COMPATTR, nullptr, 0);
if (attributeSizeBytes > 0)
{
// Get attributes (8 bit flag per character):
HeapBlock<char> attributes (attributeSizeBytes);
ImmGetCompositionString (hImc, GCS_COMPATTR, attributes, (DWORD) attributeSizeBytes);
selectionStart = 0;
for (selectionStart = 0; selectionStart < attributeSizeBytes; ++selectionStart)
if (attributes[selectionStart] == ATTR_TARGET_CONVERTED || attributes[selectionStart] == ATTR_TARGET_NOTCONVERTED)
break;
for (selectionEnd = selectionStart; selectionEnd < attributeSizeBytes; ++selectionEnd)
if (attributes[selectionEnd] != ATTR_TARGET_CONVERTED && attributes[selectionEnd] != ATTR_TARGET_NOTCONVERTED)
break;
}
}
return Range<int> (selectionStart, selectionEnd) + compositionRange.getStart();
}
void replaceCurrentSelection (TextInputTarget* const target, const String& newContent, Range<int> newSelection)
{
if (compositionInProgress)
target->setHighlightedRegion (compositionRange);
target->insertTextAtCaret (newContent);
compositionRange.setLength (newContent.length());
if (newSelection.getStart() < 0)
newSelection = Range<int>::emptyRange (compositionRange.getEnd());
target->setHighlightedRegion (newSelection);
}
Array<Range<int>> getCompositionUnderlines (HIMC hImc, LPARAM lParam) const
{
Array<Range<int>> result;
if (hImc != HIMC{} && (lParam & GCS_COMPCLAUSE) != 0)
{
auto clauseDataSizeBytes = ImmGetCompositionString (hImc, GCS_COMPCLAUSE, nullptr, 0);
if (clauseDataSizeBytes > 0)
{
const auto numItems = (size_t) clauseDataSizeBytes / sizeof (uint32);
HeapBlock<uint32> clauseData (numItems);
if (ImmGetCompositionString (hImc, GCS_COMPCLAUSE, clauseData, (DWORD) clauseDataSizeBytes) > 0)
for (size_t i = 0; i + 1 < numItems; ++i)
result.add (Range<int> ((int) clauseData[i], (int) clauseData[i + 1]) + compositionRange.getStart());
}
}
return result;
}
void moveCandidateWindowToLeftAlignWithSelection (HIMC hImc, ComponentPeer& peer, TextInputTarget* target) const
{
if (auto* targetComp = dynamic_cast<Component*> (target))
{
const auto screenPos = targetComp->localPointToGlobal (target->getCaretRectangle().getBottomLeft());
const auto relativePos = peer.globalToLocal (screenPos) * peer.getPlatformScaleFactor();
CANDIDATEFORM pos { 0, CFS_CANDIDATEPOS, D2DUtilities::toPOINT (relativePos), { 0, 0, 0, 0 } };
ImmSetCandidateWindow (hImc, &pos);
}
}
JUCE_DECLARE_NON_COPYABLE (IMEHandler)
};
void timerCallback() override
{
handlePositionChanged();
stopTimer();
}
static bool isAncestor (HWND outer, HWND inner)
{
if (outer == nullptr || inner == nullptr)
return false;
if (outer == inner)
return true;
return isAncestor (outer, GetAncestor (inner, GA_PARENT));
}
void windowShouldDismissModals (HWND originator)
{
if (shouldIgnoreModalDismiss)
return;
if (isAncestor (originator, hwnd))
sendInputAttemptWhenModalMessage();
}
// Unfortunately SetWindowsHookEx only allows us to register a static function as a hook.
// To get around this, we keep a static list of listeners which are interested in
// top-level window events, and notify all of these listeners from the callback.
class TopLevelModalDismissBroadcaster
{
public:
TopLevelModalDismissBroadcaster()
: hook (SetWindowsHookEx (WH_CALLWNDPROC,
callWndProc,
(HINSTANCE) juce::Process::getCurrentModuleInstanceHandle(),
GetCurrentThreadId()))
{}
~TopLevelModalDismissBroadcaster() noexcept
{
UnhookWindowsHookEx (hook);
}
private:
static void processMessage (int nCode, const CWPSTRUCT* info)
{
if (nCode < 0 || info == nullptr)
return;
constexpr UINT events[] { WM_MOVE,
WM_SIZE,
WM_WINDOWPOSCHANGING,
WM_NCPOINTERDOWN,
WM_NCLBUTTONDOWN,
WM_NCRBUTTONDOWN,
WM_NCMBUTTONDOWN };
if (std::find (std::begin (events), std::end (events), info->message) == std::end (events))
return;
if (info->message == WM_WINDOWPOSCHANGING)
{
const auto* windowPos = reinterpret_cast<const WINDOWPOS*> (info->lParam);
const auto windowPosFlags = windowPos->flags;
constexpr auto maskToCheck = SWP_NOMOVE | SWP_NOSIZE;
// This undocumented bit seems to get set when minimising/maximising windows with Win+D.
// If we attempt to dismiss modals while this bit is set, we might end up bringing
// modals to the front, which in turn may attempt to un-minimise them.
constexpr auto SWP_STATECHANGED = 0x8000;
if ((windowPosFlags & maskToCheck) == maskToCheck || (windowPosFlags & SWP_STATECHANGED) != 0)
return;
}
// windowMayDismissModals could affect the number of active ComponentPeer instances
for (auto i = ComponentPeer::getNumPeers(); --i >= 0;)
if (i < ComponentPeer::getNumPeers())
if (auto* hwndPeer = dynamic_cast<HWNDComponentPeer*> (ComponentPeer::getPeer (i)))
hwndPeer->windowShouldDismissModals (info->hwnd);
}
static LRESULT CALLBACK callWndProc (int nCode, WPARAM wParam, LPARAM lParam)
{
processMessage (nCode, reinterpret_cast<CWPSTRUCT*> (lParam));
return CallNextHookEx ({}, nCode, wParam, lParam);
}
HHOOK hook;
};
SharedResourcePointer<TopLevelModalDismissBroadcaster> modalDismissBroadcaster;
IMEHandler imeHandler;
bool shouldIgnoreModalDismiss = false;
/* When the user clicks on a window, the window gets sent WM_MOUSEACTIVATE, WM_ACTIVATE,
and WM_SETFOCUS, before sending a WM_LBUTTONDOWN or other pointer event.
However, if the WM_SETFOCUS message immediately calls SetFocus to move the focus to a
different window (e.g. a foreground modal window), then no mouse event will be sent to the
initially-activated window. This differs from the behaviour on other platforms, where the
mouse event always reaches the activated window. Failing to emit a mouse event breaks user
interaction: in the Toolbars pane of the WidgetsDemo, we create a foreground modal
customisation dialog. The window containing the toolbar is not modal, but still expects to
receive mouse events so that the toolbar buttons can be dragged around.
To avoid the system eating the mouse event sent to the initially-activated window, we
postpone processing the WM_SETFOCUS until *after* the activation mouse event.
*/
enum MouseActivateFlags : uint8_t
{
gotMouseActivate = 1 << 0,
gotSetFocus = 1 << 1,
};
uint8_t mouseActivateFlags = 0;
ScopedSuspendResumeNotificationRegistration suspendResumeRegistration;
std::optional<TimedCallback> monitorUpdateTimer;
std::unique_ptr<RenderContext> renderContext;
std::optional<LPARAM> captionMouseDown;
//==============================================================================
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (HWNDComponentPeer)
};
ComponentPeer* Component::createNewPeer (int styleFlags, void* parentHWND)
{
return new HWNDComponentPeer { *this, styleFlags, (HWND) parentHWND, false, 1 };
}
Image createSnapshotOfNativeWindow (void* nativeWindowHandle)
{
int numDesktopComponents = Desktop::getInstance().getNumComponents();
for (int index = 0; index < numDesktopComponents; ++index)
{
auto component = Desktop::getInstance().getComponent (index);
if (auto peer = dynamic_cast<HWNDComponentPeer*> (component->getPeer()))
if (peer->getNativeHandle() == nativeWindowHandle)
return peer->createSnapshot();
}
return {};
}
class GDIRenderContext : public RenderContext
{
public:
static constexpr auto name = "Software Renderer";
explicit GDIRenderContext (HWNDComponentPeer& peerIn)
: peer (peerIn)
{
RedrawWindow (peer.getHWND(),
nullptr,
nullptr,
RDW_ERASE | RDW_INVALIDATE | RDW_FRAME | RDW_ALLCHILDREN);
}
const char* getName() const override { return name; }
void updateConstantAlpha() override
{
InvalidateRect (peer.getHWND(), nullptr, false);
}
void handlePaintMessage() override
{
HRGN rgn = CreateRectRgn (0, 0, 0, 0);
const int regionType = GetUpdateRgn (peer.getHWND(), rgn, false);
PAINTSTRUCT paintStruct;
HDC dc = BeginPaint (peer.getHWND(), &paintStruct); // Note this can immediately generate a WM_NCPAINT
// message and become re-entrant, but that's OK
// If something in a paint handler calls, e.g. a message box, this can become reentrant and
// corrupt the image it's using to paint into, so do a check here.
static bool reentrant = false;
if (! reentrant)
{
const ScopedValueSetter<bool> setter (reentrant, true, false);
if (peer.dontRepaint)
peer.getComponent().handleCommandMessage (0); // (this triggers a repaint in the openGL context)
else
performPaint (dc, rgn, regionType, paintStruct);
}
DeleteObject (rgn);
EndPaint (peer.getHWND(), &paintStruct);
#if JUCE_MSVC
_fpreset(); // because some graphics cards can unmask FP exceptions
#endif
}
void repaint (const Rectangle<int>& area) override
{
JUCE_TRACE_EVENT_INT_RECT (etw::repaint, etw::paintKeyword, area);
deferredRepaints.add (area);
}
void dispatchDeferredRepaints() override
{
for (auto deferredRect : deferredRepaints)
{
auto r = D2DUtilities::toRECT (deferredRect);
InvalidateRect (peer.getHWND(), &r, FALSE);
}
deferredRepaints.clear();
}
void performAnyPendingRepaintsNow() override
{
if (! peer.getComponent().isVisible())
return;
dispatchDeferredRepaints();
WeakReference localRef (&peer.getComponent());
MSG m;
if (peer.getTransparencyKind() == HWNDComponentPeer::TransparencyKind::perPixel
|| PeekMessage (&m, peer.getHWND(), WM_PAINT, WM_PAINT, PM_REMOVE))
{
if (localRef != nullptr) // (the PeekMessage call can dispatch messages, which may delete this comp)
handlePaintMessage();
}
}
Image createSnapshot() override
{
return peer.getTransparencyKind() == HWNDComponentPeer::TransparencyKind::perPixel
? createSnapshotOfLayeredWindow()
: createSnapshotOfNormalWindow();
}
void onVBlank() override {}
void handleShowWindow() override {}
private:
// If we've called UpdateLayeredWindow to display the window contents, retrieving the
// contents of the window DC will fail.
// Instead, we produce a fresh render of the window into a temporary image.
// Child windows will not be included.
Image createSnapshotOfLayeredWindow() const
{
const auto rect = peer.getClientRectInScreen();
Image result { Image::ARGB, rect.getWidth(), rect.getHeight(), true, SoftwareImageType{} };
{
auto context = peer.getComponent()
.getLookAndFeel()
.createGraphicsContext (result, {}, rect.withZeroOrigin());
context->addTransform (AffineTransform::scale ((float) peer.getPlatformScaleFactor()));
peer.handlePaint (*context);
}
return result;
}
// If UpdateLayeredWindow hasn't been called, then we can blit the window contents directly
// from the window's DC.
Image createSnapshotOfNormalWindow() const
{
auto hwnd = peer.getHWND();
auto r = convertPhysicalScreenRectangleToLogical (D2DUtilities::toRectangle (getWindowScreenRect (hwnd)), hwnd);
const auto w = r.getWidth();
const auto h = r.getHeight();
WindowsBitmapImage::Ptr nativeBitmap = new WindowsBitmapImage (Image::RGB, w, h, true);
Image bitmap (nativeBitmap);
ScopedDeviceContext deviceContext { hwnd };
const auto hdc = nativeBitmap->getHDC();
if (isPerMonitorDPIAwareProcess())
{
auto scale = getScaleFactorForWindow (hwnd);
auto prevStretchMode = SetStretchBltMode (hdc, HALFTONE);
SetBrushOrgEx (hdc, 0, 0, nullptr);
StretchBlt (hdc, 0, 0, w, h,
deviceContext.dc, 0, 0, roundToInt (w * scale), roundToInt (h * scale),
SRCCOPY);
SetStretchBltMode (hdc, prevStretchMode);
}
else
{
BitBlt (hdc, 0, 0, w, h, deviceContext.dc, 0, 0, SRCCOPY);
}
return SoftwareImageType().convert (bitmap);
}
void performPaint (HDC dc, HRGN rgn, int regionType, PAINTSTRUCT& paintStruct)
{
int x = paintStruct.rcPaint.left;
int y = paintStruct.rcPaint.top;
int w = paintStruct.rcPaint.right - x;
int h = paintStruct.rcPaint.bottom - y;
const auto perPixelTransparent = peer.getTransparencyKind() == HWNDComponentPeer::TransparencyKind::perPixel;
if (perPixelTransparent)
{
// it's not possible to have a transparent window with a title bar at the moment!
jassert (! peer.hasTitleBar());
auto r = getWindowScreenRect (peer.getHWND());
x = y = 0;
w = r.right - r.left;
h = r.bottom - r.top;
}
if (w > 0 && h > 0)
{
Image& offscreenImage = offscreenImageGenerator.getImage (perPixelTransparent, w, h);
RectangleList<int> contextClip;
const Rectangle<int> clipBounds (w, h);
bool needToPaintAll = true;
if (regionType == COMPLEXREGION && ! perPixelTransparent)
{
HRGN clipRgn = CreateRectRgnIndirect (&paintStruct.rcPaint);
CombineRgn (rgn, rgn, clipRgn, RGN_AND);
DeleteObject (clipRgn);
alignas (RGNDATA) std::byte rgnData[8192];
const DWORD res = GetRegionData (rgn, sizeof (rgnData), (RGNDATA*) &rgnData);
if (res > 0 && res <= sizeof (rgnData))
{
const RGNDATAHEADER* const hdr = &(((const RGNDATA*) &rgnData)->rdh);
if (hdr->iType == RDH_RECTANGLES
&& hdr->rcBound.right - hdr->rcBound.left >= w
&& hdr->rcBound.bottom - hdr->rcBound.top >= h)
{
needToPaintAll = false;
auto rects = unalignedPointerCast<const RECT*> ((char*) &rgnData + sizeof (RGNDATAHEADER));
for (int i = (int) ((RGNDATA*) &rgnData)->rdh.nCount; --i >= 0;)
{
if (rects->right <= x + w && rects->bottom <= y + h)
{
const int cx = jmax (x, (int) rects->left);
contextClip.addWithoutMerging (Rectangle<int> (cx - x, rects->top - y,
rects->right - cx, rects->bottom - rects->top)
.getIntersection (clipBounds));
}
else
{
needToPaintAll = true;
break;
}
++rects;
}
}
}
}
if (needToPaintAll)
{
contextClip.clear();
contextClip.addWithoutMerging (Rectangle<int> (w, h));
}
ChildWindowClippingInfo childClipInfo = { dc, &peer, &contextClip, Point<int> (x, y), 0 };
EnumChildWindows (peer.getHWND(), clipChildWindowCallback, (LPARAM) &childClipInfo);
if (! contextClip.isEmpty())
{
if (perPixelTransparent)
for (auto& i : contextClip)
offscreenImage.clear (i);
{
auto context = peer.getComponent()
.getLookAndFeel()
.createGraphicsContext (offscreenImage, { -x, -y }, contextClip);
context->addTransform (AffineTransform::scale ((float) peer.getPlatformScaleFactor()));
peer.handlePaint (*context);
}
auto* image = static_cast<WindowsBitmapImage*> (offscreenImage.getPixelData().get());
if (perPixelTransparent)
{
image->updateLayeredWindow (peer.getHWND(), { x, y }, peer.getComponent().getAlpha());
}
else
{
image->blitToDC (dc, x, y);
if (peer.getTransparencyKind() == HWNDComponentPeer::TransparencyKind::constant)
SetLayeredWindowAttributes (peer.getHWND(), {}, (BYTE) (255.0f * peer.getComponent().getAlpha()), LWA_ALPHA);
}
}
if (childClipInfo.savedDC != 0)
RestoreDC (dc, childClipInfo.savedDC);
}
}
struct ChildWindowClippingInfo
{
HDC dc;
HWNDComponentPeer* peer;
RectangleList<int>* clip;
Point<int> origin;
int savedDC;
};
static BOOL CALLBACK clipChildWindowCallback (HWND hwnd, LPARAM context)
{
if (IsWindowVisible (hwnd))
{
auto& info = *(ChildWindowClippingInfo*) context;
if (GetParent (hwnd) == info.peer->getHWND())
{
auto clip = D2DUtilities::toRectangle (getWindowClientRect (hwnd));
info.clip->subtract (clip - info.origin);
if (info.savedDC == 0)
info.savedDC = SaveDC (info.dc);
ExcludeClipRect (info.dc, clip.getX(), clip.getY(), clip.getRight(), clip.getBottom());
}
}
return TRUE;
}
//==============================================================================
struct TemporaryImage final : private Timer
{
TemporaryImage() = default;
Image& getImage (bool transparent, int w, int h)
{
auto format = transparent ? Image::ARGB : Image::RGB;
if ((! image.isValid()) || image.getWidth() < w || image.getHeight() < h || image.getFormat() != format)
image = Image (new WindowsBitmapImage (format, (w + 31) & ~31, (h + 31) & ~31, false));
startTimer (3000);
return image;
}
void timerCallback() override
{
stopTimer();
image = {};
}
private:
Image image;
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (TemporaryImage)
};
HWNDComponentPeer& peer;
TemporaryImage offscreenImageGenerator;
RectangleList<int> deferredRepaints;
};
class D2DRenderContext : public RenderContext,
private Direct2DHwndContext::SwapchainDelegate
{
public:
static constexpr auto name = "Direct2D";
explicit D2DRenderContext (HWNDComponentPeer& peerIn)
: peer (peerIn)
{
}
const char* getName() const override { return name; }
void updateConstantAlpha() override
{
const auto transparent = peer.getTransparencyKind() != HWNDComponentPeer::TransparencyKind::opaque;
if (transparent != direct2DContext->supportsTransparency())
{
direct2DContext.reset();
direct2DContext = getContextForPeer (peer, *this);
}
if (direct2DContext->supportsTransparency())
direct2DContext->updateAlpha();
}
void handlePaintMessage() override
{
#if JUCE_DIRECT2D_METRICS
auto paintStartTicks = Time::getHighResolutionTicks();
#endif
updateRegion.findRECTAndValidate (peer.getHWND());
for (const auto& rect : updateRegion.getRects())
repaint (D2DUtilities::toRectangle (rect));
#if JUCE_DIRECT2D_METRICS
lastPaintStartTicks = paintStartTicks;
#endif
}
void repaint (const Rectangle<int>& area) override
{
direct2DContext->addDeferredRepaint (area);
}
void dispatchDeferredRepaints() override {}
void performAnyPendingRepaintsNow() override {}
Image createSnapshot() override
{
return direct2DContext->createSnapshot();
}
void onVBlank() override
{
handleDirect2DPaint();
}
void handleShowWindow() override
{
direct2DContext->handleShowWindow();
handleDirect2DPaint();
}
private:
void onSwapchainEvent() override
{
handleDirect2DPaint();
}
struct WrappedD2DHwndContextBase
{
virtual ~WrappedD2DHwndContextBase() = default;
virtual void addDeferredRepaint (Rectangle<int> area) = 0;
virtual Image createSnapshot() const = 0;
virtual void handleShowWindow() = 0;
virtual LowLevelGraphicsContext* startFrame (float dpiScale) = 0;
virtual void endFrame() = 0;
virtual bool supportsTransparency() const = 0;
virtual void updateAlpha() = 0;
virtual Direct2DMetrics::Ptr getMetrics() const = 0;
};
/** This is a D2D context that uses a swap chain for presentation.
D2D contexts that use a swapchain can be made transparent using DirectComposition, but this
ends up causing other problems in JUCE, such as:
- The window redirection bitmap also needs to be disabled, which is a permanent window
setting, so it can't be enabled on the same window - instead a new window needs to be created.
This means that dynamically changing a component's alpha level at runtime might force the
window to be recreated, which is not ideal.
- We can't just disable the redirection bitmap by default, because it's needed to display
child windows, notably plugin editors
- The mouse gets captured inside the entire window bounds, rather than just the non-transparent parts
To avoid these problems, we only use the swapchain to present opaque windows.
For transparent windows, we use a different technique - see below.
*/
class WrappedD2DHwndContext : public WrappedD2DHwndContextBase
{
public:
WrappedD2DHwndContext (HWND hwnd, SwapchainDelegate& swapDelegate)
: ctx (hwnd, swapDelegate) {}
void addDeferredRepaint (Rectangle<int> area) override
{
ctx.addDeferredRepaint (area);
}
Image createSnapshot() const override
{
return ctx.createSnapshot();
}
void handleShowWindow() override
{
ctx.handleShowWindow();
}
LowLevelGraphicsContext* startFrame (float scale) override
{
if (ctx.startFrame (scale))
return &ctx;
return nullptr;
}
void endFrame() override
{
ctx.endFrame();
}
bool supportsTransparency() const override
{
return false;
}
void updateAlpha() override
{
// This doesn't support transparency, so updating the alpha won't do anything
jassertfalse;
}
Direct2DMetrics::Ptr getMetrics() const override
{
return ctx.metrics;
}
private:
Direct2DHwndContext ctx;
};
class DxgiBitmapRenderer
{
public:
LowLevelGraphicsContext* startFrame (HWND hwnd, float scale, const RectangleList<int>& dirty)
{
RECT r{};
GetClientRect (hwnd, &r);
const auto w = r.right - r.left;
const auto h = r.bottom - r.top;
const auto size = D2D1::SizeU ((UINT32) w, (UINT32) h);
const auto lastAdapter = std::exchange (adapter, directX->adapters.getAdapterForHwnd (hwnd));
const auto needsNewDC = lastAdapter != adapter || deviceContext == nullptr;
if (needsNewDC)
{
deviceContext = Direct2DDeviceContext::create (adapter);
bitmap = nullptr;
context = nullptr;
}
if (deviceContext == nullptr)
return nullptr;
const auto needsNewBitmap = bitmap == nullptr || ! equal (bitmap->GetPixelSize(), size);
if (needsNewBitmap)
{
bitmap = Direct2DBitmap::createBitmap (deviceContext,
Image::ARGB,
size,
D2D1_BITMAP_OPTIONS_TARGET | D2D1_BITMAP_OPTIONS_GDI_COMPATIBLE);
context = nullptr;
}
if (bitmap == nullptr)
return nullptr;
const auto paintAreas = needsNewBitmap ? Rectangle { (int) w, (int) h } : dirty;
if (paintAreas.isEmpty())
return nullptr;
if (context == nullptr)
context = std::make_unique<Direct2DImageContext> (deviceContext, bitmap, paintAreas);
if (! context->startFrame (scale))
context = nullptr;
if (context == nullptr)
return nullptr;
context->setFill (Colours::transparentBlack);
context->fillRect ({ (int) size.width, (int) size.height }, true);
return context.get();
}
void endFrame()
{
if (context != nullptr)
context->endFrame();
}
Image getImage() const
{
return Image { new Direct2DPixelData { adapter->direct2DDevice, bitmap } };
}
ComSmartPtr<ID2D1Bitmap1> getBitmap() const
{
return bitmap;
}
Direct2DMetrics::Ptr getMetrics() const
{
if (context != nullptr)
return context->metrics;
return {};
}
private:
static constexpr bool equal (D2D1_SIZE_U a, D2D1_SIZE_U b)
{
const auto tie = [] (auto& x) { return std::tie (x.width, x.height); };
return tie (a) == tie (b);
}
SharedResourcePointer<DirectX> directX;
DxgiAdapter::Ptr adapter;
ComSmartPtr<ID2D1DeviceContext1> deviceContext;
ComSmartPtr<ID2D1Bitmap1> bitmap;
std::unique_ptr<Direct2DImageContext> context;
};
/* This wrapper facilitates drawing Direct2D content into a transparent/layered window.
As an alternative to using DirectComposition, we instead use the older technique of using
a layered window, and calling UpdateLayeredWindow to set per-pixel alpha on the window.
This will be slower than going through the swap chain, but means that we can still set
the alpha level dynamically at runtime, support child windows as before, and support
per-pixel mouse hit-testing.
UpdateLayeredWindow is an older API that expects a HDC input containing the image that is
blitted to the screen. To get an HDC out of Direct2D, we cast a D2D bitmap to IDXGISurface1,
which exposes a suitable DC. This only works if the target bitmap is constructed with the
D2D1_BITMAP_OPTIONS_GDI_COMPATIBLE option.
*/
class WrappedD2DHwndContextTransparent : public WrappedD2DHwndContextBase
{
public:
explicit WrappedD2DHwndContextTransparent (HWNDComponentPeer& p) : peer (p) {}
void addDeferredRepaint (Rectangle<int> area) override
{
deferredRepaints.add (area);
}
Image createSnapshot() const override
{
DxgiBitmapRenderer renderer;
if (auto* ctx = renderer.startFrame (peer.getHWND(), (float) peer.getPlatformScaleFactor(), {}))
{
peer.handlePaint (*ctx);
renderer.endFrame();
}
return renderer.getImage();
}
void handleShowWindow() override {}
LowLevelGraphicsContext* startFrame (float scale) override
{
auto* result = bitmapRenderer.startFrame (peer.getHWND(), scale, deferredRepaints);
if (result != nullptr)
deferredRepaints.clear();
return result;
}
void endFrame() override
{
bitmapRenderer.endFrame();
updateLayeredWindow();
}
bool supportsTransparency() const override
{
return true;
}
void updateAlpha() override
{
updateLayeredWindow();
}
Direct2DMetrics::Ptr getMetrics() const override
{
return bitmapRenderer.getMetrics();
}
private:
void updateLayeredWindow()
{
const auto bitmap = bitmapRenderer.getBitmap();
if (bitmap == nullptr)
return;
ComSmartPtr<IDXGISurface> surface;
if (const auto hr = bitmap->GetSurface (surface.resetAndGetPointerAddress());
FAILED (hr) || surface == nullptr)
{
jassertfalse;
return;
}
ComSmartPtr<IDXGISurface1> surface1;
surface.QueryInterface (surface1);
if (surface1 == nullptr)
{
jassertfalse;
return;
}
HDC hdc{};
if (const auto hr = surface1->GetDC (false, &hdc); FAILED (hr))
{
jassertfalse;
return;
}
const ScopeGuard releaseDC { [&]
{
RECT emptyRect { 0, 0, 0, 0 };
const auto hr = surface1->ReleaseDC (&emptyRect);
jassertquiet (SUCCEEDED (hr));
} };
if (peer.getTransparencyKind() == HWNDComponentPeer::TransparencyKind::perPixel)
{
WindowsBitmapImage::updateLayeredWindow (hdc, peer.getHWND(), {}, peer.getComponent().getAlpha());
}
else
{
const ScopedDeviceContext scope { peer.getHWND() };
const auto size = bitmap->GetPixelSize();
BitBlt (scope.dc, 0, 0, (int) size.width, (int) size.height, hdc, 0, 0, SRCCOPY);
if (peer.getTransparencyKind() == HWNDComponentPeer::TransparencyKind::constant)
SetLayeredWindowAttributes (peer.getHWND(), {}, (BYTE) (255.0f * peer.getComponent().getAlpha()), LWA_ALPHA);
}
}
HWNDComponentPeer& peer;
DxgiBitmapRenderer bitmapRenderer;
RectangleList<int> deferredRepaints;
};
void handleDirect2DPaint()
{
#if JUCE_DIRECT2D_METRICS
auto paintStartTicks = Time::getHighResolutionTicks();
#endif
// Use the ID2D1DeviceContext to paint a swap chain buffer, then tell the swap chain to present
// the next buffer.
//
// Direct2DLowLevelGraphicsContext::startFrame checks if there are any areas to be painted and if the
// renderer is ready to go; if so, startFrame allocates any needed Direct2D resources,
// and calls ID2D1DeviceContext::BeginDraw
//
// handlePaint() makes various calls into the Direct2DLowLevelGraphicsContext which in turn calls
// the appropriate ID2D1DeviceContext functions to draw rectangles, clip, set the fill color, etc.
//
// Direct2DLowLevelGraphicsContext::endFrame calls ID2D1DeviceContext::EndDraw to finish painting
// and then tells the swap chain to present the next swap chain back buffer.
if (auto* ctx = direct2DContext->startFrame ((float) peer.getPlatformScaleFactor()))
{
peer.handlePaint (*ctx);
direct2DContext->endFrame();
}
#if JUCE_DIRECT2D_METRICS
if (lastPaintStartTicks > 0)
{
if (auto metrics = direct2DContext->getMetrics())
{
metrics->addValueTicks (Direct2DMetrics::messageThreadPaintDuration,
Time::getHighResolutionTicks() - paintStartTicks);
metrics->addValueTicks (Direct2DMetrics::frameInterval,
paintStartTicks - lastPaintStartTicks);
}
}
lastPaintStartTicks = paintStartTicks;
#endif
}
static std::unique_ptr<WrappedD2DHwndContextBase> getContextForPeer (HWNDComponentPeer& peer,
SwapchainDelegate& delegate)
{
if (peer.getTransparencyKind() != HWNDComponentPeer::TransparencyKind::opaque)
return std::make_unique<WrappedD2DHwndContextTransparent> (peer);
return std::make_unique<WrappedD2DHwndContext> (peer.getHWND(), delegate);
}
HWNDComponentPeer& peer;
std::unique_ptr<WrappedD2DHwndContextBase> direct2DContext = getContextForPeer (peer, *this);
UpdateRegion updateRegion;
#if JUCE_ETW_TRACELOGGING
struct ETWEventProvider
{
ETWEventProvider()
{
const auto hr = TraceLoggingRegister (::juce::etw::JUCETraceLogProvider);
jassertquiet (SUCCEEDED (hr));
}
~ETWEventProvider()
{
TraceLoggingUnregister (::juce::etw::JUCETraceLogProvider);
}
};
SharedResourcePointer<ETWEventProvider> etwEventProvider;
#endif
#if JUCE_DIRECT2D_METRICS
int64 lastPaintStartTicks = 0;
#endif
};
using Constructor = std::unique_ptr<RenderContext> (*) (HWNDComponentPeer&);
struct ContextDescriptor
{
const char* name = nullptr;
Constructor construct = nullptr;
};
template <typename... T>
inline constexpr ContextDescriptor contextDescriptorList[]
{
{
T::name,
[] (HWNDComponentPeer& p) -> std::unique_ptr<RenderContext> { return std::make_unique<T> (p); }
}...
};
// To add a new rendering backend, implement RenderContext for that backend, and then append the backend to this typelist
inline constexpr auto& contextDescriptors = contextDescriptorList<GDIRenderContext, D2DRenderContext>;
void HWNDComponentPeer::setCurrentRenderingEngine (int e)
{
if (isPositiveAndBelow (e, std::size (contextDescriptors)) && (renderContext == nullptr || getCurrentRenderingEngine() != e))
{
// Reset the old context before creating the new context, because some context resources
// can only be created once per window.
renderContext.reset();
renderContext = contextDescriptors[e].construct (*this);
}
}
StringArray HWNDComponentPeer::getAvailableRenderingEngines()
{
StringArray results;
for (const auto& d : contextDescriptors)
results.add (d.name);
return results;
}
int HWNDComponentPeer::getCurrentRenderingEngine() const
{
jassert (renderContext != nullptr);
for (const auto [index, d] : enumerate (contextDescriptors, int{}))
if (d.name == renderContext->getName())
return index;
return -1;
}
JUCE_API ComponentPeer* createNonRepaintingEmbeddedWindowsPeer (Component& component, Component* parentComponent);
JUCE_API ComponentPeer* createNonRepaintingEmbeddedWindowsPeer (Component& component, Component* parentComponent)
{
if (auto parentPeer = parentComponent->getPeer())
{
// Explicitly set the top-level window to software renderer mode in case
// this is switching from Direct2D to OpenGL
//
// HWNDComponentPeer and Direct2DComponentPeer rely on virtual methods for initialization; hence the call to
// embeddedWindowPeer->initialise() after creating the peer
int styleFlags = ComponentPeer::windowIgnoresMouseClicks;
return new HWNDComponentPeer (component,
styleFlags,
(HWND) parentPeer->getNativeHandle(),
true, /* nonRepainting*/
0);
}
return nullptr;
}
//==============================================================================
bool KeyPress::isKeyCurrentlyDown (const int keyCode)
{
const auto k = [&]
{
if ((keyCode & extendedKeyModifier) != 0)
return keyCode & (extendedKeyModifier - 1);
const auto vk = BYTE (VkKeyScan ((WCHAR) keyCode) & 0xff);
return vk != (BYTE) -1 ? vk : keyCode;
}();
return HWNDComponentPeer::isKeyDown (k);
}
//==============================================================================
static DWORD getProcess (HWND hwnd)
{
DWORD result = 0;
GetWindowThreadProcessId (hwnd, &result);
return result;
}
/* Returns true if the viewComponent is embedded into a window
owned by the foreground process.
*/
bool detail::WindowingHelpers::isEmbeddedInForegroundProcess (Component* c)
{
if (c == nullptr)
return false;
auto* peer = c->getPeer();
auto* hwnd = peer != nullptr ? static_cast<HWND> (peer->getNativeHandle()) : nullptr;
if (hwnd == nullptr)
return true;
const auto fgProcess = getProcess (GetForegroundWindow());
const auto ownerProcess = getProcess (GetAncestor (hwnd, GA_ROOTOWNER));
return fgProcess == ownerProcess;
}
bool JUCE_CALLTYPE Process::isForegroundProcess()
{
if (auto fg = GetForegroundWindow())
return getProcess (fg) == GetCurrentProcessId();
return true;
}
// N/A on Windows as far as I know.
void JUCE_CALLTYPE Process::makeForegroundProcess() {}
void JUCE_CALLTYPE Process::hide() {}
//==============================================================================
bool detail::MouseInputSourceList::addSource()
{
auto numSources = sources.size();
if (numSources == 0 || canUseMultiTouch())
{
addSource (numSources, numSources == 0 ? MouseInputSource::InputSourceType::mouse
: MouseInputSource::InputSourceType::touch);
return true;
}
return false;
}
bool detail::MouseInputSourceList::canUseTouch() const
{
return canUseMultiTouch();
}
Point<float> MouseInputSource::getCurrentRawMousePosition()
{
POINT mousePos;
GetCursorPos (&mousePos);
auto p = D2DUtilities::toPoint (mousePos);
if (isPerMonitorDPIAwareThread())
p = Desktop::getInstance().getDisplays().physicalToLogical (p);
return p.toFloat();
}
void MouseInputSource::setRawMousePosition (Point<float> newPosition)
{
auto newPositionInt = newPosition.roundToInt();
#if JUCE_WIN_PER_MONITOR_DPI_AWARE
if (isPerMonitorDPIAwareThread())
newPositionInt = Desktop::getInstance().getDisplays().logicalToPhysical (newPositionInt);
#endif
auto point = D2DUtilities::toPOINT (newPositionInt);
SetCursorPos (point.x, point.y);
}
//==============================================================================
class ScreenSaverDefeater final : public Timer
{
public:
ScreenSaverDefeater()
{
startTimer (10000);
timerCallback();
}
void timerCallback() override
{
if (Process::isForegroundProcess())
{
INPUT input = {};
input.type = INPUT_MOUSE;
input.mi.mouseData = MOUSEEVENTF_MOVE;
SendInput (1, &input, sizeof (INPUT));
}
}
};
static std::unique_ptr<ScreenSaverDefeater> screenSaverDefeater;
void Desktop::setScreenSaverEnabled (const bool isEnabled)
{
if (isEnabled)
screenSaverDefeater = nullptr;
else if (screenSaverDefeater == nullptr)
screenSaverDefeater.reset (new ScreenSaverDefeater());
}
bool Desktop::isScreenSaverEnabled()
{
return screenSaverDefeater == nullptr;
}
//==============================================================================
void LookAndFeel::playAlertSound()
{
MessageBeep (MB_OK);
}
//==============================================================================
void SystemClipboard::copyTextToClipboard (const String& text)
{
if (OpenClipboard (nullptr) != 0)
{
if (EmptyClipboard() != 0)
{
auto bytesNeeded = CharPointer_UTF16::getBytesRequiredFor (text.getCharPointer()) + 4;
if (bytesNeeded > 0)
{
if (auto bufH = GlobalAlloc (GMEM_MOVEABLE | GMEM_DDESHARE | GMEM_ZEROINIT, bytesNeeded + sizeof (WCHAR)))
{
if (auto* data = static_cast<WCHAR*> (GlobalLock (bufH)))
{
text.copyToUTF16 (data, bytesNeeded);
GlobalUnlock (bufH);
SetClipboardData (CF_UNICODETEXT, bufH);
}
}
}
}
CloseClipboard();
}
}
String SystemClipboard::getTextFromClipboard()
{
String result;
if (OpenClipboard (nullptr) != 0)
{
if (auto bufH = GetClipboardData (CF_UNICODETEXT))
{
if (auto* data = (const WCHAR*) GlobalLock (bufH))
{
result = String (data, (size_t) (GlobalSize (bufH) / sizeof (WCHAR)));
GlobalUnlock (bufH);
}
}
CloseClipboard();
}
return result;
}
//==============================================================================
void Desktop::setKioskComponent (Component* kioskModeComp, bool enableOrDisable, bool /*allowMenusAndBars*/)
{
if (auto* peer = dynamic_cast<HWNDComponentPeer*> (kioskModeComp->getPeer()))
{
const auto prevFlags = (DWORD) GetWindowLong (peer->getHWND(), GWL_STYLE);
const auto nextVisibility = prevFlags & WS_VISIBLE;
const auto nextFlags = peer->computeNativeStyleFlags() | nextVisibility;
if (nextFlags != prevFlags)
{
SetWindowLong (peer->getHWND(), GWL_STYLE, nextFlags);
// After changing the window style flags, the window border visibility may have changed.
// Call SetWindowPos with no changes other than SWP_FRAMECHANGED to ensure that
// GetWindowInfo returns up-to-date border-size values.
static constexpr auto frameChangeOnly = SWP_NOSIZE
| SWP_NOMOVE
| SWP_NOZORDER
| SWP_NOREDRAW
| SWP_NOACTIVATE
| SWP_FRAMECHANGED
| SWP_NOOWNERZORDER
| SWP_NOSENDCHANGING;
SetWindowPos (peer->getHWND(), nullptr, 0, 0, 0, 0, frameChangeOnly);
}
}
else
{
jassertfalse;
}
if (kioskModeComp != nullptr && enableOrDisable)
kioskModeComp->setBounds (getDisplays().getDisplayForRect (kioskModeComp->getScreenBounds())->totalArea);
}
void Desktop::allowedOrientationsChanged() {}
//==============================================================================
static const Displays::Display* getCurrentDisplayFromScaleFactor (HWND hwnd)
{
Array<const Displays::Display*> candidateDisplays;
const auto scaleToLookFor = [&]
{
if (auto* peer = HWNDComponentPeer::getOwnerOfWindow (hwnd))
return peer->getPlatformScaleFactor();
return getScaleFactorForWindow (hwnd);
}();
auto globalScale = Desktop::getInstance().getGlobalScaleFactor();
for (auto& d : Desktop::getInstance().getDisplays().displays)
if (approximatelyEqual (d.scale / globalScale, scaleToLookFor))
candidateDisplays.add (&d);
if (candidateDisplays.size() > 0)
{
if (candidateDisplays.size() == 1)
return candidateDisplays[0];
const auto bounds = [&]
{
if (auto* peer = HWNDComponentPeer::getOwnerOfWindow (hwnd))
return peer->getComponent().getTopLevelComponent()->getBounds();
return Desktop::getInstance().getDisplays().physicalToLogical (D2DUtilities::toRectangle (getWindowScreenRect (hwnd)));
}();
const Displays::Display* retVal = nullptr;
int maxArea = -1;
for (auto* d : candidateDisplays)
{
auto intersection = d->totalArea.getIntersection (bounds);
auto area = intersection.getWidth() * intersection.getHeight();
if (area > maxArea)
{
maxArea = area;
retVal = d;
}
}
if (retVal != nullptr)
return retVal;
}
return Desktop::getInstance().getDisplays().getPrimaryDisplay();
}
//==============================================================================
struct MonitorInfo
{
MonitorInfo (bool main, RECT totalArea, RECT workArea, double d, std::optional<double> frequency) noexcept
: isMain (main),
totalAreaRect (totalArea),
workAreaRect (workArea),
dpi (d),
verticalFrequencyHz (frequency)
{
}
bool isMain;
RECT totalAreaRect, workAreaRect;
double dpi;
std::optional<double> verticalFrequencyHz;
};
static BOOL CALLBACK enumMonitorsProc (HMONITOR hm, HDC, LPRECT, LPARAM userInfo)
{
MONITORINFOEX info = {};
info.cbSize = sizeof (info);
GetMonitorInfo (hm, &info);
auto isMain = (info.dwFlags & 1 /* MONITORINFOF_PRIMARY */) != 0;
auto dpi = 0.0;
if (getDPIForMonitor != nullptr)
{
UINT dpiX = 0, dpiY = 0;
if (SUCCEEDED (getDPIForMonitor (hm, MDT_Default, &dpiX, &dpiY)))
dpi = (dpiX + dpiY) / 2.0;
}
// Call EnumDisplayDevices and EnumDisplaySettings to get the refresh rate of the monitor
BOOL ok = TRUE;
std::optional<double> frequency;
for (uint32 deviceNumber = 0; ok; ++deviceNumber)
{
DISPLAY_DEVICEW displayDevice{};
displayDevice.cb = sizeof (displayDevice);
ok = EnumDisplayDevicesW (nullptr, deviceNumber, &displayDevice, 0);
if (ok && (displayDevice.StateFlags & DISPLAY_DEVICE_ATTACHED_TO_DESKTOP))
{
DEVMODE displaySettings{};
ok = EnumDisplaySettingsW (displayDevice.DeviceName, ENUM_CURRENT_SETTINGS, &displaySettings);
if (ok)
{
if (String { displayDevice.DeviceName } == String { info.szDevice })
{
frequency = (double) displaySettings.dmDisplayFrequency;
break;
}
}
}
}
((Array<MonitorInfo>*) userInfo)->add ({ isMain, info.rcMonitor, info.rcWork, dpi, frequency });
return TRUE;
}
void Displays::findDisplays (float masterScale)
{
setDPIAwareness();
Array<MonitorInfo> monitors;
EnumDisplayMonitors (nullptr, nullptr, &enumMonitorsProc, (LPARAM) &monitors);
auto globalDPI = getGlobalDPI();
if (monitors.size() == 0)
{
auto windowRect = getWindowScreenRect (GetDesktopWindow());
monitors.add ({ true, windowRect, windowRect, globalDPI, std::optional<double>{} });
}
// make sure the first in the list is the main monitor
for (int i = 1; i < monitors.size(); ++i)
if (monitors.getReference (i).isMain)
monitors.swap (i, 0);
for (auto& monitor : monitors)
{
Display d;
d.isMain = monitor.isMain;
d.dpi = monitor.dpi;
if (approximatelyEqual (d.dpi, 0.0))
{
d.dpi = globalDPI;
d.scale = masterScale;
}
else
{
d.scale = (d.dpi / USER_DEFAULT_SCREEN_DPI) * (masterScale / Desktop::getDefaultMasterScale());
}
d.totalArea = D2DUtilities::toRectangle (monitor.totalAreaRect);
d.userArea = D2DUtilities::toRectangle (monitor.workAreaRect);
displays.add (d);
}
#if JUCE_WIN_PER_MONITOR_DPI_AWARE
if (isPerMonitorDPIAwareThread())
updateToLogical();
else
#endif
{
for (auto& d : displays)
{
d.totalArea /= masterScale;
d.userArea /= masterScale;
}
}
}
//==============================================================================
static auto extractFileHICON (const File& file)
{
WORD iconNum = 0;
WCHAR name[MAX_PATH * 2];
file.getFullPathName().copyToUTF16 (name, sizeof (name));
return IconConverters::IconPtr { ExtractAssociatedIcon ((HINSTANCE) Process::getCurrentModuleInstanceHandle(),
name,
&iconNum) };
}
Image detail::WindowingHelpers::createIconForFile (const File& file)
{
if (const auto icon = extractFileHICON (file))
return IconConverters::createImageFromHICON (icon.get());
return {};
}
//==============================================================================
class MouseCursor::PlatformSpecificHandle
{
public:
explicit PlatformSpecificHandle (const MouseCursor::StandardCursorType type)
: impl (makeHandle (type)) {}
explicit PlatformSpecificHandle (const detail::CustomMouseCursorInfo& info)
: impl (makeHandle (info)) {}
static void showInWindow (PlatformSpecificHandle* handle, ComponentPeer* peer)
{
SetCursor ([&]
{
if (handle != nullptr && handle->impl != nullptr && peer != nullptr)
return handle->impl->getCursor (*peer);
return LoadCursor (nullptr, IDC_ARROW);
}());
}
private:
struct Impl
{
virtual ~Impl() = default;
virtual HCURSOR getCursor (ComponentPeer&) = 0;
};
class BuiltinImpl : public Impl
{
public:
explicit BuiltinImpl (HCURSOR cursorIn)
: cursor (cursorIn) {}
HCURSOR getCursor (ComponentPeer&) override { return cursor; }
private:
HCURSOR cursor;
};
class ImageImpl : public Impl
{
public:
explicit ImageImpl (const detail::CustomMouseCursorInfo& infoIn) : info (infoIn) {}
HCURSOR getCursor (ComponentPeer& peer) override
{
JUCE_ASSERT_MESSAGE_THREAD;
static auto getCursorSize = getCursorSizeForPeerFunction();
const auto size = getCursorSize (peer);
const auto iter = cursorsBySize.find (size);
if (iter != cursorsBySize.end())
return iter->second.get();
const auto logicalSize = info.image.getScaledBounds();
const auto scale = (float) size / (float) unityCursorSize;
const auto physicalSize = logicalSize * scale;
const auto& image = info.image.getImage();
const auto rescaled = image.rescaled (roundToInt ((float) physicalSize.getWidth()),
roundToInt ((float) physicalSize.getHeight()));
const auto effectiveScale = rescaled.getWidth() / logicalSize.getWidth();
const auto hx = jlimit (0, rescaled.getWidth(), roundToInt ((float) info.hotspot.x * effectiveScale));
const auto hy = jlimit (0, rescaled.getHeight(), roundToInt ((float) info.hotspot.y * effectiveScale));
return cursorsBySize.emplace (size, CursorPtr { IconConverters::createHICONFromImage (rescaled, false, hx, hy) }).first->second.get();
}
private:
struct CursorDestructor
{
void operator() (HCURSOR ptr) const { if (ptr != nullptr) DestroyCursor (ptr); }
};
using CursorPtr = std::unique_ptr<std::remove_pointer_t<HCURSOR>, CursorDestructor>;
const detail::CustomMouseCursorInfo info;
std::map<int, CursorPtr> cursorsBySize;
};
static auto getCursorSizeForPeerFunction() -> int (*) (ComponentPeer&)
{
static const auto getDpiForMonitor = []() -> GetDPIForMonitorFunc
{
constexpr auto library = "SHCore.dll";
LoadLibraryA (library);
if (auto* handle = GetModuleHandleA (library))
return (GetDPIForMonitorFunc) GetProcAddress (handle, "GetDpiForMonitor");
return nullptr;
}();
static const auto getSystemMetricsForDpi = []() -> GetSystemMetricsForDpiFunc
{
constexpr auto library = "User32.dll";
LoadLibraryA (library);
if (auto* handle = GetModuleHandleA (library))
return (GetSystemMetricsForDpiFunc) GetProcAddress (handle, "GetSystemMetricsForDpi");
return nullptr;
}();
if (getDpiForMonitor == nullptr || getSystemMetricsForDpi == nullptr)
return [] (ComponentPeer&) { return unityCursorSize; };
return [] (ComponentPeer& p)
{
const ScopedThreadDPIAwarenessSetter threadDpiAwarenessSetter { p.getNativeHandle() };
UINT dpiX = 0, dpiY = 0;
if (auto* monitor = MonitorFromWindow ((HWND) p.getNativeHandle(), MONITOR_DEFAULTTONULL))
if (SUCCEEDED (getDpiForMonitor (monitor, MDT_Default, &dpiX, &dpiY)))
return getSystemMetricsForDpi (SM_CXCURSOR, dpiX);
return unityCursorSize;
};
}
static constexpr auto unityCursorSize = 32;
static std::unique_ptr<Impl> makeHandle (const detail::CustomMouseCursorInfo& info)
{
return std::make_unique<ImageImpl> (info);
}
static std::unique_ptr<Impl> makeHandle (const MouseCursor::StandardCursorType type)
{
LPCTSTR cursorName = IDC_ARROW;
switch (type)
{
case NormalCursor:
case ParentCursor: break;
case NoCursor: return std::make_unique<BuiltinImpl> (nullptr);
case WaitCursor: cursorName = IDC_WAIT; break;
case IBeamCursor: cursorName = IDC_IBEAM; break;
case PointingHandCursor: cursorName = MAKEINTRESOURCE (32649); break;
case CrosshairCursor: cursorName = IDC_CROSS; break;
case LeftRightResizeCursor:
case LeftEdgeResizeCursor:
case RightEdgeResizeCursor: cursorName = IDC_SIZEWE; break;
case UpDownResizeCursor:
case TopEdgeResizeCursor:
case BottomEdgeResizeCursor: cursorName = IDC_SIZENS; break;
case TopLeftCornerResizeCursor:
case BottomRightCornerResizeCursor: cursorName = IDC_SIZENWSE; break;
case TopRightCornerResizeCursor:
case BottomLeftCornerResizeCursor: cursorName = IDC_SIZENESW; break;
case UpDownLeftRightResizeCursor: cursorName = IDC_SIZEALL; break;
case DraggingHandCursor:
{
static const unsigned char dragHandData[]
{ 71,73,70,56,57,97,16,0,16,0,145,2,0,0,0,0,255,255,255,0,0,0,0,0,0,33,249,4,1,0,0,2,0,44,0,0,0,0,16,0,
16,0,0,2,52,148,47,0,200,185,16,130,90,12,74,139,107,84,123,39,132,117,151,116,132,146,248,60,209,138,
98,22,203,114,34,236,37,52,77,217,247,154,191,119,110,240,193,128,193,95,163,56,60,234,98,135,2,0,59 };
return makeHandle ({ ScaledImage (ImageFileFormat::loadFrom (dragHandData, sizeof (dragHandData))), { 8, 7 } });
}
case CopyingCursor:
{
static const unsigned char copyCursorData[]
{ 71,73,70,56,57,97,21,0,21,0,145,0,0,0,0,0,255,255,255,0,128,128,255,255,255,33,249,4,1,0,0,3,0,44,0,0,0,0,21,0,
21,0,0,2,72,4,134,169,171,16,199,98,11,79,90,71,161,93,56,111,78,133,218,215,137,31,82,154,100,200,86,91,202,142,
12,108,212,87,235,174, 15,54,214,126,237,226,37,96,59,141,16,37,18,201,142,157,230,204,51,112,252,114,147,74,83,
5,50,68,147,208,217,16,71,149,252,124,5,0,59,0,0 };
return makeHandle ({ ScaledImage (ImageFileFormat::loadFrom (copyCursorData, sizeof (copyCursorData))), { 1, 3 } });
}
case NumStandardCursorTypes: JUCE_FALLTHROUGH
default:
jassertfalse; break;
}
return std::make_unique<BuiltinImpl> ([&]
{
if (auto* c = LoadCursor (nullptr, cursorName))
return c;
return LoadCursor (nullptr, IDC_ARROW);
}());
}
std::unique_ptr<Impl> impl;
};
//==============================================================================
JUCE_END_IGNORE_WARNINGS_GCC_LIKE
//==============================================================================
JUCE_COMCLASS (JuceIVirtualDesktopManager, "a5cd92ff-29be-454c-8d04-d82879fb3f1b") : public IUnknown
{
public:
virtual HRESULT STDMETHODCALLTYPE IsWindowOnCurrentVirtualDesktop(
__RPC__in HWND topLevelWindow,
__RPC__out BOOL * onCurrentDesktop) = 0;
virtual HRESULT STDMETHODCALLTYPE GetWindowDesktopId(
__RPC__in HWND topLevelWindow,
__RPC__out GUID * desktopId) = 0;
virtual HRESULT STDMETHODCALLTYPE MoveWindowToDesktop(
__RPC__in HWND topLevelWindow,
__RPC__in REFGUID desktopId) = 0;
};
JUCE_COMCLASS (JuceVirtualDesktopManager, "aa509086-5ca9-4c25-8f95-589d3c07b48a");
} // namespace juce
#ifdef __CRT_UUID_DECL
__CRT_UUID_DECL (juce::JuceIVirtualDesktopManager, 0xa5cd92ff, 0x29be, 0x454c, 0x8d, 0x04, 0xd8, 0x28, 0x79, 0xfb, 0x3f, 0x1b)
__CRT_UUID_DECL (juce::JuceVirtualDesktopManager, 0xaa509086, 0x5ca9, 0x4c25, 0x8f, 0x95, 0x58, 0x9d, 0x3c, 0x07, 0xb4, 0x8a)
#endif
bool juce::detail::WindowingHelpers::isWindowOnCurrentVirtualDesktop (void* x)
{
if (x == nullptr)
return false;
ComSmartPtr<JuceIVirtualDesktopManager> manager;
JUCE_BEGIN_IGNORE_WARNINGS_GCC_LIKE ("-Wlanguage-extension-token")
manager.CoCreateInstance (__uuidof (JuceVirtualDesktopManager), CLSCTX_ALL);
JUCE_END_IGNORE_WARNINGS_GCC_LIKE
if (manager == nullptr)
return true;
BOOL current = false;
if (FAILED (manager->IsWindowOnCurrentVirtualDesktop (static_cast<HWND> (x), ¤t)))
return true;
return current != false;
}
|