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
|
/*
Copyright (C) 2016 The Qt Company Ltd.
Copyright (C) 2009 Torch Mobile Inc.
Copyright (C) 2009 Girish Ramakrishnan <girish@forwardbias.in>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Library General Public License for more details.
You should have received a copy of the GNU Library General Public License
along with this library; see the file COPYING.LIB. If not, write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA 02110-1301, USA.
*/
#include <qtest.h>
#include "../util.h"
#include <private/qinputmethod_p.h>
#include <qpainter.h>
#include <qpagelayout.h>
#include <qwebengineview.h>
#include <qwebenginepage.h>
#include <qwebenginesettings.h>
#include <qnetworkrequest.h>
#include <qdiriterator.h>
#include <qstackedlayout.h>
#include <qtemporarydir.h>
#include <QClipboard>
#include <QCompleter>
#include <QLabel>
#include <QLineEdit>
#include <QHBoxLayout>
#include <QMenu>
#include <QMimeData>
#include <QQuickItem>
#include <QQuickWidget>
#include <QtWebEngineCore/qwebenginehttprequest.h>
#include <QScopeGuard>
#include <QTcpServer>
#include <QTcpSocket>
#include <QStyle>
#include <QtWidgets/qaction.h>
#include <QWebEngineProfile>
#include <QtCore/qregularexpression.h>
#define VERIFY_INPUTMETHOD_HINTS(actual, expect) \
QVERIFY(actual == (expect | Qt::ImhNoPredictiveText | Qt::ImhNoTextHandles | Qt::ImhNoEditMenu));
#define QTRY_COMPARE_WITH_TIMEOUT_FAIL_BLOCK(__expr, __expected, __timeout, __fail_block) \
do { \
QTRY_IMPL(((__expr) == (__expected)), __timeout);\
if (__expr != __expected)\
__fail_block\
QCOMPARE((__expr), __expected); \
} while (0)
QT_BEGIN_NAMESPACE
namespace QTest {
int Q_TESTLIB_EXPORT defaultMouseDelay();
static void mouseEvent(QEvent::Type type, QWidget *widget, const QPoint &pos)
{
QTest::qWait(QTest::defaultMouseDelay());
lastMouseTimestamp += QTest::defaultMouseDelay();
QMouseEvent me(type, pos, Qt::LeftButton, Qt::LeftButton, Qt::NoModifier);
me.setTimestamp(++lastMouseTimestamp);
QSpontaneKeyEvent::setSpontaneous(&me);
qApp->sendEvent(widget, &me);
}
static void mouseMultiClick(QWidget *widget, const QPoint pos, int clickCount)
{
for (int i = 0; i < clickCount; ++i) {
mouseEvent(QMouseEvent::MouseButtonPress, widget, pos);
mouseEvent(QMouseEvent::MouseButtonRelease, widget, pos);
}
lastMouseTimestamp += mouseDoubleClickInterval;
}
}
QT_END_NAMESPACE
class tst_QWebEngineView : public QObject
{
Q_OBJECT
public Q_SLOTS:
void initTestCase();
void cleanupTestCase();
void init();
void cleanup();
private Q_SLOTS:
void renderingAfterMaxAndBack();
void renderHints();
void getWebKitVersion();
void changePage_data();
void changePage();
void reusePage_data();
void reusePage();
void microFocusCoordinates();
void focusInputTypes();
void unhandledKeyEventPropagation();
void horizontalScrollbarTest();
void crashTests();
#if !(defined(WTF_USE_QT_MOBILE_THEME) && WTF_USE_QT_MOBILE_THEME)
void setPalette_data();
void setPalette();
#endif
void doNotSendMouseKeyboardEventsWhenDisabled();
void doNotSendMouseKeyboardEventsWhenDisabled_data();
void stopSettingFocusWhenDisabled();
void stopSettingFocusWhenDisabled_data();
void focusOnNavigation_data();
void focusOnNavigation();
void focusInternalRenderWidgetHostViewQuickItem();
void doNotBreakLayout();
void changeLocale();
void mixLangLocale_data();
void mixLangLocale();
void inputMethodsTextFormat_data();
void inputMethodsTextFormat();
void keyboardEvents();
void keyboardFocusAfterPopup();
void mouseClick();
void postData();
void inputFieldOverridesShortcuts();
void softwareInputPanel();
void inputContextQueryInput();
void inputMethods();
void textSelectionInInputField();
void textSelectionOutOfInputField();
void hiddenText();
void emptyInputMethodEvent();
void imeComposition();
void imeCompositionQueryEvent_data();
void imeCompositionQueryEvent();
void newlineInTextarea();
void imeJSInputEvents();
void mouseLeave();
#ifndef QT_NO_CLIPBOARD
void globalMouseSelection();
#endif
void noContextMenu();
void contextMenu_data();
void contextMenu();
void webUIURLs_data();
void webUIURLs();
void visibilityState();
void visibilityState2();
void visibilityState3();
void jsKeyboardEvent_data();
void jsKeyboardEvent();
void deletePage();
void autoDeleteOnExternalPageDelete();
void closeOpenerTab();
void switchPage();
void setPageDeletesImplicitPage();
void setPageDeletesImplicitPage2();
void setViewDeletesImplicitPage();
void setPagePreservesExplicitPage();
void setViewPreservesExplicitPage();
void closeDiscardsPage();
void loadAfterRendererCrashed();
void navigateOnDrop_data();
void navigateOnDrop();
};
// This will be called before the first test function is executed.
// It is only called once.
void tst_QWebEngineView::initTestCase()
{
}
// This will be called after the last test function is executed.
// It is only called once.
void tst_QWebEngineView::cleanupTestCase()
{
}
// This will be called before each test function is executed.
void tst_QWebEngineView::init()
{
}
// This will be called after every test function.
void tst_QWebEngineView::cleanup()
{
}
void tst_QWebEngineView::renderHints()
{
#if !defined(QWEBENGINEVIEW_RENDERHINTS)
QSKIP("QWEBENGINEVIEW_RENDERHINTS");
#else
QWebEngineView webView;
// default is only text antialiasing + smooth pixmap transform
QVERIFY(!(webView.renderHints() & QPainter::Antialiasing));
QVERIFY(webView.renderHints() & QPainter::TextAntialiasing);
QVERIFY(webView.renderHints() & QPainter::SmoothPixmapTransform);
#if QT_DEPRECATED_SINCE(5, 14)
QVERIFY(!(webView.renderHints() & QPainter::HighQualityAntialiasing));
#endif
QVERIFY(!(webView.renderHints() & QPainter::Antialiasing));
webView.setRenderHint(QPainter::Antialiasing, true);
QVERIFY(webView.renderHints() & QPainter::Antialiasing);
QVERIFY(webView.renderHints() & QPainter::TextAntialiasing);
QVERIFY(webView.renderHints() & QPainter::SmoothPixmapTransform);
#if QT_DEPRECATED_SINCE(5, 14)
QVERIFY(!(webView.renderHints() & QPainter::HighQualityAntialiasing));
#endif
QVERIFY(!(webView.renderHints() & QPainter::Antialiasing));
webView.setRenderHint(QPainter::Antialiasing, false);
QVERIFY(!(webView.renderHints() & QPainter::Antialiasing));
QVERIFY(webView.renderHints() & QPainter::TextAntialiasing);
QVERIFY(webView.renderHints() & QPainter::SmoothPixmapTransform);
#if QT_DEPRECATED_SINCE(5, 14)
QVERIFY(!(webView.renderHints() & QPainter::HighQualityAntialiasing));
#endif
QVERIFY(!(webView.renderHints() & QPainter::Antialiasing));
webView.setRenderHint(QPainter::SmoothPixmapTransform, true);
QVERIFY(!(webView.renderHints() & QPainter::Antialiasing));
QVERIFY(webView.renderHints() & QPainter::TextAntialiasing);
QVERIFY(webView.renderHints() & QPainter::SmoothPixmapTransform);
#if QT_DEPRECATED_SINCE(5, 14)
QVERIFY(!(webView.renderHints() & QPainter::HighQualityAntialiasing));
#endif
QVERIFY(!(webView.renderHints() & QPainter::Antialiasing));
webView.setRenderHint(QPainter::SmoothPixmapTransform, false);
QVERIFY(webView.renderHints() & QPainter::TextAntialiasing);
QVERIFY(!(webView.renderHints() & QPainter::SmoothPixmapTransform));
#if QT_DEPRECATED_SINCE(5, 14)
QVERIFY(!(webView.renderHints() & QPainter::HighQualityAntialiasing));
#endif
QVERIFY(!(webView.renderHints() & QPainter::Antialiasing));
#endif
}
void tst_QWebEngineView::getWebKitVersion()
{
#if !defined(QWEBENGINEVERSION)
QSKIP("QWEBENGINEVERSION");
#else
QVERIFY(qWebKitVersion().toDouble() > 0);
#endif
}
void tst_QWebEngineView::changePage_data()
{
QString html = "<html><head><title>%1</title>"
"<link rel='icon' href='qrc:///resources/image2.png'></head></html>";
QUrl urlFrom("data:text/html," + html.arg("TitleFrom"));
QUrl urlTo("data:text/html," + html.arg("TitleTo"));
QUrl nullPage("data:text/html,<html/>");
QTest::addColumn<QUrl>("urlFrom");
QTest::addColumn<QUrl>("urlTo");
QTest::addColumn<bool>("fromIsNullPage");
QTest::addColumn<bool>("toIsNullPage");
QTest::newRow("From empty page to url") << nullPage << urlTo << true << false;
QTest::newRow("From url to empty content page") << urlFrom << nullPage << false << true;
QTest::newRow("From one content to another") << urlFrom << urlTo << false << false;
}
void tst_QWebEngineView::changePage()
{
QScopedPointer<QWebEngineView> view(new QWebEngineView); view->resize(640, 480); view->show();
QFETCH(QUrl, urlFrom);
QFETCH(QUrl, urlTo);
QFETCH(bool, fromIsNullPage);
QFETCH(bool, toIsNullPage);
QSignalSpy spyUrl(view.get(), &QWebEngineView::urlChanged);
QSignalSpy spyTitle(view.get(), &QWebEngineView::titleChanged);
QSignalSpy spyIconUrl(view.get(), &QWebEngineView::iconUrlChanged);
QSignalSpy spyIcon(view.get(), &QWebEngineView::iconChanged);
QScopedPointer<QWebEnginePage> pageFrom(new QWebEnginePage);
QSignalSpy pageFromLoadSpy(pageFrom.get(), &QWebEnginePage::loadFinished);
QSignalSpy pageFromIconLoadSpy(pageFrom.get(), &QWebEnginePage::iconChanged);
pageFrom->load(urlFrom);
QTRY_COMPARE(pageFromLoadSpy.count(), 1);
QCOMPARE(pageFromLoadSpy.last().value(0).toBool(), true);
if (!fromIsNullPage) {
QTRY_COMPARE(pageFromIconLoadSpy.count(), 1);
QVERIFY(!pageFromIconLoadSpy.last().value(0).isNull());
}
view->setPage(pageFrom.get());
QTRY_COMPARE(spyUrl.count(), 1);
QCOMPARE(spyUrl.last().value(0).toUrl(), pageFrom->url());
QTRY_COMPARE(spyTitle.count(), 1);
QCOMPARE(spyTitle.last().value(0).toString(), pageFrom->title());
QTRY_COMPARE(spyIconUrl.count(), fromIsNullPage ? 0 : 1);
QTRY_COMPARE(spyIcon.count(), fromIsNullPage ? 0 : 1);
if (!fromIsNullPage) {
QVERIFY(!pageFrom->iconUrl().isEmpty());
QCOMPARE(spyIconUrl.last().value(0).toUrl(), pageFrom->iconUrl());
QCOMPARE(spyIcon.last().value(0), QVariant::fromValue(pageFrom->icon()));
}
QScopedPointer<QWebEnginePage> pageTo(new QWebEnginePage);
QSignalSpy pageToLoadSpy(pageTo.get(), &QWebEnginePage::loadFinished);
QSignalSpy pageToIconLoadSpy(pageTo.get(), &QWebEnginePage::iconChanged);
pageTo->load(urlTo);
QTRY_COMPARE(pageToLoadSpy.count(), 1);
QCOMPARE(pageToLoadSpy.last().value(0).toBool(), true);
if (!toIsNullPage) {
QTRY_COMPARE(pageToIconLoadSpy.count(), 1);
QVERIFY(!pageToIconLoadSpy.last().value(0).isNull());
}
view->setPage(pageTo.get());
QTRY_COMPARE(spyUrl.count(), 2);
QCOMPARE(spyUrl.last().value(0).toUrl(), pageTo->url());
QTRY_COMPARE(spyTitle.count(), 2);
QCOMPARE(spyTitle.last().value(0).toString(), pageTo->title());
bool iconIsSame = fromIsNullPage == toIsNullPage;
int iconChangeNotifyCount = fromIsNullPage ? (iconIsSame ? 0 : 1) : (iconIsSame ? 1 : 2);
QTRY_COMPARE(spyIconUrl.count(), iconChangeNotifyCount);
QTRY_COMPARE(spyIcon.count(), iconChangeNotifyCount);
QCOMPARE(pageFrom->iconUrl() == pageTo->iconUrl(), iconIsSame);
if (!iconIsSame) {
QCOMPARE(spyIconUrl.last().value(0).toUrl(), pageTo->iconUrl());
QCOMPARE(spyIcon.last().value(0), QVariant::fromValue(pageTo->icon()));
}
// verify no emits on destroy with the same number of signals in spy
view.reset();
qApp->processEvents();
QTRY_COMPARE(spyUrl.count(), 2);
QTRY_COMPARE(spyTitle.count(), 2);
QTRY_COMPARE(spyIconUrl.count(), iconChangeNotifyCount);
QTRY_COMPARE(spyIcon.count(), iconChangeNotifyCount);
}
void tst_QWebEngineView::reusePage_data()
{
QTest::addColumn<QString>("html");
QTest::newRow("WithoutPlugin") << "<html><body id='b'>text</body></html>";
QTest::newRow("WindowedPlugin") << QString("<html><body id='b'>text<embed src='resources/test.swf'></embed></body></html>");
QTest::newRow("WindowlessPlugin") << QString("<html><body id='b'>text<embed src='resources/test.swf' wmode=\"transparent\"></embed></body></html>");
}
void tst_QWebEngineView::reusePage()
{
if (!QDir(TESTS_SOURCE_DIR).exists())
W_QSKIP(QString("This test requires access to resources found in '%1'").arg(TESTS_SOURCE_DIR).toLatin1().constData(), SkipAll);
QDir::setCurrent(TESTS_SOURCE_DIR);
QFETCH(QString, html);
QWebEngineView* view1 = new QWebEngineView;
QPointer<QWebEnginePage> page = new QWebEnginePage;
view1->setPage(page.data());
page.data()->settings()->setAttribute(QWebEngineSettings::PluginsEnabled, true);
page->setHtml(html, QUrl::fromLocalFile(TESTS_SOURCE_DIR));
if (html.contains("</embed>")) {
// some reasonable time for the PluginStream to feed test.swf to flash and start painting
QSignalSpy spyFinished(view1, &QWebEngineView::loadFinished);
QVERIFY(spyFinished.wait(2000));
}
view1->show();
QVERIFY(QTest::qWaitForWindowExposed(view1));
delete view1;
QVERIFY(page != 0); // deleting view must not have deleted the page, since it's not a child of view
QWebEngineView *view2 = new QWebEngineView;
view2->setPage(page.data());
view2->show(); // in Windowless mode, you should still be able to see the plugin here
QVERIFY(QTest::qWaitForWindowExposed(view2));
delete view2;
delete page.data(); // must not crash
QDir::setCurrent(QApplication::applicationDirPath());
}
// Class used in crashTests
class WebViewCrashTest : public QObject {
Q_OBJECT
QWebEngineView* m_view;
public:
bool m_invokedStop;
bool m_stopBypassed;
WebViewCrashTest(QWebEngineView* view)
: m_view(view)
, m_invokedStop(false)
, m_stopBypassed(false)
{
view->connect(view, SIGNAL(loadProgress(int)), this, SLOT(loading(int)));
}
private Q_SLOTS:
void loading(int progress)
{
qDebug() << "progress: " << progress;
if (progress > 0 && progress < 100) {
QVERIFY(!m_invokedStop);
m_view->stop();
m_invokedStop = true;
} else if (!m_invokedStop && progress == 100) {
m_stopBypassed = true;
}
}
};
// Should not crash.
void tst_QWebEngineView::crashTests()
{
// Test if loading can be stopped in loadProgress handler without crash.
// Test page should have frames.
QWebEngineView view;
WebViewCrashTest tester(&view);
QUrl url("qrc:///resources/index.html");
view.load(url);
// If the verification fails, it means that either stopping doesn't work, or the hardware is
// too slow to load the page and thus to slow to issue the first loadProgress > 0 signal.
QTRY_VERIFY_WITH_TIMEOUT(tester.m_invokedStop || tester.m_stopBypassed, 10000);
if (tester.m_stopBypassed)
QEXPECT_FAIL("", "Loading was too fast to stop", Continue);
QVERIFY(tester.m_invokedStop);
}
void tst_QWebEngineView::microFocusCoordinates()
{
QWebEngineView webView;
webView.resize(640, 480);
webView.show();
QVERIFY(QTest::qWaitForWindowExposed(&webView));
QSignalSpy scrollSpy(webView.page(), SIGNAL(scrollPositionChanged(QPointF)));
QSignalSpy loadFinishedSpy(&webView, SIGNAL(loadFinished(bool)));
webView.page()->setHtml("<html><body>"
"<input type='text' id='input1' value='' maxlength='20'/><br>"
"<canvas id='canvas1' width='500' height='500'></canvas>"
"<input type='password'/><br>"
"<canvas id='canvas2' width='500' height='500'></canvas>"
"</body></html>");
QVERIFY(loadFinishedSpy.wait());
evaluateJavaScriptSync(webView.page(), "document.getElementById('input1').focus()");
QTRY_COMPARE(evaluateJavaScriptSync(webView.page(), "document.activeElement.id").toString(), QStringLiteral("input1"));
QTRY_VERIFY(webView.focusProxy()->inputMethodQuery(Qt::ImCursorRectangle).isValid());
QVariant initialMicroFocus = webView.focusProxy()->inputMethodQuery(Qt::ImCursorRectangle);
evaluateJavaScriptSync(webView.page(), "window.scrollBy(0, 50)");
QTRY_VERIFY(scrollSpy.count() > 0);
QTRY_VERIFY(webView.focusProxy()->inputMethodQuery(Qt::ImCursorRectangle).isValid());
QVariant currentMicroFocus = webView.focusProxy()->inputMethodQuery(Qt::ImCursorRectangle);
QCOMPARE(initialMicroFocus.toRect().translated(QPoint(0,-50)), currentMicroFocus.toRect());
}
void tst_QWebEngineView::focusInputTypes()
{
const QPlatformInputContext *context = QGuiApplicationPrivate::platformIntegration()->inputContext();
bool imeHasHiddenTextCapability = context && context->hasCapability(QPlatformInputContext::HiddenTextCapability);
QWebEngineView webView;
webView.resize(640, 480);
webView.show();
QVERIFY(QTest::qWaitForWindowExposed(&webView));
QSignalSpy loadFinishedSpy(&webView, SIGNAL(loadFinished(bool)));
webView.load(QUrl("qrc:///resources/input_types.html"));
QVERIFY(loadFinishedSpy.wait());
auto inputMethodQuery = [&webView](Qt::InputMethodQuery query) {
QInputMethodQueryEvent event(query);
QApplication::sendEvent(webView.focusProxy(), &event);
return event.value(query);
};
// 'text' field
QPoint textInputCenter = elementCenter(webView.page(), "textInput");
QTest::mouseClick(webView.focusProxy(), Qt::LeftButton, {}, textInputCenter);
QTRY_COMPARE(evaluateJavaScriptSync(webView.page(), "document.activeElement.id").toString(), QStringLiteral("textInput"));
VERIFY_INPUTMETHOD_HINTS(webView.focusProxy()->inputMethodHints(), Qt::ImhPreferLowercase);
QVERIFY(webView.focusProxy()->testAttribute(Qt::WA_InputMethodEnabled));
QTRY_VERIFY(inputMethodQuery(Qt::ImEnabled).toBool());
// 'password' field
QPoint passwordInputCenter = elementCenter(webView.page(), "passwordInput");
QTest::mouseClick(webView.focusProxy(), Qt::LeftButton, {}, passwordInputCenter);
QTRY_COMPARE(evaluateJavaScriptSync(webView.page(), "document.activeElement.id").toString(), QStringLiteral("passwordInput"));
VERIFY_INPUTMETHOD_HINTS(webView.focusProxy()->inputMethodHints(), (Qt::ImhSensitiveData | Qt::ImhNoPredictiveText | Qt::ImhNoAutoUppercase | Qt::ImhHiddenText));
QVERIFY(!webView.focusProxy()->testAttribute(Qt::WA_InputMethodEnabled));
QTRY_COMPARE(inputMethodQuery(Qt::ImEnabled).toBool(), imeHasHiddenTextCapability);
// 'tel' field
QPoint telInputCenter = elementCenter(webView.page(), "telInput");
QTest::mouseClick(webView.focusProxy(), Qt::LeftButton, {}, telInputCenter);
QTRY_COMPARE(evaluateJavaScriptSync(webView.page(), "document.activeElement.id").toString(), QStringLiteral("telInput"));
VERIFY_INPUTMETHOD_HINTS(webView.focusProxy()->inputMethodHints(), Qt::ImhDialableCharactersOnly);
QVERIFY(webView.focusProxy()->testAttribute(Qt::WA_InputMethodEnabled));
QTRY_VERIFY(inputMethodQuery(Qt::ImEnabled).toBool());
// 'number' field
QPoint numberInputCenter = elementCenter(webView.page(), "numberInput");
QTest::mouseClick(webView.focusProxy(), Qt::LeftButton, {}, numberInputCenter);
QTRY_COMPARE(evaluateJavaScriptSync(webView.page(), "document.activeElement.id").toString(), QStringLiteral("numberInput"));
VERIFY_INPUTMETHOD_HINTS(webView.focusProxy()->inputMethodHints(), Qt::ImhFormattedNumbersOnly);
QVERIFY(webView.focusProxy()->testAttribute(Qt::WA_InputMethodEnabled));
QTRY_VERIFY(inputMethodQuery(Qt::ImEnabled).toBool());
// 'email' field
QPoint emailInputCenter = elementCenter(webView.page(), "emailInput");
QTest::mouseClick(webView.focusProxy(), Qt::LeftButton, {}, emailInputCenter);
QTRY_COMPARE(evaluateJavaScriptSync(webView.page(), "document.activeElement.id").toString(), QStringLiteral("emailInput"));
VERIFY_INPUTMETHOD_HINTS(webView.focusProxy()->inputMethodHints(), Qt::ImhEmailCharactersOnly);
QVERIFY(webView.focusProxy()->testAttribute(Qt::WA_InputMethodEnabled));
QTRY_VERIFY(inputMethodQuery(Qt::ImEnabled).toBool());
// 'url' field
QPoint urlInputCenter = elementCenter(webView.page(), "urlInput");
QTest::mouseClick(webView.focusProxy(), Qt::LeftButton, {}, urlInputCenter);
QTRY_COMPARE(evaluateJavaScriptSync(webView.page(), "document.activeElement.id").toString(), QStringLiteral("urlInput"));
VERIFY_INPUTMETHOD_HINTS(webView.focusProxy()->inputMethodHints(), (Qt::ImhUrlCharactersOnly | Qt::ImhNoPredictiveText | Qt::ImhNoAutoUppercase));
QVERIFY(webView.focusProxy()->testAttribute(Qt::WA_InputMethodEnabled));
QTRY_VERIFY(inputMethodQuery(Qt::ImEnabled).toBool());
// 'password' field
QTest::mouseClick(webView.focusProxy(), Qt::LeftButton, {}, passwordInputCenter);
QTRY_COMPARE(evaluateJavaScriptSync(webView.page(), "document.activeElement.id").toString(), QStringLiteral("passwordInput"));
VERIFY_INPUTMETHOD_HINTS(webView.focusProxy()->inputMethodHints(), (Qt::ImhSensitiveData | Qt::ImhNoPredictiveText | Qt::ImhNoAutoUppercase | Qt::ImhHiddenText));
QVERIFY(!webView.focusProxy()->testAttribute(Qt::WA_InputMethodEnabled));
QTRY_COMPARE(inputMethodQuery(Qt::ImEnabled).toBool(), imeHasHiddenTextCapability);
// 'text' type
QTest::mouseClick(webView.focusProxy(), Qt::LeftButton, {}, textInputCenter);
QTRY_COMPARE(evaluateJavaScriptSync(webView.page(), "document.activeElement.id").toString(), QStringLiteral("textInput"));
VERIFY_INPUTMETHOD_HINTS(webView.focusProxy()->inputMethodHints(), Qt::ImhPreferLowercase);
QVERIFY(webView.focusProxy()->testAttribute(Qt::WA_InputMethodEnabled));
QTRY_VERIFY(inputMethodQuery(Qt::ImEnabled).toBool());
// 'password' field
QTest::mouseClick(webView.focusProxy(), Qt::LeftButton, {}, passwordInputCenter);
QTRY_COMPARE(evaluateJavaScriptSync(webView.page(), "document.activeElement.id").toString(), QStringLiteral("passwordInput"));
VERIFY_INPUTMETHOD_HINTS(webView.focusProxy()->inputMethodHints(), (Qt::ImhSensitiveData | Qt::ImhNoPredictiveText | Qt::ImhNoAutoUppercase | Qt::ImhHiddenText));
QVERIFY(!webView.focusProxy()->testAttribute(Qt::WA_InputMethodEnabled));
QTRY_COMPARE(inputMethodQuery(Qt::ImEnabled).toBool(), imeHasHiddenTextCapability);
// 'text area' field
QPoint textAreaCenter = elementCenter(webView.page(), "textArea");
QTest::mouseClick(webView.focusProxy(), Qt::LeftButton, {}, textAreaCenter);
QTRY_COMPARE(evaluateJavaScriptSync(webView.page(), "document.activeElement.id").toString(), QStringLiteral("textArea"));
VERIFY_INPUTMETHOD_HINTS(webView.focusProxy()->inputMethodHints(), (Qt::ImhMultiLine | Qt::ImhPreferLowercase));
QVERIFY(webView.focusProxy()->testAttribute(Qt::WA_InputMethodEnabled));
QTRY_VERIFY(inputMethodQuery(Qt::ImEnabled).toBool());
}
class KeyEventRecordingWidget : public QWidget {
public:
QList<QKeyEvent> pressEvents;
QList<QKeyEvent> releaseEvents;
void keyPressEvent(QKeyEvent *e) override { pressEvents << *e; }
void keyReleaseEvent(QKeyEvent *e) override { releaseEvents << *e; }
};
void tst_QWebEngineView::unhandledKeyEventPropagation()
{
KeyEventRecordingWidget parentWidget;
QWebEngineView webView(&parentWidget);
webView.resize(640, 480);
parentWidget.show();
QVERIFY(QTest::qWaitForWindowExposed(&webView));
QSignalSpy loadFinishedSpy(&webView, SIGNAL(loadFinished(bool)));
webView.load(QUrl("qrc:///resources/keyboardEvents.html"));
QVERIFY(loadFinishedSpy.wait());
evaluateJavaScriptSync(webView.page(), "document.getElementById('first_div').focus()");
QTRY_COMPARE(evaluateJavaScriptSync(webView.page(), "document.activeElement.id").toString(), QStringLiteral("first_div"));
QTest::sendKeyEvent(QTest::Press, webView.focusProxy(), Qt::Key_Right, QString(), Qt::NoModifier);
QTest::sendKeyEvent(QTest::Release, webView.focusProxy(), Qt::Key_Right, QString(), Qt::NoModifier);
// Right arrow key is unhandled thus focus is not changed
QTRY_COMPARE(parentWidget.releaseEvents.size(), 1);
QCOMPARE(evaluateJavaScriptSync(webView.page(), "document.activeElement.id").toString(), QStringLiteral("first_div"));
QTest::sendKeyEvent(QTest::Press, webView.focusProxy(), Qt::Key_Tab, QString(), Qt::NoModifier);
QTest::sendKeyEvent(QTest::Release, webView.focusProxy(), Qt::Key_Tab, QString(), Qt::NoModifier);
// Tab key is handled thus focus is changed
QTRY_COMPARE(parentWidget.releaseEvents.size(), 2);
QCOMPARE(evaluateJavaScriptSync(webView.page(), "document.activeElement.id").toString(), QStringLiteral("second_div"));
QTest::sendKeyEvent(QTest::Press, webView.focusProxy(), Qt::Key_Left, QString(), Qt::NoModifier);
QTest::sendKeyEvent(QTest::Release, webView.focusProxy(), Qt::Key_Left, QString(), Qt::NoModifier);
// Left arrow key is unhandled thus focus is not changed
QTRY_COMPARE(parentWidget.releaseEvents.size(), 3);
QCOMPARE(evaluateJavaScriptSync(webView.page(), "document.activeElement.id").toString(), QStringLiteral("second_div"));
// Focus the button and press 'y'.
evaluateJavaScriptSync(webView.page(), "document.getElementById('submit_button').focus()");
QTRY_COMPARE(evaluateJavaScriptSync(webView.page(), "document.activeElement.id").toString(), QStringLiteral("submit_button"));
QTest::sendKeyEvent(QTest::Press, webView.focusProxy(), Qt::Key_Y, 'y', Qt::NoModifier);
QTest::sendKeyEvent(QTest::Release, webView.focusProxy(), Qt::Key_Y, 'y', Qt::NoModifier);
QTRY_COMPARE(parentWidget.releaseEvents.size(), 4);
// The page will consume the Tab key to change focus between elements while the arrow
// keys won't be used.
QCOMPARE(parentWidget.pressEvents.size(), 3);
QCOMPARE(parentWidget.pressEvents[0].key(), (int)Qt::Key_Right);
QCOMPARE(parentWidget.pressEvents[1].key(), (int)Qt::Key_Left);
QCOMPARE(parentWidget.pressEvents[2].key(), (int)Qt::Key_Y);
// Key releases will all come back unconsumed.
QCOMPARE(parentWidget.releaseEvents[0].key(), (int)Qt::Key_Right);
QCOMPARE(parentWidget.releaseEvents[1].key(), (int)Qt::Key_Tab);
QCOMPARE(parentWidget.releaseEvents[2].key(), (int)Qt::Key_Left);
QCOMPARE(parentWidget.releaseEvents[3].key(), (int)Qt::Key_Y);
}
void tst_QWebEngineView::horizontalScrollbarTest()
{
QString html("<html><body>"
"<div style='width: 1000px; height: 1000px; background-color: green' />"
"</body></html>");
QWebEngineView view;
view.setFixedSize(600, 600);
view.show();
QVERIFY(QTest::qWaitForWindowExposed(&view));
QSignalSpy loadSpy(view.page(), SIGNAL(loadFinished(bool)));
view.setHtml(html);
QTRY_COMPARE(loadSpy.count(), 1);
QVERIFY(view.page()->scrollPosition() == QPoint(0, 0));
QSignalSpy scrollSpy(view.page(), SIGNAL(scrollPositionChanged(QPointF)));
// Note: The test below assumes that the layout direction is Qt::LeftToRight.
QTest::mouseClick(view.focusProxy(), Qt::LeftButton, {}, QPoint(550, 595));
scrollSpy.wait();
QVERIFY(view.page()->scrollPosition().x() > 0);
// Note: The test below assumes that the layout direction is Qt::LeftToRight.
QTest::mouseClick(view.focusProxy(), Qt::LeftButton, {}, QPoint(20, 595));
scrollSpy.wait();
QVERIFY(view.page()->scrollPosition() == QPoint(0, 0));
}
#if !(defined(WTF_USE_QT_MOBILE_THEME) && WTF_USE_QT_MOBILE_THEME)
void tst_QWebEngineView::setPalette_data()
{
QTest::addColumn<bool>("active");
QTest::addColumn<bool>("background");
QTest::newRow("activeBG") << true << true;
QTest::newRow("activeFG") << true << false;
QTest::newRow("inactiveBG") << false << true;
QTest::newRow("inactiveFG") << false << false;
}
// Render a QWebEngineView to a QImage twice, each time with a different palette set,
// verify that images rendered are not the same, confirming WebCore usage of
// custom palette on selections.
void tst_QWebEngineView::setPalette()
{
#if !defined(QWEBCONTENTVIEW_SETPALETTE)
QSKIP("QWEBCONTENTVIEW_SETPALETTE");
#else
QString html = "<html><head></head>"
"<body>"
"Some text here"
"</body>"
"</html>";
QFETCH(bool, active);
QFETCH(bool, background);
QWidget* activeView = 0;
// Use controlView to manage active/inactive state of test views by raising
// or lowering their position in the window stack.
QWebEngineView controlView;
controlView.setHtml(html);
QWebEngineView view1;
QPalette palette1;
QBrush brush1(Qt::red);
brush1.setStyle(Qt::SolidPattern);
if (active && background) {
// Rendered image must have red background on an active QWebEngineView.
palette1.setBrush(QPalette::Active, QPalette::Highlight, brush1);
} else if (active && !background) {
// Rendered image must have red foreground on an active QWebEngineView.
palette1.setBrush(QPalette::Active, QPalette::HighlightedText, brush1);
} else if (!active && background) {
// Rendered image must have red background on an inactive QWebEngineView.
palette1.setBrush(QPalette::Inactive, QPalette::Highlight, brush1);
} else if (!active && !background) {
// Rendered image must have red foreground on an inactive QWebEngineView.
palette1.setBrush(QPalette::Inactive, QPalette::HighlightedText, brush1);
}
view1.setPalette(palette1);
view1.setHtml(html);
view1.page()->setViewportSize(view1.page()->contentsSize());
view1.show();
QTest::qWaitForWindowExposed(&view1);
if (!active) {
controlView.show();
QTest::qWaitForWindowExposed(&controlView);
activeView = &controlView;
controlView.activateWindow();
} else {
view1.activateWindow();
activeView = &view1;
}
QTRY_COMPARE(QApplication::activeWindow(), activeView);
view1.page()->triggerAction(QWebEnginePage::SelectAll);
QImage img1(view1.page()->viewportSize(), QImage::Format_ARGB32);
QPainter painter1(&img1);
view1.page()->render(&painter1);
painter1.end();
view1.close();
controlView.close();
QWebEngineView view2;
QPalette palette2;
QBrush brush2(Qt::blue);
brush2.setStyle(Qt::SolidPattern);
if (active && background) {
// Rendered image must have blue background on an active QWebEngineView.
palette2.setBrush(QPalette::Active, QPalette::Highlight, brush2);
} else if (active && !background) {
// Rendered image must have blue foreground on an active QWebEngineView.
palette2.setBrush(QPalette::Active, QPalette::HighlightedText, brush2);
} else if (!active && background) {
// Rendered image must have blue background on an inactive QWebEngineView.
palette2.setBrush(QPalette::Inactive, QPalette::Highlight, brush2);
} else if (!active && !background) {
// Rendered image must have blue foreground on an inactive QWebEngineView.
palette2.setBrush(QPalette::Inactive, QPalette::HighlightedText, brush2);
}
view2.setPalette(palette2);
view2.setHtml(html);
view2.page()->setViewportSize(view2.page()->contentsSize());
view2.show();
QTest::qWaitForWindowExposed(&view2);
if (!active) {
controlView.show();
QTest::qWaitForWindowExposed(&controlView);
activeView = &controlView;
controlView.activateWindow();
} else {
view2.activateWindow();
activeView = &view2;
}
QTRY_COMPARE(QApplication::activeWindow(), activeView);
view2.page()->triggerAction(QWebEnginePage::SelectAll);
QImage img2(view2.page()->viewportSize(), QImage::Format_ARGB32);
QPainter painter2(&img2);
view2.page()->render(&painter2);
painter2.end();
view2.close();
controlView.close();
QVERIFY(img1 != img2);
#endif
}
#endif
void tst_QWebEngineView::renderingAfterMaxAndBack()
{
#if !defined(QWEBENGINEPAGE_RENDER)
QSKIP("QWEBENGINEPAGE_RENDER");
#else
QUrl url = QUrl("data:text/html,<html><head></head>"
"<body width=1024 height=768 bgcolor=red>"
"</body>"
"</html>");
QWebEngineView view;
view.page()->load(url);
QSignalSpy spyFinished(&view, &QWebEngineView::loadFinished);
QVERIFY(spyFinished.wait());
view.show();
view.page()->settings()->setMaximumPagesInCache(3);
QTest::qWaitForWindowExposed(&view);
QPixmap reference(view.page()->viewportSize());
reference.fill(Qt::red);
QPixmap image(view.page()->viewportSize());
QPainter painter(&image);
view.page()->render(&painter);
QCOMPARE(image, reference);
QUrl url2 = QUrl("data:text/html,<html><head></head>"
"<body width=1024 height=768 bgcolor=blue>"
"</body>"
"</html>");
view.page()->load(url2);
QVERIFY(spyFinished.wait());
view.showMaximized();
QTest::qWaitForWindowExposed(&view);
QPixmap reference2(view.page()->viewportSize());
reference2.fill(Qt::blue);
QPixmap image2(view.page()->viewportSize());
QPainter painter2(&image2);
view.page()->render(&painter2);
QCOMPARE(image2, reference2);
view.back();
QPixmap reference3(view.page()->viewportSize());
reference3.fill(Qt::red);
QPixmap image3(view.page()->viewportSize());
QPainter painter3(&image3);
view.page()->render(&painter3);
QCOMPARE(image3, reference3);
#endif
}
class KeyboardAndMouseEventRecordingWidget : public QWidget {
public:
explicit KeyboardAndMouseEventRecordingWidget(QWidget *parent = 0) :
QWidget(parent), m_eventCounter(0) {}
bool event(QEvent *event) override
{
QString eventString;
switch (event->type()) {
case QEvent::TabletPress:
case QEvent::TabletRelease:
case QEvent::TabletMove:
case QEvent::MouseButtonPress:
case QEvent::MouseButtonRelease:
case QEvent::MouseButtonDblClick:
case QEvent::MouseMove:
case QEvent::TouchBegin:
case QEvent::TouchUpdate:
case QEvent::TouchEnd:
case QEvent::TouchCancel:
case QEvent::ContextMenu:
case QEvent::KeyPress:
case QEvent::KeyRelease:
#ifndef QT_NO_WHEELEVENT
case QEvent::Wheel:
#endif
++m_eventCounter;
event->setAccepted(true);
QDebug(&eventString) << event;
m_eventHistory.append(eventString);
return true;
default:
break;
}
return QWidget::event(event);
}
void clearEventCount()
{
m_eventCounter = 0;
}
int eventCount()
{
return m_eventCounter;
}
void printEventHistory()
{
qDebug() << "Received events are:";
for (int i = 0; i < m_eventHistory.size(); ++i) {
qDebug() << m_eventHistory[i];
}
}
private:
int m_eventCounter;
QVector<QString> m_eventHistory;
};
void tst_QWebEngineView::doNotSendMouseKeyboardEventsWhenDisabled()
{
QFETCH(bool, viewEnabled);
QFETCH(int, resultEventCount);
KeyboardAndMouseEventRecordingWidget parentWidget;
parentWidget.resize(640, 480);
QWebEngineView webView(&parentWidget);
webView.setEnabled(viewEnabled);
parentWidget.setLayout(new QStackedLayout);
parentWidget.layout()->addWidget(&webView);
webView.resize(640, 480);
parentWidget.show();
QVERIFY(QTest::qWaitForWindowExposed(&webView));
QSignalSpy loadSpy(&webView, SIGNAL(loadFinished(bool)));
webView.setHtml("<html><head><title>Title</title></head><body>Hello"
"<input id=\"input\" type=\"text\"></body></html>");
QTRY_COMPARE(loadSpy.count(), 1);
// When the webView is enabled, the events are swallowed by it, and the parent widget
// does not receive any events, otherwise all events are processed by the parent widget.
parentWidget.clearEventCount();
QTest::mousePress(parentWidget.windowHandle(), Qt::LeftButton);
QTest::mouseMove(parentWidget.windowHandle(), QPoint(100, 100));
QTest::mouseRelease(parentWidget.windowHandle(), Qt::LeftButton,
Qt::KeyboardModifiers(), QPoint(100, 100));
// Wait a bit for the mouse events to be processed, so they don't interfere with the js focus
// below.
QTest::qWait(100);
evaluateJavaScriptSync(webView.page(), "document.getElementById(\"input\").focus()");
QTest::keyPress(parentWidget.windowHandle(), Qt::Key_H);
// Wait a bit for the key press to be handled. We have to do it, because the compare
// below could immediately finish successfully, without alloing for the events to be handled.
QTest::qWait(100);
QTRY_COMPARE_WITH_TIMEOUT_FAIL_BLOCK(parentWidget.eventCount(), resultEventCount,
1000, parentWidget.printEventHistory(););
}
void tst_QWebEngineView::doNotSendMouseKeyboardEventsWhenDisabled_data()
{
QTest::addColumn<bool>("viewEnabled");
QTest::addColumn<int>("resultEventCount");
QTest::newRow("enabled view receives events") << true << 0;
QTest::newRow("disabled view does not receive events") << false << 4;
}
void tst_QWebEngineView::stopSettingFocusWhenDisabled()
{
QFETCH(bool, viewEnabled);
QFETCH(bool, focusResult);
QWebEngineView webView;
webView.settings()->setAttribute(QWebEngineSettings::FocusOnNavigationEnabled, true);
webView.resize(640, 480);
webView.show();
webView.setEnabled(viewEnabled);
QVERIFY(QTest::qWaitForWindowExposed(&webView));
QSignalSpy loadSpy(&webView, SIGNAL(loadFinished(bool)));
webView.setHtml("<html><head><title>Title</title></head><body>Hello"
"<input id=\"input\" type=\"text\"></body></html>");
QTRY_COMPARE(loadSpy.count(), 1);
QTRY_COMPARE_WITH_TIMEOUT(webView.hasFocus(), focusResult, 1000);
evaluateJavaScriptSync(webView.page(), "document.getElementById(\"input\").focus()");
QTRY_COMPARE_WITH_TIMEOUT(webView.hasFocus(), focusResult, 1000);
}
void tst_QWebEngineView::stopSettingFocusWhenDisabled_data()
{
QTest::addColumn<bool>("viewEnabled");
QTest::addColumn<bool>("focusResult");
QTest::newRow("enabled view gets focus") << true << true;
QTest::newRow("disabled view does not get focus") << false << false;
}
void tst_QWebEngineView::focusOnNavigation_data()
{
QTest::addColumn<bool>("focusOnNavigation");
QTest::addColumn<bool>("viewReceivedFocus");
QTest::newRow("focusOnNavigation true") << true << true;
QTest::newRow("focusOnNavigation false") << false << false;
}
void tst_QWebEngineView::focusOnNavigation()
{
QFETCH(bool, focusOnNavigation);
QFETCH(bool, viewReceivedFocus);
#define triggerJavascriptFocus()\
evaluateJavaScriptSync(webView->page(), "document.getElementById(\"input\").focus()");
#define loadAndTriggerFocusAndCompare()\
QTRY_COMPARE(loadSpy.count(), 1);\
triggerJavascriptFocus();\
QTRY_COMPARE(webView->hasFocus(), viewReceivedFocus);
// Create a container widget, that will hold a line edit that has initial focus, and a web
// engine view.
QScopedPointer<QWidget> containerWidget(new QWidget);
QLineEdit *label = new QLineEdit;
label->setText(QString::fromLatin1("Text"));
label->setFocus();
// Create the web view, and set its focusOnNavigation property.
QWebEngineView *webView = new QWebEngineView;
QWebEngineSettings *settings = webView->page()->settings();
settings->setAttribute(QWebEngineSettings::FocusOnNavigationEnabled, focusOnNavigation);
webView->resize(300, 300);
QHBoxLayout *layout = new QHBoxLayout;
layout->addWidget(label);
layout->addWidget(webView);
containerWidget->setLayout(layout);
containerWidget->show();
QVERIFY(QTest::qWaitForWindowExposed(containerWidget.data()));
// Load the content, invoke javascript focus on the view, and check which widget has focus.
QSignalSpy loadSpy(webView, SIGNAL(loadFinished(bool)));
webView->setHtml("<html><head><title>Title</title></head><body>Hello"
"<input id=\"input\" type=\"text\"></body></html>");
loadAndTriggerFocusAndCompare();
// Load a different page, and check focus.
loadSpy.clear();
webView->setHtml("<html><head><title>Title</title></head><body>Hello 2"
"<input id=\"input\" type=\"text\"></body></html>");
loadAndTriggerFocusAndCompare();
// Navigate to previous page in history, check focus.
loadSpy.clear();
webView->triggerPageAction(QWebEnginePage::Back);
loadAndTriggerFocusAndCompare();
// Navigate to next page in history, check focus.
loadSpy.clear();
webView->triggerPageAction(QWebEnginePage::Forward);
loadAndTriggerFocusAndCompare();
// Reload page, check focus.
loadSpy.clear();
webView->triggerPageAction(QWebEnginePage::Reload);
loadAndTriggerFocusAndCompare();
// Reload page bypassing cache, check focus.
loadSpy.clear();
webView->triggerPageAction(QWebEnginePage::ReloadAndBypassCache);
loadAndTriggerFocusAndCompare();
// Manually forcing focus on web view should work.
webView->setFocus();
QTRY_COMPARE(webView->hasFocus(), true);
// Clean up.
#undef loadAndTriggerFocusAndCompare
#undef triggerJavascriptFocus
}
void tst_QWebEngineView::focusInternalRenderWidgetHostViewQuickItem()
{
// Create a container widget, that will hold a line edit that has initial focus, and a web
// engine view.
QScopedPointer<QWidget> containerWidget(new QWidget);
QLineEdit *label = new QLineEdit;
label->setText(QString::fromLatin1("Text"));
label->setFocus();
// Create the web view, and set its focusOnNavigation property to false, so it doesn't
// get initial focus.
QWebEngineView *webView = new QWebEngineView;
QWebEngineSettings *settings = webView->page()->settings();
settings->setAttribute(QWebEngineSettings::FocusOnNavigationEnabled, false);
webView->resize(300, 300);
QHBoxLayout *layout = new QHBoxLayout;
layout->addWidget(label);
layout->addWidget(webView);
containerWidget->setLayout(layout);
containerWidget->show();
QVERIFY(QTest::qWaitForWindowExposed(containerWidget.data()));
// Load the content, and check that focus is not set.
QSignalSpy loadSpy(webView, SIGNAL(loadFinished(bool)));
webView->setHtml("<html><head><title>Title</title></head><body>Hello"
"<input id=\"input\" type=\"text\"></body></html>");
QTRY_COMPARE(loadSpy.count(), 1);
QTRY_COMPARE(webView->hasFocus(), false);
// Manually trigger focus.
webView->setFocus();
// Check that focus is set in QWebEngineView and all internal classes.
QTRY_COMPARE(webView->hasFocus(), true);
QQuickWidget *renderWidgetHostViewQtDelegateWidget =
qobject_cast<QQuickWidget *>(webView->focusProxy());
QVERIFY(renderWidgetHostViewQtDelegateWidget);
QTRY_COMPARE(renderWidgetHostViewQtDelegateWidget->hasFocus(), true);
QQuickItem *renderWidgetHostViewQuickItem =
renderWidgetHostViewQtDelegateWidget->rootObject();
QVERIFY(renderWidgetHostViewQuickItem);
QTRY_COMPARE(renderWidgetHostViewQuickItem->hasFocus(), true);
}
void tst_QWebEngineView::doNotBreakLayout()
{
QScopedPointer<QWidget> containerWidget(new QWidget);
QHBoxLayout *layout = new QHBoxLayout;
layout->addWidget(new QWidget);
layout->addWidget(new QWidget);
layout->addWidget(new QWidget);
layout->addWidget(new QWebEngineView);
containerWidget->setLayout(layout);
containerWidget->setGeometry(50, 50, 800, 600);
containerWidget->show();
QVERIFY(QTest::qWaitForWindowExposed(containerWidget.data()));
QSize previousSize = static_cast<QWidgetItem *>(layout->itemAt(0))->widget()->size();
for (int i = 1; i < layout->count(); i++) {
QSize actualSize = static_cast<QWidgetItem *>(layout->itemAt(i))->widget()->size();
// There could be smaller differences on some platforms
QVERIFY(qAbs(previousSize.width() - actualSize.width()) <= 2);
QVERIFY(qAbs(previousSize.height() - actualSize.height()) <= 2);
previousSize = actualSize;
}
}
void tst_QWebEngineView::changeLocale()
{
QStringList errorLines;
QUrl url("http://non.existent/");
QLocale::setDefault(QLocale("de"));
QWebEngineView viewDE;
QSignalSpy loadFinishedSpyDE(&viewDE, SIGNAL(loadFinished(bool)));
viewDE.load(url);
QTRY_COMPARE_WITH_TIMEOUT(loadFinishedSpyDE.count(), 1, 20000);
QTRY_VERIFY(!toPlainTextSync(viewDE.page()).isEmpty());
#if QT_VERSION >= QT_VERSION_CHECK(5, 15, 0)
errorLines = toPlainTextSync(viewDE.page()).split(QRegularExpression("[\r\n]"), Qt::SkipEmptyParts);
#else
errorLines = toPlainTextSync(viewDE.page()).split(QRegularExpression("[\r\n]"), QString::SkipEmptyParts);
#endif
QCOMPARE(errorLines.first().toUtf8(), QByteArrayLiteral("Die Website ist nicht erreichbar"));
QLocale::setDefault(QLocale("en"));
QWebEngineView viewEN;
QSignalSpy loadFinishedSpyEN(&viewEN, SIGNAL(loadFinished(bool)));
viewEN.load(url);
QTRY_COMPARE_WITH_TIMEOUT(loadFinishedSpyEN.count(), 1, 20000);
QTRY_VERIFY(!toPlainTextSync(viewEN.page()).isEmpty());
#if QT_VERSION >= QT_VERSION_CHECK(5, 15, 0)
errorLines = toPlainTextSync(viewEN.page()).split(QRegularExpression("[\r\n]"), Qt::SkipEmptyParts);
#else
errorLines = toPlainTextSync(viewEN.page()).split(QRegularExpression("[\r\n]"), QString::SkipEmptyParts);
#endif
QCOMPARE(errorLines.first().toUtf8(), QByteArrayLiteral("This site can\xE2\x80\x99t be reached"));
// Reset error page
viewDE.load(QUrl("about:blank"));
QVERIFY(loadFinishedSpyDE.wait());
loadFinishedSpyDE.clear();
// Check whether an existing QWebEngineView keeps the language settings after changing the default locale
viewDE.load(url);
QTRY_COMPARE_WITH_TIMEOUT(loadFinishedSpyDE.count(), 1, 20000);
QTRY_VERIFY(!toPlainTextSync(viewDE.page()).isEmpty());
#if QT_VERSION >= QT_VERSION_CHECK(5, 15, 0)
errorLines = toPlainTextSync(viewDE.page()).split(QRegularExpression("[\r\n]"), Qt::SkipEmptyParts);
#else
errorLines = toPlainTextSync(viewDE.page()).split(QRegularExpression("[\r\n]"), QString::SkipEmptyParts);
#endif
QCOMPARE(errorLines.first().toUtf8(), QByteArrayLiteral("Die Website ist nicht erreichbar"));
}
void tst_QWebEngineView::mixLangLocale_data()
{
QTest::addColumn<QString>("locale");
QTest::addColumn<QByteArray>("formattedNumber");
QTest::newRow("en_DK") << "en-DK" << QByteArray("1.234.567.890");
QTest::newRow("de") << "de" << QByteArray("1.234.567.890");
QTest::newRow("de_CH") << "de-CH" << QByteArray("1’234’567’890");
QTest::newRow("eu_ES") << "eu-ES" << QByteArray("1.234.567.890");
QTest::newRow("hu_HU") << "hu-HU" << QByteArray("1\xC2\xA0""234\xC2\xA0""567\xC2\xA0""890"); // no-break spaces
}
void tst_QWebEngineView::mixLangLocale()
{
QFETCH(QString, locale);
QFETCH(QByteArray, formattedNumber);
QLocale::setDefault(locale);
QWebEngineView view;
QSignalSpy loadSpy(&view, &QWebEngineView::loadFinished);
bool terminated = false;
auto sc = connect(view.page(), &QWebEnginePage::renderProcessTerminated, [&] () { terminated = true; });
view.load(QUrl("qrc:///resources/dummy.html"));
QTRY_VERIFY(terminated || loadSpy.count() == 1);
QVERIFY2(!terminated,
qPrintable(QString("Locale [%1] terminated: %2, loaded: %3").arg(locale).arg(terminated).arg(loadSpy.count())));
QVERIFY(loadSpy.first().first().toBool());
QString content = toPlainTextSync(view.page());
QVERIFY2(!content.isEmpty() && content.contains("test content"), qPrintable(content));
QCOMPARE(evaluateJavaScriptSync(view.page(), "navigator.language").toString(), QLocale().bcp47Name());
if (locale == "eu-ES")
QEXPECT_FAIL("", "Basque number formatting is somehow dependent on environment", Continue);
QCOMPARE(evaluateJavaScriptSync(view.page(), "Number(1234567890).toLocaleString()").toByteArray(), formattedNumber);
QLocale::setDefault(QLocale("en"));
}
void tst_QWebEngineView::inputMethodsTextFormat_data()
{
QTest::addColumn<QString>("string");
QTest::addColumn<int>("start");
QTest::addColumn<int>("length");
QTest::addColumn<int>("underlineStyle");
QTest::addColumn<QColor>("underlineColor");
QTest::addColumn<QColor>("backgroundColor");
QTest::newRow("") << QString("") << 0 << 0 << static_cast<int>(QTextCharFormat::SingleUnderline) << QColor("red") << QColor();
QTest::newRow("Q") << QString("Q") << 0 << 1 << static_cast<int>(QTextCharFormat::SingleUnderline) << QColor("red") << QColor();
QTest::newRow("Qt") << QString("Qt") << 0 << 1 << static_cast<int>(QTextCharFormat::SingleUnderline) << QColor("red") << QColor();
QTest::newRow("Qt") << QString("Qt") << 0 << 2 << static_cast<int>(QTextCharFormat::SingleUnderline) << QColor("red") << QColor();
QTest::newRow("Qt") << QString("Qt") << 1 << 1 << static_cast<int>(QTextCharFormat::SingleUnderline) << QColor("red") << QColor();
QTest::newRow("Qt ") << QString("Qt ") << 0 << 1 << static_cast<int>(QTextCharFormat::SingleUnderline) << QColor("red") << QColor();
QTest::newRow("Qt ") << QString("Qt ") << 1 << 1 << static_cast<int>(QTextCharFormat::SingleUnderline) << QColor("red") << QColor();
QTest::newRow("Qt ") << QString("Qt ") << 2 << 1 << static_cast<int>(QTextCharFormat::SingleUnderline) << QColor("red") << QColor();
QTest::newRow("Qt ") << QString("Qt ") << 2 << -1 << static_cast<int>(QTextCharFormat::SingleUnderline) << QColor("red") << QColor();
QTest::newRow("Qt ") << QString("Qt ") << -2 << 3 << static_cast<int>(QTextCharFormat::SingleUnderline) << QColor("red") << QColor();
QTest::newRow("Qt ") << QString("Qt ") << -1 << -1 << static_cast<int>(QTextCharFormat::SingleUnderline) << QColor("red") << QColor();
QTest::newRow("Qt ") << QString("Qt ") << 0 << 3 << static_cast<int>(QTextCharFormat::SingleUnderline) << QColor("red") << QColor();
QTest::newRow("The Qt") << QString("The Qt") << 0 << 1 << static_cast<int>(QTextCharFormat::SingleUnderline) << QColor("red") << QColor();
QTest::newRow("The Qt Company") << QString("The Qt Company") << 0 << 1 << static_cast<int>(QTextCharFormat::SingleUnderline) << QColor("red") << QColor();
QTest::newRow("The Qt Company") << QString("The Qt Company") << 0 << 3 << static_cast<int>(QTextCharFormat::SingleUnderline) << QColor("green") << QColor();
QTest::newRow("The Qt Company") << QString("The Qt Company") << 4 << 2 << static_cast<int>(QTextCharFormat::SingleUnderline) << QColor("green") << QColor("red");
QTest::newRow("The Qt Company") << QString("The Qt Company") << 7 << 7 << static_cast<int>(QTextCharFormat::NoUnderline) << QColor("green") << QColor("red");
QTest::newRow("The Qt Company") << QString("The Qt Company") << 7 << 7 << static_cast<int>(QTextCharFormat::NoUnderline) << QColor() << QColor("red");
}
void tst_QWebEngineView::inputMethodsTextFormat()
{
QWebEngineView view;
view.settings()->setAttribute(QWebEngineSettings::FocusOnNavigationEnabled, true);
QSignalSpy loadFinishedSpy(&view, SIGNAL(loadFinished(bool)));
view.setHtml("<html><body>"
" <input type='text' id='input1' style='font-family: serif' value='' maxlength='20'/>"
"</body></html>");
QTRY_COMPARE(loadFinishedSpy.count(), 1);
evaluateJavaScriptSync(view.page(), "document.getElementById('input1').focus()");
view.show();
QVERIFY(QTest::qWaitForWindowExposed(&view));
QFETCH(QString, string);
QFETCH(int, start);
QFETCH(int, length);
QFETCH(int, underlineStyle);
QFETCH(QColor, underlineColor);
QFETCH(QColor, backgroundColor);
QList<QInputMethodEvent::Attribute> attrs;
QTextCharFormat format;
format.setUnderlineStyle(static_cast<QTextCharFormat::UnderlineStyle>(underlineStyle));
format.setUnderlineColor(underlineColor);
// Setting background color is disabled for Qt WebEngine because some IME manager
// sets background color to black and there is no API for setting the foreground color.
// This may result black text on black background. However, we still test it to ensure
// changing background color doesn't cause any crash.
if (backgroundColor.isValid())
format.setBackground(QBrush(backgroundColor));
attrs.append(QInputMethodEvent::Attribute(QInputMethodEvent::TextFormat, start, length, format));
QInputMethodEvent im(string, attrs);
QVERIFY(QApplication::sendEvent(view.focusProxy(), &im));
QTRY_COMPARE(evaluateJavaScriptSync(view.page(), "document.getElementById('input1').value").toString(), string);
}
void tst_QWebEngineView::keyboardEvents()
{
QWebEngineView view;
view.show();
QSignalSpy loadFinishedSpy(&view, SIGNAL(loadFinished(bool)));
view.load(QUrl("qrc:///resources/keyboardEvents.html"));
QVERIFY(loadFinishedSpy.wait());
QStringList elements;
elements << "first_div" << "second_div";
elements << "text_input" << "radio1" << "checkbox1" << "checkbox2";
elements << "number_input" << "range_input" << "search_input";
elements << "submit_button" << "combobox" << "first_hyperlink" << "second_hyperlink";
// Iterate over the elements of the test page with the Tab key. This tests whether any
// element blocks the in-page navigation by Tab.
for (const QString &elementId : elements) {
QTRY_COMPARE(evaluateJavaScriptSync(view.page(), "document.activeElement.id").toString(), elementId);
QTest::keyPress(view.focusProxy(), Qt::Key_Tab);
}
// Move back to the radio buttons with the Shift+Tab key combination
for (int i = 0; i < 10; ++i)
QTest::keyPress(view.focusProxy(), Qt::Key_Tab, Qt::ShiftModifier);
QTRY_COMPARE(evaluateJavaScriptSync(view.page(), "document.activeElement.id").toString(), QStringLiteral("radio2"));
// Test the Space key by checking a radio button
QVERIFY(!evaluateJavaScriptSync(view.page(), "document.getElementById('radio2').checked").toBool());
QTest::keyClick(view.focusProxy(), Qt::Key_Space);
QTRY_VERIFY(evaluateJavaScriptSync(view.page(), "document.getElementById('radio2').checked").toBool());
// Test the Left key by switching the radio button
QVERIFY(!evaluateJavaScriptSync(view.page(), "document.getElementById('radio1').checked").toBool());
QTest::keyPress(view.focusProxy(), Qt::Key_Left);
QTRY_COMPARE(evaluateJavaScriptSync(view.page(), "document.activeElement.id").toString(), QStringLiteral("radio1"));
QVERIFY(!evaluateJavaScriptSync(view.page(), "document.getElementById('radio2').checked").toBool());
QVERIFY(evaluateJavaScriptSync(view.page(), "document.getElementById('radio1').checked").toBool());
// Test the Space key by unchecking a checkbox
evaluateJavaScriptSync(view.page(), "document.getElementById('checkbox1').focus()");
QVERIFY(evaluateJavaScriptSync(view.page(), "document.getElementById('checkbox1').checked").toBool());
QTest::keyClick(view.focusProxy(), Qt::Key_Space);
QTRY_VERIFY(!evaluateJavaScriptSync(view.page(), "document.getElementById('checkbox1').checked").toBool());
// Test the Up and Down keys by changing the value of a spinbox
evaluateJavaScriptSync(view.page(), "document.getElementById('number_input').focus()");
QCOMPARE(evaluateJavaScriptSync(view.page(), "document.getElementById('number_input').value").toInt(), 5);
QTest::keyPress(view.focusProxy(), Qt::Key_Up);
QTRY_COMPARE(evaluateJavaScriptSync(view.page(), "document.getElementById('number_input').value").toInt(), 6);
QTest::keyPress(view.focusProxy(), Qt::Key_Down);
QTRY_COMPARE(evaluateJavaScriptSync(view.page(), "document.getElementById('number_input').value").toInt(), 5);
// Test the Left, Right, Home, PageUp, End and PageDown keys by changing the value of a slider
evaluateJavaScriptSync(view.page(), "document.getElementById('range_input').focus()");
QCOMPARE(evaluateJavaScriptSync(view.page(), "document.getElementById('range_input').value").toString(), QStringLiteral("5"));
QTest::keyPress(view.focusProxy(), Qt::Key_Left);
QTRY_COMPARE(evaluateJavaScriptSync(view.page(), "document.getElementById('range_input').value").toString(), QStringLiteral("4"));
QTest::keyPress(view.focusProxy(), Qt::Key_Right);
QTRY_COMPARE(evaluateJavaScriptSync(view.page(), "document.getElementById('range_input').value").toString(), QStringLiteral("5"));
QTest::keyPress(view.focusProxy(), Qt::Key_Home);
QTRY_COMPARE(evaluateJavaScriptSync(view.page(), "document.getElementById('range_input').value").toString(), QStringLiteral("0"));
QTest::keyPress(view.focusProxy(), Qt::Key_PageUp);
QTRY_COMPARE(evaluateJavaScriptSync(view.page(), "document.getElementById('range_input').value").toString(), QStringLiteral("1"));
QTest::keyPress(view.focusProxy(), Qt::Key_End);
QTRY_COMPARE(evaluateJavaScriptSync(view.page(), "document.getElementById('range_input').value").toString(), QStringLiteral("10"));
QTest::keyPress(view.focusProxy(), Qt::Key_PageDown);
QTRY_COMPARE(evaluateJavaScriptSync(view.page(), "document.getElementById('range_input').value").toString(), QStringLiteral("9"));
// Test the Escape key by removing the content of a search field
evaluateJavaScriptSync(view.page(), "document.getElementById('search_input').focus()");
QCOMPARE(evaluateJavaScriptSync(view.page(), "document.getElementById('search_input').value").toString(), QStringLiteral("test"));
QTest::keyPress(view.focusProxy(), Qt::Key_Escape);
QTRY_VERIFY(evaluateJavaScriptSync(view.page(), "document.getElementById('search_input').value").toString().isEmpty());
// Test the alpha keys by changing the values in a combobox
evaluateJavaScriptSync(view.page(), "document.getElementById('combobox').focus()");
QCOMPARE(evaluateJavaScriptSync(view.page(), "document.getElementById('combobox').value").toString(), QStringLiteral("a"));
QTest::keyPress(view.focusProxy(), Qt::Key_B);
QTRY_COMPARE(evaluateJavaScriptSync(view.page(), "document.getElementById('combobox').value").toString(), QStringLiteral("b"));
// Must wait with the second key press to simulate selection of another element
QTest::keyPress(view.focusProxy(), Qt::Key_C, Qt::NoModifier, 1100 /* blink::typeAheadTimeout + 0.1s */);
QTRY_COMPARE(evaluateJavaScriptSync(view.page(), "document.getElementById('combobox').value").toString(), QStringLiteral("c"));
// Test the Enter key by loading a page with a hyperlink
evaluateJavaScriptSync(view.page(), "document.getElementById('first_hyperlink').focus()");
QTest::keyPress(view.focusProxy(), Qt::Key_Enter);
QVERIFY(loadFinishedSpy.wait());
}
class WebViewWithUrlBar : public QWidget {
public:
QLineEdit *lineEdit = new QLineEdit;
QCompleter *urlCompleter = new QCompleter({ QStringLiteral("test") }, lineEdit);
QWebEngineView *webView = new QWebEngineView;
QVBoxLayout *layout = new QVBoxLayout;
WebViewWithUrlBar()
{
resize(500, 500);
setLayout(layout);
layout->addWidget(lineEdit);
layout->addWidget(webView);
lineEdit->setCompleter(urlCompleter);
lineEdit->setFocus();
}
};
void tst_QWebEngineView::keyboardFocusAfterPopup()
{
const QString html = QStringLiteral(
"<html>"
" <body onload=\"document.getElementById('input1').focus()\">"
" <input id=input1 type=text/>"
" </body>"
"</html>");
WebViewWithUrlBar window;
QSignalSpy loadFinishedSpy(window.webView, &QWebEngineView::loadFinished);
connect(window.lineEdit, &QLineEdit::editingFinished, [&] { window.webView->setHtml(html); });
window.webView->settings()->setAttribute(QWebEngineSettings::FocusOnNavigationEnabled, true);
window.show();
// Focus will initially go to the QLineEdit.
QTRY_COMPARE(QApplication::focusWidget(), window.lineEdit);
// Trigger QCompleter's popup and select the first suggestion.
QTest::keyClick(QApplication::focusWindow(), Qt::Key_T);
QTRY_VERIFY(QApplication::activePopupWidget());
QTest::keyClick(QApplication::focusWindow(), Qt::Key_Down);
QTest::keyClick(QApplication::focusWindow(), Qt::Key_Enter);
// Due to FocusOnNavigationEnabled, focus should now move to the webView.
QTRY_COMPARE(QApplication::focusWidget(), window.webView->focusProxy());
// Keyboard events sent to the window should go to the <input> element.
QVERIFY(loadFinishedSpy.count() || loadFinishedSpy.wait());
QTest::keyClick(QApplication::focusWindow(), Qt::Key_X);
QTRY_COMPARE(evaluateJavaScriptSync(window.webView->page(), "document.getElementById('input1').value").toString(),
QStringLiteral("x"));
}
void tst_QWebEngineView::mouseClick()
{
QWebEngineView view;
view.show();
view.resize(200, 200);
QVERIFY(QTest::qWaitForWindowExposed(&view));
QSignalSpy loadFinishedSpy(&view, SIGNAL(loadFinished(bool)));
QSignalSpy selectionChangedSpy(&view, SIGNAL(selectionChanged()));
QPoint textInputCenter;
// Single Click
view.settings()->setAttribute(QWebEngineSettings::FocusOnNavigationEnabled, false);
selectionChangedSpy.clear();
view.setHtml("<html><body>"
"<form><input id='input' width='150' type='text' value='The Qt Company' /></form>"
"</body></html>");
QVERIFY(loadFinishedSpy.wait());
QVERIFY(evaluateJavaScriptSync(view.page(), "document.activeElement.id").toString().isEmpty());
textInputCenter = elementCenter(view.page(), "input");
QTest::mouseClick(view.focusProxy(), Qt::LeftButton, {}, textInputCenter);
QTRY_COMPARE(evaluateJavaScriptSync(view.page(), "document.activeElement.id").toString(), QStringLiteral("input"));
QCOMPARE(selectionChangedSpy.count(), 0);
QVERIFY(view.focusProxy()->inputMethodQuery(Qt::ImCurrentSelection).toString().isEmpty());
// Double click
view.settings()->setAttribute(QWebEngineSettings::FocusOnNavigationEnabled, true);
selectionChangedSpy.clear();
view.setHtml("<html><body onload='document.getElementById(\"input\").focus()'>"
"<form><input id='input' width='150' type='text' value='The Qt Company' /></form>"
"</body></html>");
QVERIFY(loadFinishedSpy.wait());
textInputCenter = elementCenter(view.page(), "input");
QTest::mouseMultiClick(view.focusProxy(), textInputCenter, 2);
QVERIFY(selectionChangedSpy.wait());
QCOMPARE(selectionChangedSpy.count(), 1);
QCOMPARE(evaluateJavaScriptSync(view.page(), "document.activeElement.id").toString(), QStringLiteral("input"));
QCOMPARE(view.focusProxy()->inputMethodQuery(Qt::ImCurrentSelection).toString(), QStringLiteral("Company"));
QTest::mouseClick(view.focusProxy(), Qt::LeftButton, {}, textInputCenter);
QVERIFY(selectionChangedSpy.wait());
QCOMPARE(selectionChangedSpy.count(), 2);
QVERIFY(view.focusProxy()->inputMethodQuery(Qt::ImCurrentSelection).toString().isEmpty());
// Triple click
view.settings()->setAttribute(QWebEngineSettings::FocusOnNavigationEnabled, true);
selectionChangedSpy.clear();
view.setHtml("<html><body onload='document.getElementById(\"input\").focus()'>"
"<form><input id='input' width='150' type='text' value='The Qt Company' /></form>"
"</body></html>");
QVERIFY(loadFinishedSpy.wait());
textInputCenter = elementCenter(view.page(), "input");
QTest::mouseMultiClick(view.focusProxy(), textInputCenter, 3);
QVERIFY(selectionChangedSpy.wait());
QTRY_COMPARE(selectionChangedSpy.count(), 2);
QCOMPARE(evaluateJavaScriptSync(view.page(), "document.activeElement.id").toString(), QStringLiteral("input"));
QCOMPARE(view.focusProxy()->inputMethodQuery(Qt::ImCurrentSelection).toString(), QStringLiteral("The Qt Company"));
QTest::mouseClick(view.focusProxy(), Qt::LeftButton, {}, textInputCenter);
QVERIFY(selectionChangedSpy.wait());
QCOMPARE(selectionChangedSpy.count(), 3);
QVERIFY(view.focusProxy()->inputMethodQuery(Qt::ImCurrentSelection).toString().isEmpty());
}
void tst_QWebEngineView::postData()
{
QMap<QString, QString> postData;
// use reserved characters to make the test harder to pass
postData[QStringLiteral("Spä=m")] = QStringLiteral("ëgg:s");
postData[QStringLiteral("foo\r\n")] = QStringLiteral("ba&r");
QEventLoop eventloop;
// Set up dummy "HTTP" server
QTcpServer server;
connect(&server, &QTcpServer::newConnection, this, [this, &server, &eventloop, &postData](){
QTcpSocket* socket = server.nextPendingConnection();
connect(socket, &QAbstractSocket::disconnected, this, [&eventloop](){
eventloop.quit();
});
connect(socket, &QIODevice::readyRead, this, [socket, &server, &postData](){
QByteArray rawData = socket->readAll();
QStringList lines = QString::fromLocal8Bit(rawData).split("\r\n");
// examine request
#if QT_VERSION >= QT_VERSION_CHECK(5, 15, 0)
QStringList request = lines[0].split(" ", Qt::SkipEmptyParts);
#else
QStringList request = lines[0].split(" ", QString::SkipEmptyParts);
#endif
bool requestOk = request.length() > 2
&& request[2].toUpper().startsWith("HTTP/")
&& request[0].toUpper() == "POST"
&& request[1] == "/";
if (!requestOk) // POST and HTTP/... can be switched(?)
requestOk = request.length() > 2
&& request[0].toUpper().startsWith("HTTP/")
&& request[2].toUpper() == "POST"
&& request[1] == "/";
// examine headers
int line = 1;
bool headersOk = true;
for (; headersOk && line < lines.length(); line++) {
QStringList headerParts = lines[line].split(":");
if (headerParts.length() < 2)
break;
QString headerKey = headerParts[0].trimmed().toLower();
QString headerValue = headerParts[1].trimmed().toLower();
if (headerKey == "host")
headersOk = headersOk && (headerValue == "127.0.0.1")
&& (headerParts.length() == 3)
&& (headerParts[2].trimmed()
== QString::number(server.serverPort()));
if (headerKey == "content-type")
headersOk = headersOk && (headerValue == "application/x-www-form-urlencoded");
}
// examine body
bool bodyOk = true;
if (lines.length() == line+2) {
QStringList postedFields = lines[line+1].split("&");
QMap<QString, QString> postedData;
for (int i = 0; bodyOk && i < postedFields.length(); i++) {
QStringList postedField = postedFields[i].split("=");
if (postedField.length() == 2)
postedData[QUrl::fromPercentEncoding(postedField[0].toLocal8Bit())]
= QUrl::fromPercentEncoding(postedField[1].toLocal8Bit());
else
bodyOk = false;
}
bodyOk = bodyOk && (postedData == postData);
} else { // no body at all or more than 1 line
bodyOk = false;
}
// send response
socket->write("HTTP/1.1 200 OK\r\n");
socket->write("Content-Type: text/html\r\n");
socket->write("Content-Length: 39\r\n\r\n");
if (requestOk && headersOk && bodyOk)
// 6 6 11 7 7 2 = 39 (Content-Length)
socket->write("<html><body>Test Passed</body></html>\r\n");
else
socket->write("<html><body>Test Failed</body></html>\r\n");
socket->flush();
if (!requestOk || !headersOk || !bodyOk) {
qDebug() << "Dummy HTTP Server: received request was not as expected";
qDebug() << rawData;
QVERIFY(requestOk); // one of them will yield useful output and make the test fail
QVERIFY(headersOk);
QVERIFY(bodyOk);
}
socket->close();
});
});
if (!server.listen())
QFAIL("Dummy HTTP Server: listen() failed");
// Manual, hard coded client (commented out, but not removed - for reference and just in case)
/*
QTcpSocket client;
connect(&client, &QIODevice::readyRead, this, [&client, &eventloop](){
qDebug() << "Dummy HTTP client: data received";
qDebug() << client.readAll();
eventloop.quit();
});
connect(&client, &QAbstractSocket::connected, this, [&client](){
client.write("HTTP/1.1 / GET\r\n\r\n");
});
client.connectToHost(QHostAddress::LocalHost, server.serverPort());
*/
// send the POST request
QWebEngineView view;
QString sPort = QString::number(server.serverPort());
view.load(QWebEngineHttpRequest::postRequest(QUrl("http://127.0.0.1:"+sPort), postData));
// timeout after 10 seconds
QTimer timeoutGuard(this);
connect(&timeoutGuard, &QTimer::timeout, this, [&eventloop](){
eventloop.quit();
QFAIL("Dummy HTTP Server: waiting for data timed out");
});
timeoutGuard.setSingleShot(true);
timeoutGuard.start(10000);
// start the test
eventloop.exec();
timeoutGuard.stop();
server.close();
}
void tst_QWebEngineView::inputFieldOverridesShortcuts()
{
bool actionTriggered = false;
QAction *action = new QAction;
connect(action, &QAction::triggered, [&actionTriggered] () { actionTriggered = true; });
QWebEngineView view;
view.addAction(action);
QSignalSpy loadFinishedSpy(&view, SIGNAL(loadFinished(bool)));
view.setHtml(QString("<html><body>"
"<button id=\"btn1\" type=\"button\">push it real good</button>"
"<input id=\"input1\" type=\"text\" value=\"x\">"
"<input id=\"pass1\" type=\"password\" value=\"x\">"
"</body></html>"));
QVERIFY(loadFinishedSpy.wait());
view.show();
QVERIFY(QTest::qWaitForWindowActive(&view));
auto inputFieldValue = [&view] () -> QString {
return evaluateJavaScriptSync(view.page(),
"document.getElementById('input1').value").toString();
};
auto passwordFieldValue = [&view] () -> QString {
return evaluateJavaScriptSync(view.page(),
"document.getElementById('pass1').value").toString();
};
// The input form is not focused. The action is triggered on pressing Shift+Delete.
action->setShortcut(Qt::SHIFT + Qt::Key_Delete);
QTest::keyClick(view.windowHandle(), Qt::Key_Delete, Qt::ShiftModifier);
QTRY_VERIFY(actionTriggered);
QCOMPARE(inputFieldValue(), QString("x"));
// The input form is not focused. The action is triggered on pressing X.
action->setShortcut(Qt::Key_X);
actionTriggered = false;
QTest::keyClick(view.windowHandle(), Qt::Key_X);
QTRY_VERIFY(actionTriggered);
QCOMPARE(inputFieldValue(), QString("x"));
// The input form is focused. The action is not triggered, and the form's text changed.
evaluateJavaScriptSync(view.page(), "document.getElementById('input1').focus();");
QTRY_COMPARE(evaluateJavaScriptSync(view.page(), "document.activeElement.id").toString(), QStringLiteral("input1"));
actionTriggered = false;
QTest::keyClick(view.windowHandle(), Qt::Key_Y);
QTRY_COMPARE(inputFieldValue(), QString("yx"));
QTest::keyClick(view.windowHandle(), Qt::Key_X);
QTRY_COMPARE(inputFieldValue(), QString("yxx"));
QVERIFY(!actionTriggered);
// The password input form is focused. The action is not triggered, and the form's text changed.
evaluateJavaScriptSync(view.page(), "document.getElementById('pass1').focus();");
QTRY_COMPARE(evaluateJavaScriptSync(view.page(), "document.activeElement.id").toString(), QStringLiteral("pass1"));
actionTriggered = false;
QTest::keyClick(view.windowHandle(), Qt::Key_Y);
QTRY_COMPARE(passwordFieldValue(), QString("yx"));
QTest::keyClick(view.windowHandle(), Qt::Key_X);
QTRY_COMPARE(passwordFieldValue(), QString("yxx"));
QVERIFY(!actionTriggered);
// The input form is focused. Make sure we don't override all short cuts.
// A Ctrl-1 action is no default Qt key binding and should be triggerable.
evaluateJavaScriptSync(view.page(), "document.getElementById('input1').focus();");
QTRY_COMPARE(evaluateJavaScriptSync(view.page(), "document.activeElement.id").toString(), QStringLiteral("input1"));
action->setShortcut(Qt::CTRL + Qt::Key_1);
QTest::keyClick(view.windowHandle(), Qt::Key_1, Qt::ControlModifier);
QTRY_VERIFY(actionTriggered);
QCOMPARE(inputFieldValue(), QString("yxx"));
// The input form is focused. The following shortcuts are not overridden
// thus handled by Qt WebEngine. Make sure the subsequent shortcuts with text
// character don't cause assert due to an unconsumed editor command.
QTest::keyClick(view.windowHandle(), Qt::Key_A, Qt::ControlModifier);
QTest::keyClick(view.windowHandle(), Qt::Key_C, Qt::ControlModifier);
QTest::keyClick(view.windowHandle(), Qt::Key_V, Qt::ControlModifier);
QTest::keyClick(view.windowHandle(), Qt::Key_V, Qt::ControlModifier);
QTRY_COMPARE(inputFieldValue(), QString("yxxyxx"));
// Remove focus from the input field. A QKeySequence::Copy action must be triggerable.
evaluateJavaScriptSync(view.page(), "document.getElementById('btn1').focus();");
QTRY_COMPARE(evaluateJavaScriptSync(view.page(), "document.activeElement.id").toString(), QStringLiteral("btn1"));
action->setShortcut(QKeySequence::Copy);
actionTriggered = false;
QTest::keyClick(view.windowHandle(), Qt::Key_C, Qt::ControlModifier);
QTRY_VERIFY(actionTriggered);
}
struct InputMethodInfo
{
InputMethodInfo(const int cursorPosition,
const int anchorPosition,
QString surroundingText,
QString selectedText)
: cursorPosition(cursorPosition)
, anchorPosition(anchorPosition)
, surroundingText(surroundingText)
, selectedText(selectedText)
{}
int cursorPosition;
int anchorPosition;
QString surroundingText;
QString selectedText;
};
class TestInputContext : public QPlatformInputContext
{
public:
TestInputContext()
: m_visible(false)
{
QInputMethodPrivate* inputMethodPrivate = QInputMethodPrivate::get(qApp->inputMethod());
inputMethodPrivate->testContext = this;
}
~TestInputContext()
{
QInputMethodPrivate* inputMethodPrivate = QInputMethodPrivate::get(qApp->inputMethod());
inputMethodPrivate->testContext = 0;
}
virtual void showInputPanel()
{
m_visible = true;
}
virtual void hideInputPanel()
{
m_visible = false;
}
virtual bool isInputPanelVisible() const
{
return m_visible;
}
virtual void update(Qt::InputMethodQueries queries)
{
if (!qApp->focusObject())
return;
if (!(queries & Qt::ImQueryInput))
return;
QInputMethodQueryEvent imQueryEvent(Qt::ImQueryInput);
QApplication::sendEvent(qApp->focusObject(), &imQueryEvent);
const int cursorPosition = imQueryEvent.value(Qt::ImCursorPosition).toInt();
const int anchorPosition = imQueryEvent.value(Qt::ImAnchorPosition).toInt();
QString surroundingText = imQueryEvent.value(Qt::ImSurroundingText).toString();
QString selectedText = imQueryEvent.value(Qt::ImCurrentSelection).toString();
infos.append(InputMethodInfo(cursorPosition, anchorPosition, surroundingText, selectedText));
}
bool m_visible;
QList<InputMethodInfo> infos;
};
void tst_QWebEngineView::softwareInputPanel()
{
TestInputContext testContext;
QWebEngineView view;
view.resize(640, 480);
view.show();
QSignalSpy loadFinishedSpy(&view, SIGNAL(loadFinished(bool)));
view.setHtml("<html><body>"
" <input type='text' id='input1' value='' size='50'/>"
"</body></html>");
QVERIFY(loadFinishedSpy.wait());
QPoint textInputCenter = elementCenter(view.page(), "input1");
QTest::mouseClick(view.focusProxy(), Qt::LeftButton, {}, textInputCenter);
QTRY_COMPARE(evaluateJavaScriptSync(view.page(), "document.activeElement.id").toString(), QStringLiteral("input1"));
// This part of the test checks if the SIP (Software Input Panel) is triggered,
// which normally happens on mobile platforms, when a user input form receives
// a mouse click.
int inputPanel = view.style()->styleHint(QStyle::SH_RequestSoftwareInputPanel);
// For non-mobile platforms RequestSoftwareInputPanel event is not called
// because there is no SIP (Software Input Panel) triggered. In the case of a
// mobile platform, an input panel, e.g. virtual keyboard, is usually invoked
// and the RequestSoftwareInputPanel event is called. For these two situations
// this part of the test can verified as the checks below.
if (inputPanel)
QTRY_VERIFY(testContext.isInputPanelVisible());
else
QTRY_VERIFY(!testContext.isInputPanelVisible());
testContext.hideInputPanel();
QTest::mouseClick(view.focusProxy(), Qt::LeftButton, {}, textInputCenter);
QTRY_VERIFY(testContext.isInputPanelVisible());
view.setHtml("<html><body><p id='para'>nothing to input here</p></body></html>");
QVERIFY(loadFinishedSpy.wait());
testContext.hideInputPanel();
QPoint paraCenter = elementCenter(view.page(), "para");
QTest::mouseClick(view.focusProxy(), Qt::LeftButton, {}, paraCenter);
QVERIFY(!testContext.isInputPanelVisible());
// Check sending RequestSoftwareInputPanel event
view.page()->setHtml("<html><body>"
" <input type='text' id='input1' value='QtWebEngine inputMethod'/>"
" <div id='btnDiv' onclick='i=document.getElementById("input1"); i.focus();'>abc</div>"
"</body></html>");
QVERIFY(loadFinishedSpy.wait());
QPoint btnDivCenter = elementCenter(view.page(), "btnDiv");
QTest::mouseClick(view.focusProxy(), Qt::LeftButton, {}, btnDivCenter);
QVERIFY(!testContext.isInputPanelVisible());
}
void tst_QWebEngineView::inputContextQueryInput()
{
QWebEngineView view;
view.resize(640, 480);
view.show();
// testContext will be destroyed before the view, so no events are sent accidentally
// when the view is destroyed.
TestInputContext testContext;
QSignalSpy selectionChangedSpy(&view, SIGNAL(selectionChanged()));
QSignalSpy loadFinishedSpy(&view, SIGNAL(loadFinished(bool)));
view.setHtml("<html><body>"
" <input type='text' id='input1' value='' size='50'/>"
"</body></html>");
QTRY_COMPARE(loadFinishedSpy.count(), 1);
QVERIFY(QTest::qWaitForWindowExposed(&view));
QCOMPARE(testContext.infos.count(), 0);
// Set focus on an input field.
QPoint textInputCenter = elementCenter(view.page(), "input1");
QTest::mouseClick(view.focusProxy(), Qt::LeftButton, {}, textInputCenter);
QTRY_COMPARE(testContext.infos.count(), 2);
QCOMPARE(evaluateJavaScriptSync(view.page(), "document.activeElement.id").toString(), QStringLiteral("input1"));
foreach (const InputMethodInfo &info, testContext.infos) {
QCOMPARE(info.cursorPosition, 0);
QCOMPARE(info.anchorPosition, 0);
QCOMPARE(info.surroundingText, QStringLiteral(""));
QCOMPARE(info.selectedText, QStringLiteral(""));
}
testContext.infos.clear();
// Change content of an input field from JavaScript.
evaluateJavaScriptSync(view.page(), "document.getElementById('input1').value='QtWebEngine';");
QTRY_COMPARE(testContext.infos.count(), 1);
QCOMPARE(testContext.infos[0].cursorPosition, 11);
QCOMPARE(testContext.infos[0].anchorPosition, 11);
QCOMPARE(testContext.infos[0].surroundingText, QStringLiteral("QtWebEngine"));
QCOMPARE(testContext.infos[0].selectedText, QStringLiteral(""));
testContext.infos.clear();
// Change content of an input field by key press.
QTest::keyClick(view.focusProxy(), Qt::Key_Exclam);
QTRY_COMPARE(testContext.infos.count(), 1);
QCOMPARE(testContext.infos[0].cursorPosition, 12);
QCOMPARE(testContext.infos[0].anchorPosition, 12);
QCOMPARE(testContext.infos[0].surroundingText, QStringLiteral("QtWebEngine!"));
QCOMPARE(testContext.infos[0].selectedText, QStringLiteral(""));
testContext.infos.clear();
// Change cursor position.
QTest::keyClick(view.focusProxy(), Qt::Key_Left);
QTRY_COMPARE(testContext.infos.count(), 1);
QCOMPARE(testContext.infos[0].cursorPosition, 11);
QCOMPARE(testContext.infos[0].anchorPosition, 11);
QCOMPARE(testContext.infos[0].surroundingText, QStringLiteral("QtWebEngine!"));
QCOMPARE(testContext.infos[0].selectedText, QStringLiteral(""));
testContext.infos.clear();
// Selection by IME.
{
QList<QInputMethodEvent::Attribute> attributes;
QInputMethodEvent::Attribute newSelection(QInputMethodEvent::Selection, 2, 12, QVariant());
attributes.append(newSelection);
QInputMethodEvent event("", attributes);
QApplication::sendEvent(view.focusProxy(), &event);
}
QTRY_COMPARE(testContext.infos.count(), 2);
QTRY_COMPARE(selectionChangedSpy.count(), 1);
// As a first step, Chromium moves the cursor to the start of the selection.
// We don't filter this in QtWebEngine because we don't know yet if this is part of a selection.
QCOMPARE(testContext.infos[0].cursorPosition, 2);
QCOMPARE(testContext.infos[0].anchorPosition, 2);
QCOMPARE(testContext.infos[0].surroundingText, QStringLiteral("QtWebEngine!"));
QCOMPARE(testContext.infos[0].selectedText, QStringLiteral(""));
// The update of the selection.
QCOMPARE(testContext.infos[1].cursorPosition, 12);
QCOMPARE(testContext.infos[1].anchorPosition, 2);
QCOMPARE(testContext.infos[1].surroundingText, QStringLiteral("QtWebEngine!"));
QCOMPARE(testContext.infos[1].selectedText, QStringLiteral("WebEngine!"));
testContext.infos.clear();
selectionChangedSpy.clear();
// Clear selection by IME.
{
QList<QInputMethodEvent::Attribute> attributes;
QInputMethodEvent::Attribute newSelection(QInputMethodEvent::Selection, 0, 0, QVariant());
attributes.append(newSelection);
QInputMethodEvent event("", attributes);
QApplication::sendEvent(view.focusProxy(), &event);
}
QTRY_COMPARE(testContext.infos.count(), 1);
QTRY_COMPARE(selectionChangedSpy.count(), 1);
QCOMPARE(testContext.infos[0].cursorPosition, 0);
QCOMPARE(testContext.infos[0].anchorPosition, 0);
QCOMPARE(testContext.infos[0].surroundingText, QStringLiteral("QtWebEngine!"));
QCOMPARE(testContext.infos[0].selectedText, QStringLiteral(""));
testContext.infos.clear();
selectionChangedSpy.clear();
// Compose text.
{
QList<QInputMethodEvent::Attribute> attributes;
QInputMethodEvent event("123", attributes);
QApplication::sendEvent(view.focusProxy(), &event);
}
QTRY_COMPARE(testContext.infos.count(), 1);
QCOMPARE(testContext.infos[0].cursorPosition, 3);
QCOMPARE(testContext.infos[0].anchorPosition, 3);
QCOMPARE(testContext.infos[0].surroundingText, QStringLiteral("QtWebEngine!"));
QCOMPARE(testContext.infos[0].selectedText, QStringLiteral(""));
QCOMPARE(evaluateJavaScriptSync(view.page(), "document.getElementById('input1').value").toString(), QStringLiteral("123QtWebEngine!"));
testContext.infos.clear();
// Cancel composition.
{
QList<QInputMethodEvent::Attribute> attributes;
QInputMethodEvent event("", attributes);
QApplication::sendEvent(view.focusProxy(), &event);
}
QTRY_COMPARE(testContext.infos.count(), 2);
foreach (const InputMethodInfo &info, testContext.infos) {
QCOMPARE(info.cursorPosition, 0);
QCOMPARE(info.anchorPosition, 0);
QCOMPARE(info.surroundingText, QStringLiteral("QtWebEngine!"));
QCOMPARE(info.selectedText, QStringLiteral(""));
}
QCOMPARE(evaluateJavaScriptSync(view.page(), "document.getElementById('input1').value").toString(), QStringLiteral("QtWebEngine!"));
testContext.infos.clear();
// Commit text.
{
QList<QInputMethodEvent::Attribute> attributes;
QInputMethodEvent event("", attributes);
event.setCommitString(QStringLiteral("123"), 0, 0);
QApplication::sendEvent(view.focusProxy(), &event);
}
QTRY_COMPARE(testContext.infos.count(), 1);
QCOMPARE(testContext.infos[0].cursorPosition, 3);
QCOMPARE(testContext.infos[0].anchorPosition, 3);
QCOMPARE(testContext.infos[0].surroundingText, QStringLiteral("123QtWebEngine!"));
QCOMPARE(testContext.infos[0].selectedText, QStringLiteral(""));
QCOMPARE(evaluateJavaScriptSync(view.page(), "document.getElementById('input1').value").toString(), QStringLiteral("123QtWebEngine!"));
testContext.infos.clear();
// Focus out.
QTest::keyPress(view.focusProxy(), Qt::Key_Tab);
QTRY_COMPARE(testContext.infos.count(), 1);
QTRY_COMPARE(evaluateJavaScriptSync(view.page(), "document.activeElement.id").toString(), QStringLiteral(""));
testContext.infos.clear();
}
void tst_QWebEngineView::inputMethods()
{
QWebEngineView view;
view.settings()->setAttribute(QWebEngineSettings::FocusOnNavigationEnabled, true);
view.resize(640, 480);
view.show();
QSignalSpy selectionChangedSpy(&view, SIGNAL(selectionChanged()));
QSignalSpy loadFinishedSpy(&view, SIGNAL(loadFinished(bool)));
view.settings()->setFontFamily(QWebEngineSettings::SerifFont, view.settings()->fontFamily(QWebEngineSettings::FixedFont));
view.setHtml("<html><body>"
" <input type='text' id='input1' style='font-family: serif' value='' maxlength='20' size='50'/>"
"</body></html>");
QTRY_COMPARE(loadFinishedSpy.size(), 1);
QVERIFY(QTest::qWaitForWindowExposed(&view));
QPoint textInputCenter = elementCenter(view.page(), "input1");
QTest::mouseClick(view.focusProxy(), Qt::LeftButton, {}, textInputCenter);
QTRY_COMPARE(evaluateJavaScriptSync(view.page(), "document.activeElement.id").toString(), QStringLiteral("input1"));
// ImCursorRectangle
QVariant variant = view.focusProxy()->inputMethodQuery(Qt::ImCursorRectangle);
QVERIFY(elementGeometry(view.page(), "input1").contains(variant.toRect().topLeft()));
// We assigned the serif font family to be the same as the fixed font family.
// Then test ImFont on a serif styled element, we should get our fixed font family.
variant = view.focusProxy()->inputMethodQuery(Qt::ImFont);
QFont font = variant.value<QFont>();
QEXPECT_FAIL("", "UNIMPLEMENTED: RenderWidgetHostViewQt::inputMethodQuery(Qt::ImFont)", Continue);
QCOMPARE(view.settings()->fontFamily(QWebEngineSettings::FixedFont), font.family());
QList<QInputMethodEvent::Attribute> inputAttributes;
// Insert text
{
QString text = QStringLiteral("QtWebEngine");
QInputMethodEvent eventText(text, inputAttributes);
QApplication::sendEvent(view.focusProxy(), &eventText);
QTRY_COMPARE(evaluateJavaScriptSync(view.page(), "document.getElementById('input1').value").toString(), text);
QCOMPARE(selectionChangedSpy.count(), 0);
}
{
QString text = QStringLiteral("QtWebEngine");
QInputMethodEvent eventText("", inputAttributes);
eventText.setCommitString(text, 0, 0);
QApplication::sendEvent(view.focusProxy(), &eventText);
QTRY_COMPARE(evaluateJavaScriptSync(view.page(), "document.getElementById('input1').value").toString(), text);
QCOMPARE(selectionChangedSpy.count(), 0);
}
// ImMaximumTextLength
QEXPECT_FAIL("", "UNIMPLEMENTED: RenderWidgetHostViewQt::inputMethodQuery(Qt::ImMaximumTextLength)", Continue);
QCOMPARE(view.focusProxy()->inputMethodQuery(Qt::ImMaximumTextLength).toInt(), 20);
// Set selection
inputAttributes << QInputMethodEvent::Attribute(QInputMethodEvent::Selection, 3, 2, QVariant());
QInputMethodEvent eventSelection1("", inputAttributes);
QApplication::sendEvent(view.focusProxy(), &eventSelection1);
QTRY_COMPARE(selectionChangedSpy.size(), 1);
QCOMPARE(view.focusProxy()->inputMethodQuery(Qt::ImAnchorPosition).toInt(), 3);
QCOMPARE(view.focusProxy()->inputMethodQuery(Qt::ImCursorPosition).toInt(), 5);
QCOMPARE(view.focusProxy()->inputMethodQuery(Qt::ImCurrentSelection).toString(), QString("eb"));
QCOMPARE(view.focusProxy()->inputMethodQuery(Qt::ImSurroundingText).toString(), QString("QtWebEngine"));
// Set selection with negative length
inputAttributes << QInputMethodEvent::Attribute(QInputMethodEvent::Selection, 6, -5, QVariant());
QInputMethodEvent eventSelection2("", inputAttributes);
QApplication::sendEvent(view.focusProxy(), &eventSelection2);
QTRY_COMPARE(selectionChangedSpy.size(), 2);
QCOMPARE(view.focusProxy()->inputMethodQuery(Qt::ImAnchorPosition).toInt(), 1);
QCOMPARE(view.focusProxy()->inputMethodQuery(Qt::ImCursorPosition).toInt(), 6);
QCOMPARE(view.focusProxy()->inputMethodQuery(Qt::ImCurrentSelection).toString(), QString("tWebE"));
QCOMPARE(view.focusProxy()->inputMethodQuery(Qt::ImSurroundingText).toString(), QString("QtWebEngine"));
QList<QInputMethodEvent::Attribute> attributes;
// Clear the selection, so the next test does not clear any contents.
QInputMethodEvent::Attribute newSelection(QInputMethodEvent::Selection, 0, 0, QVariant());
attributes.append(newSelection);
QInputMethodEvent eventComposition("composition", attributes);
QApplication::sendEvent(view.focusProxy(), &eventComposition);
QTRY_COMPARE(selectionChangedSpy.size(), 3);
QCOMPARE(view.focusProxy()->inputMethodQuery(Qt::ImCurrentSelection).toString(), QString(""));
// An ongoing composition should not change the surrounding text before it is committed.
QCOMPARE(view.focusProxy()->inputMethodQuery(Qt::ImSurroundingText).toString(), QString("QtWebEngine"));
// Cancel current composition first
inputAttributes << QInputMethodEvent::Attribute(QInputMethodEvent::Selection, 0, 0, QVariant());
QInputMethodEvent eventSelection3("", inputAttributes);
QApplication::sendEvent(view.focusProxy(), &eventSelection3);
// Cancelling composition should not clear the surrounding text
QCOMPARE(view.focusProxy()->inputMethodQuery(Qt::ImSurroundingText).toString(), QString("QtWebEngine"));
}
void tst_QWebEngineView::textSelectionInInputField()
{
QWebEngineView view;
view.settings()->setAttribute(QWebEngineSettings::FocusOnNavigationEnabled, true);
view.resize(640, 480);
view.show();
QSignalSpy selectionChangedSpy(&view, SIGNAL(selectionChanged()));
QSignalSpy loadFinishedSpy(&view, SIGNAL(loadFinished(bool)));
view.setHtml("<html><body>"
" <input type='text' id='input1' value='QtWebEngine' size='50'/>"
"</body></html>");
QVERIFY(loadFinishedSpy.wait());
QVERIFY(QTest::qWaitForWindowExposed(&view));
// Tests for Selection when the Editor is NOT in Composition mode
// LEFT to RIGHT selection
// Mouse click event moves the current cursor to the end of the text
QPoint textInputCenter = elementCenter(view.page(), "input1");
QTest::mouseClick(view.focusProxy(), Qt::LeftButton, {}, textInputCenter);
QTRY_COMPARE(evaluateJavaScriptSync(view.page(), "document.activeElement.id").toString(), QStringLiteral("input1"));
QTRY_COMPARE(view.focusProxy()->inputMethodQuery(Qt::ImCursorPosition).toInt(), 11);
QTRY_COMPARE(view.focusProxy()->inputMethodQuery(Qt::ImAnchorPosition).toInt(), 11);
// There was no selection to be changed by the click
QCOMPARE(selectionChangedSpy.count(), 0);
QList<QInputMethodEvent::Attribute> attributes;
QInputMethodEvent event(QString(), attributes);
event.setCommitString("XXX", 0, 0);
QApplication::sendEvent(view.focusProxy(), &event);
QTRY_COMPARE(view.focusProxy()->inputMethodQuery(Qt::ImSurroundingText).toString(), QString("QtWebEngineXXX"));
QCOMPARE(selectionChangedSpy.count(), 0);
event.setCommitString(QString(), -2, 2); // Erase two characters.
QApplication::sendEvent(view.focusProxy(), &event);
QTRY_COMPARE(view.focusProxy()->inputMethodQuery(Qt::ImSurroundingText).toString(), QString("QtWebEngineX"));
QCOMPARE(selectionChangedSpy.count(), 0);
event.setCommitString(QString(), -1, 1); // Erase one character.
QApplication::sendEvent(view.focusProxy(), &event);
QTRY_COMPARE(view.focusProxy()->inputMethodQuery(Qt::ImSurroundingText).toString(), QString("QtWebEngine"));
QCOMPARE(selectionChangedSpy.count(), 0);
// Move to the start of the line
QTest::keyClick(view.focusProxy(), Qt::Key_Home);
// Move 2 characters RIGHT
for (int j = 0; j < 2; ++j)
QTest::keyClick(view.focusProxy(), Qt::Key_Right);
// Select to the end of the line
QTest::keyClick(view.focusProxy(), Qt::Key_End, Qt::ShiftModifier);
QVERIFY(selectionChangedSpy.wait());
QCOMPARE(selectionChangedSpy.count(), 1);
QCOMPARE(view.focusProxy()->inputMethodQuery(Qt::ImAnchorPosition).toInt(), 2);
QCOMPARE(view.focusProxy()->inputMethodQuery(Qt::ImCursorPosition).toInt(), 11);
QCOMPARE(view.focusProxy()->inputMethodQuery(Qt::ImCurrentSelection).toString(), QString("WebEngine"));
// RIGHT to LEFT selection
// Deselect the selection (this moves the current cursor to the end of the text)
QTest::mouseClick(view.focusProxy(), Qt::LeftButton, {}, textInputCenter);
QVERIFY(selectionChangedSpy.wait());
QCOMPARE(selectionChangedSpy.count(), 2);
QCOMPARE(view.focusProxy()->inputMethodQuery(Qt::ImAnchorPosition).toInt(), 11);
QCOMPARE(view.focusProxy()->inputMethodQuery(Qt::ImCursorPosition).toInt(), 11);
QCOMPARE(view.focusProxy()->inputMethodQuery(Qt::ImCurrentSelection).toString(), QString(""));
// Move 2 characters LEFT
for (int i = 0; i < 2; ++i)
QTest::keyClick(view.focusProxy(), Qt::Key_Left);
// Select to the start of the line
QTest::keyClick(view.focusProxy(), Qt::Key_Home, Qt::ShiftModifier);
QVERIFY(selectionChangedSpy.wait());
QCOMPARE(selectionChangedSpy.count(), 3);
QCOMPARE(view.focusProxy()->inputMethodQuery(Qt::ImAnchorPosition).toInt(), 9);
QCOMPARE(view.focusProxy()->inputMethodQuery(Qt::ImCursorPosition).toInt(), 0);
QCOMPARE(view.focusProxy()->inputMethodQuery(Qt::ImCurrentSelection).toString(), QString("QtWebEngi"));
}
void tst_QWebEngineView::textSelectionOutOfInputField()
{
QWebEngineView view;
view.settings()->setAttribute(QWebEngineSettings::FocusOnNavigationEnabled, true);
view.resize(640, 480);
view.show();
QSignalSpy selectionChangedSpy(&view, SIGNAL(selectionChanged()));
QSignalSpy loadFinishedSpy(&view, SIGNAL(loadFinished(bool)));
view.setHtml("<html><body>"
" This is a text"
"</body></html>");
QVERIFY(loadFinishedSpy.wait());
QVERIFY(QTest::qWaitForWindowExposed(&view));
QCOMPARE(selectionChangedSpy.count(), 0);
QVERIFY(!view.hasSelection());
QVERIFY(view.page()->selectedText().isEmpty());
// Simple click should not update text selection, however it updates selection bounds in Chromium
QTest::mouseClick(view.focusProxy(), Qt::LeftButton, {}, view.geometry().center());
QCOMPARE(selectionChangedSpy.count(), 0);
QVERIFY(!view.hasSelection());
QVERIFY(view.page()->selectedText().isEmpty());
// Select text by ctrl+a
QTest::keyClick(view.windowHandle(), Qt::Key_A, Qt::ControlModifier);
QVERIFY(selectionChangedSpy.wait());
QCOMPARE(selectionChangedSpy.count(), 1);
QVERIFY(view.hasSelection());
QCOMPARE(view.page()->selectedText(), QString("This is a text"));
// Deselect text by mouse click
QTest::mouseClick(view.focusProxy(), Qt::LeftButton, {}, view.geometry().center());
QVERIFY(selectionChangedSpy.wait());
QCOMPARE(selectionChangedSpy.count(), 2);
QVERIFY(!view.hasSelection());
QVERIFY(view.page()->selectedText().isEmpty());
// Select text by ctrl+a
QTest::keyClick(view.windowHandle(), Qt::Key_A, Qt::ControlModifier);
QVERIFY(selectionChangedSpy.wait());
QCOMPARE(selectionChangedSpy.count(), 3);
QVERIFY(view.hasSelection());
QCOMPARE(view.page()->selectedText(), QString("This is a text"));
// Deselect text via discard+undiscard
view.hide();
view.page()->setLifecycleState(QWebEnginePage::LifecycleState::Discarded);
view.show();
QVERIFY(loadFinishedSpy.wait());
QCOMPARE(selectionChangedSpy.count(), 4);
QVERIFY(!view.hasSelection());
QVERIFY(view.page()->selectedText().isEmpty());
selectionChangedSpy.clear();
view.setHtml("<html><body>"
" This is a text"
" <br>"
" <input type='text' id='input1' value='QtWebEngine' size='50'/>"
"</body></html>");
QVERIFY(loadFinishedSpy.wait());
QVERIFY(QTest::qWaitForWindowExposed(&view));
QCOMPARE(selectionChangedSpy.count(), 0);
QVERIFY(!view.hasSelection());
QVERIFY(view.page()->selectedText().isEmpty());
// Make sure the input field does not have the focus
evaluateJavaScriptSync(view.page(), "document.getElementById('input1').blur()");
QTRY_VERIFY(evaluateJavaScriptSync(view.page(), "document.activeElement.id").toString().isEmpty());
// Select the whole page by ctrl+a
QTest::keyClick(view.windowHandle(), Qt::Key_A, Qt::ControlModifier);
QVERIFY(selectionChangedSpy.wait());
QCOMPARE(selectionChangedSpy.count(), 1);
QVERIFY(view.hasSelection());
QVERIFY(view.page()->selectedText().startsWith(QString("This is a text")));
// Remove selection by clicking into an input field
QPoint textInputCenter = elementCenter(view.page(), "input1");
QTest::mouseClick(view.focusProxy(), Qt::LeftButton, {}, textInputCenter);
QVERIFY(selectionChangedSpy.wait());
QCOMPARE(evaluateJavaScriptSync(view.page(), "document.activeElement.id").toString(), QStringLiteral("input1"));
QCOMPARE(selectionChangedSpy.count(), 2);
QVERIFY(!view.hasSelection());
QVERIFY(view.page()->selectedText().isEmpty());
// Select the content of the input field by ctrl+a
QTest::keyClick(view.windowHandle(), Qt::Key_A, Qt::ControlModifier);
QVERIFY(selectionChangedSpy.wait());
QCOMPARE(selectionChangedSpy.count(), 3);
QVERIFY(view.hasSelection());
QCOMPARE(view.page()->selectedText(), QString("QtWebEngine"));
// Deselect input field's text by mouse click
QTest::mouseClick(view.focusProxy(), Qt::LeftButton, {}, view.geometry().center());
QVERIFY(selectionChangedSpy.wait());
QCOMPARE(selectionChangedSpy.count(), 4);
QVERIFY(!view.hasSelection());
QVERIFY(view.page()->selectedText().isEmpty());
}
void tst_QWebEngineView::hiddenText()
{
QWebEngineView view;
view.resize(640, 480);
view.show();
QSignalSpy loadFinishedSpy(&view, SIGNAL(loadFinished(bool)));
view.setHtml("<html><body>"
" <input type='text' id='input1' value='QtWebEngine' size='50'/><br>"
" <input type='password' id='password1'/>"
"</body></html>");
QVERIFY(loadFinishedSpy.wait());
QPoint passwordInputCenter = elementCenter(view.page(), "password1");
QTest::mouseClick(view.focusProxy(), Qt::LeftButton, {}, passwordInputCenter);
QTRY_COMPARE(evaluateJavaScriptSync(view.page(), "document.activeElement.id").toString(), QStringLiteral("password1"));
QVERIFY(!view.focusProxy()->testAttribute(Qt::WA_InputMethodEnabled));
QVERIFY(view.focusProxy()->inputMethodHints() & Qt::ImhHiddenText);
QPoint textInputCenter = elementCenter(view.page(), "input1");
QTest::mouseClick(view.focusProxy(), Qt::LeftButton, {}, textInputCenter);
QTRY_COMPARE(evaluateJavaScriptSync(view.page(), "document.activeElement.id").toString(), QStringLiteral("input1"));
QVERIFY(!(view.focusProxy()->inputMethodHints() & Qt::ImhHiddenText));
}
void tst_QWebEngineView::emptyInputMethodEvent()
{
QWebEngineView view;
view.settings()->setAttribute(QWebEngineSettings::FocusOnNavigationEnabled, true);
view.resize(640, 480);
view.show();
QSignalSpy selectionChangedSpy(&view, SIGNAL(selectionChanged()));
QSignalSpy loadFinishedSpy(&view, SIGNAL(loadFinished(bool)));
view.setHtml("<html><body>"
" <input type='text' id='input1' value='QtWebEngine'/>"
"</body></html>");
QVERIFY(loadFinishedSpy.wait());
QVERIFY(QTest::qWaitForWindowExposed(&view));
evaluateJavaScriptSync(view.page(), "var inputEle = document.getElementById('input1'); inputEle.focus(); inputEle.select();");
QTRY_COMPARE(selectionChangedSpy.count(), 1);
// 1. Empty input method event does not clear text
QInputMethodEvent emptyEvent;
QVERIFY(QApplication::sendEvent(view.focusProxy(), &emptyEvent));
qApp->processEvents();
QCOMPARE(evaluateJavaScriptSync(view.page(), "document.getElementById('input1').value").toString(), QStringLiteral("QtWebEngine"));
QTRY_COMPARE(view.focusProxy()->inputMethodQuery(Qt::ImSurroundingText).toString(), QStringLiteral("QtWebEngine"));
// Reset: clear input field
evaluateJavaScriptSync(view.page(), "var inputEle = document.getElementById('input1').value = ''");
QTRY_VERIFY(evaluateJavaScriptSync(view.page(), "document.getElementById('input1').value").toString().isEmpty());
QTRY_VERIFY(view.focusProxy()->inputMethodQuery(Qt::ImSurroundingText).toString().isEmpty());
// 2. Cancel IME composition with empty input method event
// Start IME composition
QList<QInputMethodEvent::Attribute> attributes;
QInputMethodEvent eventComposition("a", attributes);
QVERIFY(QApplication::sendEvent(view.focusProxy(), &eventComposition));
QTRY_COMPARE(evaluateJavaScriptSync(view.page(), "document.getElementById('input1').value").toString(), QStringLiteral("a"));
QTRY_VERIFY(view.focusProxy()->inputMethodQuery(Qt::ImSurroundingText).toString().isEmpty());
// Cancel IME composition
QVERIFY(QApplication::sendEvent(view.focusProxy(), &emptyEvent));
QTRY_VERIFY(evaluateJavaScriptSync(view.page(), "document.getElementById('input1').value").toString().isEmpty());
QTRY_VERIFY(view.focusProxy()->inputMethodQuery(Qt::ImSurroundingText).toString().isEmpty());
// Try key press after cancelled IME composition
QTest::keyClick(view.focusProxy(), Qt::Key_B);
QTRY_COMPARE(evaluateJavaScriptSync(view.page(), "document.getElementById('input1').value").toString(), QStringLiteral("b"));
QTRY_COMPARE(view.focusProxy()->inputMethodQuery(Qt::ImSurroundingText).toString(), QStringLiteral("b"));
}
void tst_QWebEngineView::imeComposition()
{
QWebEngineView view;
view.settings()->setAttribute(QWebEngineSettings::FocusOnNavigationEnabled, true);
view.resize(640, 480);
view.show();
QSignalSpy selectionChangedSpy(&view, SIGNAL(selectionChanged()));
QSignalSpy loadFinishedSpy(&view, SIGNAL(loadFinished(bool)));
view.setHtml("<html><body>"
" <input type='text' id='input1' value='QtWebEngine inputMethod'/>"
"</body></html>");
QVERIFY(loadFinishedSpy.wait());
QVERIFY(QTest::qWaitForWindowExposed(&view));
evaluateJavaScriptSync(view.page(), "var inputEle = document.getElementById('input1'); inputEle.focus(); inputEle.select();");
QTRY_COMPARE(selectionChangedSpy.count(), 1);
// Clear the selection, also cancel the ongoing composition if there is one.
{
QList<QInputMethodEvent::Attribute> attributes;
QInputMethodEvent::Attribute newSelection(QInputMethodEvent::Selection, 0, 0, QVariant());
attributes.append(newSelection);
QInputMethodEvent event("", attributes);
QApplication::sendEvent(view.focusProxy(), &event);
selectionChangedSpy.wait();
QCOMPARE(selectionChangedSpy.count(), 2);
}
QCOMPARE(view.focusProxy()->inputMethodQuery(Qt::ImSurroundingText).toString(), QString("QtWebEngine inputMethod"));
QCOMPARE(view.focusProxy()->inputMethodQuery(Qt::ImAnchorPosition).toInt(), 0);
QCOMPARE(view.focusProxy()->inputMethodQuery(Qt::ImCursorPosition).toInt(), 0);
QCOMPARE(view.focusProxy()->inputMethodQuery(Qt::ImCurrentSelection).toString(), QString(""));
selectionChangedSpy.clear();
// 1. Insert a character to the beginning of the line.
// Send temporary text, which makes the editor has composition 'm'.
{
QList<QInputMethodEvent::Attribute> attributes;
QInputMethodEvent event("m", attributes);
QApplication::sendEvent(view.focusProxy(), &event);
}
QCOMPARE(view.focusProxy()->inputMethodQuery(Qt::ImSurroundingText).toString(), QString("QtWebEngine inputMethod"));
QCOMPARE(view.focusProxy()->inputMethodQuery(Qt::ImCursorPosition).toInt(), 0);
QCOMPARE(view.focusProxy()->inputMethodQuery(Qt::ImAnchorPosition).toInt(), 0);
QCOMPARE(view.focusProxy()->inputMethodQuery(Qt::ImCurrentSelection).toString(), QString(""));
QCOMPARE(selectionChangedSpy.count(), 0);
// Send temporary text, which makes the editor has composition 'n'.
{
QList<QInputMethodEvent::Attribute> attributes;
QInputMethodEvent event("n", attributes);
QApplication::sendEvent(view.focusProxy(), &event);
}
QCOMPARE(view.focusProxy()->inputMethodQuery(Qt::ImSurroundingText).toString(), QString("QtWebEngine inputMethod"));
QCOMPARE(view.focusProxy()->inputMethodQuery(Qt::ImCursorPosition).toInt(), 0);
QCOMPARE(view.focusProxy()->inputMethodQuery(Qt::ImAnchorPosition).toInt(), 0);
QCOMPARE(view.focusProxy()->inputMethodQuery(Qt::ImCurrentSelection).toString(), QString(""));
QCOMPARE(selectionChangedSpy.count(), 0);
// Send commit text, which makes the editor conforms composition.
{
QList<QInputMethodEvent::Attribute> attributes;
QInputMethodEvent event("", attributes);
event.setCommitString("o");
QApplication::sendEvent(view.focusProxy(), &event);
}
QTRY_COMPARE(view.focusProxy()->inputMethodQuery(Qt::ImSurroundingText).toString(), QString("oQtWebEngine inputMethod"));
QCOMPARE(view.focusProxy()->inputMethodQuery(Qt::ImCursorPosition).toInt(), 1);
QCOMPARE(view.focusProxy()->inputMethodQuery(Qt::ImAnchorPosition).toInt(), 1);
QCOMPARE(view.focusProxy()->inputMethodQuery(Qt::ImCurrentSelection).toString(), QString(""));
QCOMPARE(selectionChangedSpy.count(), 0);
// 2. insert a character to the middle of the line.
// Send temporary text, which makes the editor has composition 'd'.
{
QList<QInputMethodEvent::Attribute> attributes;
QInputMethodEvent event("d", attributes);
QApplication::sendEvent(view.focusProxy(), &event);
}
QCOMPARE(view.focusProxy()->inputMethodQuery(Qt::ImSurroundingText).toString(), QString("oQtWebEngine inputMethod"));
QCOMPARE(view.focusProxy()->inputMethodQuery(Qt::ImCursorPosition).toInt(), 1);
QCOMPARE(view.focusProxy()->inputMethodQuery(Qt::ImAnchorPosition).toInt(), 1);
QCOMPARE(view.focusProxy()->inputMethodQuery(Qt::ImCurrentSelection).toString(), QString(""));
QCOMPARE(selectionChangedSpy.count(), 0);
// Send commit text, which makes the editor conforms composition.
{
QList<QInputMethodEvent::Attribute> attributes;
QInputMethodEvent event("", attributes);
event.setCommitString("e");
QApplication::sendEvent(view.focusProxy(), &event);
}
QTRY_COMPARE(view.focusProxy()->inputMethodQuery(Qt::ImSurroundingText).toString(), QString("oeQtWebEngine inputMethod"));
QCOMPARE(view.focusProxy()->inputMethodQuery(Qt::ImCursorPosition).toInt(), 2);
QCOMPARE(view.focusProxy()->inputMethodQuery(Qt::ImAnchorPosition).toInt(), 2);
QCOMPARE(view.focusProxy()->inputMethodQuery(Qt::ImCurrentSelection).toString(), QString(""));
QCOMPARE(selectionChangedSpy.count(), 0);
// 3. Insert a character to the end of the line.
QTest::keyClick(view.focusProxy(), Qt::Key_End);
QTRY_COMPARE(view.focusProxy()->inputMethodQuery(Qt::ImCursorPosition).toInt(), 25);
QTRY_COMPARE(view.focusProxy()->inputMethodQuery(Qt::ImAnchorPosition).toInt(), 25);
// Send temporary text, which makes the editor has composition 't'.
{
QList<QInputMethodEvent::Attribute> attributes;
QInputMethodEvent event("t", attributes);
QApplication::sendEvent(view.focusProxy(), &event);
}
QCOMPARE(view.focusProxy()->inputMethodQuery(Qt::ImSurroundingText).toString(), QString("oeQtWebEngine inputMethod"));
QCOMPARE(view.focusProxy()->inputMethodQuery(Qt::ImCursorPosition).toInt(), 25);
QCOMPARE(view.focusProxy()->inputMethodQuery(Qt::ImAnchorPosition).toInt(), 25);
QCOMPARE(view.focusProxy()->inputMethodQuery(Qt::ImCurrentSelection).toString(), QString(""));
QCOMPARE(selectionChangedSpy.count(), 0);
// Send commit text, which makes the editor conforms composition.
{
QList<QInputMethodEvent::Attribute> attributes;
QInputMethodEvent event("", attributes);
event.setCommitString("t");
QApplication::sendEvent(view.focusProxy(), &event);
}
QTRY_COMPARE(view.focusProxy()->inputMethodQuery(Qt::ImSurroundingText).toString(), QString("oeQtWebEngine inputMethodt"));
QCOMPARE(view.focusProxy()->inputMethodQuery(Qt::ImCursorPosition).toInt(), 26);
QCOMPARE(view.focusProxy()->inputMethodQuery(Qt::ImAnchorPosition).toInt(), 26);
QCOMPARE(view.focusProxy()->inputMethodQuery(Qt::ImCurrentSelection).toString(), QString(""));
QCOMPARE(selectionChangedSpy.count(), 0);
// 4. Replace the selection.
#ifndef Q_OS_MACOS
QTest::keyClick(view.focusProxy(), Qt::Key_Left, Qt::ShiftModifier | Qt::ControlModifier);
#else
QTest::keyClick(view.focusProxy(), Qt::Key_Left, Qt::ShiftModifier | Qt::AltModifier);
#endif
QVERIFY(selectionChangedSpy.wait());
QCOMPARE(selectionChangedSpy.count(), 1);
QCOMPARE(view.focusProxy()->inputMethodQuery(Qt::ImSurroundingText).toString(), QString("oeQtWebEngine inputMethodt"));
QCOMPARE(view.focusProxy()->inputMethodQuery(Qt::ImCursorPosition).toInt(), 14);
QCOMPARE(view.focusProxy()->inputMethodQuery(Qt::ImAnchorPosition).toInt(), 26);
QCOMPARE(view.focusProxy()->inputMethodQuery(Qt::ImCurrentSelection).toString(), QString("inputMethodt"));
// Send temporary text, which makes the editor has composition 'w'.
{
QList<QInputMethodEvent::Attribute> attributes;
QInputMethodEvent event("w", attributes);
QApplication::sendEvent(view.focusProxy(), &event);
// The new composition should clear the previous selection
QVERIFY(selectionChangedSpy.wait());
QCOMPARE(selectionChangedSpy.count(), 2);
}
QCOMPARE(view.focusProxy()->inputMethodQuery(Qt::ImSurroundingText).toString(), QString("oeQtWebEngine "));
// The cursor should be positioned at the end of the composition text
QCOMPARE(view.focusProxy()->inputMethodQuery(Qt::ImCursorPosition).toInt(), 15);
QCOMPARE(view.focusProxy()->inputMethodQuery(Qt::ImAnchorPosition).toInt(), 15);
QCOMPARE(view.focusProxy()->inputMethodQuery(Qt::ImCurrentSelection).toString(), QString(""));
// Send commit text, which makes the editor conforms composition.
{
QList<QInputMethodEvent::Attribute> attributes;
QInputMethodEvent event("", attributes);
event.setCommitString("2");
QApplication::sendEvent(view.focusProxy(), &event);
}
// There is no text selection to be changed at this point thus we can't wait for selectionChanged signal.
QTRY_COMPARE(view.focusProxy()->inputMethodQuery(Qt::ImSurroundingText).toString(), QString("oeQtWebEngine 2"));
QTRY_COMPARE(view.focusProxy()->inputMethodQuery(Qt::ImCursorPosition).toInt(), 15);
QTRY_COMPARE(view.focusProxy()->inputMethodQuery(Qt::ImAnchorPosition).toInt(), 15);
QTRY_COMPARE(view.focusProxy()->inputMethodQuery(Qt::ImCurrentSelection).toString(), QString(""));
QCOMPARE(selectionChangedSpy.count(), 2);
selectionChangedSpy.clear();
// 5. Mimic behavior of QtVirtualKeyboard with enabled text prediction.
evaluateJavaScriptSync(view.page(), "document.getElementById('input1').value='QtWebEngine';");
QTRY_COMPARE(evaluateJavaScriptSync(view.page(), "document.getElementById('input1').value").toString(), QString("QtWebEngine"));
// Move cursor into position.
QTest::keyClick(view.focusProxy(), Qt::Key_Home);
for (int j = 0; j < 2; ++j)
QTest::keyClick(view.focusProxy(), Qt::Key_Right);
QTRY_COMPARE(view.focusProxy()->inputMethodQuery(Qt::ImCursorPosition).toInt(), 2);
// Turn text into composition by using negative start position.
{
int replaceFrom = -1 * view.focusProxy()->inputMethodQuery(Qt::ImCursorPosition).toInt();
int replaceLength = view.focusProxy()->inputMethodQuery(Qt::ImSurroundingText).toString().size();
QList<QInputMethodEvent::Attribute> attributes;
QInputMethodEvent event("QtWebEngine", attributes);
event.setCommitString(QString(), replaceFrom, replaceLength);
QApplication::sendEvent(view.focusProxy(), &event);
}
QTRY_COMPARE(view.focusProxy()->inputMethodQuery(Qt::ImSurroundingText).toString(), QString(""));
QCOMPARE(view.focusProxy()->inputMethodQuery(Qt::ImCursorPosition).toInt(), 11);
QCOMPARE(view.focusProxy()->inputMethodQuery(Qt::ImAnchorPosition).toInt(), 11);
QCOMPARE(view.focusProxy()->inputMethodQuery(Qt::ImCurrentSelection).toString(), QString(""));
QCOMPARE(evaluateJavaScriptSync(view.page(), "document.getElementById('input1').value").toString(), QString("QtWebEngine"));
// Commit.
{
QList<QInputMethodEvent::Attribute> attributes;
QInputMethodEvent event(QString(), attributes);
event.setCommitString("QtWebEngine", 0, 0);
QApplication::sendEvent(view.focusProxy(), &event);
}
QTRY_COMPARE(view.focusProxy()->inputMethodQuery(Qt::ImSurroundingText).toString(), QString("QtWebEngine"));
QCOMPARE(view.focusProxy()->inputMethodQuery(Qt::ImCursorPosition).toInt(), 11);
QCOMPARE(view.focusProxy()->inputMethodQuery(Qt::ImAnchorPosition).toInt(), 11);
QCOMPARE(view.focusProxy()->inputMethodQuery(Qt::ImCurrentSelection).toString(), QString(""));
QCOMPARE(evaluateJavaScriptSync(view.page(), "document.getElementById('input1').value").toString(), QString("QtWebEngine"));
QCOMPARE(selectionChangedSpy.count(), 0);
}
void tst_QWebEngineView::newlineInTextarea()
{
QWebEngineView view;
view.settings()->setAttribute(QWebEngineSettings::FocusOnNavigationEnabled, true);
view.resize(640, 480);
view.show();
QSignalSpy loadFinishedSpy(&view, SIGNAL(loadFinished(bool)));
view.page()->setHtml("<html><body>"
" <textarea rows='5' cols='1' id='input1'></textarea>"
"</body></html>");
QVERIFY(loadFinishedSpy.wait());
QVERIFY(QTest::qWaitForWindowExposed(&view));
evaluateJavaScriptSync(view.page(), "var inputEle = document.getElementById('input1'); inputEle.focus(); inputEle.select();");
QTRY_VERIFY(evaluateJavaScriptSync(view.page(), "document.getElementById('input1').value").toString().isEmpty());
// Enter Key without key text
QKeyEvent keyPressEnter(QEvent::KeyPress, Qt::Key_Enter, Qt::NoModifier);
QKeyEvent keyReleaseEnter(QEvent::KeyRelease, Qt::Key_Enter, Qt::NoModifier);
QApplication::sendEvent(view.focusProxy(), &keyPressEnter);
QApplication::sendEvent(view.focusProxy(), &keyReleaseEnter);
QList<QInputMethodEvent::Attribute> attribs;
QInputMethodEvent eventText(QString(), attribs);
eventText.setCommitString("\n");
QApplication::sendEvent(view.focusProxy(), &eventText);
QInputMethodEvent eventText2(QString(), attribs);
eventText2.setCommitString("third line");
QApplication::sendEvent(view.focusProxy(), &eventText2);
qApp->processEvents();
QTRY_COMPARE(evaluateJavaScriptSync(view.page(), "document.getElementById('input1').value").toString(), QString("\n\nthird line"));
QTRY_COMPARE(view.focusProxy()->inputMethodQuery(Qt::ImSurroundingText).toString(), QString("\n\nthird line"));
// Enter Key with key text '\r'
evaluateJavaScriptSync(view.page(), "var inputEle = document.getElementById('input1'); inputEle.value = ''; inputEle.focus(); inputEle.select();");
QTRY_VERIFY(evaluateJavaScriptSync(view.page(), "document.getElementById('input1').value").toString().isEmpty());
QKeyEvent keyPressEnterWithCarriageReturn(QEvent::KeyPress, Qt::Key_Enter, Qt::NoModifier, "\r");
QKeyEvent keyReleaseEnterWithCarriageReturn(QEvent::KeyRelease, Qt::Key_Enter, Qt::NoModifier);
QApplication::sendEvent(view.focusProxy(), &keyPressEnterWithCarriageReturn);
QApplication::sendEvent(view.focusProxy(), &keyReleaseEnterWithCarriageReturn);
QApplication::sendEvent(view.focusProxy(), &eventText);
QApplication::sendEvent(view.focusProxy(), &eventText2);
qApp->processEvents();
QTRY_COMPARE(evaluateJavaScriptSync(view.page(), "document.getElementById('input1').value").toString(), QString("\n\nthird line"));
QTRY_COMPARE(view.focusProxy()->inputMethodQuery(Qt::ImSurroundingText).toString(), QString("\n\nthird line"));
// Enter Key with key text '\n'
evaluateJavaScriptSync(view.page(), "var inputEle = document.getElementById('input1'); inputEle.value = ''; inputEle.focus(); inputEle.select();");
QTRY_VERIFY(evaluateJavaScriptSync(view.page(), "document.getElementById('input1').value").toString().isEmpty());
QKeyEvent keyPressEnterWithLineFeed(QEvent::KeyPress, Qt::Key_Enter, Qt::NoModifier, "\n");
QKeyEvent keyReleaseEnterWithLineFeed(QEvent::KeyRelease, Qt::Key_Enter, Qt::NoModifier, "\n");
QApplication::sendEvent(view.focusProxy(), &keyPressEnterWithLineFeed);
QApplication::sendEvent(view.focusProxy(), &keyReleaseEnterWithLineFeed);
QApplication::sendEvent(view.focusProxy(), &eventText);
QApplication::sendEvent(view.focusProxy(), &eventText2);
qApp->processEvents();
QTRY_COMPARE(evaluateJavaScriptSync(view.page(), "document.getElementById('input1').value").toString(), QString("\n\nthird line"));
QTRY_COMPARE(view.focusProxy()->inputMethodQuery(Qt::ImSurroundingText).toString(), QString("\n\nthird line"));
// Enter Key with key text "\n\r"
evaluateJavaScriptSync(view.page(), "var inputEle = document.getElementById('input1'); inputEle.value = ''; inputEle.focus(); inputEle.select();");
QTRY_VERIFY(evaluateJavaScriptSync(view.page(), "document.getElementById('input1').value").toString().isEmpty());
QKeyEvent keyPressEnterWithLFCR(QEvent::KeyPress, Qt::Key_Enter, Qt::NoModifier, "\n\r");
QKeyEvent keyReleaseEnterWithLFCR(QEvent::KeyRelease, Qt::Key_Enter, Qt::NoModifier, "\n\r");
QApplication::sendEvent(view.focusProxy(), &keyPressEnterWithLFCR);
QApplication::sendEvent(view.focusProxy(), &keyReleaseEnterWithLFCR);
QApplication::sendEvent(view.focusProxy(), &eventText);
QApplication::sendEvent(view.focusProxy(), &eventText2);
qApp->processEvents();
QTRY_COMPARE(evaluateJavaScriptSync(view.page(), "document.getElementById('input1').value").toString(), QString("\n\nthird line"));
QTRY_COMPARE(view.focusProxy()->inputMethodQuery(Qt::ImSurroundingText).toString(), QString("\n\nthird line"));
// Return Key without key text
evaluateJavaScriptSync(view.page(), "var inputEle = document.getElementById('input1'); inputEle.value = ''; inputEle.focus(); inputEle.select();");
QTRY_VERIFY(evaluateJavaScriptSync(view.page(), "document.getElementById('input1').value").toString().isEmpty());
QKeyEvent keyPressReturn(QEvent::KeyPress, Qt::Key_Enter, Qt::NoModifier);
QKeyEvent keyReleaseReturn(QEvent::KeyRelease, Qt::Key_Enter, Qt::NoModifier);
QApplication::sendEvent(view.focusProxy(), &keyPressReturn);
QApplication::sendEvent(view.focusProxy(), &keyReleaseReturn);
QApplication::sendEvent(view.focusProxy(), &eventText);
QApplication::sendEvent(view.focusProxy(), &eventText2);
qApp->processEvents();
QTRY_COMPARE(evaluateJavaScriptSync(view.page(), "document.getElementById('input1').value").toString(), QString("\n\nthird line"));
QTRY_COMPARE(view.focusProxy()->inputMethodQuery(Qt::ImSurroundingText).toString(), QString("\n\nthird line"));
}
void tst_QWebEngineView::imeJSInputEvents()
{
QWebEngineView view;
view.resize(640, 480);
view.settings()->setAttribute(QWebEngineSettings::FocusOnNavigationEnabled, true);
view.show();
auto logLines = [&view]() -> QStringList {
return evaluateJavaScriptSync(view.page(), "log.textContent").toString().split("\n").filter(QRegularExpression(".+"));
};
QSignalSpy loadFinishedSpy(&view, SIGNAL(loadFinished(bool)));
view.page()->setHtml("<html>"
"<head><script>"
" var input, log;"
" function verboseEvent(ev) {"
" log.textContent += ev + ' ' + ev.type + ' ' + ev.data + '\\n';"
" }"
" function clear(ev) {"
" log.textContent = '';"
" input.textContent = '';"
" }"
" function init() {"
" input = document.getElementById('input');"
" log = document.getElementById('log');"
" events = [ 'textInput', 'beforeinput', 'input', 'compositionstart', 'compositionupdate', 'compositionend' ];"
" for (var e in events)"
" input.addEventListener(events[e], verboseEvent);"
" }"
"</script></head>"
"<body onload='init()'>"
" <div id='input' contenteditable='true' style='border-style: solid;'></div>"
" <pre id='log'></pre>"
"</body></html>");
QVERIFY(loadFinishedSpy.wait());
QVERIFY(QTest::qWaitForWindowExposed(&view));
evaluateJavaScriptSync(view.page(), "document.getElementById('input').focus()");
QTRY_COMPARE(evaluateJavaScriptSync(view.page(), "document.activeElement.id").toString(), QStringLiteral("input"));
// 1. Commit text (this is how dead keys work on Linux).
{
QList<QInputMethodEvent::Attribute> attributes;
QInputMethodEvent event("", attributes);
event.setCommitString("commit");
QApplication::sendEvent(view.focusProxy(), &event);
qApp->processEvents();
}
// Simply committing text should not trigger any JS composition event.
QTRY_COMPARE(logLines().count(), 3);
QCOMPARE(logLines()[0], QStringLiteral("[object InputEvent] beforeinput commit"));
QCOMPARE(logLines()[1], QStringLiteral("[object TextEvent] textInput commit"));
QCOMPARE(logLines()[2], QStringLiteral("[object InputEvent] input commit"));
evaluateJavaScriptSync(view.page(), "clear()");
QTRY_VERIFY(evaluateJavaScriptSync(view.page(), "log.textContent + input.textContent").toString().isEmpty());
// 2. Start composition then commit text (this is how dead keys work on macOS).
{
QList<QInputMethodEvent::Attribute> attributes;
QInputMethodEvent event("preedit", attributes);
QApplication::sendEvent(view.focusProxy(), &event);
qApp->processEvents();
}
QTRY_COMPARE(logLines().count(), 4);
QCOMPARE(logLines()[0], QStringLiteral("[object CompositionEvent] compositionstart "));
QCOMPARE(logLines()[1], QStringLiteral("[object InputEvent] beforeinput preedit"));
QCOMPARE(logLines()[2], QStringLiteral("[object CompositionEvent] compositionupdate preedit"));
QCOMPARE(logLines()[3], QStringLiteral("[object InputEvent] input preedit"));
{
QList<QInputMethodEvent::Attribute> attributes;
QInputMethodEvent event("", attributes);
event.setCommitString("commit");
QApplication::sendEvent(view.focusProxy(), &event);
qApp->processEvents();
}
QTRY_COMPARE(logLines().count(), 9);
QCOMPARE(logLines()[4], QStringLiteral("[object InputEvent] beforeinput commit"));
QCOMPARE(logLines()[5], QStringLiteral("[object CompositionEvent] compositionupdate commit"));
QCOMPARE(logLines()[6], QStringLiteral("[object TextEvent] textInput commit"));
QCOMPARE(logLines()[7], QStringLiteral("[object InputEvent] input commit"));
QCOMPARE(logLines()[8], QStringLiteral("[object CompositionEvent] compositionend commit"));
evaluateJavaScriptSync(view.page(), "clear()");
QTRY_VERIFY(evaluateJavaScriptSync(view.page(), "log.textContent + input.textContent").toString().isEmpty());
// 3. Start composition then cancel it with an empty IME event.
{
QList<QInputMethodEvent::Attribute> attributes;
QInputMethodEvent event("preedit", attributes);
QApplication::sendEvent(view.focusProxy(), &event);
qApp->processEvents();
}
QTRY_COMPARE(logLines().count(), 4);
QCOMPARE(logLines()[0], QStringLiteral("[object CompositionEvent] compositionstart "));
QCOMPARE(logLines()[1], QStringLiteral("[object InputEvent] beforeinput preedit"));
QCOMPARE(logLines()[2], QStringLiteral("[object CompositionEvent] compositionupdate preedit"));
QCOMPARE(logLines()[3], QStringLiteral("[object InputEvent] input preedit"));
{
QList<QInputMethodEvent::Attribute> attributes;
QInputMethodEvent event("", attributes);
QApplication::sendEvent(view.focusProxy(), &event);
qApp->processEvents();
}
QTRY_COMPARE(logLines().count(), 9);
QCOMPARE(logLines()[4], QStringLiteral("[object InputEvent] beforeinput "));
QCOMPARE(logLines()[5], QStringLiteral("[object CompositionEvent] compositionupdate "));
QCOMPARE(logLines()[6], QStringLiteral("[object TextEvent] textInput "));
QCOMPARE(logLines()[7], QStringLiteral("[object InputEvent] input null"));
QCOMPARE(logLines()[8], QStringLiteral("[object CompositionEvent] compositionend "));
evaluateJavaScriptSync(view.page(), "clear()");
QTRY_VERIFY(evaluateJavaScriptSync(view.page(), "log.textContent + input.textContent").toString().isEmpty());
// 4. Send empty IME event.
{
QList<QInputMethodEvent::Attribute> attributes;
QInputMethodEvent event("", attributes);
QApplication::sendEvent(view.focusProxy(), &event);
qApp->processEvents();
}
// No JS event is expected.
QTest::qWait(100);
QVERIFY(logLines().isEmpty());
evaluateJavaScriptSync(view.page(), "clear()");
QTRY_VERIFY(evaluateJavaScriptSync(view.page(), "log.textContent + input.textContent").toString().isEmpty());
}
void tst_QWebEngineView::imeCompositionQueryEvent_data()
{
QTest::addColumn<QString>("receiverObjectName");
QTest::newRow("focusObject") << QString("focusObject");
QTest::newRow("focusProxy") << QString("focusProxy");
QTest::newRow("focusWidget") << QString("focusWidget");
}
void tst_QWebEngineView::imeCompositionQueryEvent()
{
QWebEngineView view;
view.resize(640, 480);
view.settings()->setAttribute(QWebEngineSettings::FocusOnNavigationEnabled, true);
view.show();
QSignalSpy loadFinishedSpy(&view, SIGNAL(loadFinished(bool)));
view.setHtml("<html><body>"
" <input type='text' id='input1' />"
"</body></html>");
QVERIFY(loadFinishedSpy.wait());
QVERIFY(QTest::qWaitForWindowExposed(&view));
evaluateJavaScriptSync(view.page(), "document.getElementById('input1').focus()");
QTRY_COMPARE(evaluateJavaScriptSync(view.page(), "document.activeElement.id").toString(), QStringLiteral("input1"));
QObject *input = nullptr;
QFETCH(QString, receiverObjectName);
if (receiverObjectName == "focusObject") {
QTRY_VERIFY(qApp->focusObject());
input = qApp->focusObject();
} else if (receiverObjectName == "focusProxy") {
QTRY_VERIFY(view.focusProxy());
input = view.focusProxy();
} else if (receiverObjectName == "focusWidget") {
QTRY_VERIFY(view.focusWidget());
input = view.focusWidget();
}
QInputMethodQueryEvent srrndTextQuery(Qt::ImSurroundingText);
QInputMethodQueryEvent cursorPosQuery(Qt::ImCursorPosition);
QInputMethodQueryEvent anchorPosQuery(Qt::ImAnchorPosition);
// Set composition
{
QList<QInputMethodEvent::Attribute> attributes;
QInputMethodEvent event("composition", attributes);
QApplication::sendEvent(input, &event);
qApp->processEvents();
}
QTRY_COMPARE(evaluateJavaScriptSync(view.page(), "document.getElementById('input1').value").toString(), QString("composition"));
QTRY_COMPARE(view.focusProxy()->inputMethodQuery(Qt::ImCursorPosition).toInt(), 11);
QApplication::sendEvent(input, &srrndTextQuery);
QApplication::sendEvent(input, &cursorPosQuery);
QApplication::sendEvent(input, &anchorPosQuery);
qApp->processEvents();
QTRY_COMPARE(srrndTextQuery.value(Qt::ImSurroundingText).toString(), QString(""));
QTRY_COMPARE(cursorPosQuery.value(Qt::ImCursorPosition).toInt(), 11);
QTRY_COMPARE(anchorPosQuery.value(Qt::ImAnchorPosition).toInt(), 11);
// Send commit
{
QList<QInputMethodEvent::Attribute> attributes;
QInputMethodEvent event("", attributes);
event.setCommitString("composition");
QApplication::sendEvent(input, &event);
qApp->processEvents();
}
QTRY_COMPARE(evaluateJavaScriptSync(view.page(), "document.getElementById('input1').value").toString(), QString("composition"));
QTRY_COMPARE(view.focusProxy()->inputMethodQuery(Qt::ImSurroundingText).toString(), QString("composition"));
QApplication::sendEvent(input, &srrndTextQuery);
QApplication::sendEvent(input, &cursorPosQuery);
QApplication::sendEvent(input, &anchorPosQuery);
qApp->processEvents();
QTRY_COMPARE(srrndTextQuery.value(Qt::ImSurroundingText).toString(), QString("composition"));
QTRY_COMPARE(cursorPosQuery.value(Qt::ImCursorPosition).toInt(), 11);
QTRY_COMPARE(anchorPosQuery.value(Qt::ImAnchorPosition).toInt(), 11);
}
#ifndef QT_NO_CLIPBOARD
void tst_QWebEngineView::globalMouseSelection()
{
if (!QApplication::clipboard()->supportsSelection()) {
QSKIP("Test only relevant for systems with selection");
return;
}
QApplication::clipboard()->clear(QClipboard::Selection);
QWebEngineView view;
view.resize(640, 480);
view.show();
QSignalSpy selectionChangedSpy(&view, SIGNAL(selectionChanged()));
QSignalSpy loadFinishedSpy(&view, SIGNAL(loadFinished(bool)));
view.setHtml("<html><body>"
" <input type='text' id='input1' value='QtWebEngine' size='50' />"
"</body></html>");
QVERIFY(loadFinishedSpy.wait());
// Select text via JavaScript
evaluateJavaScriptSync(view.page(), "var inputEle = document.getElementById('input1'); inputEle.focus(); inputEle.select();");
QTRY_COMPARE(selectionChangedSpy.count(), 1);
QVERIFY(QApplication::clipboard()->text(QClipboard::Selection).isEmpty());
// Deselect the selection (this moves the current cursor to the end of the text)
QPoint textInputCenter = elementCenter(view.page(), "input1");
QTest::mouseClick(view.focusProxy(), Qt::LeftButton, {}, textInputCenter);
QVERIFY(selectionChangedSpy.wait());
QCOMPARE(selectionChangedSpy.count(), 2);
QVERIFY(QApplication::clipboard()->text(QClipboard::Selection).isEmpty());
// Select to the start of the line
QTest::keyClick(view.focusProxy(), Qt::Key_Home, Qt::ShiftModifier);
QVERIFY(selectionChangedSpy.wait());
QCOMPARE(selectionChangedSpy.count(), 3);
QCOMPARE(QApplication::clipboard()->text(QClipboard::Selection), QStringLiteral("QtWebEngine"));
}
#endif
void tst_QWebEngineView::noContextMenu()
{
QWidget wrapper;
wrapper.setContextMenuPolicy(Qt::CustomContextMenu);
connect(&wrapper, &QWidget::customContextMenuRequested, [&wrapper](const QPoint &pt) {
QMenu* menu = new QMenu(&wrapper);
menu->addAction("Action1");
menu->addAction("Action2");
menu->popup(pt);
});
QWebEngineView view(&wrapper);
view.setContextMenuPolicy(Qt::NoContextMenu);
wrapper.show();
QVERIFY(view.findChildren<QMenu *>().isEmpty());
QVERIFY(wrapper.findChildren<QMenu *>().isEmpty());
QTest::mouseMove(wrapper.windowHandle(), QPoint(10,10));
QTest::mouseClick(wrapper.windowHandle(), Qt::RightButton);
QTRY_COMPARE(wrapper.findChildren<QMenu *>().count(), 1);
QVERIFY(view.findChildren<QMenu *>().isEmpty());
}
void tst_QWebEngineView::contextMenu_data()
{
QTest::addColumn<int>("childrenCount");
QTest::addColumn<bool>("isCustomMenu");
QTest::addColumn<Qt::ContextMenuPolicy>("contextMenuPolicy");
QTest::newRow("defaultContextMenu") << 1 << false << Qt::DefaultContextMenu;
QTest::newRow("customContextMenu") << 1 << true << Qt::CustomContextMenu;
QTest::newRow("preventContextMenu") << 0 << false << Qt::PreventContextMenu;
}
void tst_QWebEngineView::contextMenu()
{
QFETCH(int, childrenCount);
QFETCH(bool, isCustomMenu);
QFETCH(Qt::ContextMenuPolicy, contextMenuPolicy);
QWebEngineView view;
QMenu *customMenu = nullptr;
if (contextMenuPolicy == Qt::CustomContextMenu) {
connect(&view, &QWebEngineView::customContextMenuRequested, [&view, &customMenu] (const QPoint &pt) {
Q_ASSERT(!customMenu);
customMenu = new QMenu(&view);
customMenu->addAction("Action1");
customMenu->addAction("Action2");
customMenu->popup(pt);
});
}
view.setContextMenuPolicy(contextMenuPolicy);
// input is supposed to be skipped before first real navigation in >= 79
QSignalSpy loadSpy(&view, &QWebEngineView::loadFinished);
view.load(QUrl("about:blank"));
view.resize(640, 480);
view.show();
QTRY_COMPARE(loadSpy.count(), 1);
QVERIFY(view.findChildren<QMenu *>().isEmpty());
QTest::mouseMove(view.windowHandle(), QPoint(10,10));
QTest::mouseClick(view.windowHandle(), Qt::RightButton);
// verify for zero children will always succeed, so should be tested with at least minor timeout
if (childrenCount <= 0) {
QVERIFY(!QTest::qWaitFor([&view] () { return view.findChildren<QMenu *>().count() > 0; }, 500));
} else {
QTRY_COMPARE(view.findChildren<QMenu *>().count(), childrenCount);
if (isCustomMenu) {
QCOMPARE(view.findChildren<QMenu *>().first(), customMenu);
}
}
QCOMPARE(!!customMenu, isCustomMenu);
}
void tst_QWebEngineView::mouseLeave()
{
QScopedPointer<QWidget> containerWidget(new QWidget);
QLabel *label = new QLabel(containerWidget.data());
label->setStyleSheet("background-color: red;");
label->setSizePolicy(QSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed));
label->setMinimumHeight(100);
QWebEngineView *view = new QWebEngineView(containerWidget.data());
view->setSizePolicy(QSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed));
view->setMinimumHeight(100);
QVBoxLayout *layout = new QVBoxLayout;
layout->setAlignment(Qt::AlignTop);
layout->setSpacing(0);
layout->setContentsMargins(0, 0, 0, 0);
layout->addWidget(label);
layout->addWidget(view);
containerWidget->setLayout(layout);
containerWidget->show();
QVERIFY(QTest::qWaitForWindowExposed(containerWidget.data()));
QTest::mouseMove(containerWidget->windowHandle(), QPoint(1, 1));
auto innerText = [view]() -> QString {
return evaluateJavaScriptSync(view->page(), "document.getElementById('testDiv').innerText").toString();
};
QSignalSpy loadFinishedSpy(view, SIGNAL(loadFinished(bool)));
view->setHtml("<html>"
"<head><script>"
"function init() {"
" var div = document.getElementById('testDiv');"
" div.onmouseenter = function(e) { div.innerText = 'Mouse IN' };"
" div.onmouseleave = function(e) { div.innerText = 'Mouse OUT' };"
"}"
"</script></head>"
"<body onload='init()' style='margin: 0px; padding: 0px'>"
" <div id='testDiv' style='width: 100%; height: 100%; background-color: green' />"
"</body>"
"</html>");
QVERIFY(loadFinishedSpy.wait());
// Make sure the testDiv text is empty.
evaluateJavaScriptSync(view->page(), "document.getElementById('testDiv').innerText = ''");
QTRY_VERIFY(innerText().isEmpty());
QTest::mouseMove(containerWidget->windowHandle(), QPoint(50, 150));
QTRY_COMPARE(innerText(), QStringLiteral("Mouse IN"));
QTest::mouseMove(containerWidget->windowHandle(), QPoint(50, 50));
QTRY_COMPARE(innerText(), QStringLiteral("Mouse OUT"));
}
void tst_QWebEngineView::webUIURLs_data()
{
QTest::addColumn<QUrl>("url");
QTest::addColumn<bool>("supported");
QTest::newRow("about") << QUrl("chrome://about") << false;
QTest::newRow("accessibility") << QUrl("chrome://accessibility") << true;
QTest::newRow("appcache-internals") << QUrl("chrome://appcache-internals") << true;
QTest::newRow("apps") << QUrl("chrome://apps") << false;
QTest::newRow("autofill-internals") << QUrl("chrome://autofill-internals") << false;
QTest::newRow("blob-internals") << QUrl("chrome://blob-internals") << true;
QTest::newRow("bluetooth-internals") << QUrl("chrome://bluetooth-internals") << false;
QTest::newRow("bookmarks") << QUrl("chrome://bookmarks") << false;
QTest::newRow("chrome-urls") << QUrl("chrome://chrome-urls") << false;
QTest::newRow("components") << QUrl("chrome://components") << false;
QTest::newRow("conversion-internals") << QUrl("chrome://conversion-internals") << true;
QTest::newRow("crashes") << QUrl("chrome://crashes") << false;
QTest::newRow("credits") << QUrl("chrome://credits") << false;
QTest::newRow("device-log") << QUrl("chrome://device-log") << false;
QTest::newRow("devices") << QUrl("chrome://devices") << false;
QTest::newRow("dino") << QUrl("chrome://dino") << false; // It works but this is an error page
QTest::newRow("discards") << QUrl("chrome://discards") << false;
QTest::newRow("download-internals") << QUrl("chrome://download-internals") << false;
QTest::newRow("downloads") << QUrl("chrome://downloads") << false;
QTest::newRow("extensions") << QUrl("chrome://extensions") << false;
QTest::newRow("flags") << QUrl("chrome://flags") << false;
QTest::newRow("gcm-internals") << QUrl("chrome://gcm-internals") << false;
QTest::newRow("gpu") << QUrl("chrome://gpu") << true;
QTest::newRow("help") << QUrl("chrome://help") << false;
QTest::newRow("histograms") << QUrl("chrome://histograms") << true;
QTest::newRow("history") << QUrl("chrome://history") << false;
QTest::newRow("indexeddb-internals") << QUrl("chrome://indexeddb-internals") << true;
QTest::newRow("inspect") << QUrl("chrome://inspect") << false;
QTest::newRow("interstitials") << QUrl("chrome://interstitials") << false;
QTest::newRow("interventions-internals") << QUrl("chrome://interventions-internals") << false;
QTest::newRow("invalidations") << QUrl("chrome://invalidations") << false;
QTest::newRow("linux-proxy-config") << QUrl("chrome://linux-proxy-config") << false;
QTest::newRow("local-state") << QUrl("chrome://local-state") << false;
QTest::newRow("management") << QUrl("chrome://management") << false;
QTest::newRow("media-engagement") << QUrl("chrome://media-engagement") << false;
QTest::newRow("media-internals") << QUrl("chrome://media-internals") << true;
QTest::newRow("net-export") << QUrl("chrome://net-export") << false;
QTest::newRow("net-internals") << QUrl("chrome://net-internals") << true;
QTest::newRow("network-error") << QUrl("chrome://network-error") << false;
QTest::newRow("network-errors") << QUrl("chrome://network-errors") << true;
QTest::newRow("ntp-tiles-internals") << QUrl("chrome://ntp-tiles-internals") << false;
QTest::newRow("omnibox") << QUrl("chrome://omnibox") << false;
QTest::newRow("password-manager-internals") << QUrl("chrome://password-manager-internals") << false;
QTest::newRow("policy") << QUrl("chrome://policy") << false;
QTest::newRow("predictors") << QUrl("chrome://predictors") << false;
QTest::newRow("prefs-internals") << QUrl("chrome://prefs-internals") << false;
QTest::newRow("print") << QUrl("chrome://print") << false;
QTest::newRow("process-internals") << QUrl("chrome://process-internals") << true;
QTest::newRow("quota-internals") << QUrl("chrome://quota-internals") << true;
QTest::newRow("safe-browsing") << QUrl("chrome://safe-browsing") << false;
#ifdef Q_OS_LINUX
QTest::newRow("sandbox") << QUrl("chrome://sandbox") << true;
#else
QTest::newRow("sandbox") << QUrl("chrome://sandbox") << false;
#endif
QTest::newRow("serviceworker-internals") << QUrl("chrome://serviceworker-internals") << true;
QTest::newRow("settings") << QUrl("chrome://settings") << false;
QTest::newRow("signin-internals") << QUrl("chrome://signin-internals") << false;
QTest::newRow("site-engagement") << QUrl("chrome://site-engagement") << false;
QTest::newRow("suggestions") << QUrl("chrome://suggestions") << false;
QTest::newRow("supervised-user-internals") << QUrl("chrome://supervised-user-internals") << false;
QTest::newRow("sync-internals") << QUrl("chrome://sync-internals") << false;
QTest::newRow("system") << QUrl("chrome://system") << false;
QTest::newRow("terms") << QUrl("chrome://terms") << false;
QTest::newRow("tracing") << QUrl("chrome://tracing") << true;
QTest::newRow("translate-internals") << QUrl("chrome://translate-internals") << false;
QTest::newRow("ukm") << QUrl("chrome://ukm") << true;
QTest::newRow("usb-internals") << QUrl("chrome://usb-internals") << false;
QTest::newRow("user-actions") << QUrl("chrome://user-actions") << true;
QTest::newRow("version") << QUrl("chrome://version") << false;
QTest::newRow("webrtc-internals") << QUrl("chrome://webrtc-internals") << true;
QTest::newRow("webrtc-logs") << QUrl("chrome://webrtc-logs") << true;
}
void tst_QWebEngineView::webUIURLs()
{
QFETCH(QUrl, url);
QFETCH(bool, supported);
QWebEngineView view;
view.settings()->setAttribute(QWebEngineSettings::ErrorPageEnabled, false);
QSignalSpy loadFinishedSpy(&view, SIGNAL(loadFinished(bool)));
view.load(url);
QTRY_COMPARE_WITH_TIMEOUT(loadFinishedSpy.count(), 1, 30000);
QCOMPARE(loadFinishedSpy.takeFirst().at(0).toBool(), supported);
}
void tst_QWebEngineView::visibilityState()
{
QWebEngineView view;
QSignalSpy spy(&view, &QWebEngineView::loadFinished);
view.load(QStringLiteral("about:blank"));
QVERIFY(spy.count() || spy.wait());
QVERIFY(spy.takeFirst().takeFirst().toBool());
QCOMPARE(evaluateJavaScriptSync(view.page(), "document.visibilityState").toString(), QStringLiteral("hidden"));
view.show();
QVERIFY(QTest::qWaitForWindowExposed(&view));
QCOMPARE(evaluateJavaScriptSync(view.page(), "document.visibilityState").toString(), QStringLiteral("visible"));
}
void tst_QWebEngineView::visibilityState2()
{
QWebEngineView view;
QSignalSpy spy(&view, &QWebEngineView::loadFinished);
view.show();
view.load(QStringLiteral("about:blank"));
view.hide();
QVERIFY(spy.count() || spy.wait());
QVERIFY(spy.takeFirst().takeFirst().toBool());
QCOMPARE(evaluateJavaScriptSync(view.page(), "document.visibilityState").toString(), QStringLiteral("hidden"));
}
void tst_QWebEngineView::visibilityState3()
{
QWebEnginePage page1;
QWebEnginePage page2;
QSignalSpy spy1(&page1, &QWebEnginePage::loadFinished);
QSignalSpy spy2(&page2, &QWebEnginePage::loadFinished);
page1.load(QStringLiteral("about:blank"));
page2.load(QStringLiteral("about:blank"));
QVERIFY(spy1.count() || spy1.wait());
QVERIFY(spy2.count() || spy2.wait());
QWebEngineView view;
view.setPage(&page1);
view.show();
QCOMPARE(evaluateJavaScriptSync(&page1, "document.visibilityState").toString(), QStringLiteral("visible"));
QCOMPARE(evaluateJavaScriptSync(&page2, "document.visibilityState").toString(), QStringLiteral("hidden"));
view.setPage(&page2);
QCOMPARE(evaluateJavaScriptSync(&page1, "document.visibilityState").toString(), QStringLiteral("hidden"));
QCOMPARE(evaluateJavaScriptSync(&page2, "document.visibilityState").toString(), QStringLiteral("visible"));
}
void tst_QWebEngineView::jsKeyboardEvent_data()
{
QTest::addColumn<char>("key");
QTest::addColumn<Qt::KeyboardModifiers>("modifiers");
QTest::addColumn<QString>("expected");
#if defined(Q_OS_MACOS)
// See Qt::AA_MacDontSwapCtrlAndMeta
Qt::KeyboardModifiers controlModifier = Qt::MetaModifier;
#else
Qt::KeyboardModifiers controlModifier = Qt::ControlModifier;
#endif
QTest::newRow("Ctrl+Shift+A") << 'A' << (controlModifier | Qt::ShiftModifier) << QStringLiteral(
"16,ShiftLeft,Shift,false,true,false;"
"17,ControlLeft,Control,true,true,false;"
"65,KeyA,A,true,true,false;");
QTest::newRow("Ctrl+z") << 'z' << controlModifier << QStringLiteral(
"17,ControlLeft,Control,true,false,false;"
"90,KeyZ,z,true,false,false;");
}
void tst_QWebEngineView::jsKeyboardEvent()
{
QWebEngineView view;
evaluateJavaScriptSync(
view.page(),
"var log = '';"
"addEventListener('keydown', (ev) => {"
" log += [ev.keyCode, ev.code, ev.key, ev.ctrlKey, ev.shiftKey, ev.altKey].join(',') + ';';"
"});");
QFETCH(char, key);
QFETCH(Qt::KeyboardModifiers, modifiers);
QFETCH(QString, expected);
// Note that this only tests the fallback code path where native scan codes are not used.
QTest::keyClick(view.focusProxy(), key, modifiers);
QTRY_VERIFY(evaluateJavaScriptSync(view.page(), "log") != QVariant(QString()));
QCOMPARE(evaluateJavaScriptSync(view.page(), "log"), expected);
}
void tst_QWebEngineView::deletePage()
{
QWebEngineView view;
QWebEnginePage *page = view.page();
QVERIFY(page);
QCOMPARE(page->parent(), &view);
delete page;
// Test that a new page is created and that it is useful:
QVERIFY(view.page());
QSignalSpy spy(view.page(), &QWebEnginePage::loadFinished);
view.page()->load(QStringLiteral("about:blank"));
QTRY_VERIFY(spy.count());
}
void tst_QWebEngineView::autoDeleteOnExternalPageDelete()
{
QPointer<QWebEngineView> view = new QWebEngineView;
QPointer<QWebEnginePage> page = new QWebEnginePage;
auto sg = qScopeGuard([&] () { delete view; delete page; });
QSignalSpy spy(page, &QWebEnginePage::loadFinished);
view->setPage(page);
view->show();
view->resize(320, 240);
page->load(QUrl("about:blank"));
QTRY_VERIFY(spy.count());
QVERIFY(page->parent() != view);
auto sc = QObject::connect(page, &QWebEnginePage::destroyed, view, &QWebEngineView::deleteLater);
QTimer::singleShot(0, page, &QObject::deleteLater);
QTRY_VERIFY(!page);
QTRY_VERIFY(!view);
}
class TestView : public QWebEngineView {
Q_OBJECT
public:
TestView(QWidget *parent = nullptr) : QWebEngineView(parent)
{
}
QWebEngineView *createWindow(QWebEnginePage::WebWindowType) override
{
TestView *view = new TestView(parentWidget());
createdWindows.append(view);
return view;
}
QList<TestView *> createdWindows;
};
void tst_QWebEngineView::closeOpenerTab()
{
QWidget rootWidget;
rootWidget.resize(600, 400);
auto *testView = new TestView(&rootWidget);
testView->settings()->setAttribute(QWebEngineSettings::JavascriptCanOpenWindows, true);
QSignalSpy loadFinishedSpy(testView, SIGNAL(loadFinished(bool)));
testView->setUrl(QStringLiteral("about:blank"));
QTRY_VERIFY(loadFinishedSpy.count());
testView->page()->runJavaScript(QStringLiteral("window.open('about:blank','_blank')"));
QTRY_COMPARE(testView->createdWindows.size(), 1);
auto *newView = testView->createdWindows.at(0);
newView->show();
rootWidget.show();
QVERIFY(QTest::qWaitForWindowExposed(newView));
QVERIFY(newView->focusProxy()->isVisible());
delete testView;
QVERIFY(newView->focusProxy()->isVisible());
}
void tst_QWebEngineView::switchPage()
{
QWebEngineProfile profile;
QWebEnginePage page1(&profile);
QWebEnginePage page2(&profile);
QSignalSpy loadFinishedSpy1(&page1, SIGNAL(loadFinished(bool)));
QSignalSpy loadFinishedSpy2(&page2, SIGNAL(loadFinished(bool)));
page1.setHtml("<html><body bgcolor=\"#000000\"></body></html>");
page2.setHtml("<html><body bgcolor=\"#ffffff\"></body></html>");
QTRY_VERIFY(loadFinishedSpy1.count() && loadFinishedSpy2.count());
QWebEngineView webView;
webView.resize(300,300);
webView.show();
webView.setPage(&page1);
QTRY_COMPARE(webView.grab().toImage().pixelColor(QPoint(150,150)), Qt::black);
webView.setPage(&page2);
QTRY_COMPARE(webView.grab().toImage().pixelColor(QPoint(150,150)), Qt::white);
webView.setPage(&page1);
QTRY_COMPARE(webView.grab().toImage().pixelColor(QPoint(150,150)), Qt::black);
}
void tst_QWebEngineView::setPageDeletesImplicitPage()
{
QWebEngineView view;
QPointer<QWebEnginePage> implicitPage = view.page();
QWebEnginePage explicitPage;
view.setPage(&explicitPage);
QCOMPARE(view.page(), &explicitPage);
QVERIFY(!implicitPage); // should be deleted
}
void tst_QWebEngineView::setPageDeletesImplicitPage2()
{
QWebEngineView view1;
QWebEngineView view2;
QPointer<QWebEnginePage> implicitPage = view1.page();
view2.setPage(view1.page());
QVERIFY(implicitPage);
QVERIFY(view1.page() != implicitPage);
QWebEnginePage explicitPage;
view2.setPage(&explicitPage);
QCOMPARE(view2.page(), &explicitPage);
QVERIFY(!implicitPage); // should be deleted
}
void tst_QWebEngineView::setViewDeletesImplicitPage()
{
QWebEngineView view;
QPointer<QWebEnginePage> implicitPage = view.page();
QWebEnginePage explicitPage;
explicitPage.setView(&view);
QCOMPARE(view.page(), &explicitPage);
QVERIFY(!implicitPage); // should be deleted
}
void tst_QWebEngineView::setPagePreservesExplicitPage()
{
QWebEngineView view;
QPointer<QWebEnginePage> explicitPage1 = new QWebEnginePage(&view);
QPointer<QWebEnginePage> explicitPage2 = new QWebEnginePage(&view);
view.setPage(explicitPage1.data());
view.setPage(explicitPage2.data());
QCOMPARE(view.page(), explicitPage2.data());
QVERIFY(explicitPage1); // should not be deleted
}
void tst_QWebEngineView::setViewPreservesExplicitPage()
{
QWebEngineView view;
QPointer<QWebEnginePage> explicitPage1 = new QWebEnginePage(&view);
QPointer<QWebEnginePage> explicitPage2 = new QWebEnginePage(&view);
explicitPage1->setView(&view);
explicitPage2->setView(&view);
QCOMPARE(view.page(), explicitPage2.data());
QVERIFY(explicitPage1); // should not be deleted
}
void tst_QWebEngineView::closeDiscardsPage()
{
QWebEngineProfile profile;
QWebEnginePage page(&profile);
QWebEngineView view;
view.setPage(&page);
view.resize(300, 300);
view.show();
QVERIFY(QTest::qWaitForWindowExposed(&view));
QCOMPARE(page.isVisible(), true);
QCOMPARE(page.lifecycleState(), QWebEnginePage::LifecycleState::Active);
view.close();
QCOMPARE(page.isVisible(), false);
QCOMPARE(page.lifecycleState(), QWebEnginePage::LifecycleState::Discarded);
}
void tst_QWebEngineView::loadAfterRendererCrashed()
{
QWebEngineView view;
view.resize(640, 480);
view.show();
QVERIFY(QTest::qWaitForWindowExposed(&view));
bool terminated = false;
connect(view.page(), &QWebEnginePage::renderProcessTerminated, [&] () { terminated = true; });
view.load(QUrl("chrome://crash"));
QTRY_VERIFY_WITH_TIMEOUT(terminated, 30000);
QSignalSpy loadSpy(&view, &QWebEngineView::loadFinished);
view.load(QUrl("qrc:///resources/dummy.html"));
QTRY_COMPARE(loadSpy.count(), 1);
QVERIFY(loadSpy.first().first().toBool());
}
void tst_QWebEngineView::navigateOnDrop_data()
{
QTest::addColumn<QUrl>("url");
QTest::newRow("file") << QUrl::fromLocalFile(QDir(TESTS_SOURCE_DIR).absoluteFilePath("qwebengineview/resources/dummy.html"));
QTest::newRow("qrc") << QUrl("qrc:///resources/dummy.html");
}
void tst_QWebEngineView::navigateOnDrop()
{
QFETCH(QUrl, url);
struct WebEngineView : QWebEngineView {
QWebEngineView* createWindow(QWebEnginePage::WebWindowType /* type */) override { return this; }
} view;
view.resize(640, 480);
view.show();
QVERIFY(QTest::qWaitForWindowExposed(&view));
QSignalSpy loadSpy(&view, &QWebEngineView::loadFinished);
QMimeData mimeData;
mimeData.setUrls({ url });
auto sendEvents = [&] () {
QDragEnterEvent dee(view.rect().center(), Qt::CopyAction, &mimeData, Qt::LeftButton, Qt::NoModifier);
QApplication::sendEvent(&view, &dee);
QDropEvent de(view.rect().center(), Qt::CopyAction, &mimeData, Qt::LeftButton, Qt::NoModifier);
QApplication::sendEvent(&view, &de);
};
sendEvents();
QTRY_COMPARE(loadSpy.count(), 1);
QVERIFY(loadSpy.first().first().toBool());
QCOMPARE(view.url(), url);
}
QTEST_MAIN(tst_QWebEngineView)
#include "tst_qwebengineview.moc"
|