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
|
// Copyright 2012 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <stddef.h>
#include <stdint.h>
#include <memory>
#include <tuple>
#include <utility>
#include "base/command_line.h"
#include "base/functional/bind.h"
#include "base/location.h"
#include "base/memory/raw_ptr.h"
#include "base/run_loop.h"
#include "base/task/single_thread_task_runner.h"
#include "base/test/metrics/histogram_tester.h"
#include "base/test/scoped_feature_list.h"
#include "base/test/simple_test_tick_clock.h"
#include "base/time/time.h"
#include "base/timer/timer.h"
#include "build/build_config.h"
#include "cc/mojom/render_frame_metadata.mojom.h"
#include "cc/trees/render_frame_metadata.h"
#include "components/input/input_constants.h"
#include "components/input/switches.h"
#include "components/viz/common/surfaces/local_surface_id.h"
#include "components/viz/common/surfaces/parent_local_surface_id_allocator.h"
#include "components/viz/test/begin_frame_args_test.h"
#include "content/browser/blob_storage/chrome_blob_storage_context.h"
#include "content/browser/gpu/compositor_util.h"
#include "content/browser/renderer_host/data_transfer_util.h"
#include "content/browser/renderer_host/display_feature.h"
#include "content/browser/renderer_host/frame_token_message_queue.h"
#include "content/browser/renderer_host/input/touch_emulator_impl.h"
#include "content/browser/renderer_host/mock_render_widget_host.h"
#include "content/browser/renderer_host/render_view_host_delegate_view.h"
#include "content/browser/renderer_host/render_widget_host_delegate.h"
#include "content/browser/renderer_host/render_widget_host_view_base.h"
#include "content/browser/renderer_host/visible_time_request_trigger.h"
#include "content/browser/site_instance_group.h"
#include "content/browser/storage_partition_impl.h"
#include "content/common/content_constants_internal.h"
#include "content/public/browser/keyboard_event_processing_result.h"
#include "content/public/common/content_features.h"
#include "content/public/common/content_switches.h"
#include "content/public/common/drop_data.h"
#include "content/public/test/browser_task_environment.h"
#include "content/public/test/mock_render_process_host.h"
#include "content/public/test/test_browser_context.h"
#include "content/test/mock_render_input_router.h"
#include "content/test/mock_widget.h"
#include "content/test/mock_widget_input_handler.h"
#include "content/test/stub_render_widget_host_owner_delegate.h"
#include "content/test/test_render_view_host.h"
#include "content/test/test_render_widget_host.h"
#include "mojo/public/cpp/bindings/pending_receiver.h"
#include "mojo/public/cpp/bindings/pending_remote.h"
#include "mojo/public/cpp/bindings/remote.h"
#include "skia/ext/skia_utils_base.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "third_party/blink/public/common/input/synthetic_web_input_event_builders.h"
#include "third_party/blink/public/common/input/web_mouse_event.h"
#include "third_party/blink/public/common/page/page_zoom.h"
#include "third_party/blink/public/common/widget/visual_properties.h"
#include "third_party/blink/public/mojom/drag/drag.mojom.h"
#include "third_party/blink/public/mojom/input/input_handler.mojom-shared.h"
#include "third_party/blink/public/mojom/input/touch_event.mojom.h"
#include "ui/base/cursor/cursor.h"
#include "ui/display/display_util.h"
#include "ui/display/screen.h"
#include "ui/events/base_event_utils.h"
#include "ui/events/blink/blink_features.h"
#include "ui/events/blink/web_input_event_traits.h"
#include "ui/events/gesture_detection/gesture_provider_config_helper.h"
#include "ui/events/keycodes/keyboard_codes.h"
#include "ui/gfx/canvas.h"
#if BUILDFLAG(IS_ANDROID)
#include "base/strings/utf_string_conversions.h"
#include "content/browser/renderer_host/render_widget_host_view_android.h"
#include "ui/android/screen_android.h"
#endif
#if BUILDFLAG(IS_MAC)
#include "content/browser/renderer_host/test_render_widget_host_view_mac_factory.h"
#endif
#if BUILDFLAG(IS_APPLE)
#include "ui/display/test/test_screen.h"
#endif
#if BUILDFLAG(IS_IOS)
#include "content/browser/renderer_host/test_render_widget_host_view_ios_factory.h"
#endif
#if defined(USE_AURA) || BUILDFLAG(IS_APPLE)
#include "content/public/test/test_image_transport_factory.h"
#endif
#if defined(USE_AURA)
#include "components/input/events_helper.h"
#include "content/browser/renderer_host/render_widget_host_view_aura.h"
#include "ui/aura/test/test_screen.h"
#include "ui/events/event.h"
#endif
using blink::WebGestureDevice;
using blink::WebGestureEvent;
using blink::WebInputEvent;
using blink::WebKeyboardEvent;
using blink::WebMouseEvent;
using blink::WebMouseWheelEvent;
using blink::WebTouchEvent;
using testing::_;
using testing::Return;
namespace content {
namespace {
// RenderWidgetHostProcess -----------------------------------------------------
class RenderWidgetHostProcess : public MockRenderProcessHost {
public:
explicit RenderWidgetHostProcess(BrowserContext* browser_context)
: MockRenderProcessHost(browser_context) {
}
RenderWidgetHostProcess(const RenderWidgetHostProcess&) = delete;
RenderWidgetHostProcess& operator=(const RenderWidgetHostProcess&) = delete;
~RenderWidgetHostProcess() override {}
bool IsInitializedAndNotDead() override { return true; }
};
// TestView --------------------------------------------------------------------
// This test view allows us to specify the size, and keep track of acked
// touch-events.
class TestView : public TestRenderWidgetHostView {
public:
explicit TestView(RenderWidgetHostImpl* rwh)
: TestRenderWidgetHostView(rwh),
unhandled_wheel_event_count_(0),
acked_event_count_(0),
gesture_event_type_(WebInputEvent::Type::kUndefined),
use_fake_compositor_viewport_pixel_size_(false),
ack_result_(blink::mojom::InputEventResultState::kUnknown) {
local_surface_id_allocator_.GenerateId();
}
TestView(const TestView&) = delete;
TestView& operator=(const TestView&) = delete;
// Sets the bounds returned by GetViewBounds.
void SetBounds(const gfx::Rect& bounds) override {
if (bounds_ == bounds)
return;
bounds_ = bounds;
local_surface_id_allocator_.GenerateId();
}
void SetScreenInfo(const display::ScreenInfo& screen_info) {
if (screen_info_ == screen_info)
return;
screen_info_ = screen_info;
local_surface_id_allocator_.GenerateId();
}
void InvalidateLocalSurfaceId() { local_surface_id_allocator_.Invalidate(); }
display::ScreenInfo GetScreenInfo() const override { return screen_info_; }
display::ScreenInfos GetScreenInfos() const override {
return display::ScreenInfos(screen_info_);
}
const WebTouchEvent& acked_event() const { return acked_event_; }
int acked_event_count() const { return acked_event_count_; }
void ClearAckedEvent() {
acked_event_.SetType(blink::WebInputEvent::Type::kUndefined);
acked_event_count_ = 0;
}
const WebMouseWheelEvent& unhandled_wheel_event() const {
return unhandled_wheel_event_;
}
int unhandled_wheel_event_count() const {
return unhandled_wheel_event_count_;
}
WebInputEvent::Type gesture_event_type() const { return gesture_event_type_; }
blink::mojom::InputEventResultState ack_result() const { return ack_result_; }
void SetMockCompositorViewportPixelSize(
const gfx::Size& mock_compositor_viewport_pixel_size) {
if (use_fake_compositor_viewport_pixel_size_ &&
mock_compositor_viewport_pixel_size_ ==
mock_compositor_viewport_pixel_size) {
return;
}
use_fake_compositor_viewport_pixel_size_ = true;
mock_compositor_viewport_pixel_size_ = mock_compositor_viewport_pixel_size;
local_surface_id_allocator_.GenerateId();
}
void ClearMockCompositorViewportPixelSize() {
if (!use_fake_compositor_viewport_pixel_size_)
return;
use_fake_compositor_viewport_pixel_size_ = false;
local_surface_id_allocator_.GenerateId();
}
// RenderWidgetHostView override.
gfx::Rect GetViewBounds() override { return bounds_; }
const viz::LocalSurfaceId& GetLocalSurfaceId() const override {
return local_surface_id_allocator_.GetCurrentLocalSurfaceId();
}
void SetInsets(const gfx::Insets& insets) override { insets_ = insets; }
gfx::Size GetVisibleViewportSize() override {
gfx::Rect requested_rect(GetRequestedRendererSize());
requested_rect.Inset(insets_);
return requested_rect.size();
}
gfx::Size GetVisibleViewportSizeDevicePx() override {
gfx::Rect requested_rect(GetRequestedRendererSizeDevicePx());
requested_rect.Inset(insets_);
return requested_rect.size();
}
void ProcessAckedTouchEvent(
const input::TouchEventWithLatencyInfo& touch,
blink::mojom::InputEventResultState ack_result) override {
acked_event_ = touch.event;
++acked_event_count_;
}
void WheelEventAck(const WebMouseWheelEvent& event,
blink::mojom::InputEventResultState ack_result) override {
if (ack_result == blink::mojom::InputEventResultState::kConsumed)
return;
unhandled_wheel_event_count_++;
unhandled_wheel_event_ = event;
}
void GestureEventAck(
const WebGestureEvent& event,
blink::mojom::InputEventResultSource ack_source,
blink::mojom::InputEventResultState ack_result) override {
gesture_event_type_ = event.GetType();
ack_result_ = ack_result;
}
gfx::Size GetCompositorViewportPixelSize() override {
if (use_fake_compositor_viewport_pixel_size_)
return mock_compositor_viewport_pixel_size_;
return TestRenderWidgetHostView::GetCompositorViewportPixelSize();
}
protected:
WebMouseWheelEvent unhandled_wheel_event_;
int unhandled_wheel_event_count_;
WebTouchEvent acked_event_;
int acked_event_count_;
WebInputEvent::Type gesture_event_type_;
gfx::Rect bounds_;
bool use_fake_compositor_viewport_pixel_size_;
gfx::Size mock_compositor_viewport_pixel_size_;
blink::mojom::InputEventResultState ack_result_;
viz::ParentLocalSurfaceIdAllocator local_surface_id_allocator_;
display::ScreenInfo screen_info_;
gfx::Insets insets_;
};
// MockRenderViewHostDelegateView ------------------------------------------
class MockRenderViewHostDelegateView : public RenderViewHostDelegateView {
public:
MockRenderViewHostDelegateView() = default;
MockRenderViewHostDelegateView(const MockRenderViewHostDelegateView&) =
delete;
MockRenderViewHostDelegateView& operator=(
const MockRenderViewHostDelegateView&) = delete;
~MockRenderViewHostDelegateView() override = default;
int start_dragging_count() const { return start_dragging_count_; }
// RenderViewHostDelegateView:
void StartDragging(const DropData& drop_data,
const url::Origin& source_origin,
blink::DragOperationsMask allowed_ops,
const gfx::ImageSkia& image,
const gfx::Vector2d& cursor_offset,
const gfx::Rect& drag_obj_rect,
const blink::mojom::DragEventSourceInfo& event_info,
RenderWidgetHostImpl* source_rwh) override {
++start_dragging_count_;
}
private:
int start_dragging_count_ = 0;
};
// FakeRenderFrameMetadataObserver -----------------------------------------
// Fake out the renderer side of mojom::RenderFrameMetadataObserver, allowing
// for RenderWidgetHostImpl to be created.
//
// All methods are no-opts, the provided mojo receiver and remote are held, but
// never bound.
class FakeRenderFrameMetadataObserver
: public cc::mojom::RenderFrameMetadataObserver {
public:
FakeRenderFrameMetadataObserver(
mojo::PendingReceiver<cc::mojom::RenderFrameMetadataObserver> receiver,
mojo::PendingRemote<cc::mojom::RenderFrameMetadataObserverClient>
client_remote);
FakeRenderFrameMetadataObserver(const FakeRenderFrameMetadataObserver&) =
delete;
FakeRenderFrameMetadataObserver& operator=(
const FakeRenderFrameMetadataObserver&) = delete;
~FakeRenderFrameMetadataObserver() override {}
#if BUILDFLAG(IS_ANDROID)
void UpdateRootScrollOffsetUpdateFrequency(
cc::mojom::RootScrollOffsetUpdateFrequency frequency) override {}
#endif
void ReportAllFrameSubmissionsForTesting(bool enabled) override {}
private:
mojo::PendingReceiver<cc::mojom::RenderFrameMetadataObserver> receiver_;
mojo::PendingRemote<cc::mojom::RenderFrameMetadataObserverClient>
client_remote_;
};
FakeRenderFrameMetadataObserver::FakeRenderFrameMetadataObserver(
mojo::PendingReceiver<cc::mojom::RenderFrameMetadataObserver> receiver,
mojo::PendingRemote<cc::mojom::RenderFrameMetadataObserverClient>
client_remote)
: receiver_(std::move(receiver)),
client_remote_(std::move(client_remote)) {}
// MockInputEventObserver -------------------------------------------------
class MockInputEventObserver : public RenderWidgetHost::InputEventObserver {
public:
MOCK_METHOD2(OnInputEvent,
void(const RenderWidgetHost& widget,
const blink::WebInputEvent&));
#if BUILDFLAG(IS_ANDROID)
MOCK_METHOD1(OnImeTextCommittedEvent, void(const std::u16string& text_str));
MOCK_METHOD1(OnImeSetComposingTextEvent,
void(const std::u16string& text_str));
MOCK_METHOD0(OnImeFinishComposingTextEvent, void());
#endif
};
// MockRenderWidgetHostDelegate --------------------------------------------
class MockRenderWidgetHostDelegate : public RenderWidgetHostDelegate {
public:
MockRenderWidgetHostDelegate()
: prehandle_keyboard_event_(false),
prehandle_keyboard_event_is_shortcut_(false),
prehandle_keyboard_event_called_(false),
prehandle_keyboard_event_type_(WebInputEvent::Type::kUndefined),
unhandled_keyboard_event_called_(false),
unhandled_keyboard_event_type_(WebInputEvent::Type::kUndefined),
handle_wheel_event_(false),
handle_wheel_event_called_(false),
unresponsive_timer_fired_(false),
ignore_input_events_(false),
render_view_host_delegate_view_(new MockRenderViewHostDelegateView()) {}
~MockRenderWidgetHostDelegate() override {}
// Tests that make sure we ignore keyboard event acknowledgments to events we
// didn't send work by making sure we didn't call UnhandledKeyboardEvent().
bool unhandled_keyboard_event_called() const {
return unhandled_keyboard_event_called_;
}
WebInputEvent::Type unhandled_keyboard_event_type() const {
return unhandled_keyboard_event_type_;
}
bool prehandle_mouse_event_called() const {
return prehandle_mouse_event_called_;
}
bool prehandle_keyboard_event_called() const {
return prehandle_keyboard_event_called_;
}
WebInputEvent::Type prehandle_keyboard_event_type() const {
return prehandle_keyboard_event_type_;
}
void set_prehandle_mouse_event(bool handle) {
prehandle_mouse_event_ = handle;
}
void set_prehandle_keyboard_event(bool handle) {
prehandle_keyboard_event_ = handle;
}
void set_handle_wheel_event(bool handle) {
handle_wheel_event_ = handle;
}
void set_prehandle_keyboard_event_is_shortcut(bool is_shortcut) {
prehandle_keyboard_event_is_shortcut_ = is_shortcut;
}
bool handle_wheel_event_called() const { return handle_wheel_event_called_; }
bool unresponsive_timer_fired() const { return unresponsive_timer_fired_; }
MockRenderViewHostDelegateView* mock_delegate_view() {
return render_view_host_delegate_view_.get();
}
void SetZoomLevel(double zoom_level) { zoom_level_ = zoom_level; }
double GetPendingZoomLevel(RenderWidgetHostImpl* rwh) override {
return zoom_level_;
}
void FocusOwningWebContents(
RenderWidgetHostImpl* render_widget_host) override {
focus_owning_web_contents_call_count++;
}
int GetFocusOwningWebContentsCallCount() const {
return focus_owning_web_contents_call_count;
}
void OnVerticalScrollDirectionChanged(
viz::VerticalScrollDirection scroll_direction) override {
++on_vertical_scroll_direction_changed_call_count_;
last_vertical_scroll_direction_ = scroll_direction;
}
int GetOnVerticalScrollDirectionChangedCallCount() const {
return on_vertical_scroll_direction_changed_call_count_;
}
viz::VerticalScrollDirection GetLastVerticalScrollDirection() const {
return last_vertical_scroll_direction_;
}
RenderViewHostDelegateView* GetDelegateView() override {
return mock_delegate_view();
}
void SetIgnoreInputEvents(bool ignore_input_events) {
ignore_input_events_ = ignore_input_events;
}
bool IsFullscreen() override { return is_fullscreen_; }
void set_is_fullscreen(bool enabled) { is_fullscreen_ = enabled; }
MOCK_METHOD(bool,
IsWaitingForPointerLockPrompt,
(RenderWidgetHostImpl * host),
(override));
protected:
bool PreHandleMouseEvent(const blink::WebMouseEvent& event) override {
prehandle_mouse_event_called_ = true;
if (prehandle_mouse_event_) {
return true;
}
return false;
}
KeyboardEventProcessingResult PreHandleKeyboardEvent(
const input::NativeWebKeyboardEvent& event) override {
prehandle_keyboard_event_type_ = event.GetType();
prehandle_keyboard_event_called_ = true;
if (prehandle_keyboard_event_)
return KeyboardEventProcessingResult::HANDLED;
return prehandle_keyboard_event_is_shortcut_
? KeyboardEventProcessingResult::NOT_HANDLED_IS_SHORTCUT
: KeyboardEventProcessingResult::NOT_HANDLED;
}
bool HandleKeyboardEvent(
const input::NativeWebKeyboardEvent& event) override {
unhandled_keyboard_event_type_ = event.GetType();
unhandled_keyboard_event_called_ = true;
return true;
}
bool HandleWheelEvent(const blink::WebMouseWheelEvent& event) override {
handle_wheel_event_called_ = true;
return handle_wheel_event_;
}
void RendererUnresponsive(
RenderWidgetHostImpl* render_widget_host,
base::RepeatingClosure hang_monitor_restarter) override {
unresponsive_timer_fired_ = true;
}
bool ShouldIgnoreInputEvents() override { return ignore_input_events_; }
bool ShouldIgnoreWebInputEvents(const blink::WebInputEvent& event) override {
return ignore_input_events_;
}
void ExecuteEditCommand(const std::string& command,
const std::optional<std::u16string>& value) override {
}
void Undo() override {}
void Redo() override {}
void Cut() override {}
void Copy() override {}
void Paste() override {}
void PasteAndMatchStyle() override {}
void SelectAll() override {}
VisibleTimeRequestTrigger& GetVisibleTimeRequestTrigger() override {
return visible_time_request_trigger_;
}
private:
bool prehandle_mouse_event_ = false;
bool prehandle_mouse_event_called_ = false;
bool prehandle_keyboard_event_;
bool prehandle_keyboard_event_is_shortcut_;
bool prehandle_keyboard_event_called_;
WebInputEvent::Type prehandle_keyboard_event_type_;
bool unhandled_keyboard_event_called_;
WebInputEvent::Type unhandled_keyboard_event_type_;
bool handle_wheel_event_;
bool handle_wheel_event_called_;
bool unresponsive_timer_fired_;
bool ignore_input_events_;
std::unique_ptr<MockRenderViewHostDelegateView>
render_view_host_delegate_view_;
double zoom_level_ = 0;
int focus_owning_web_contents_call_count = 0;
int on_vertical_scroll_direction_changed_call_count_ = 0;
viz::VerticalScrollDirection last_vertical_scroll_direction_ =
viz::VerticalScrollDirection::kNull;
bool is_fullscreen_ = false;
VisibleTimeRequestTrigger visible_time_request_trigger_;
};
class MockRenderWidgetHostOwnerDelegate
: public StubRenderWidgetHostOwnerDelegate {
public:
MOCK_METHOD1(SetBackgroundOpaque, void(bool opaque));
MOCK_METHOD0(IsMainFrameActive, bool());
};
// RenderWidgetHostTest --------------------------------------------------------
class RenderWidgetHostTest : public testing::Test {
public:
RenderWidgetHostTest() : last_simulated_event_time_(ui::EventTimeForNow()) {}
RenderWidgetHostTest(const RenderWidgetHostTest&) = delete;
RenderWidgetHostTest& operator=(const RenderWidgetHostTest&) = delete;
~RenderWidgetHostTest() override = default;
bool KeyPressEventCallback(const input::NativeWebKeyboardEvent& /* event */) {
return handle_key_press_event_;
}
bool MouseEventCallback(const blink::WebMouseEvent& /* event */) {
return handle_mouse_event_;
}
void ClearVisualProperties() {
base::RunLoop().RunUntilIdle();
widget_.ClearVisualProperties();
}
void ClearScreenRects() {
base::RunLoop().RunUntilIdle();
widget_.ClearScreenRects();
}
bool HasTouchEventHandlers(bool has_handlers) { return has_handlers; }
bool HasHitTestableScrollbar(bool has_scrollbar) { return has_scrollbar; }
protected:
// testing::Test
void SetUp() override {
base::CommandLine* command_line = base::CommandLine::ForCurrentProcess();
command_line->AppendSwitch(input::switches::kValidateInputEventStream);
browser_context_ = std::make_unique<TestBrowserContext>();
delegate_ = std::make_unique<MockRenderWidgetHostDelegate>();
process_ =
std::make_unique<RenderWidgetHostProcess>(browser_context_.get());
site_instance_group_ =
base::WrapRefCounted(SiteInstanceGroup::CreateForTesting(
browser_context_.get(), process_.get()));
sink_ = &process_->sink();
#if defined(USE_AURA) || BUILDFLAG(IS_APPLE)
ImageTransportFactory::SetFactory(
std::make_unique<TestImageTransportFactory>());
#endif
#if BUILDFLAG(IS_ANDROID)
// calls display::Screen::SetScreenInstance().
ui::SetScreenAndroid(false /* use_display_wide_color_gamut */);
#endif
#if BUILDFLAG(IS_APPLE)
screen_ = std::make_unique<display::test::TestScreen>();
display::Screen::SetScreenInstance(screen_.get());
#endif
#if defined(USE_AURA)
screen_.reset(aura::TestScreen::Create(gfx::Size()));
display::Screen::SetScreenInstance(screen_.get());
#endif
host_ = MockRenderWidgetHost::Create(
/* frame_tree= */ nullptr, delegate_.get(),
site_instance_group_->GetSafeRef(), process_->GetNextRoutingID(),
widget_.GetNewRemote());
// Set up the RenderWidgetHost as being for a main frame.
host_->set_owner_delegate(&mock_owner_delegate_);
// Act like there is no RenderWidget present in the renderer yet.
EXPECT_CALL(mock_owner_delegate_, IsMainFrameActive())
.WillRepeatedly(Return(false));
view_ = std::make_unique<TestView>(host_.get());
ConfigureView(view_.get());
host_->SetView(view_.get());
// Act like we've created a RenderWidget.
host_->GetInitialVisualProperties();
EXPECT_CALL(mock_owner_delegate_, IsMainFrameActive())
.WillRepeatedly(Return(true));
mojo::PendingRemote<cc::mojom::RenderFrameMetadataObserver>
renderer_render_frame_metadata_observer_remote;
mojo::PendingRemote<cc::mojom::RenderFrameMetadataObserverClient>
render_frame_metadata_observer_remote;
mojo::PendingReceiver<cc::mojom::RenderFrameMetadataObserverClient>
render_frame_metadata_observer_client_receiver =
render_frame_metadata_observer_remote
.InitWithNewPipeAndPassReceiver();
renderer_render_frame_metadata_observer_ =
std::make_unique<FakeRenderFrameMetadataObserver>(
renderer_render_frame_metadata_observer_remote
.InitWithNewPipeAndPassReceiver(),
std::move(render_frame_metadata_observer_remote));
host_->RegisterRenderFrameMetadataObserver(
std::move(render_frame_metadata_observer_client_receiver),
std::move(renderer_render_frame_metadata_observer_remote));
// The blink::mojom::Widget is already set during MockRenderWidgetHost
// construction.
host_->BindFrameWidgetInterfaces(
mojo::PendingAssociatedRemote<blink::mojom::FrameWidgetHost>()
.InitWithNewEndpointAndPassReceiver(),
TestRenderWidgetHost::CreateStubFrameWidgetRemote());
host_->RendererWidgetCreated(/*for_frame_widget=*/true);
host_->input_router()->MakeActive();
}
void TearDown() override {
sink_ = nullptr;
view_.reset();
host_.reset();
delegate_.reset();
process_->Cleanup();
site_instance_group_.reset();
process_.reset();
browser_context_.reset();
#if defined(USE_AURA) || BUILDFLAG(IS_APPLE)
ImageTransportFactory::Terminate();
#endif
#if defined(USE_AURA) || BUILDFLAG(IS_APPLE) || BUILDFLAG(IS_ANDROID)
display::Screen::SetScreenInstance(nullptr);
screen_.reset();
#endif
// Process all pending tasks to avoid leaks.
base::RunLoop().RunUntilIdle();
}
virtual void ConfigureView(TestView* view) {}
void ReinitalizeHost() {
host_->BindWidgetInterfaces(
mojo::AssociatedRemote<blink::mojom::WidgetHost>()
.BindNewEndpointAndPassDedicatedReceiver(),
widget_.GetNewRemote());
host_->BindFrameWidgetInterfaces(
mojo::AssociatedRemote<blink::mojom::FrameWidgetHost>()
.BindNewEndpointAndPassDedicatedReceiver(),
TestRenderWidgetHost::CreateStubFrameWidgetRemote());
host_->RendererWidgetCreated(/*for_frame_widget=*/true);
}
base::TimeTicks GetNextSimulatedEventTime() {
last_simulated_event_time_ += simulated_event_time_delta_;
return last_simulated_event_time_;
}
input::NativeWebKeyboardEvent CreateNativeWebKeyboardEvent(
WebInputEvent::Type type) {
return input::NativeWebKeyboardEvent(type, /*modifiers=*/0,
GetNextSimulatedEventTime());
}
void SimulateKeyboardEvent(WebInputEvent::Type type) {
host_->ForwardKeyboardEvent(CreateNativeWebKeyboardEvent(type));
}
void SimulateKeyboardEventWithCommands(WebInputEvent::Type type) {
std::vector<blink::mojom::EditCommandPtr> edit_commands;
edit_commands.push_back(blink::mojom::EditCommand::New("name", "value"));
host_->ForwardKeyboardEventWithCommands(CreateNativeWebKeyboardEvent(type),
ui::LatencyInfo(),
std::move(edit_commands), nullptr);
}
void SimulateMouseEvent(WebInputEvent::Type type) {
host_->ForwardMouseEvent(blink::SyntheticWebMouseEventBuilder::Build(type));
}
void SimulateMouseEventWithLatencyInfo(WebInputEvent::Type type,
const ui::LatencyInfo& ui_latency) {
host_->ForwardMouseEventWithLatencyInfo(
blink::SyntheticWebMouseEventBuilder::Build(type), ui_latency);
}
void SimulateWheelEvent(float dX, float dY, int modifiers, bool precise) {
host_->ForwardWheelEvent(blink::SyntheticWebMouseWheelEventBuilder::Build(
0, 0, dX, dY, modifiers,
precise ? ui::ScrollGranularity::kScrollByPrecisePixel
: ui::ScrollGranularity::kScrollByPixel));
}
void SimulateWheelEvent(float dX,
float dY,
int modifiers,
bool precise,
WebMouseWheelEvent::Phase phase) {
WebMouseWheelEvent wheel_event =
blink::SyntheticWebMouseWheelEventBuilder::Build(
0, 0, dX, dY, modifiers,
precise ? ui::ScrollGranularity::kScrollByPrecisePixel
: ui::ScrollGranularity::kScrollByPixel);
wheel_event.phase = phase;
host_->ForwardWheelEvent(wheel_event);
}
void SimulateWheelEventWithLatencyInfo(float dX,
float dY,
int modifiers,
bool precise,
const ui::LatencyInfo& ui_latency) {
host_->ForwardWheelEventWithLatencyInfo(
blink::SyntheticWebMouseWheelEventBuilder::Build(
0, 0, dX, dY, modifiers,
precise ? ui::ScrollGranularity::kScrollByPrecisePixel
: ui::ScrollGranularity::kScrollByPixel),
ui_latency);
}
void SimulateWheelEventWithLatencyInfo(float dX,
float dY,
int modifiers,
bool precise,
const ui::LatencyInfo& ui_latency,
WebMouseWheelEvent::Phase phase) {
WebMouseWheelEvent wheel_event =
blink::SyntheticWebMouseWheelEventBuilder::Build(
0, 0, dX, dY, modifiers,
precise ? ui::ScrollGranularity::kScrollByPrecisePixel
: ui::ScrollGranularity::kScrollByPixel);
wheel_event.phase = phase;
host_->ForwardWheelEventWithLatencyInfo(wheel_event, ui_latency);
}
void SimulateMouseMove(int x, int y, int modifiers) {
SimulateMouseEvent(WebInputEvent::Type::kMouseMove, x, y, modifiers, false);
}
void SimulateMouseEvent(
WebInputEvent::Type type, int x, int y, int modifiers, bool pressed) {
WebMouseEvent event =
blink::SyntheticWebMouseEventBuilder::Build(type, x, y, modifiers);
if (pressed)
event.button = WebMouseEvent::Button::kLeft;
event.SetTimeStamp(GetNextSimulatedEventTime());
host_->ForwardMouseEvent(event);
}
// Inject simple synthetic WebGestureEvent instances.
void SimulateGestureEvent(WebInputEvent::Type type,
WebGestureDevice sourceDevice) {
host_->ForwardGestureEvent(
blink::SyntheticWebGestureEventBuilder::Build(type, sourceDevice));
}
void SimulateGestureEventWithLatencyInfo(WebInputEvent::Type type,
WebGestureDevice sourceDevice,
const ui::LatencyInfo& ui_latency) {
host_->GetRenderInputRouter()->ForwardGestureEventWithLatencyInfo(
blink::SyntheticWebGestureEventBuilder::Build(type, sourceDevice),
ui_latency);
}
// Set the timestamp for the touch-event.
void SetTouchTimestamp(base::TimeTicks timestamp) {
touch_event_.SetTimestamp(timestamp);
}
// Sends a touch event (irrespective of whether the page has a touch-event
// handler or not).
uint32_t SendTouchEvent() {
uint32_t touch_event_id = touch_event_.unique_touch_event_id;
host_->GetRenderInputRouter()->ForwardTouchEventWithLatencyInfo(
touch_event_, ui::LatencyInfo());
touch_event_.ResetPoints();
return touch_event_id;
}
int PressTouchPoint(int x, int y) {
return touch_event_.PressPoint(x, y);
}
void MoveTouchPoint(int index, int x, int y) {
touch_event_.MovePoint(index, x, y);
}
void ReleaseTouchPoint(int index) {
touch_event_.ReleasePoint(index);
}
const WebInputEvent* GetInputEventFromMessage(const IPC::Message& message) {
base::PickleIterator iter(message);
const char* data;
size_t data_length;
if (!iter.ReadData(&data, &data_length))
return nullptr;
return reinterpret_cast<const WebInputEvent*>(data);
}
BrowserTaskEnvironment task_environment_{
base::test::TaskEnvironment::TimeSource::MOCK_TIME};
std::unique_ptr<TestBrowserContext> browser_context_;
std::unique_ptr<RenderWidgetHostProcess> process_;
scoped_refptr<SiteInstanceGroup> site_instance_group_;
std::unique_ptr<MockRenderWidgetHostDelegate> delegate_;
testing::NiceMock<MockRenderWidgetHostOwnerDelegate> mock_owner_delegate_;
std::unique_ptr<MockRenderWidgetHost> host_;
std::unique_ptr<TestView> view_;
std::unique_ptr<display::Screen> screen_;
bool handle_key_press_event_ = false;
bool handle_mouse_event_ = false;
base::TimeTicks last_simulated_event_time_;
base::TimeDelta simulated_event_time_delta_;
raw_ptr<IPC::TestSink> sink_;
std::unique_ptr<FakeRenderFrameMetadataObserver>
renderer_render_frame_metadata_observer_;
MockWidget widget_;
private:
blink::SyntheticWebTouchEvent touch_event_;
};
// RenderWidgetHostWithSourceTest ----------------------------------------------
// This is for tests that are to be run for all source devices.
class RenderWidgetHostWithSourceTest
: public RenderWidgetHostTest,
public testing::WithParamInterface<WebGestureDevice> {};
} // namespace
// -----------------------------------------------------------------------------
// Tests that renderer doesn't change bounds while browser has its
// bounds changed (and until bounds are acked), which might be a result
// of a system's display compositor/server changing bounds of an
// application.
TEST_F(RenderWidgetHostTest, DoNotAcceptPopupBoundsUntilScreenRectsAcked) {
// The host should wait for the screen rects ack now as SendScreenRects were
// called during the initialization step.
EXPECT_TRUE(host_->waiting_for_screen_rects_ack_);
// Execute pending callbacks and clear screen rects.
ClearScreenRects();
// Lets mojo to pass the message from the renderer to the browser (from widget
// to host).
base::RunLoop().RunUntilIdle();
// The host shouldn't wait for ack now as it has received it.
EXPECT_FALSE(host_->waiting_for_screen_rects_ack_);
// Change the bounds of the view and send screen rects.
view_->SetBounds({10, 20, 300, 200});
// Pass updated bounds from the browser to the renderer.
host_->SendScreenRects();
// The host should wait for the screen rects ack now.
EXPECT_TRUE(host_->waiting_for_screen_rects_ack_);
// Store the current view's bounds and pretend popup bounds are
// being changed. However, they mustn't be changed as the host is still
// waiting for the screen rects ack. This ensures that the renderer
// doesn't clobber browser's bounds.
auto old_view_bounds = view_->GetViewBounds();
auto new_popup_view_bounds = gfx::Rect(5, 5, 20, 20);
// Act like a renderer sending new bounds to the browser.
static_cast<blink::mojom::PopupWidgetHost*>(host_.get())
->SetPopupBounds(new_popup_view_bounds, base::DoNothing());
// The view still has the old bounds...
EXPECT_EQ(old_view_bounds, view_->GetViewBounds());
// which are not the same as the new bounds that were tried to be
// set.
EXPECT_NE(view_->GetViewBounds(), new_popup_view_bounds);
// Clear the screen rects and send the ack callback back to the host.
ClearScreenRects();
// Allows mojo to pass the message from the renderer to the browser
// (ClearScreenRects executed a callback via mojo that notifies the browser
// that the renderer completed processing the new rects).
base::RunLoop().RunUntilIdle();
// The change must have been acked by now.
EXPECT_FALSE(host_->waiting_for_screen_rects_ack_);
// Pretend that the renderer changes the popup bounds again...
static_cast<blink::mojom::PopupWidgetHost*>(host_.get())
->SetPopupBounds(new_popup_view_bounds, base::DoNothing());
// And the host must accept them now as the screen rects have been
// acked.
EXPECT_EQ(new_popup_view_bounds, view_->GetViewBounds());
}
TEST_F(RenderWidgetHostTest, SynchronizeVisualProperties) {
ClearVisualProperties();
// The initial zoom is 0 so host should not send a sync message
delegate_->SetZoomLevel(0);
EXPECT_FALSE(host_->SynchronizeVisualProperties());
EXPECT_FALSE(host_->visual_properties_ack_pending_);
base::RunLoop().RunUntilIdle();
EXPECT_EQ(0u, widget_.ReceivedVisualProperties().size());
ClearVisualProperties();
// The zoom has changed so host should send out a sync message.
double new_zoom_level = blink::ZoomFactorToZoomLevel(0.25);
delegate_->SetZoomLevel(new_zoom_level);
EXPECT_TRUE(host_->SynchronizeVisualProperties());
EXPECT_FALSE(host_->visual_properties_ack_pending_);
EXPECT_NEAR(new_zoom_level, host_->old_visual_properties_->zoom_level, 0.01);
base::RunLoop().RunUntilIdle();
EXPECT_EQ(1u, widget_.ReceivedVisualProperties().size());
ClearVisualProperties();
// The initial bounds is the empty rect, so setting it to the same thing
// shouldn't send the resize message.
view_->SetBounds(gfx::Rect());
host_->SynchronizeVisualProperties();
EXPECT_FALSE(host_->visual_properties_ack_pending_);
base::RunLoop().RunUntilIdle();
EXPECT_EQ(0u, widget_.ReceivedVisualProperties().size());
ClearVisualProperties();
// No visual properties ACK if the physical backing gets set, but the view
// bounds are zero.
view_->SetMockCompositorViewportPixelSize(gfx::Size(200, 200));
host_->SynchronizeVisualProperties();
EXPECT_FALSE(host_->visual_properties_ack_pending_);
base::RunLoop().RunUntilIdle();
EXPECT_EQ(1u, widget_.ReceivedVisualProperties().size());
ClearVisualProperties();
// Setting the view bounds to nonzero should send out the notification.
// but should not expect ack for empty physical backing size.
gfx::Rect original_size(0, 0, 100, 100);
view_->SetBounds(original_size);
view_->SetMockCompositorViewportPixelSize(gfx::Size());
host_->SynchronizeVisualProperties();
EXPECT_FALSE(host_->visual_properties_ack_pending_);
EXPECT_EQ(original_size.size(),
host_->old_visual_properties_->new_size_device_px);
base::RunLoop().RunUntilIdle();
EXPECT_EQ(1u, widget_.ReceivedVisualProperties().size());
ClearVisualProperties();
// Setting the bounds and physical backing size to nonzero should send out
// the notification and expect an ack.
view_->ClearMockCompositorViewportPixelSize();
host_->SynchronizeVisualProperties();
EXPECT_TRUE(host_->visual_properties_ack_pending_);
EXPECT_EQ(original_size.size(),
host_->old_visual_properties_->new_size_device_px);
cc::RenderFrameMetadata metadata;
metadata.viewport_size_in_pixels = original_size.size();
metadata.local_surface_id = std::nullopt;
static_cast<RenderFrameMetadataProvider::Observer&>(*host_)
.OnLocalSurfaceIdChanged(metadata);
EXPECT_FALSE(host_->visual_properties_ack_pending_);
base::RunLoop().RunUntilIdle();
EXPECT_EQ(1u, widget_.ReceivedVisualProperties().size());
ClearVisualProperties();
gfx::Rect second_size(0, 0, 110, 110);
EXPECT_FALSE(host_->visual_properties_ack_pending_);
view_->SetBounds(second_size);
EXPECT_TRUE(host_->SynchronizeVisualProperties());
EXPECT_TRUE(host_->visual_properties_ack_pending_);
ClearVisualProperties();
// Sending out a new notification should NOT send out a new IPC message since
// a visual properties ACK is pending.
gfx::Rect third_size(0, 0, 120, 120);
process_->sink().ClearMessages();
view_->SetBounds(third_size);
EXPECT_FALSE(host_->SynchronizeVisualProperties());
EXPECT_TRUE(host_->visual_properties_ack_pending_);
base::RunLoop().RunUntilIdle();
EXPECT_EQ(0u, widget_.ReceivedVisualProperties().size());
ClearVisualProperties();
// Send a update that's a visual properties ACK, but for the original_size we
// sent. Since this isn't the second_size, the message handler should
// immediately send a new resize message for the new size to the renderer.
metadata.viewport_size_in_pixels = original_size.size();
metadata.local_surface_id = std::nullopt;
static_cast<RenderFrameMetadataProvider::Observer&>(*host_)
.OnLocalSurfaceIdChanged(metadata);
EXPECT_TRUE(host_->visual_properties_ack_pending_);
EXPECT_EQ(third_size.size(),
host_->old_visual_properties_->new_size_device_px);
base::RunLoop().RunUntilIdle();
EXPECT_EQ(1u, widget_.ReceivedVisualProperties().size());
ClearVisualProperties();
// Send the visual properties ACK for the latest size.
metadata.viewport_size_in_pixels = third_size.size();
metadata.local_surface_id = std::nullopt;
static_cast<RenderFrameMetadataProvider::Observer&>(*host_)
.OnLocalSurfaceIdChanged(metadata);
EXPECT_FALSE(host_->visual_properties_ack_pending_);
EXPECT_EQ(third_size.size(),
host_->old_visual_properties_->new_size_device_px);
base::RunLoop().RunUntilIdle();
EXPECT_EQ(0u, widget_.ReceivedVisualProperties().size());
ClearVisualProperties();
// Now clearing the bounds should send out a notification but we shouldn't
// expect a visual properties ACK (since the renderer won't ack empty sizes).
// The message should contain the new size (0x0) and not the previous one that
// we skipped.
view_->SetBounds(gfx::Rect());
host_->SynchronizeVisualProperties();
EXPECT_FALSE(host_->visual_properties_ack_pending_);
EXPECT_EQ(gfx::Size(), host_->old_visual_properties_->new_size_device_px);
base::RunLoop().RunUntilIdle();
EXPECT_EQ(1u, widget_.ReceivedVisualProperties().size());
ClearVisualProperties();
// Send a rect that has no area but has either width or height set.
view_->SetBounds(gfx::Rect(0, 0, 0, 30));
host_->SynchronizeVisualProperties();
EXPECT_FALSE(host_->visual_properties_ack_pending_);
EXPECT_EQ(gfx::Size(0, 30),
host_->old_visual_properties_->new_size_device_px);
base::RunLoop().RunUntilIdle();
EXPECT_EQ(1u, widget_.ReceivedVisualProperties().size());
ClearVisualProperties();
// Set the same size again. It should not be sent again.
host_->SynchronizeVisualProperties();
EXPECT_FALSE(host_->visual_properties_ack_pending_);
EXPECT_EQ(gfx::Size(0, 30),
host_->old_visual_properties_->new_size_device_px);
base::RunLoop().RunUntilIdle();
EXPECT_EQ(0u, widget_.ReceivedVisualProperties().size());
ClearVisualProperties();
// A different size should be sent again, however.
view_->SetBounds(gfx::Rect(0, 0, 0, 31));
host_->SynchronizeVisualProperties();
EXPECT_FALSE(host_->visual_properties_ack_pending_);
EXPECT_EQ(gfx::Size(0, 31),
host_->old_visual_properties_->new_size_device_px);
base::RunLoop().RunUntilIdle();
EXPECT_EQ(1u, widget_.ReceivedVisualProperties().size());
ClearVisualProperties();
// An invalid LocalSurfaceId should result in no change to the
// |visual_properties_ack_pending_| bit.
view_->SetBounds(gfx::Rect(25, 25));
view_->InvalidateLocalSurfaceId();
host_->SynchronizeVisualProperties();
EXPECT_FALSE(host_->visual_properties_ack_pending_);
EXPECT_EQ(gfx::Size(25, 25),
host_->old_visual_properties_->new_size_device_px);
base::RunLoop().RunUntilIdle();
EXPECT_EQ(1u, widget_.ReceivedVisualProperties().size());
}
// Test that a resize event is sent if SynchronizeVisualProperties() is called
// after a ScreenInfo change.
TEST_F(RenderWidgetHostTest, ResizeScreenInfo) {
display::ScreenInfo screen_info;
screen_info.rect = gfx::Rect(0, 0, 800, 600);
screen_info.available_rect = gfx::Rect(0, 0, 800, 600);
screen_info.orientation_type =
display::mojom::ScreenOrientation::kPortraitPrimary;
ClearVisualProperties();
view_->SetScreenInfo(screen_info);
base::RunLoop().RunUntilIdle();
EXPECT_EQ(0u, widget_.ReceivedVisualProperties().size());
EXPECT_TRUE(host_->SynchronizeVisualProperties());
// blink::mojom::Widget::UpdateVisualProperties sent to the renderer.
base::RunLoop().RunUntilIdle();
ASSERT_EQ(1u, widget_.ReceivedVisualProperties().size());
EXPECT_FALSE(host_->visual_properties_ack_pending_);
screen_info.orientation_angle = 180;
screen_info.orientation_type =
display::mojom::ScreenOrientation::kLandscapePrimary;
ClearVisualProperties();
view_->SetScreenInfo(screen_info);
base::RunLoop().RunUntilIdle();
EXPECT_EQ(0u, widget_.ReceivedVisualProperties().size());
EXPECT_TRUE(host_->SynchronizeVisualProperties());
// blink::mojom::Widget::UpdateVisualProperties sent to the renderer.
base::RunLoop().RunUntilIdle();
ASSERT_EQ(1u, widget_.ReceivedVisualProperties().size());
EXPECT_FALSE(host_->visual_properties_ack_pending_);
screen_info.device_scale_factor = 2.f;
ClearVisualProperties();
view_->SetScreenInfo(screen_info);
base::RunLoop().RunUntilIdle();
EXPECT_EQ(0u, widget_.ReceivedVisualProperties().size());
EXPECT_TRUE(host_->SynchronizeVisualProperties());
// blink::mojom::Widget::UpdateVisualProperties sent to the renderer.
base::RunLoop().RunUntilIdle();
ASSERT_EQ(1u, widget_.ReceivedVisualProperties().size());
EXPECT_FALSE(host_->visual_properties_ack_pending_);
// No screen change.
ClearVisualProperties();
view_->SetScreenInfo(screen_info);
EXPECT_FALSE(host_->SynchronizeVisualProperties());
base::RunLoop().RunUntilIdle();
EXPECT_EQ(0u, widget_.ReceivedVisualProperties().size());
EXPECT_FALSE(host_->visual_properties_ack_pending_);
}
// Test that the reported new_size includes the scale factor.
TEST_F(RenderWidgetHostTest, NewSizeIncludesScaleFactor) {
display::ScreenInfo screen_info;
screen_info.rect = gfx::Rect(0, 0, 800, 600);
screen_info.available_rect = gfx::Rect(0, 0, 800, 600);
screen_info.orientation_type =
display::mojom::ScreenOrientation::kPortraitPrimary;
screen_info.device_scale_factor = 2.f;
ClearVisualProperties();
view_->SetScreenInfo(screen_info);
base::RunLoop().RunUntilIdle();
EXPECT_EQ(0u, widget_.ReceivedVisualProperties().size());
gfx::Rect original_size(0, 0, 101, 100);
view_->SetBounds(original_size);
EXPECT_TRUE(host_->SynchronizeVisualProperties());
// blink::mojom::Widget::UpdateVisualProperties sent to the renderer.
base::RunLoop().RunUntilIdle();
ASSERT_EQ(1u, widget_.ReceivedVisualProperties().size());
auto new_size = widget_.ReceivedVisualProperties()[0].new_size_device_px;
EXPECT_EQ(202, new_size.width());
EXPECT_EQ(200, new_size.height());
auto visible_viewport_size =
widget_.ReceivedVisualProperties()[0].visible_viewport_size_device_px;
EXPECT_EQ(202, visible_viewport_size.width());
EXPECT_EQ(200, visible_viewport_size.height());
EXPECT_TRUE(host_->visual_properties_ack_pending_);
}
// Tests that SynchronizeVisualProperties which occurs while hidden, before an
// Eviction, becomes unthrottled when becoming visible again. So that we do not
// wait for an ack that will never arrive.
//
// This ensures the Widget can begin frame production on the newly embedded
// Surface after the initial eviction.
TEST_F(RenderWidgetHostTest, EvictUnthrottlesSynchronizeVisualProperties) {
display::ScreenInfo screen_info;
screen_info.rect = gfx::Rect(0, 0, 800, 600);
screen_info.available_rect = gfx::Rect(0, 0, 800, 600);
screen_info.orientation_type =
display::mojom::ScreenOrientation::kPortraitPrimary;
screen_info.device_scale_factor = 2.f;
ClearVisualProperties();
// While hidden we will still synchronize to the Renderer. Though we will
// throttle future updates on `visual_properties_ack_pending_`.
host_->WasHidden();
view_->SetScreenInfo(screen_info);
base::RunLoop().RunUntilIdle();
EXPECT_EQ(0u, widget_.ReceivedVisualProperties().size());
gfx::Rect original_size(0, 0, 101, 100);
view_->SetBounds(original_size);
EXPECT_TRUE(host_->SynchronizeVisualProperties());
EXPECT_TRUE(host_->visual_properties_ack_pending_);
// blink::mojom::Widget::UpdateVisualProperties sent to the renderer.
base::RunLoop().RunUntilIdle();
ASSERT_EQ(1u, widget_.ReceivedVisualProperties().size());
auto new_size = widget_.ReceivedVisualProperties()[0].new_size_device_px;
EXPECT_EQ(202, new_size.width());
EXPECT_EQ(200, new_size.height());
auto visible_viewport_size =
widget_.ReceivedVisualProperties()[0].visible_viewport_size_device_px;
EXPECT_EQ(202, visible_viewport_size.width());
EXPECT_EQ(200, visible_viewport_size.height());
EXPECT_TRUE(host_->visual_properties_ack_pending_);
widget_.ClearVisualProperties();
// `MockRenderWidgetHostOwnerDelegate` doesn't extend `RenderViewHostImpl` so
// the legacy `static_cast` in `RenderViewHostImpl::From` crash here. So we
// cannot use `host_->CollectSurfaceIdsForEviction` in tests. Mark the view as
// evicted directly.
view_->set_is_evicted();
// Set a new size so we have difference in property to synchronize.
gfx::Rect restore_size(0, 0, 1337, 42);
view_->SetBounds(restore_size);
host_->WasShown({} /* record_tab_switch_time_request */);
EXPECT_TRUE(host_->visual_properties_ack_pending_);
base::RunLoop().RunUntilIdle();
ASSERT_EQ(1u, widget_.ReceivedVisualProperties().size());
}
// Ensure VisualProperties continues reporting the size of the current screen,
// not the viewport, when the frame is fullscreen. See crbug.com/1367416.
TEST_F(RenderWidgetHostTest, ScreenSizeInFullscreen) {
const gfx::Rect kScreenBounds(0, 0, 800, 600);
const gfx::Rect kViewBounds(55, 66, 600, 500);
display::ScreenInfo screen_info;
screen_info.rect = kScreenBounds;
screen_info.available_rect = kScreenBounds;
screen_info.orientation_type =
display::mojom::ScreenOrientation::kPortraitPrimary;
view_->SetScreenInfo(screen_info);
ClearVisualProperties();
// Do initial VisualProperties sync while not fullscreened.
view_->SetBounds(kViewBounds);
ASSERT_FALSE(delegate_->IsFullscreen());
host_->SynchronizeVisualPropertiesIgnoringPendingAck();
// blink::mojom::Widget::UpdateVisualProperties sent to the renderer.
base::RunLoop().RunUntilIdle();
EXPECT_EQ(1u, widget_.ReceivedVisualProperties().size());
blink::VisualProperties props = widget_.ReceivedVisualProperties().at(0);
EXPECT_EQ(kScreenBounds, props.screen_infos.current().rect);
EXPECT_EQ(kScreenBounds, props.screen_infos.current().available_rect);
EXPECT_EQ(kViewBounds.size(), props.new_size_device_px);
// Enter fullscreen and do another VisualProperties sync.
delegate_->set_is_fullscreen(true);
host_->SynchronizeVisualPropertiesIgnoringPendingAck();
// blink::mojom::Widget::UpdateVisualProperties sent to the renderer.
base::RunLoop().RunUntilIdle();
EXPECT_EQ(2u, widget_.ReceivedVisualProperties().size());
props = widget_.ReceivedVisualProperties().at(1);
EXPECT_EQ(kScreenBounds, props.screen_infos.current().rect);
EXPECT_EQ(kScreenBounds, props.screen_infos.current().available_rect);
EXPECT_EQ(kViewBounds.size(), props.new_size_device_px);
// Exit fullscreen and do another VisualProperties sync.
delegate_->set_is_fullscreen(false);
host_->SynchronizeVisualPropertiesIgnoringPendingAck();
// blink::mojom::Widget::UpdateVisualProperties sent to the renderer.
base::RunLoop().RunUntilIdle();
EXPECT_EQ(3u, widget_.ReceivedVisualProperties().size());
props = widget_.ReceivedVisualProperties().at(2);
EXPECT_EQ(kScreenBounds, props.screen_infos.current().rect);
EXPECT_EQ(kScreenBounds, props.screen_infos.current().available_rect);
EXPECT_EQ(kViewBounds.size(), props.new_size_device_px);
}
TEST_F(RenderWidgetHostTest, RootViewportSegments) {
gfx::Rect screen_rect(0, 0, 800, 600);
display::ScreenInfo screen_info;
screen_info.rect = screen_rect;
screen_info.available_rect = screen_rect;
screen_info.orientation_type =
display::mojom::ScreenOrientation::kPortraitPrimary;
view_->SetScreenInfo(screen_info);
// Set a vertical display feature which must result in two viewport segments,
// side-by-side.
const int kDisplayFeatureLength = 20;
DisplayFeature emulated_display_feature{
DisplayFeature::Orientation::kVertical,
/* offset */ screen_rect.width() / 2 - kDisplayFeatureLength / 2,
/* mask_length */ kDisplayFeatureLength};
RenderWidgetHostViewBase* render_widget_host_view = view_.get();
render_widget_host_view->OverrideDisplayFeatureForEmulation(
&emulated_display_feature);
ClearScreenRects();
view_->SetBounds(screen_rect);
host_->SendScreenRects();
ClearVisualProperties();
// Run SynchronizeVisualProperties and validate the viewport segments sent to
// the renderer are correct.
EXPECT_TRUE(host_->SynchronizeVisualProperties());
base::RunLoop().RunUntilIdle();
EXPECT_EQ(1u, widget_.ReceivedVisualProperties().size());
auto viewport_segments =
widget_.ReceivedVisualProperties().at(0).root_widget_viewport_segments;
EXPECT_EQ(viewport_segments.size(), 2u);
gfx::Rect expected_first_rect(0, 0, 390, 600);
EXPECT_EQ(viewport_segments[0], expected_first_rect);
gfx::Rect expected_second_rect(410, 0, 390, 600);
EXPECT_EQ(viewport_segments[1], expected_second_rect);
ClearVisualProperties();
// Setting a bottom inset (simulating virtual keyboard displaying on Aura)
// should result in 'shorter' segments.
auto insets = gfx::Insets::TLBR(0, 0, 100, 0);
view_->SetInsets(insets);
expected_first_rect.Inset(insets);
expected_second_rect.Inset(insets);
host_->SynchronizeVisualPropertiesIgnoringPendingAck();
base::RunLoop().RunUntilIdle();
EXPECT_EQ(1u, widget_.ReceivedVisualProperties().size());
auto inset_viewport_segments =
widget_.ReceivedVisualProperties().at(0).root_widget_viewport_segments;
EXPECT_EQ(inset_viewport_segments.size(), 2u);
EXPECT_EQ(inset_viewport_segments[0], expected_first_rect);
EXPECT_EQ(inset_viewport_segments[1], expected_second_rect);
ClearVisualProperties();
view_->SetInsets(gfx::Insets(0));
// Setting back to empty should result in a single rect. The previous call
// resized the widget and causes a pending ack. This is unrelated to what
// we're testing here so ignore the pending ack by using
// |SynchronizeVisualPropertiesIgnoringPendingAck()|.
render_widget_host_view->OverrideDisplayFeatureForEmulation(nullptr);
host_->SynchronizeVisualPropertiesIgnoringPendingAck();
base::RunLoop().RunUntilIdle();
EXPECT_EQ(1u, widget_.ReceivedVisualProperties().size());
auto single_viewport_segments =
widget_.ReceivedVisualProperties().at(0).root_widget_viewport_segments;
EXPECT_EQ(single_viewport_segments.size(), 1u);
EXPECT_EQ(single_viewport_segments[0], gfx::Rect(0, 0, 800, 600));
ClearVisualProperties();
// Set a horizontal display feature which results in two viewport segments
// stacked on top of each other.
emulated_display_feature = {
DisplayFeature::Orientation::kHorizontal,
/* offset */ screen_rect.height() / 2 - kDisplayFeatureLength / 2,
/* mask_length */ kDisplayFeatureLength};
render_widget_host_view->OverrideDisplayFeatureForEmulation(
&emulated_display_feature);
host_->SynchronizeVisualPropertiesIgnoringPendingAck();
base::RunLoop().RunUntilIdle();
EXPECT_EQ(1u, widget_.ReceivedVisualProperties().size());
auto vertical_viewport_segments =
widget_.ReceivedVisualProperties().at(0).root_widget_viewport_segments;
EXPECT_EQ(vertical_viewport_segments.size(), 2u);
expected_first_rect = gfx::Rect(0, 0, 800, 290);
EXPECT_EQ(vertical_viewport_segments[0], expected_first_rect);
expected_second_rect = gfx::Rect(0, 310, 800, 290);
EXPECT_EQ(vertical_viewport_segments[1], expected_second_rect);
ClearVisualProperties();
// If the segments don't change, there should be no IPC message sent.
host_->SynchronizeVisualPropertiesIgnoringPendingAck();
base::RunLoop().RunUntilIdle();
EXPECT_EQ(0u, widget_.ReceivedVisualProperties().size());
}
TEST_F(RenderWidgetHostTest, ReceiveFrameTokenFromCrashedRenderer) {
// The Renderer sends a monotonically increasing frame token.
host_->DidProcessFrame(2, base::TimeTicks::Now());
// Simulate a renderer crash.
host_->SetView(nullptr);
host_->RendererExited();
// Receive an in-flight frame token (it needs to monotonically increase)
// while the RenderWidget is gone.
host_->DidProcessFrame(3, base::TimeTicks::Now());
// The renderer is recreated.
host_->SetView(view_.get());
// Make a new RenderWidget when the renderer is recreated and inform that a
// RenderWidget is being created.
blink::VisualProperties props = host_->GetInitialVisualProperties();
// The RenderWidget is recreated with the initial VisualProperties.
ReinitalizeHost();
// The new RenderWidget sends a frame token, which is lower than what the
// previous RenderWidget sent. This should be okay, as the expected token has
// been reset.
host_->DidProcessFrame(1, base::TimeTicks::Now());
}
TEST_F(RenderWidgetHostTest, ReceiveFrameTokenFromDeletedRenderWidget) {
// The RenderWidget sends a monotonically increasing frame token.
host_->DidProcessFrame(2, base::TimeTicks::Now());
// The RenderWidget is destroyed in the renderer process as the main frame
// is removed from this RenderWidgetHost's RenderWidgetView, but the
// RenderWidgetView is still kept around for another RenderFrame.
EXPECT_CALL(mock_owner_delegate_, IsMainFrameActive())
.WillRepeatedly(Return(false));
// Receive an in-flight frame token (it needs to monotonically increase)
// while the RenderWidget is gone.
host_->DidProcessFrame(3, base::TimeTicks::Now());
// Make a new RenderWidget when the renderer is recreated and inform that a
// RenderWidget is being created.
blink::VisualProperties props = host_->GetInitialVisualProperties();
// The RenderWidget is recreated with the initial VisualProperties.
EXPECT_CALL(mock_owner_delegate_, IsMainFrameActive())
.WillRepeatedly(Return(true));
// The new RenderWidget sends a frame token, which is lower than what the
// previous RenderWidget sent. This should be okay, as the expected token has
// been reset.
host_->DidProcessFrame(1, base::TimeTicks::Now());
}
// Tests setting background transparency.
TEST_F(RenderWidgetHostTest, Background) {
RenderWidgetHostViewBase* view;
#if defined(USE_AURA)
view = new RenderWidgetHostViewAura(host_.get());
#elif BUILDFLAG(IS_ANDROID)
view = new RenderWidgetHostViewAndroid(host_.get(),
/*parent_native_view=*/nullptr,
/*parent_layer=*/nullptr);
#elif BUILDFLAG(IS_MAC)
view = CreateRenderWidgetHostViewMacForTesting(host_.get());
#elif BUILDFLAG(IS_IOS)
view = CreateRenderWidgetHostViewIOSForTesting(host_.get());
#endif
#if !BUILDFLAG(IS_ANDROID)
// TODO(derat): Call this on all platforms: http://crbug.com/102450.
view->InitAsChild(gfx::NativeView());
#endif
host_->SetView(view);
ASSERT_FALSE(view->GetBackgroundColor());
{
// The background is assumed opaque by default, so choosing opaque won't
// do anything if it's not set to transparent first.
EXPECT_CALL(mock_owner_delegate_, SetBackgroundOpaque(_)).Times(0);
view->SetBackgroundColor(SK_ColorRED);
EXPECT_EQ(unsigned{SK_ColorRED}, *view->GetBackgroundColor());
}
{
// Another opaque color doesn't inform the view of any change.
EXPECT_CALL(mock_owner_delegate_, SetBackgroundOpaque(_)).Times(0);
view->SetBackgroundColor(SK_ColorBLUE);
EXPECT_EQ(unsigned{SK_ColorBLUE}, *view->GetBackgroundColor());
}
{
// The owner delegate will be called to pass it over IPC to the
// `blink::WebView`.
EXPECT_CALL(mock_owner_delegate_, SetBackgroundOpaque(false));
view->SetBackgroundColor(SK_ColorTRANSPARENT);
#if BUILDFLAG(IS_MAC)
// Mac replaces transparent background colors with white. See the comment in
// RenderWidgetHostViewMac::GetBackgroundColor. (https://crbug.com/735407)
EXPECT_EQ(unsigned{SK_ColorWHITE}, *view->GetBackgroundColor());
#else
// The browser side will represent the background color as transparent
// immediately.
EXPECT_EQ(unsigned{SK_ColorTRANSPARENT}, *view->GetBackgroundColor());
#endif
}
{
// Setting back an opaque color informs the view.
EXPECT_CALL(mock_owner_delegate_, SetBackgroundOpaque(true));
view->SetBackgroundColor(SK_ColorBLUE);
EXPECT_EQ(unsigned{SK_ColorBLUE}, *view->GetBackgroundColor());
}
#if BUILDFLAG(IS_ANDROID)
// Surface Eviction attempts to crawl the FrameTree. This makes use of
// RenderViewHostImpl::From which performs a static_cast on the
// RenderWidgetHostOwnerDelegate. Our MockRenderWidgetHostOwnerDelegate is not
// a RenderViewHostImpl, so it crashes. Clear this here as it is not needed
// for TearDown.
host_->set_owner_delegate(nullptr);
#endif // BUILDFLAG(IS_ANDROID)
host_->SetView(nullptr);
view->Destroy();
}
// Test that the RenderWidgetHost tells the renderer when it is hidden and
// shown, and can accept a racey update from the renderer after hiding.
TEST_F(RenderWidgetHostTest, HideShowMessages) {
// Hide the widget, it should have sent out a message to the renderer.
EXPECT_FALSE(host_->is_hidden_);
{
base::RunLoop run_loop;
widget_.SetShownHiddenCallback(run_loop.QuitClosure());
host_->WasHidden();
run_loop.Run();
}
EXPECT_TRUE(host_->is_hidden_);
ASSERT_TRUE(widget_.IsHidden().has_value());
EXPECT_TRUE(widget_.IsHidden().value());
// Send it an update as from the renderer.
process_->sink().ClearMessages();
cc::RenderFrameMetadata metadata;
metadata.viewport_size_in_pixels = gfx::Size(100, 100);
metadata.local_surface_id = std::nullopt;
static_cast<RenderFrameMetadataProvider::Observer&>(*host_)
.OnLocalSurfaceIdChanged(metadata);
// Now unhide.
widget_.ClearHidden();
ASSERT_FALSE(widget_.IsHidden().has_value());
{
base::RunLoop run_loop;
widget_.SetShownHiddenCallback(run_loop.QuitClosure());
host_->WasShown({} /* record_tab_switch_time_request */);
run_loop.Run();
}
EXPECT_FALSE(host_->is_hidden_);
// It should have sent out a mojo message.
ASSERT_TRUE(widget_.IsHidden().has_value());
EXPECT_FALSE(widget_.IsHidden().value());
}
TEST_F(RenderWidgetHostTest, IgnoreKeyEventsHandledByRenderer) {
// Simulate a keyboard event.
SimulateKeyboardEvent(WebInputEvent::Type::kRawKeyDown);
// Make sure we sent the input event to the renderer.
MockWidgetInputHandler::MessageVector dispatched_events =
host_->mock_render_input_router()->GetAndResetDispatchedMessages();
ASSERT_EQ(1u, dispatched_events.size());
ASSERT_TRUE(dispatched_events[0]->ToEvent());
// Send the simulated response from the renderer back.
dispatched_events[0]->ToEvent()->CallCallback(
blink::mojom::InputEventResultState::kConsumed);
EXPECT_FALSE(delegate_->unhandled_keyboard_event_called());
}
TEST_F(RenderWidgetHostTest, SendEditCommandsBeforeKeyEvent) {
// Simulate a keyboard event.
SimulateKeyboardEventWithCommands(WebInputEvent::Type::kRawKeyDown);
// Make sure we sent commands and key event to the renderer.
MockWidgetInputHandler::MessageVector dispatched_events =
host_->mock_render_input_router()->GetAndResetDispatchedMessages();
ASSERT_EQ(2u, dispatched_events.size());
ASSERT_TRUE(dispatched_events[0]->ToEditCommand());
ASSERT_TRUE(dispatched_events[1]->ToEvent());
// Send the simulated response from the renderer back.
dispatched_events[1]->ToEvent()->CallCallback(
blink::mojom::InputEventResultState::kConsumed);
}
TEST_F(RenderWidgetHostTest, PreHandleMouseEvent) {
// Simulate the situation that the browser handled the mouse event during
// pre-handle phrase.
delegate_->set_prehandle_mouse_event(true);
// Simulate a mouse event.
SimulateMouseEvent(WebMouseEvent::Type::kMouseDown);
EXPECT_TRUE(delegate_->prehandle_mouse_event_called());
// Make sure the mouse event is not sent to the renderer.
MockWidgetInputHandler::MessageVector dispatched_events =
host_->mock_render_input_router()->GetAndResetDispatchedMessages();
EXPECT_EQ(0u, dispatched_events.size());
// Simulate the situation that the browser didn't handle the mouse event
// during pre-handle phrase.
delegate_->set_prehandle_mouse_event(false);
// Simulate a mouse event.
SimulateMouseEvent(WebMouseEvent::Type::kMouseUp);
// Make sure the mouse event is sent to the renderer.
dispatched_events =
host_->mock_render_input_router()->GetAndResetDispatchedMessages();
ASSERT_EQ(1u, dispatched_events.size());
ASSERT_TRUE(dispatched_events[0]->ToEvent());
EXPECT_EQ(WebMouseEvent::Type::kMouseUp,
dispatched_events[0]->ToEvent()->Event()->Event().GetType());
}
TEST_F(RenderWidgetHostTest, PreHandleRawKeyDownEvent) {
// Simulate the situation that the browser handled the key down event during
// pre-handle phrase.
delegate_->set_prehandle_keyboard_event(true);
// Simulate a keyboard event.
SimulateKeyboardEventWithCommands(WebInputEvent::Type::kRawKeyDown);
EXPECT_TRUE(delegate_->prehandle_keyboard_event_called());
EXPECT_EQ(WebInputEvent::Type::kRawKeyDown,
delegate_->prehandle_keyboard_event_type());
// Make sure the commands and key event are not sent to the renderer.
MockWidgetInputHandler::MessageVector dispatched_events =
host_->mock_render_input_router()->GetAndResetDispatchedMessages();
EXPECT_EQ(0u, dispatched_events.size());
// The browser won't pre-handle a Char event.
delegate_->set_prehandle_keyboard_event(false);
// Forward the Char event.
SimulateKeyboardEvent(WebInputEvent::Type::kChar);
// Make sure the Char event is suppressed.
dispatched_events =
host_->mock_render_input_router()->GetAndResetDispatchedMessages();
EXPECT_EQ(0u, dispatched_events.size());
// Forward the KeyUp event.
SimulateKeyboardEvent(WebInputEvent::Type::kKeyUp);
// Make sure the KeyUp event is suppressed.
dispatched_events =
host_->mock_render_input_router()->GetAndResetDispatchedMessages();
EXPECT_EQ(0u, dispatched_events.size());
// Forward the Esc RawKeyDown event.
std::vector<blink::mojom::EditCommandPtr> edit_commands;
edit_commands.push_back(blink::mojom::EditCommand::New("name", "value"));
auto event = CreateNativeWebKeyboardEvent(WebInputEvent::Type::kKeyUp);
event.windows_key_code = ui::VKEY_ESCAPE;
host_->ForwardKeyboardEventWithCommands(event, ui::LatencyInfo(),
std::move(edit_commands), nullptr);
// The event should be prehandled by the browser but will never be sent to the
// renderer, no matter the event is handled or not.
EXPECT_TRUE(delegate_->prehandle_keyboard_event_called());
EXPECT_EQ(WebInputEvent::Type::kKeyUp,
delegate_->prehandle_keyboard_event_type());
dispatched_events =
host_->mock_render_input_router()->GetAndResetDispatchedMessages();
EXPECT_EQ(0u, dispatched_events.size());
// Simulate a new RawKeyDown event.
SimulateKeyboardEvent(WebInputEvent::Type::kRawKeyDown);
dispatched_events =
host_->mock_render_input_router()->GetAndResetDispatchedMessages();
ASSERT_EQ(1u, dispatched_events.size());
ASSERT_TRUE(dispatched_events[0]->ToEvent());
EXPECT_EQ(WebInputEvent::Type::kRawKeyDown,
dispatched_events[0]->ToEvent()->Event()->Event().GetType());
// Send the simulated response from the renderer back.
dispatched_events[0]->ToEvent()->CallCallback(
blink::mojom::InputEventResultState::kNotConsumed);
EXPECT_TRUE(delegate_->unhandled_keyboard_event_called());
EXPECT_EQ(WebInputEvent::Type::kRawKeyDown,
delegate_->unhandled_keyboard_event_type());
}
TEST_F(RenderWidgetHostTest, RawKeyDownShortcutEvent) {
// Simulate the situation that the browser marks the key down as a keyboard
// shortcut, but doesn't consume it in the pre-handle phase.
delegate_->set_prehandle_keyboard_event_is_shortcut(true);
// Simulate a keyboard event.
SimulateKeyboardEvent(WebInputEvent::Type::kRawKeyDown);
EXPECT_TRUE(delegate_->prehandle_keyboard_event_called());
EXPECT_EQ(WebInputEvent::Type::kRawKeyDown,
delegate_->prehandle_keyboard_event_type());
// Make sure the RawKeyDown event is sent to the renderer.
MockWidgetInputHandler::MessageVector dispatched_events =
host_->mock_render_input_router()->GetAndResetDispatchedMessages();
ASSERT_EQ(1u, dispatched_events.size());
ASSERT_TRUE(dispatched_events[0]->ToEvent());
EXPECT_EQ(WebInputEvent::Type::kRawKeyDown,
dispatched_events[0]->ToEvent()->Event()->Event().GetType());
// Send the simulated response from the renderer back.
dispatched_events[0]->ToEvent()->CallCallback(
blink::mojom::InputEventResultState::kNotConsumed);
EXPECT_EQ(WebInputEvent::Type::kRawKeyDown,
delegate_->unhandled_keyboard_event_type());
// The browser won't pre-handle a Char event.
delegate_->set_prehandle_keyboard_event_is_shortcut(false);
// Forward the Char event.
SimulateKeyboardEvent(WebInputEvent::Type::kChar);
// The Char event is not suppressed; the renderer will ignore it
// if the preceding RawKeyDown shortcut goes unhandled.
dispatched_events =
host_->mock_render_input_router()->GetAndResetDispatchedMessages();
ASSERT_EQ(1u, dispatched_events.size());
ASSERT_TRUE(dispatched_events[0]->ToEvent());
EXPECT_EQ(WebInputEvent::Type::kChar,
dispatched_events[0]->ToEvent()->Event()->Event().GetType());
// Send the simulated response from the renderer back.
dispatched_events[0]->ToEvent()->CallCallback(
blink::mojom::InputEventResultState::kNotConsumed);
EXPECT_EQ(WebInputEvent::Type::kChar,
delegate_->unhandled_keyboard_event_type());
// Forward the KeyUp event.
SimulateKeyboardEvent(WebInputEvent::Type::kKeyUp);
// Make sure only KeyUp was sent to the renderer.
dispatched_events =
host_->mock_render_input_router()->GetAndResetDispatchedMessages();
ASSERT_EQ(1u, dispatched_events.size());
ASSERT_TRUE(dispatched_events[0]->ToEvent());
EXPECT_EQ(WebInputEvent::Type::kKeyUp,
dispatched_events[0]->ToEvent()->Event()->Event().GetType());
// Send the simulated response from the renderer back.
dispatched_events[0]->ToEvent()->CallCallback(
blink::mojom::InputEventResultState::kNotConsumed);
EXPECT_EQ(WebInputEvent::Type::kKeyUp,
delegate_->unhandled_keyboard_event_type());
}
TEST_F(RenderWidgetHostTest, UnhandledWheelEvent) {
SimulateWheelEvent(-5, 0, 0, true, WebMouseWheelEvent::kPhaseBegan);
MockWidgetInputHandler::MessageVector dispatched_events =
host_->mock_render_input_router()->GetAndResetDispatchedMessages();
ASSERT_EQ(1u, dispatched_events.size());
ASSERT_TRUE(dispatched_events[0]->ToEvent());
EXPECT_EQ(WebInputEvent::Type::kMouseWheel,
dispatched_events[0]->ToEvent()->Event()->Event().GetType());
// Send the simulated response from the renderer back.
dispatched_events[0]->ToEvent()->CallCallback(
blink::mojom::InputEventResultState::kNotConsumed);
EXPECT_TRUE(delegate_->handle_wheel_event_called());
EXPECT_EQ(1, view_->unhandled_wheel_event_count());
EXPECT_EQ(-5, view_->unhandled_wheel_event().delta_x);
}
TEST_F(RenderWidgetHostTest, HandleWheelEvent) {
// Indicate that we're going to handle this wheel event
delegate_->set_handle_wheel_event(true);
SimulateWheelEvent(-5, 0, 0, true, WebMouseWheelEvent::kPhaseBegan);
MockWidgetInputHandler::MessageVector dispatched_events =
host_->mock_render_input_router()->GetAndResetDispatchedMessages();
ASSERT_EQ(1u, dispatched_events.size());
ASSERT_TRUE(dispatched_events[0]->ToEvent());
EXPECT_EQ(WebInputEvent::Type::kMouseWheel,
dispatched_events[0]->ToEvent()->Event()->Event().GetType());
// Send the simulated response from the renderer back.
dispatched_events[0]->ToEvent()->CallCallback(
blink::mojom::InputEventResultState::kNotConsumed);
// ensure the wheel event handler was invoked
EXPECT_TRUE(delegate_->handle_wheel_event_called());
// and that it suppressed the unhandled wheel event handler.
EXPECT_EQ(0, view_->unhandled_wheel_event_count());
}
TEST_F(RenderWidgetHostTest, EventsCausingFocus) {
SimulateMouseEvent(WebInputEvent::Type::kMouseDown);
EXPECT_EQ(1, delegate_->GetFocusOwningWebContentsCallCount());
PressTouchPoint(0, 1);
SendTouchEvent();
EXPECT_EQ(2, delegate_->GetFocusOwningWebContentsCallCount());
ReleaseTouchPoint(0);
SendTouchEvent();
EXPECT_EQ(2, delegate_->GetFocusOwningWebContentsCallCount());
SimulateGestureEvent(WebInputEvent::Type::kGestureTapDown,
blink::WebGestureDevice::kTouchscreen);
EXPECT_EQ(2, delegate_->GetFocusOwningWebContentsCallCount());
SimulateGestureEvent(WebInputEvent::Type::kGestureTap,
blink::WebGestureDevice::kTouchscreen);
EXPECT_EQ(3, delegate_->GetFocusOwningWebContentsCallCount());
}
TEST_F(RenderWidgetHostTest, UnhandledGestureEvent) {
SimulateGestureEvent(WebInputEvent::Type::kGestureTwoFingerTap,
blink::WebGestureDevice::kTouchscreen);
MockWidgetInputHandler::MessageVector dispatched_events =
host_->mock_render_input_router()->GetAndResetDispatchedMessages();
ASSERT_EQ(1u, dispatched_events.size());
ASSERT_TRUE(dispatched_events[0]->ToEvent());
EXPECT_EQ(WebInputEvent::Type::kGestureTwoFingerTap,
dispatched_events[0]->ToEvent()->Event()->Event().GetType());
// Send the simulated response from the renderer back.
dispatched_events[0]->ToEvent()->CallCallback(
blink::mojom::InputEventResultState::kNotConsumed);
EXPECT_EQ(WebInputEvent::Type::kGestureTwoFingerTap,
view_->gesture_event_type());
EXPECT_EQ(blink::mojom::InputEventResultState::kNotConsumed,
view_->ack_result());
}
// Test that the hang monitor timer expires properly if a new timer is started
// while one is in progress (see crbug.com/11007).
TEST_F(RenderWidgetHostTest, DontPostponeInputEventAckTimeout) {
base::TimeDelta delay = input::kHungRendererDelay;
// Start a timeout.
host_->GetRenderInputRouter()->StartInputEventAckTimeoutForTesting();
task_environment_.FastForwardBy(delay / 2);
// Add another timeout.
EXPECT_FALSE(delegate_->unresponsive_timer_fired());
host_->GetRenderInputRouter()->StartInputEventAckTimeoutForTesting();
// Wait long enough for first timeout and see if it fired.
task_environment_.FastForwardBy(delay);
EXPECT_TRUE(delegate_->unresponsive_timer_fired());
}
// Test that the hang monitor timer expires properly if it is started, stopped,
// and then started again.
TEST_F(RenderWidgetHostTest, StopAndStartInputEventAckTimeout) {
// Start a timeout, then stop it.
host_->GetRenderInputRouter()->StartInputEventAckTimeoutForTesting();
host_->GetRenderInputRouter()->StopInputEventAckTimeout();
// Start it again to ensure it still works.
EXPECT_FALSE(delegate_->unresponsive_timer_fired());
host_->GetRenderInputRouter()->StartInputEventAckTimeoutForTesting();
// Wait long enough for first timeout and see if it fired.
task_environment_.FastForwardBy(input::kHungRendererDelay +
base::Milliseconds(10));
EXPECT_TRUE(delegate_->unresponsive_timer_fired());
}
// Test that the hang monitor timer is effectively disabled when the widget is
// hidden.
TEST_F(RenderWidgetHostTest, InputEventAckTimeoutDisabledForInputWhenHidden) {
SimulateMouseEvent(WebInputEvent::Type::kMouseMove, 10, 10, 0, false);
// Hiding the widget should deactivate the timeout.
host_->WasHidden();
// The timeout should not fire.
EXPECT_FALSE(delegate_->unresponsive_timer_fired());
task_environment_.FastForwardBy(input::kHungRendererDelay +
base::Milliseconds(10));
EXPECT_FALSE(delegate_->unresponsive_timer_fired());
// The timeout should never reactivate while hidden.
SimulateMouseEvent(WebInputEvent::Type::kMouseMove, 10, 10, 0, false);
task_environment_.FastForwardBy(input::kHungRendererDelay +
base::Milliseconds(10));
EXPECT_FALSE(delegate_->unresponsive_timer_fired());
// Showing the widget should restore the timeout, as the events have
// not yet been ack'ed.
host_->WasShown({} /* record_tab_switch_time_request */);
task_environment_.FastForwardBy(input::kHungRendererDelay +
base::Milliseconds(10));
EXPECT_TRUE(delegate_->unresponsive_timer_fired());
}
// Test that the hang monitor catches two input events but only one ack.
// This can happen if the second input event causes the renderer to hang.
// This test will catch a regression of crbug.com/111185.
TEST_F(RenderWidgetHostTest, MultipleInputEvents) {
// Send two events but only one ack.
SimulateKeyboardEvent(WebInputEvent::Type::kRawKeyDown);
task_environment_.FastForwardBy(input::kHungRendererDelay / 2);
SimulateKeyboardEvent(WebInputEvent::Type::kRawKeyDown);
MockWidgetInputHandler::MessageVector dispatched_events =
host_->mock_render_input_router()->GetAndResetDispatchedMessages();
ASSERT_EQ(2u, dispatched_events.size());
ASSERT_TRUE(dispatched_events[0]->ToEvent());
// Send the simulated response from the renderer back.
dispatched_events[0]->ToEvent()->CallCallback(
blink::mojom::InputEventResultState::kConsumed);
// Wait long enough for second timeout and see if it fired.
task_environment_.FastForwardBy(input::kHungRendererDelay +
base::Milliseconds(10));
EXPECT_TRUE(delegate_->unresponsive_timer_fired());
}
TEST_F(RenderWidgetHostTest, IgnoreInputEvent) {
host_->SetupForInputRouterTest();
delegate_->SetIgnoreInputEvents(true);
SimulateKeyboardEvent(WebInputEvent::Type::kRawKeyDown);
EXPECT_FALSE(host_->mock_input_router()->sent_keyboard_event_);
SimulateMouseEvent(WebInputEvent::Type::kMouseMove);
EXPECT_FALSE(host_->mock_input_router()->sent_mouse_event_);
SimulateWheelEvent(0, 100, 0, true);
EXPECT_FALSE(host_->mock_input_router()->sent_wheel_event_);
SimulateGestureEvent(WebInputEvent::Type::kGestureScrollBegin,
blink::WebGestureDevice::kTouchpad);
EXPECT_FALSE(host_->mock_input_router()->sent_gesture_event_);
PressTouchPoint(100, 100);
SendTouchEvent();
EXPECT_FALSE(host_->mock_input_router()->send_touch_event_not_cancelled_);
}
TEST_F(RenderWidgetHostTest, KeyboardListenerIgnoresEvent) {
host_->SetupForInputRouterTest();
host_->AddKeyPressEventCallback(base::BindRepeating(
&RenderWidgetHostTest::KeyPressEventCallback, base::Unretained(this)));
handle_key_press_event_ = false;
SimulateKeyboardEvent(WebInputEvent::Type::kRawKeyDown);
EXPECT_TRUE(host_->mock_input_router()->sent_keyboard_event_);
}
TEST_F(RenderWidgetHostTest, KeyboardListenerSuppressFollowingEvents) {
host_->SetupForInputRouterTest();
host_->AddKeyPressEventCallback(base::BindRepeating(
&RenderWidgetHostTest::KeyPressEventCallback, base::Unretained(this)));
// The callback handles the first event
handle_key_press_event_ = true;
SimulateKeyboardEvent(WebInputEvent::Type::kRawKeyDown);
EXPECT_FALSE(host_->mock_input_router()->sent_keyboard_event_);
// Following Char events should be suppressed
handle_key_press_event_ = false;
SimulateKeyboardEvent(WebInputEvent::Type::kChar);
EXPECT_FALSE(host_->mock_input_router()->sent_keyboard_event_);
SimulateKeyboardEvent(WebInputEvent::Type::kChar);
EXPECT_FALSE(host_->mock_input_router()->sent_keyboard_event_);
// Sending RawKeyDown event should stop suppression
SimulateKeyboardEvent(WebInputEvent::Type::kRawKeyDown);
EXPECT_TRUE(host_->mock_input_router()->sent_keyboard_event_);
host_->mock_input_router()->sent_keyboard_event_ = false;
SimulateKeyboardEvent(WebInputEvent::Type::kChar);
EXPECT_TRUE(host_->mock_input_router()->sent_keyboard_event_);
}
TEST_F(RenderWidgetHostTest, MouseEventCallbackCanHandleEvent) {
host_->SetupForInputRouterTest();
host_->AddMouseEventCallback(base::BindRepeating(
&RenderWidgetHostTest::MouseEventCallback, base::Unretained(this)));
handle_mouse_event_ = true;
SimulateMouseEvent(WebInputEvent::Type::kMouseDown);
EXPECT_FALSE(host_->mock_input_router()->sent_mouse_event_);
handle_mouse_event_ = false;
SimulateMouseEvent(WebInputEvent::Type::kMouseDown);
EXPECT_TRUE(host_->mock_input_router()->sent_mouse_event_);
}
TEST_F(RenderWidgetHostTest, InputRouterReceivesHasTouchEventHandlers) {
host_->SetupForInputRouterTest();
ASSERT_FALSE(host_->mock_input_router()->has_handlers_);
auto touch_event_consumers = blink::mojom::TouchEventConsumers::New(
HasTouchEventHandlers(true), HasHitTestableScrollbar(false));
host_->SetHasTouchEventConsumers(std::move(touch_event_consumers));
EXPECT_TRUE(host_->mock_input_router()->has_handlers_);
}
void CheckLatencyInfoComponentInMessage(
MockWidgetInputHandler::MessageVector& dispatched_events,
WebInputEvent::Type expected_type) {
ASSERT_EQ(1u, dispatched_events.size());
ASSERT_TRUE(dispatched_events[0]->ToEvent());
EXPECT_TRUE(dispatched_events[0]->ToEvent()->Event()->Event().GetType() ==
expected_type);
EXPECT_TRUE(
dispatched_events[0]->ToEvent()->Event()->latency_info().FindLatency(
ui::INPUT_EVENT_LATENCY_BEGIN_RWH_COMPONENT, nullptr));
dispatched_events[0]->ToEvent()->CallCallback(
blink::mojom::InputEventResultState::kConsumed);
}
void CheckLatencyInfoComponentInGestureScrollUpdate(
MockWidgetInputHandler::MessageVector& dispatched_events) {
ASSERT_EQ(2u, dispatched_events.size());
ASSERT_TRUE(dispatched_events[0]->ToEvent());
ASSERT_TRUE(dispatched_events[1]->ToEvent());
EXPECT_EQ(WebInputEvent::Type::kTouchScrollStarted,
dispatched_events[0]->ToEvent()->Event()->Event().GetType());
EXPECT_EQ(WebInputEvent::Type::kGestureScrollUpdate,
dispatched_events[1]->ToEvent()->Event()->Event().GetType());
EXPECT_TRUE(
dispatched_events[1]->ToEvent()->Event()->latency_info().FindLatency(
ui::INPUT_EVENT_LATENCY_BEGIN_RWH_COMPONENT, nullptr));
dispatched_events[1]->ToEvent()->CallCallback(
blink::mojom::InputEventResultState::kConsumed);
}
// Tests that after input event passes through RWHI through ForwardXXXEvent()
// or ForwardXXXEventWithLatencyInfo(), LatencyInfo component
// ui::INPUT_EVENT_LATENCY_BEGIN_RWH_COMPONENT will always present in the
// event's LatencyInfo.
TEST_F(RenderWidgetHostTest, InputEventRWHLatencyComponent) {
auto touch_event_consumers = blink::mojom::TouchEventConsumers::New(
HasTouchEventHandlers(true), HasHitTestableScrollbar(false));
host_->SetHasTouchEventConsumers(std::move(touch_event_consumers));
// Tests RWHI::ForwardWheelEvent().
SimulateWheelEvent(-5, 0, 0, true, WebMouseWheelEvent::kPhaseBegan);
MockWidgetInputHandler::MessageVector dispatched_events =
host_->mock_render_input_router()->GetAndResetDispatchedMessages();
CheckLatencyInfoComponentInMessage(dispatched_events,
WebInputEvent::Type::kMouseWheel);
// Tests RWHI::ForwardWheelEventWithLatencyInfo().
SimulateWheelEventWithLatencyInfo(-5, 0, 0, true, ui::LatencyInfo(),
WebMouseWheelEvent::kPhaseChanged);
dispatched_events =
host_->mock_render_input_router()->GetAndResetDispatchedMessages();
CheckLatencyInfoComponentInMessage(dispatched_events,
WebInputEvent::Type::kMouseWheel);
// Tests RWHI::ForwardMouseEvent().
SimulateMouseEvent(WebInputEvent::Type::kMouseMove);
dispatched_events =
host_->mock_render_input_router()->GetAndResetDispatchedMessages();
CheckLatencyInfoComponentInMessage(dispatched_events,
WebInputEvent::Type::kMouseMove);
// Tests RWHI::ForwardMouseEventWithLatencyInfo().
SimulateMouseEventWithLatencyInfo(WebInputEvent::Type::kMouseMove,
ui::LatencyInfo());
dispatched_events =
host_->mock_render_input_router()->GetAndResetDispatchedMessages();
CheckLatencyInfoComponentInMessage(dispatched_events,
WebInputEvent::Type::kMouseMove);
// Tests RWHI::ForwardGestureEvent().
PressTouchPoint(0, 1);
SendTouchEvent();
widget_.SetTouchActionFromMain(cc::TouchAction::kAuto);
dispatched_events =
host_->mock_render_input_router()->GetAndResetDispatchedMessages();
CheckLatencyInfoComponentInMessage(dispatched_events,
WebInputEvent::Type::kTouchStart);
SimulateGestureEvent(WebInputEvent::Type::kGestureScrollBegin,
blink::WebGestureDevice::kTouchscreen);
dispatched_events =
host_->mock_render_input_router()->GetAndResetDispatchedMessages();
CheckLatencyInfoComponentInMessage(dispatched_events,
WebInputEvent::Type::kGestureScrollBegin);
// Tests RIR::ForwardGestureEventWithLatencyInfo().
SimulateGestureEventWithLatencyInfo(WebInputEvent::Type::kGestureScrollUpdate,
blink::WebGestureDevice::kTouchscreen,
ui::LatencyInfo());
dispatched_events =
host_->mock_render_input_router()->GetAndResetDispatchedMessages();
CheckLatencyInfoComponentInGestureScrollUpdate(dispatched_events);
ReleaseTouchPoint(0);
SendTouchEvent();
dispatched_events =
host_->mock_render_input_router()->GetAndResetDispatchedMessages();
// Tests RWHI::ForwardTouchEventWithLatencyInfo().
PressTouchPoint(0, 1);
SendTouchEvent();
dispatched_events =
host_->mock_render_input_router()->GetAndResetDispatchedMessages();
CheckLatencyInfoComponentInMessage(dispatched_events,
WebInputEvent::Type::kTouchStart);
}
TEST_F(RenderWidgetHostTest, RendererExitedResetsInputRouter) {
EXPECT_EQ(0u, host_->GetRenderInputRouter()->in_flight_event_count());
SimulateKeyboardEvent(WebInputEvent::Type::kRawKeyDown);
EXPECT_EQ(1u, host_->GetRenderInputRouter()->in_flight_event_count());
EXPECT_FALSE(host_->input_router()->HasPendingEvents());
blink::WebMouseWheelEvent event;
event.phase = blink::WebMouseWheelEvent::kPhaseBegan;
{
input::ScopedDispatchToRendererCallback dispatch_callback(
host_->GetRenderInputRouter()->GetDispatchToRendererCallback());
host_->input_router()->SendWheelEvent(
input::MouseWheelEventWithLatencyInfo(event),
dispatch_callback.callback);
}
EXPECT_TRUE(host_->input_router()->HasPendingEvents());
// RendererExited will delete the view.
host_->SetView(new TestView(host_.get()));
host_->RendererExited();
// The renderer is recreated.
host_->SetView(view_.get());
// Make a new RenderWidget when the renderer is recreated and inform that a
// RenderWidget is being created.
blink::VisualProperties props = host_->GetInitialVisualProperties();
// The RenderWidget is recreated with the initial VisualProperties.
ReinitalizeHost();
// Make sure the input router is in a fresh state.
ASSERT_FALSE(host_->input_router()->HasPendingEvents());
// There should be no in flight events. https://crbug.com/615090#152.
EXPECT_EQ(0u, host_->GetRenderInputRouter()->in_flight_event_count());
}
TEST_F(RenderWidgetHostTest, DestroyingRenderWidgetResetsInputRouter) {
EXPECT_EQ(0u, host_->GetRenderInputRouter()->in_flight_event_count());
SimulateKeyboardEvent(WebInputEvent::Type::kRawKeyDown);
EXPECT_EQ(1u, host_->GetRenderInputRouter()->in_flight_event_count());
EXPECT_FALSE(host_->input_router()->HasPendingEvents());
blink::WebMouseWheelEvent event;
event.phase = blink::WebMouseWheelEvent::kPhaseBegan;
{
input::ScopedDispatchToRendererCallback dispatch_callback(
host_->GetRenderInputRouter()->GetDispatchToRendererCallback());
host_->input_router()->SendWheelEvent(
input::MouseWheelEventWithLatencyInfo(event),
dispatch_callback.callback);
}
EXPECT_TRUE(host_->input_router()->HasPendingEvents());
// The RenderWidget is destroyed in the renderer process as the main frame
// is removed from this RenderWidgetHost's RenderWidgetView, but the
// RenderWidgetView is still kept around for another RenderFrame.
EXPECT_CALL(mock_owner_delegate_, IsMainFrameActive())
.WillRepeatedly(Return(false));
// Make a new RenderWidget when the renderer is recreated and inform that a
// RenderWidget is being created.
blink::VisualProperties props = host_->GetInitialVisualProperties();
// The RenderWidget is recreated with the initial VisualProperties.
EXPECT_CALL(mock_owner_delegate_, IsMainFrameActive())
.WillRepeatedly(Return(true));
// Make sure the input router is in a fresh state.
EXPECT_FALSE(host_->input_router()->HasPendingEvents());
// There should be no in flight events. https://crbug.com/615090#152.
EXPECT_EQ(0u, host_->GetRenderInputRouter()->in_flight_event_count());
}
TEST_F(RenderWidgetHostTest, RendererExitedResetsScreenRectsAck) {
// Screen rects are sent during initialization, but we are waiting for an ack.
base::RunLoop().RunUntilIdle();
EXPECT_EQ(1u, widget_.ReceivedScreenRects().size());
// Waiting for the ack prevents further sending.
host_->SendScreenRects();
host_->SendScreenRects();
base::RunLoop().RunUntilIdle();
EXPECT_EQ(1u, widget_.ReceivedScreenRects().size());
// RendererExited will delete the view.
host_->SetView(new TestView(host_.get()));
host_->RendererExited();
// Still can't send until the RenderWidget is replaced.
host_->SendScreenRects();
base::RunLoop().RunUntilIdle();
EXPECT_EQ(1u, widget_.ReceivedScreenRects().size());
// The renderer is recreated.
host_->SetView(view_.get());
// Make a new RenderWidget when the renderer is recreated and inform that a
// RenderWidget is being created.
blink::VisualProperties props = host_->GetInitialVisualProperties();
// The RenderWidget is recreated with the initial VisualProperties.
ReinitalizeHost();
// The RenderWidget is shown when navigation completes. This sends screen
// rects again. The IPC is sent as it's not waiting for an ack.
host_->WasShown({});
base::RunLoop().RunUntilIdle();
EXPECT_EQ(2u, widget_.ReceivedScreenRects().size());
}
TEST_F(RenderWidgetHostTest, DestroyingRenderWidgetResetsScreenRectsAck) {
// Screen rects are sent during initialization, but we are waiting for an ack.
base::RunLoop().RunUntilIdle();
EXPECT_EQ(1u, widget_.ReceivedScreenRects().size());
// Waiting for the ack prevents further sending.
host_->SendScreenRects();
host_->SendScreenRects();
base::RunLoop().RunUntilIdle();
EXPECT_EQ(1u, widget_.ReceivedScreenRects().size());
// If screen rects haven't changed, don't send them to the widget.
ClearScreenRects();
host_->SendScreenRects();
base::RunLoop().RunUntilIdle();
EXPECT_EQ(0u, widget_.ReceivedScreenRects().size());
// The RenderWidget has been destroyed in the renderer.
EXPECT_CALL(mock_owner_delegate_, IsMainFrameActive())
.WillRepeatedly(Return(false));
// Still can't send until the RenderWidget is replaced.
host_->SendScreenRects();
base::RunLoop().RunUntilIdle();
EXPECT_EQ(0u, widget_.ReceivedScreenRects().size());
// Make a new RenderWidget when the renderer is recreated and inform that a
// RenderWidget is being created.
blink::VisualProperties props = host_->GetInitialVisualProperties();
// The RenderWidget is recreated with the initial VisualProperties.
EXPECT_CALL(mock_owner_delegate_, IsMainFrameActive())
.WillRepeatedly(Return(true));
// We are able to send screen rects again. The IPC is sent as it's not waiting
// for an ack.
host_->SendScreenRects();
base::RunLoop().RunUntilIdle();
EXPECT_EQ(1u, widget_.ReceivedScreenRects().size());
}
// Regression test for http://crbug.com/401859 and http://crbug.com/522795.
TEST_F(RenderWidgetHostTest, RendererExitedResetsIsHidden) {
// RendererExited will delete the view.
host_->SetView(new TestView(host_.get()));
host_->WasShown({} /* record_tab_switch_time_request */);
ASSERT_FALSE(host_->is_hidden());
host_->RendererExited();
ASSERT_TRUE(host_->is_hidden());
// Make sure the input router is in a fresh state.
ASSERT_FALSE(host_->input_router()->HasPendingEvents());
}
TEST_F(RenderWidgetHostTest, VisualProperties) {
gfx::Rect bounds(0, 0, 100, 100);
gfx::Rect compositor_viewport_pixel_rect(40, 50);
view_->SetBounds(bounds);
view_->SetMockCompositorViewportPixelSize(
compositor_viewport_pixel_rect.size());
blink::VisualProperties visual_properties = host_->GetVisualProperties();
EXPECT_EQ(bounds.size(), visual_properties.new_size_device_px);
EXPECT_EQ(compositor_viewport_pixel_rect,
visual_properties.compositor_viewport_pixel_rect);
}
// Make sure no dragging occurs after renderer exited. See crbug.com/704832.
TEST_F(RenderWidgetHostTest, RendererExitedNoDrag) {
host_->SetView(new TestView(host_.get()));
EXPECT_EQ(delegate_->mock_delegate_view()->start_dragging_count(), 0);
GURL http_url = GURL("http://www.domain.com/index.html");
DropData drop_data;
drop_data.url = http_url;
drop_data.html_base_url = http_url;
FileSystemAccessManagerImpl* file_system_manager =
static_cast<StoragePartitionImpl*>(process_->GetStoragePartition())
->GetFileSystemAccessManager();
blink::DragOperationsMask drag_operation = blink::kDragOperationEvery;
host_->StartDragging(
DropDataToDragData(
drop_data, file_system_manager, process_->GetDeprecatedID(),
ChromeBlobStorageContext::GetFor(process_->GetBrowserContext())),
url::Origin(), drag_operation, SkBitmap(), gfx::Vector2d(), gfx::Rect(),
blink::mojom::DragEventSourceInfo::New());
EXPECT_EQ(delegate_->mock_delegate_view()->start_dragging_count(), 1);
// Simulate that renderer exited due navigation to the next page.
host_->RendererExited();
EXPECT_FALSE(host_->GetView());
host_->StartDragging(
DropDataToDragData(
drop_data, file_system_manager, process_->GetDeprecatedID(),
ChromeBlobStorageContext::GetFor(process_->GetBrowserContext())),
url::Origin(), drag_operation, SkBitmap(), gfx::Vector2d(), gfx::Rect(),
blink::mojom::DragEventSourceInfo::New());
EXPECT_EQ(delegate_->mock_delegate_view()->start_dragging_count(), 1);
}
// Hiding the RenderWidgetHostImpl instance via a call to WasHidden should
// not reject a pending pointer lock, if the operation is waiting for the
// user to make a selection on the permission prompt.
TEST_F(RenderWidgetHostTest,
WasHiddenDoesNotRejectPointerLockIfWaitingForPrompt) {
// Set up the mock delegate to return true for
// IsWaitingForPointerLockPrompt().
EXPECT_CALL(*delegate_, IsWaitingForPointerLockPrompt(
static_cast<RenderWidgetHostImpl*>(host_.get())))
.WillOnce(Return(true));
// Hide the RenderWidgetHostImpl instance.
host_->WasHidden();
EXPECT_FALSE(host_->pointer_lock_rejected());
}
// Hiding the RenderWidgetHostImpl instance via a call to WasHidden should
// reject a pending pointer lock, if the operation is not waiting for the
// user to make a selection on the permission prompt.
TEST_F(RenderWidgetHostTest, WasHiddenRejectsPointerLockIfNotWaitingForPrompt) {
// Set up the mock delegate to return false for
// IsWaitingForPointerLockPrompt().
EXPECT_CALL(*delegate_, IsWaitingForPointerLockPrompt(
static_cast<RenderWidgetHostImpl*>(host_.get())))
.WillOnce(Return(false));
// Hide the RenderWidgetHostImpl instance.
host_->WasHidden();
EXPECT_TRUE(host_->pointer_lock_rejected());
}
class RenderWidgetHostInitialSizeTest : public RenderWidgetHostTest {
public:
RenderWidgetHostInitialSizeTest()
: RenderWidgetHostTest(), initial_size_(200, 100) {}
void ConfigureView(TestView* view) override {
view->SetBounds(gfx::Rect(initial_size_));
}
protected:
gfx::Size initial_size_;
};
TEST_F(RenderWidgetHostInitialSizeTest, InitialSize) {
// Having an initial size set means that the size information had been sent
// with the request to new up the `blink::WebView` and so subsequent
// SynchronizeVisualProperties calls should not result in new IPC (unless the
// size has actually changed).
EXPECT_FALSE(host_->SynchronizeVisualProperties());
EXPECT_EQ(initial_size_, host_->old_visual_properties_->new_size_device_px);
EXPECT_TRUE(host_->visual_properties_ack_pending_);
}
TEST_F(RenderWidgetHostTest, HideUnthrottlesResize) {
ClearVisualProperties();
view_->SetBounds(gfx::Rect(100, 100));
EXPECT_TRUE(host_->SynchronizeVisualProperties());
// blink::mojom::Widget::UpdateVisualProperties sent to the renderer.
base::RunLoop().RunUntilIdle();
EXPECT_EQ(1u, widget_.ReceivedVisualProperties().size());
{
// Size sent to the renderer.
EXPECT_EQ(gfx::Size(100, 100),
widget_.ReceivedVisualProperties().at(0).new_size_device_px);
}
// An ack is pending, throttling further updates.
EXPECT_TRUE(host_->visual_properties_ack_pending_);
// Hiding the widget should unthrottle resize.
host_->WasHidden();
EXPECT_FALSE(host_->visual_properties_ack_pending_);
}
// Tests that event dispatch after the delegate has been detached doesn't cause
// a crash. See crbug.com/563237.
TEST_F(RenderWidgetHostTest, EventDispatchPostDetach) {
auto touch_event_consumers = blink::mojom::TouchEventConsumers::New(
HasTouchEventHandlers(true), HasHitTestableScrollbar(false));
host_->SetHasTouchEventConsumers(std::move(touch_event_consumers));
process_->sink().ClearMessages();
host_->DetachDelegate();
// Tests RIR::ForwardGestureEventWithLatencyInfo().
SimulateGestureEventWithLatencyInfo(WebInputEvent::Type::kGestureScrollUpdate,
blink::WebGestureDevice::kTouchscreen,
ui::LatencyInfo());
// Tests RWHI::ForwardWheelEventWithLatencyInfo().
SimulateWheelEventWithLatencyInfo(-5, 0, 0, true, ui::LatencyInfo());
ASSERT_FALSE(host_->input_router()->HasPendingEvents());
}
// If a navigation happens while the widget is hidden, we shouldn't show
// contents of the previous page when we become visible.
TEST_F(RenderWidgetHostTest, NavigateInBackgroundShowsBlank) {
// When visible, navigation does not immediately call into
// ClearDisplayedGraphics.
host_->WasShown({} /* record_tab_switch_time_request */);
host_->DidNavigate();
host_->InitializePaintHolding(true);
EXPECT_FALSE(host_->new_content_rendering_timeout_fired());
// Hide then show. ClearDisplayedGraphics must be called.
host_->WasHidden();
host_->WasShown({} /* record_tab_switch_time_request */);
EXPECT_TRUE(host_->new_content_rendering_timeout_fired());
host_->reset_new_content_rendering_timeout_fired();
// Hide, navigate, then show. ClearDisplayedGraphics must be called.
host_->WasHidden();
host_->DidNavigate();
host_->InitializePaintHolding(true);
host_->WasShown({} /* record_tab_switch_time_request */);
EXPECT_TRUE(host_->new_content_rendering_timeout_fired());
}
// Tests that fling events are not dispatched when the wheel event is consumed.
TEST_F(RenderWidgetHostTest, NoFlingEventsWhenLastScrollEventConsumed) {
// Simulate a consumed wheel event.
SimulateWheelEvent(10, 0, 0, true, WebMouseWheelEvent::kPhaseBegan);
MockWidgetInputHandler::MessageVector dispatched_events =
host_->mock_render_input_router()->GetAndResetDispatchedMessages();
ASSERT_EQ(1u, dispatched_events.size());
ASSERT_TRUE(dispatched_events[0]->ToEvent());
dispatched_events[0]->ToEvent()->CallCallback(
blink::mojom::InputEventResultState::kConsumed);
// A GestureFlingStart event following a consumed scroll event should not be
// dispatched.
SimulateGestureEvent(blink::WebInputEvent::Type::kGestureFlingStart,
blink::WebGestureDevice::kTouchpad);
dispatched_events =
host_->mock_render_input_router()->GetAndResetDispatchedMessages();
EXPECT_EQ(0u, dispatched_events.size());
}
// Tests that fling events are dispatched when some, but not all, scroll events
// were consumed.
TEST_F(RenderWidgetHostTest, FlingEventsWhenSomeScrollEventsConsumed) {
// Simulate a consumed wheel event.
SimulateWheelEvent(10, 0, 0, true, WebMouseWheelEvent::kPhaseBegan);
MockWidgetInputHandler::MessageVector dispatched_events =
host_->mock_render_input_router()->GetAndResetDispatchedMessages();
ASSERT_EQ(1u, dispatched_events.size());
ASSERT_TRUE(dispatched_events[0]->ToEvent());
dispatched_events[0]->ToEvent()->CallCallback(
blink::mojom::InputEventResultState::kConsumed);
// Followed by a not consumed wheel event.
SimulateWheelEvent(10, 0, 0, true, WebMouseWheelEvent::kPhaseChanged);
dispatched_events =
host_->mock_render_input_router()->GetAndResetDispatchedMessages();
ASSERT_EQ(1u, dispatched_events.size());
ASSERT_TRUE(dispatched_events[0]->ToEvent());
dispatched_events[0]->ToEvent()->CallCallback(
blink::mojom::InputEventResultState::kNotConsumed);
// A GestureFlingStart event following the scroll events should be dispatched.
SimulateGestureEvent(blink::WebInputEvent::Type::kGestureFlingStart,
blink::WebGestureDevice::kTouchpad);
dispatched_events =
host_->mock_render_input_router()->GetAndResetDispatchedMessages();
EXPECT_NE(0u, dispatched_events.size());
}
TEST_F(RenderWidgetHostTest, AddAndRemoveInputEventObserver) {
MockInputEventObserver observer;
// Add InputEventObserver.
host_->AddInputEventObserver(&observer);
// Confirm OnInputEvent is triggered.
input::NativeWebKeyboardEvent native_event =
CreateNativeWebKeyboardEvent(WebInputEvent::Type::kChar);
EXPECT_CALL(observer, OnInputEvent(_, _)).Times(1);
std::move(host_->GetRenderInputRouter()->GetDispatchToRendererCallback())
.Run(native_event, input::DispatchToRendererResult::kNotDispatched);
// Remove InputEventObserver.
host_->RemoveInputEventObserver(&observer);
// Confirm InputEventObserver is removed.
EXPECT_CALL(observer, OnInputEvent(_, _)).Times(0);
std::move(host_->GetRenderInputRouter()->GetDispatchToRendererCallback())
.Run(native_event, input::DispatchToRendererResult::kNotDispatched);
}
TEST_F(RenderWidgetHostTest, ScopedObservationWithInputEventObserver) {
// Verify that the specialization of `ScopedObserverationTraits` correctly
// adds and removes InputEventObservers.
MockInputEventObserver observer;
base::ScopedObservation<RenderWidgetHost,
RenderWidgetHost::InputEventObserver>
scoped_observation(&observer);
// Add InputEventObserver.
scoped_observation.Observe(host_.get());
// Confirm OnInputEvent is triggered.
input::NativeWebKeyboardEvent native_event =
CreateNativeWebKeyboardEvent(WebInputEvent::Type::kChar);
EXPECT_CALL(observer, OnInputEvent(_, _)).Times(1);
std::move(host_->GetRenderInputRouter()->GetDispatchToRendererCallback())
.Run(native_event, input::DispatchToRendererResult::kNotDispatched);
// Remove InputEventObserver.
scoped_observation.Reset();
// Confirm InputEventObserver is removed.
EXPECT_CALL(observer, OnInputEvent(_, _)).Times(0);
std::move(host_->GetRenderInputRouter()->GetDispatchToRendererCallback())
.Run(native_event, input::DispatchToRendererResult::kNotDispatched);
}
#if BUILDFLAG(IS_ANDROID)
TEST_F(RenderWidgetHostTest, AddAndRemoveImeInputEventObserver) {
MockInputEventObserver observer;
// Add ImeInputEventObserver.
host_->AddImeInputEventObserver(&observer);
// Confirm ImeFinishComposingTextEvent is triggered.
EXPECT_CALL(observer, OnImeFinishComposingTextEvent()).Times(1);
host_->ImeFinishComposingText(true);
// Remove ImeInputEventObserver.
host_->RemoveImeInputEventObserver(&observer);
// Confirm ImeInputEventObserver is removed.
EXPECT_CALL(observer, OnImeFinishComposingTextEvent()).Times(0);
host_->ImeFinishComposingText(true);
}
#endif
// Tests that vertical scroll direction changes are propagated to the delegate.
TEST_F(RenderWidgetHostTest, OnVerticalScrollDirectionChanged) {
const auto NotifyVerticalScrollDirectionChanged =
[this](viz::VerticalScrollDirection scroll_direction) {
static uint32_t frame_token = 1u;
host_->frame_token_message_queue_->DidProcessFrame(
frame_token, base::TimeTicks::Now());
cc::RenderFrameMetadata metadata;
metadata.new_vertical_scroll_direction = scroll_direction;
static_cast<cc::mojom::RenderFrameMetadataObserverClient*>(
host_->render_frame_metadata_provider())
->OnRenderFrameMetadataChanged(frame_token++, metadata);
};
// Verify initial state.
EXPECT_EQ(0, delegate_->GetOnVerticalScrollDirectionChangedCallCount());
EXPECT_EQ(viz::VerticalScrollDirection::kNull,
delegate_->GetLastVerticalScrollDirection());
// Verify that we will *not* propagate a vertical scroll of |kNull| which is
// only used to indicate the absence of a change in vertical scroll direction.
NotifyVerticalScrollDirectionChanged(viz::VerticalScrollDirection::kNull);
EXPECT_EQ(0, delegate_->GetOnVerticalScrollDirectionChangedCallCount());
EXPECT_EQ(viz::VerticalScrollDirection::kNull,
delegate_->GetLastVerticalScrollDirection());
// Verify that we will propagate a vertical scroll |kUp|.
NotifyVerticalScrollDirectionChanged(viz::VerticalScrollDirection::kUp);
EXPECT_EQ(1, delegate_->GetOnVerticalScrollDirectionChangedCallCount());
EXPECT_EQ(viz::VerticalScrollDirection::kUp,
delegate_->GetLastVerticalScrollDirection());
// Verify that we will propagate a vertical scroll |kDown|.
NotifyVerticalScrollDirectionChanged(viz::VerticalScrollDirection::kDown);
EXPECT_EQ(2, delegate_->GetOnVerticalScrollDirectionChangedCallCount());
EXPECT_EQ(viz::VerticalScrollDirection::kDown,
delegate_->GetLastVerticalScrollDirection());
}
TEST_F(RenderWidgetHostTest, SetCursorWithBitmap) {
SkBitmap bitmap;
bitmap.allocN32Pixels(1, 1);
bitmap.eraseColor(SK_ColorGREEN);
const ui::Cursor cursor =
ui::Cursor::NewCustom(std::move(bitmap), gfx::Point());
host_->SetCursor(cursor);
EXPECT_EQ(cursor, view_->last_cursor());
}
} // namespace content
|