File: WebKitWebView.cpp

package info (click to toggle)
webkit2gtk 2.42.2-1~deb12u1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 362,452 kB
  • sloc: cpp: 2,881,971; javascript: 282,447; ansic: 134,088; python: 43,789; ruby: 18,308; perl: 15,872; asm: 14,389; xml: 4,395; yacc: 2,350; sh: 2,074; java: 1,734; lex: 1,323; makefile: 288; pascal: 60
file content (5597 lines) | stat: -rw-r--r-- 212,376 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
/*
 * Portions Copyright (c) 2011 Motorola Mobility, Inc.  All rights reserved.
 * Copyright (C) 2014 Collabora Ltd.
 * Copyright (C) 2011, 2017, 2020 Igalia S.L.
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Library General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Library General Public License for more details.
 *
 * You should have received a copy of the GNU Library General Public License
 * along with this library; see the file COPYING.LIB.  If not, write to
 * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
 * Boston, MA 02110-1301, USA.
 */

#include "config.h"
#include "WebKitWebView.h"

#include "APIContentWorld.h"
#include "APIData.h"
#include "APINavigation.h"
#include "APISerializedScriptValue.h"
#include "DataReference.h"
#include "ImageOptions.h"
#include "NotificationService.h"
#include "PageLoadState.h"
#include "ProvisionalPageProxy.h"
#include "WebContextMenuItem.h"
#include "WebContextMenuItemData.h"
#include "WebFrameProxy.h"
#include "WebKitAuthenticationRequestPrivate.h"
#include "WebKitBackForwardListPrivate.h"
#include "WebKitContextMenuClient.h"
#include "WebKitContextMenuItemPrivate.h"
#include "WebKitContextMenuPrivate.h"
#include "WebKitDownloadPrivate.h"
#include "WebKitEditingCommands.h"
#include "WebKitEditorStatePrivate.h"
#include "WebKitEnumTypes.h"
#include "WebKitError.h"
#include "WebKitFormClient.h"
#include "WebKitHitTestResultPrivate.h"
#include "WebKitIconLoadingClient.h"
#include "WebKitInputMethodContextPrivate.h"
#include "WebKitNavigationClient.h"
#include "WebKitNotificationPrivate.h"
#include "WebKitPermissionStateQueryPrivate.h"
#include "WebKitPrivate.h"
#include "WebKitResponsePolicyDecision.h"
#include "WebKitScriptDialogPrivate.h"
#include "WebKitSettingsPrivate.h"
#include "WebKitUIClient.h"
#include "WebKitURIRequestPrivate.h"
#include "WebKitURIResponsePrivate.h"
#include "WebKitUserMessagePrivate.h"
#include "WebKitWebContextPrivate.h"
#include "WebKitWebResourceLoadManager.h"
#include "WebKitWebResourcePrivate.h"
#include "WebKitWebViewInternal.h"
#include "WebKitWebViewPrivate.h"
#include "WebKitWebViewSessionStatePrivate.h"
#include "WebKitWebsiteDataManagerPrivate.h"
#include "WebKitWebsitePoliciesPrivate.h"
#include "WebKitWindowPropertiesPrivate.h"
#include "WebPageMessages.h"
#include <JavaScriptCore/APICast.h>
#include <JavaScriptCore/JSRetainPtr.h>
#include <WebCore/CertificateInfo.h>
#include <WebCore/JSDOMExceptionHandling.h>
#include <WebCore/PlatformScreen.h>
#include <WebCore/RefPtrCairo.h>
#include <WebCore/RunJavaScriptParameters.h>
#include <WebCore/SharedBuffer.h>
#include <WebCore/URLSoup.h>
#include <glib/gi18n-lib.h>
#include <jsc/JSCContextPrivate.h>
#include <libsoup/soup.h>
#include <wtf/SetForScope.h>
#include <wtf/URL.h>
#include <wtf/glib/GRefPtr.h>
#include <wtf/glib/WTFGType.h>
#include <wtf/text/CString.h>
#include <wtf/text/StringBuilder.h>

#if PLATFORM(GTK)
#include "WebKitFaviconDatabasePrivate.h"
#include "WebKitInputMethodContextImplGtk.h"
#include "WebKitPointerLockPermissionRequest.h"
#include "WebKitPrintOperationPrivate.h"
#include "WebKitWebInspectorPrivate.h"
#include "WebKitWebViewBasePrivate.h"
#include <WebCore/GUniquePtrGtk.h>
#include <WebCore/GdkCairoUtilities.h>
#include <WebCore/RefPtrCairo.h>
#endif

#if PLATFORM(WPE)
#include "WPEView.h"
#include "WebKitOptionMenuPrivate.h"
#include "WebKitWebViewBackendPrivate.h"
#include "WebKitWebViewClient.h"
#endif

#if ENABLE(2022_GLIB_API)
#include "WebKitNetworkSessionPrivate.h"
#else
#include "WebKitJavascriptResultPrivate.h"
#endif

using namespace WebKit;
using namespace WebCore;

/**
 * WebKitWebView:
 *
 * The central class of the WPE WebKit and WebKitGTK APIs.
 *
 * #WebKitWebView is the central class of the WPE WebKit and WebKitGTK
 * APIs. It is responsible for managing the drawing of the content and
 * forwarding of events. You can load any URI into the #WebKitWebView or
 * a data string. With #WebKitSettings you can control various aspects
 * of the rendering and loading of the content.
 *
 * Note that in WebKitGTK, #WebKitWebView is scrollable by itself, so
 * you don't need to embed it in a #GtkScrolledWindow.
 */

enum {
    LOAD_CHANGED,
    LOAD_FAILED,
    LOAD_FAILED_WITH_TLS_ERRORS,

    CREATE,
    READY_TO_SHOW,
    RUN_AS_MODAL,
    CLOSE,

    SCRIPT_DIALOG,

    DECIDE_POLICY,
    PERMISSION_REQUEST,

    MOUSE_TARGET_CHANGED,

#if PLATFORM(GTK)
    PRINT,
#endif

    RESOURCE_LOAD_STARTED,

    ENTER_FULLSCREEN,
    LEAVE_FULLSCREEN,

    RUN_FILE_CHOOSER,

    CONTEXT_MENU,
    CONTEXT_MENU_DISMISSED,

    SUBMIT_FORM,

    INSECURE_CONTENT_DETECTED,

#if PLATFORM(GTK) && !USE(GTK4)
    WEB_PROCESS_CRASHED,
#endif
    WEB_PROCESS_TERMINATED,

    AUTHENTICATE,

    SHOW_NOTIFICATION,

#if PLATFORM(GTK)
    RUN_COLOR_CHOOSER,
#endif
    SHOW_OPTION_MENU,

    USER_MESSAGE_RECEIVED,

    QUERY_PERMISSION_STATE,

    LAST_SIGNAL
};

enum {
    PROP_0,

#if PLATFORM(WPE)
    PROP_BACKEND,
#endif

    PROP_WEB_CONTEXT,
    PROP_RELATED_VIEW,
    PROP_SETTINGS,
    PROP_USER_CONTENT_MANAGER,
#if ENABLE(2022_GLIB_API)
    PROP_NETWORK_SESSION,
#endif
    PROP_TITLE,
    PROP_ESTIMATED_LOAD_PROGRESS,

#if PLATFORM(GTK)
    PROP_FAVICON,
#endif

    PROP_URI,
    PROP_ZOOM_LEVEL,
    PROP_IS_LOADING,
    PROP_IS_PLAYING_AUDIO,
#if !ENABLE(2022_GLIB_API)
    PROP_IS_EPHEMERAL,
#endif
    PROP_IS_CONTROLLED_BY_AUTOMATION,
    PROP_AUTOMATION_PRESENTATION_TYPE,
    PROP_EDITABLE,
    PROP_PAGE_ID,
    PROP_IS_MUTED,
    PROP_WEBSITE_POLICIES,
    PROP_IS_WEB_PROCESS_RESPONSIVE,

    PROP_CAMERA_CAPTURE_STATE,
    PROP_MICROPHONE_CAPTURE_STATE,
    PROP_DISPLAY_CAPTURE_STATE,

    PROP_WEB_EXTENSION_MODE,
    PROP_DEFAULT_CONTENT_SECURITY_POLICY,

    N_PROPERTIES,
};

static GParamSpec* sObjProperties[N_PROPERTIES] = { nullptr, };

class PageLoadStateObserver;

#if PLATFORM(WPE)
static unsigned frameDisplayCallbackID;
struct FrameDisplayedCallback {
    WTF_MAKE_STRUCT_FAST_ALLOCATED;
    FrameDisplayedCallback(WebKitFrameDisplayedCallback callback, gpointer userData = nullptr, GDestroyNotify destroyNotifyFunction = nullptr)
        : id(++frameDisplayCallbackID)
        , callback(callback)
        , userData(userData)
        , destroyNotifyFunction(destroyNotifyFunction)
    {
    }

    ~FrameDisplayedCallback()
    {
        if (destroyNotifyFunction)
            destroyNotifyFunction(userData);
    }

    FrameDisplayedCallback(FrameDisplayedCallback&&) = default;
    FrameDisplayedCallback(const FrameDisplayedCallback&) = delete;
    FrameDisplayedCallback& operator=(const FrameDisplayedCallback&) = delete;

    unsigned id { 0 };
    WebKitFrameDisplayedCallback callback { nullptr };
    gpointer userData { nullptr };
    GDestroyNotify destroyNotifyFunction { nullptr };
};
#endif // PLATFORM(WPE)

struct _WebKitWebViewPrivate {
    WTF_MAKE_STRUCT_FAST_ALLOCATED;
    ~_WebKitWebViewPrivate()
    {
        // For modal dialogs, make sure the main loop is stopped when finalizing the webView.
        if (modalLoop && g_main_loop_is_running(modalLoop.get()))
            g_main_loop_quit(modalLoop.get());
    }

#if PLATFORM(WPE)
    GRefPtr<WebKitWebViewBackend> backend;
    std::unique_ptr<WKWPE::View> view;
    Vector<FrameDisplayedCallback> frameDisplayedCallbacks;
    bool inFrameDisplayed;
    HashSet<unsigned> frameDisplayedCallbacksToRemove;
#endif

    WebKitWebView* relatedView;
    CString title;
    CString customTextEncoding;
    CString activeURI;
    bool isActiveURIChangeBlocked;
    bool isLoading;
#if !ENABLE(2022_GLIB_API)
    bool isEphemeral;
#endif
    bool isControlledByAutomation;
    WebKitAutomationBrowsingContextPresentation automationPresentationType;

    std::unique_ptr<PageLoadStateObserver> loadObserver;

    GRefPtr<WebKitBackForwardList> backForwardList;
    GRefPtr<WebKitSettings> settings;
    GRefPtr<WebKitUserContentManager> userContentManager;
    GRefPtr<WebKitWebContext> context;
    GRefPtr<WebKitWindowProperties> windowProperties;
    GRefPtr<WebKitEditorState> editorState;

    GRefPtr<GMainLoop> modalLoop;

    GRefPtr<WebKitHitTestResult> mouseTargetHitTestResult;
    OptionSet<WebEventModifier> mouseTargetModifiers;

    GRefPtr<WebKitFindController> findController;

    GRefPtr<WebKitWebResource> mainResource;
    std::unique_ptr<WebKitWebResourceLoadManager> resourceLoadManager;

    WebKitScriptDialog* currentScriptDialog;

#if PLATFORM(GTK)
#if !ENABLE(2022_GLIB_API)
    GRefPtr<JSCContext> jsContext;
#endif

    GRefPtr<WebKitWebInspector> inspector;

#if USE(GTK4)
    GRefPtr<GdkTexture> favicon;
#else
    RefPtr<cairo_surface_t> favicon;
#endif
    GRefPtr<GCancellable> faviconCancellable;

    CString faviconURI;
    unsigned long faviconChangedHandlerID;
#endif

    GRefPtr<WebKitAuthenticationRequest> authenticationRequest;

#if ENABLE(2022_GLIB_API)
    GRefPtr<WebKitNetworkSession> networkSession;
#else
    GRefPtr<WebKitWebsiteDataManager> websiteDataManager;
#endif
    GRefPtr<WebKitWebsitePolicies> websitePolicies;

    CString defaultContentSecurityPolicy;
    WebKitWebExtensionMode webExtensionMode;

    double textScaleFactor;

    bool isWebProcessResponsive;
};

static guint signals[LAST_SIGNAL] = { 0, };

#if PLATFORM(GTK)
WEBKIT_DEFINE_TYPE(WebKitWebView, webkit_web_view, WEBKIT_TYPE_WEB_VIEW_BASE)
#elif PLATFORM(WPE)
WEBKIT_DEFINE_TYPE(WebKitWebView, webkit_web_view, G_TYPE_OBJECT)
#endif

static inline WebPageProxy& getPage(WebKitWebView* webView)
{
#if PLATFORM(GTK)
    auto* page = webkitWebViewBaseGetPage(reinterpret_cast<WebKitWebViewBase*>(webView));
    ASSERT(page);
    return *page;
#elif PLATFORM(WPE)
    ASSERT(webView->priv->view);
    return webView->priv->view->page();
#endif
}

static void webkitWebViewSetIsLoading(WebKitWebView* webView, bool isLoading)
{
    if (webView->priv->isLoading == isLoading)
        return;

    webView->priv->isLoading = isLoading;
    g_object_notify_by_pspec(G_OBJECT(webView), sObjProperties[PROP_IS_LOADING]);
}

void webkitWebViewIsPlayingAudioChanged(WebKitWebView* webView)
{
    g_object_notify_by_pspec(G_OBJECT(webView), sObjProperties[PROP_IS_PLAYING_AUDIO]);
}

void webkitWebViewMediaCaptureStateDidChange(WebKitWebView* webView, WebCore::MediaProducer::MediaStateFlags mediaStateFlags)
{
    if (mediaStateFlags.isEmpty()) {
        g_object_notify_by_pspec(G_OBJECT(webView), sObjProperties[PROP_CAMERA_CAPTURE_STATE]);
        g_object_notify_by_pspec(G_OBJECT(webView), sObjProperties[PROP_DISPLAY_CAPTURE_STATE]);
        g_object_notify_by_pspec(G_OBJECT(webView), sObjProperties[PROP_MICROPHONE_CAPTURE_STATE]);
        return;
    }
    if (mediaStateFlags.containsAny(WebCore::MediaProducer::MicrophoneCaptureMask))
        g_object_notify_by_pspec(G_OBJECT(webView), sObjProperties[PROP_MICROPHONE_CAPTURE_STATE]);
    if (mediaStateFlags.containsAny(WebCore::MediaProducer::VideoCaptureMask))
        g_object_notify_by_pspec(G_OBJECT(webView), sObjProperties[PROP_CAMERA_CAPTURE_STATE]);
    if (mediaStateFlags.containsAny(WebCore::MediaProducer::DisplayCaptureMask))
        g_object_notify_by_pspec(G_OBJECT(webView), sObjProperties[PROP_DISPLAY_CAPTURE_STATE]);
}

class PageLoadStateObserver final : public PageLoadState::Observer {
    WTF_MAKE_FAST_ALLOCATED;
public:
    PageLoadStateObserver(WebKitWebView* webView)
        : m_webView(webView)
    {
    }

private:
    void willChangeIsLoading() override
    {
        g_object_freeze_notify(G_OBJECT(m_webView));
    }
    void didChangeIsLoading() override
    {
        webkitWebViewSetIsLoading(m_webView, getPage(m_webView).pageLoadState().isLoading());
        g_object_thaw_notify(G_OBJECT(m_webView));
    }

    void willChangeTitle() override
    {
        g_object_freeze_notify(G_OBJECT(m_webView));
    }
    void didChangeTitle() override
    {
        m_webView->priv->title = getPage(m_webView).pageLoadState().title().utf8();
        g_object_notify_by_pspec(G_OBJECT(m_webView), sObjProperties[PROP_TITLE]);
        g_object_thaw_notify(G_OBJECT(m_webView));
    }

    void willChangeActiveURL() override
    {
        if (m_webView->priv->isActiveURIChangeBlocked)
            return;
        g_object_freeze_notify(G_OBJECT(m_webView));
    }
    void didChangeActiveURL() override
    {
        if (m_webView->priv->isActiveURIChangeBlocked)
            return;
        m_webView->priv->activeURI = getPage(m_webView).pageLoadState().activeURL().utf8();
        g_object_notify_by_pspec(G_OBJECT(m_webView), sObjProperties[PROP_URI]);
        g_object_thaw_notify(G_OBJECT(m_webView));
    }

    void willChangeHasOnlySecureContent() override { }
    void didChangeHasOnlySecureContent() override { }

    void willChangeEstimatedProgress() override
    {
        g_object_freeze_notify(G_OBJECT(m_webView));
    }
    void didChangeEstimatedProgress() override
    {
        g_object_notify_by_pspec(G_OBJECT(m_webView), sObjProperties[PROP_ESTIMATED_LOAD_PROGRESS]);
        g_object_thaw_notify(G_OBJECT(m_webView));
    }

    void willChangeCanGoBack() override { }
    void didChangeCanGoBack() override { }
    void willChangeCanGoForward() override { }
    void didChangeCanGoForward() override { }
    void willChangeNetworkRequestsInProgress() override { }
    void didChangeNetworkRequestsInProgress() override { }
    void willChangeCertificateInfo() override { }
    void didChangeCertificateInfo() override { }
    void willChangeWebProcessIsResponsive() override { }
    void didChangeWebProcessIsResponsive() override { }
    void didSwapWebProcesses() override { };

    WebKitWebView* m_webView;
};

#if PLATFORM(WPE)
WebKitWebViewClient::WebKitWebViewClient(WebKitWebView* webView)
    : m_webView(webView)
{ }

GRefPtr<WebKitOptionMenu> WebKitWebViewClient::showOptionMenu(WebKitPopupMenu& popupMenu, const WebCore::IntRect& rect, const Vector<WebPopupItem>& items, int32_t selectedIndex)
{
    GRefPtr<WebKitOptionMenu> menu = adoptGRef(webkitOptionMenuCreate(popupMenu, items, selectedIndex));
    if (webkitWebViewShowOptionMenu(WEBKIT_WEB_VIEW(m_webView), rect, menu.get()))
        return menu;
    return nullptr;
}

void WebKitWebViewClient::frameDisplayed(WKWPE::View&)
{
    {
        SetForScope inFrameDisplayedGuard(m_webView->priv->inFrameDisplayed, true);
        for (const auto& callback : m_webView->priv->frameDisplayedCallbacks) {
            if (!m_webView->priv->frameDisplayedCallbacksToRemove.contains(callback.id))
                callback.callback(m_webView, callback.userData);
        }
    }

    while (!m_webView->priv->frameDisplayedCallbacksToRemove.isEmpty()) {
        auto id = m_webView->priv->frameDisplayedCallbacksToRemove.takeAny();
        m_webView->priv->frameDisplayedCallbacks.removeFirstMatching([id](const auto& item) {
            return item.id == id;
        });
    }
}

void WebKitWebViewClient::willStartLoad(WKWPE::View&)
{
    webkitWebViewWillStartLoad(m_webView);
}

void WebKitWebViewClient::didChangePageID(WKWPE::View&)
{
    webkitWebViewDidChangePageID(m_webView);
}

void WebKitWebViewClient::didReceiveUserMessage(WKWPE::View&, UserMessage&& message, CompletionHandler<void(UserMessage&&)>&& completionHandler)
{
    webkitWebViewDidReceiveUserMessage(m_webView, WTFMove(message), WTFMove(completionHandler));
}

WebKitWebResourceLoadManager* WebKitWebViewClient::webResourceLoadManager()
{
    return webkitWebViewGetWebResourceLoadManager(m_webView);
}

#if ENABLE(FULLSCREEN_API)
void WebKitWebViewClient::enterFullScreen(WKWPE::View&)
{
    webkitWebViewEnterFullScreen(m_webView);
}

void WebKitWebViewClient::exitFullScreen(WKWPE::View&)
{
    webkitWebViewExitFullScreen(m_webView);
}
#endif
#endif

static gboolean webkitWebViewLoadFail(WebKitWebView* webView, WebKitLoadEvent, const char* failingURI, GError* error)
{
    if (g_error_matches(error, WEBKIT_NETWORK_ERROR, WEBKIT_NETWORK_ERROR_CANCELLED)
#if ENABLE(2022_GLIB_API)
        || g_error_matches(error, WEBKIT_MEDIA_ERROR, WEBKIT_MEDIA_ERROR_WILL_HANDLE_LOAD)
#else
        || g_error_matches(error, WEBKIT_PLUGIN_ERROR, WEBKIT_PLUGIN_ERROR_WILL_HANDLE_LOAD)
#endif
        || g_error_matches(error, WEBKIT_POLICY_ERROR, WEBKIT_POLICY_ERROR_FRAME_LOAD_INTERRUPTED_BY_POLICY_CHANGE))
        return FALSE;

    GUniquePtr<char> htmlString(g_strdup_printf("<html><body>%s</body></html>", error->message));
    webkit_web_view_load_alternate_html(webView, htmlString.get(), failingURI, 0);

    return TRUE;
}

#if PLATFORM(GTK)
static GtkWidget* webkitWebViewCreate(WebKitWebView*, WebKitNavigationAction*)
{
    return nullptr;
}
#else
static WebKitWebView* webkitWebViewCreate(WebKitWebView*, WebKitNavigationAction*)
{
    return nullptr;
}
#endif

static gboolean webkitWebViewDecidePolicy(WebKitWebView*, WebKitPolicyDecision* decision, WebKitPolicyDecisionType decisionType)
{
    if (decisionType != WEBKIT_POLICY_DECISION_TYPE_RESPONSE) {
        webkit_policy_decision_use(decision);
        return TRUE;
    }

    WebKitURIResponse* response = webkit_response_policy_decision_get_response(WEBKIT_RESPONSE_POLICY_DECISION(decision));
    const ResourceResponse& resourceResponse = webkitURIResponseGetResourceResponse(response);
    if (resourceResponse.isAttachment()) {
        webkit_policy_decision_download(decision);
        return TRUE;
    }

    if (webkit_response_policy_decision_is_mime_type_supported(WEBKIT_RESPONSE_POLICY_DECISION(decision)) || webkit_uri_response_get_status_code(response) == SOUP_STATUS_NO_CONTENT)
        webkit_policy_decision_use(decision);
    else
        webkit_policy_decision_ignore(decision);

    return TRUE;
}

static gboolean webkitWebViewPermissionRequest(WebKitWebView*, WebKitPermissionRequest* request)
{
#if ENABLE(POINTER_LOCK)
    if (WEBKIT_IS_POINTER_LOCK_PERMISSION_REQUEST(request)) {
        webkit_permission_request_allow(request);
        return TRUE;
    }
#endif

    webkit_permission_request_deny(request);
    return TRUE;
}

static void allowModalDialogsChanged(WebKitSettings* settings, GParamSpec*, WebKitWebView* webView)
{
    getPage(webView).setCanRunModal(webkit_settings_get_allow_modal_dialogs(settings));
}

static void zoomTextOnlyChanged(WebKitSettings* settings, GParamSpec*, WebKitWebView* webView)
{
    auto& page = getPage(webView);
    gboolean zoomTextOnly = webkit_settings_get_zoom_text_only(settings);
    gdouble pageZoomLevel = zoomTextOnly ? 1 : page.textZoomFactor();
    gdouble textZoomLevel = zoomTextOnly ? page.pageZoomFactor() : 1;
    page.setPageAndTextZoomFactors(pageZoomLevel, textZoomLevel);
}

static void userAgentChanged(WebKitSettings* settings, GParamSpec*, WebKitWebView* webView)
{
    getPage(webView).setCustomUserAgent(String::fromUTF8(webkit_settings_get_user_agent(settings)));
}

static gboolean webkitWebViewIsEphemeral(WebKitWebView* webView)
{
#if ENABLE(2022_GLIB_API)
    return webkit_network_session_is_ephemeral(webView->priv->networkSession.get());
#else
    return webView->priv->isEphemeral;
#endif
}

#if PLATFORM(GTK)
static void enableBackForwardNavigationGesturesChanged(WebKitSettings* settings, GParamSpec*, WebKitWebView* webView)
{
    gboolean enable = webkit_settings_get_enable_back_forward_navigation_gestures(settings);
    webkitWebViewBaseSetEnableBackForwardNavigationGesture(WEBKIT_WEB_VIEW_BASE(webView), enable);
}

#if USE(GTK4)
static void webkitWebViewUpdateFavicon(WebKitWebView* webView, GdkTexture* favicon)
#else
static void webkitWebViewUpdateFavicon(WebKitWebView* webView, cairo_surface_t* favicon)
#endif
{
    WebKitWebViewPrivate* priv = webView->priv;
    if (priv->favicon.get() == favicon)
        return;

    priv->favicon = favicon;
    g_object_notify_by_pspec(G_OBJECT(webView), sObjProperties[PROP_FAVICON]);
}

static void webkitWebViewCancelFaviconRequest(WebKitWebView* webView)
{
    if (!webView->priv->faviconCancellable)
        return;

    g_cancellable_cancel(webView->priv->faviconCancellable.get());
    webView->priv->faviconCancellable = nullptr;
}

static void gotFaviconCallback(GObject* object, GAsyncResult* result, gpointer userData)
{
    GUniqueOutPtr<GError> error;
#if USE(GTK4)
    GRefPtr<GdkTexture> favicon = adoptGRef(webkit_favicon_database_get_favicon_finish(WEBKIT_FAVICON_DATABASE(object), result, &error.outPtr()));
#else
    RefPtr<cairo_surface_t> favicon = adoptRef(webkit_favicon_database_get_favicon_finish(WEBKIT_FAVICON_DATABASE(object), result, &error.outPtr()));
#endif
    if (g_error_matches(error.get(), G_IO_ERROR, G_IO_ERROR_CANCELLED))
        return;

    WebKitWebView* webView = WEBKIT_WEB_VIEW(userData);
    webkitWebViewUpdateFavicon(webView, favicon.get());
    webView->priv->faviconCancellable = 0;
}

static WebKitFaviconDatabase* webkitWebViewGetFaviconDatabase(WebKitWebView* webView)
{
#if ENABLE(2022_GLIB_API)
    return webkit_website_data_manager_get_favicon_database(webkitWebViewGetWebsiteDataManager(webView));
#else
    return webkit_web_context_get_favicon_database(webView->priv->context.get());
#endif
}

static void webkitWebViewRequestFavicon(WebKitWebView* webView)
{
    webkitWebViewCancelFaviconRequest(webView);

    WebKitWebViewPrivate* priv = webView->priv;
    auto* database = webkitWebViewGetFaviconDatabase(webView);
    if (!database)
        return;

    priv->faviconCancellable = adoptGRef(g_cancellable_new());
    webkitFaviconDatabaseGetFaviconInternal(database, priv->activeURI.data(), webkitWebViewIsEphemeral(webView), priv->faviconCancellable.get(), gotFaviconCallback, webView);
}

static void webkitWebViewUpdateFaviconURI(WebKitWebView* webView, const char* faviconURI)
{
    if (webView->priv->faviconURI == faviconURI)
        return;

    webView->priv->faviconURI = faviconURI;
    webkitWebViewRequestFavicon(webView);
}

static void faviconChangedCallback(WebKitFaviconDatabase*, const char* pageURI, const char* faviconURI, WebKitWebView* webView)
{
    if (webView->priv->activeURI != pageURI)
        return;

    webkitWebViewUpdateFaviconURI(webView, faviconURI);
}
#endif

static bool webkitWebViewIsConstructed(WebKitWebView* webView)
{
    // The loadObserver is set in webkitWebViewConstructed, right after the
    // WebPageProxy is created, so we use it to check if the view has been
    // constructed instead of adding a boolean member only for that.
    return !!webView->priv->loadObserver;
}

static void webkitWebViewUpdateSettings(WebKitWebView* webView)
{
    // The "settings" property is set on construction, and in that
    // case webkit_web_view_set_settings() will be called *before* the
    // WebPageProxy has been created so we should do an early return.
    if (!webkitWebViewIsConstructed(webView))
        return;

    auto& page = getPage(webView);
    WebKitSettings* settings = webView->priv->settings.get();
    page.setPreferences(*webkitSettingsGetPreferences(settings));
    page.setCanRunModal(webkit_settings_get_allow_modal_dialogs(settings));
    page.setCustomUserAgent(String::fromUTF8(webkit_settings_get_user_agent(settings)));
#if PLATFORM(GTK)
    enableBackForwardNavigationGesturesChanged(settings, nullptr, webView);
#endif

    g_signal_connect(settings, "notify::allow-modal-dialogs", G_CALLBACK(allowModalDialogsChanged), webView);
    g_signal_connect(settings, "notify::zoom-text-only", G_CALLBACK(zoomTextOnlyChanged), webView);
    g_signal_connect(settings, "notify::user-agent", G_CALLBACK(userAgentChanged), webView);
#if PLATFORM(GTK)
    g_signal_connect(settings, "notify::enable-back-forward-navigation-gestures", G_CALLBACK(enableBackForwardNavigationGesturesChanged), webView);
#endif
}

static void webkitWebViewDisconnectSettingsSignalHandlers(WebKitWebView* webView)
{
    if (!webkitWebViewIsConstructed(webView))
        return;

    WebKitSettings* settings = webView->priv->settings.get();
    g_signal_handlers_disconnect_by_func(settings, reinterpret_cast<gpointer>(allowModalDialogsChanged), webView);
    g_signal_handlers_disconnect_by_func(settings, reinterpret_cast<gpointer>(zoomTextOnlyChanged), webView);
    g_signal_handlers_disconnect_by_func(settings, reinterpret_cast<gpointer>(userAgentChanged), webView);
#if PLATFORM(GTK)
    g_signal_handlers_disconnect_by_func(settings, reinterpret_cast<gpointer>(enableBackForwardNavigationGesturesChanged), webView);
#endif
}

#if PLATFORM(GTK)
static void webkitWebViewWatchForChangesInFavicon(WebKitWebView* webView)
{
    WebKitWebViewPrivate* priv = webView->priv;
    if (priv->faviconChangedHandlerID)
        return;

    auto* database = webkitWebViewGetFaviconDatabase(webView);
    if (!database)
        return;

    priv->faviconChangedHandlerID = g_signal_connect_object(database, "favicon-changed", G_CALLBACK(faviconChangedCallback), webView, static_cast<GConnectFlags>(0));
}
#endif

static void webkitWebViewConstructed(GObject* object)
{
    G_OBJECT_CLASS(webkit_web_view_parent_class)->constructed(object);

    WebKitWebView* webView = WEBKIT_WEB_VIEW(object);
    WebKitWebViewPrivate* priv = webView->priv;
    if (priv->relatedView) {
        if (priv->context)
            g_critical("WebKitWebView web-context property can't be set when related-view is set too, passed web-context value is ignored.");
        priv->context = webkit_web_view_get_context(priv->relatedView);
#if ENABLE(2022_GLIB_API)
        if (priv->networkSession)
            g_critical("WebKitWebView network-session property can't be set when related-view is set too, passed network-session value is ignored.");
        priv->networkSession = webkit_web_view_get_network_session(priv->relatedView);
#else
        if (priv->isEphemeral)
            g_critical("WebKitWebView is-ephemeral property can't be set when related-view is set too, passed is-ephemeral value is ignored.");
        priv->isEphemeral = webkit_web_view_is_ephemeral(priv->relatedView);
#endif
        if (priv->isControlledByAutomation)
            g_critical("WebKitWebView is-controlled-by-automation can't be set when related-view is set too, passed is-controlled-by-automation value is ignored.");
        priv->isControlledByAutomation = webkit_web_view_is_controlled_by_automation(priv->relatedView);
    } else if (!priv->context)
        priv->context = webkit_web_context_get_default();
#if !ENABLE(2022_GLIB_API)
    else if (!priv->isEphemeral)
        priv->isEphemeral = webkit_web_context_is_ephemeral(priv->context.get());
#endif

    if (!priv->settings)
        priv->settings = adoptGRef(webkit_settings_new());

    if (!priv->userContentManager)
        priv->userContentManager = adoptGRef(webkit_user_content_manager_new());

#if ENABLE(2022_GLIB_API)
#if ENABLE(REMOTE_INSPECTOR)
    if (priv->isControlledByAutomation)
        priv->networkSession = webkit_web_context_get_network_session_for_automation(priv->context.get());
#endif
    if (!priv->networkSession)
        priv->networkSession = webkit_network_session_get_default();
#else
    if (priv->isEphemeral && !webkit_web_context_is_ephemeral(priv->context.get())) {
        priv->websiteDataManager = adoptGRef(webkit_website_data_manager_new_ephemeral());
        auto* contextDataManager = webkit_web_context_get_website_data_manager(priv->context.get());
        webkit_website_data_manager_set_tls_errors_policy(priv->websiteDataManager.get(), webkit_website_data_manager_get_tls_errors_policy(contextDataManager));
        auto proxySettings = webkitWebsiteDataManagerGetDataStore(contextDataManager).networkProxySettings();
        webkitWebsiteDataManagerGetDataStore(priv->websiteDataManager.get()).setNetworkProxySettings(WTFMove(proxySettings));
    }
#endif

    if (!priv->websitePolicies)
        priv->websitePolicies = adoptGRef(webkit_website_policies_new());

    webkitWebContextCreatePageForWebView(priv->context.get(), webView, priv->userContentManager.get(), priv->relatedView, priv->websitePolicies.get());

    priv->loadObserver = makeUnique<PageLoadStateObserver>(webView);
    getPage(webView).pageLoadState().addObserver(*priv->loadObserver);

    priv->resourceLoadManager = makeUnique<WebKitWebResourceLoadManager>(webView);

    // The related view is only valid during the construction.
    priv->relatedView = nullptr;

    attachNavigationClientToView(webView);
    attachUIClientToView(webView);
    attachContextMenuClientToView(webView);
    attachFormClientToView(webView);

#if PLATFORM(GTK)
    attachIconLoadingClientToView(webView);

    GRefPtr<WebKitInputMethodContext> imContext = adoptGRef(webkitInputMethodContextImplGtkNew());
    webkitInputMethodContextSetWebView(imContext.get(), webView);
    webkitWebViewBaseSetInputMethodContext(WEBKIT_WEB_VIEW_BASE(webView), imContext.get());
#endif

#if PLATFORM(WPE)
    priv->view->setClient(makeUnique<WebKitWebViewClient>(webView));
#endif

    // This needs to be after attachUIClientToView() because WebPageProxy::setUIClient() calls setCanRunModal() with true.
    // See https://bugs.webkit.org/show_bug.cgi?id=135412.
    webkitWebViewUpdateSettings(webView);

    priv->backForwardList = adoptGRef(webkitBackForwardListCreate(&getPage(webView).backForwardList()));
    priv->windowProperties = adoptGRef(webkitWindowPropertiesCreate());

    priv->textScaleFactor = WebCore::screenDPI() / 96.;
    getPage(webView).setTextZoomFactor(priv->textScaleFactor);
    WebCore::setScreenDPIObserverHandler([webView] {
        auto& page = getPage(webView);
        auto zoomFactor = page.textZoomFactor() / webView->priv->textScaleFactor;
        webView->priv->textScaleFactor = WebCore::screenDPI() / 96.;
        page.setTextZoomFactor(zoomFactor * webView->priv->textScaleFactor);
    }, webView);

    priv->isWebProcessResponsive = true;
}

static void webkitWebViewSetProperty(GObject* object, guint propId, const GValue* value, GParamSpec* paramSpec)
{
    WebKitWebView* webView = WEBKIT_WEB_VIEW(object);

    switch (propId) {
#if PLATFORM(WPE)
    case PROP_BACKEND: {
        gpointer backend = g_value_get_boxed(value);
        webView->priv->backend = backend ? adoptGRef(static_cast<WebKitWebViewBackend*>(backend)) : nullptr;
        break;
    }
#endif
    case PROP_WEB_CONTEXT: {
        gpointer webContext = g_value_get_object(value);
        webView->priv->context = webContext ? WEBKIT_WEB_CONTEXT(webContext) : nullptr;
        break;
    }
    case PROP_RELATED_VIEW: {
        gpointer relatedView = g_value_get_object(value);
        webView->priv->relatedView = relatedView ? WEBKIT_WEB_VIEW(relatedView) : nullptr;
        break;
    }
    case PROP_SETTINGS: {
        if (gpointer settings = g_value_get_object(value))
            webkit_web_view_set_settings(webView, WEBKIT_SETTINGS(settings));
        break;
    }
    case PROP_USER_CONTENT_MANAGER: {
        gpointer userContentManager = g_value_get_object(value);
        webView->priv->userContentManager = userContentManager ? WEBKIT_USER_CONTENT_MANAGER(userContentManager) : nullptr;
        break;
    }
#if ENABLE(2022_GLIB_API)
    case PROP_NETWORK_SESSION: {
        gpointer networkSession = g_value_get_object(value);
        webView->priv->networkSession = networkSession ? WEBKIT_NETWORK_SESSION(networkSession) : nullptr;
        break;
    }
#endif
    case PROP_ZOOM_LEVEL:
        webkit_web_view_set_zoom_level(webView, g_value_get_double(value));
        break;
#if !ENABLE(2022_GLIB_API)
    case PROP_IS_EPHEMERAL:
        webView->priv->isEphemeral = g_value_get_boolean(value);
        break;
#endif
    case PROP_IS_CONTROLLED_BY_AUTOMATION:
        webView->priv->isControlledByAutomation = g_value_get_boolean(value);
        break;
    case PROP_AUTOMATION_PRESENTATION_TYPE:
        webView->priv->automationPresentationType = static_cast<WebKitAutomationBrowsingContextPresentation>(g_value_get_enum(value));
        break;
    case PROP_EDITABLE:
        webkit_web_view_set_editable(webView, g_value_get_boolean(value));
        break;
    case PROP_IS_MUTED:
        webkit_web_view_set_is_muted(webView, g_value_get_boolean(value));
        break;
    case PROP_WEBSITE_POLICIES:
        webView->priv->websitePolicies = static_cast<WebKitWebsitePolicies*>(g_value_get_object(value));
        break;
    case PROP_CAMERA_CAPTURE_STATE:
        webkit_web_view_set_camera_capture_state(webView, static_cast<WebKitMediaCaptureState>(g_value_get_enum(value)));
        break;
    case PROP_MICROPHONE_CAPTURE_STATE:
        webkit_web_view_set_microphone_capture_state(webView, static_cast<WebKitMediaCaptureState>(g_value_get_enum(value)));
        break;
    case PROP_DISPLAY_CAPTURE_STATE:
        webkit_web_view_set_display_capture_state(webView, static_cast<WebKitMediaCaptureState>(g_value_get_enum(value)));
        break;
    case PROP_WEB_EXTENSION_MODE:
        webView->priv->webExtensionMode = static_cast<WebKitWebExtensionMode>(g_value_get_enum(value));
        break;
    case PROP_DEFAULT_CONTENT_SECURITY_POLICY:
        webView->priv->defaultContentSecurityPolicy = CString(g_value_get_string(value));
        break;
    default:
        G_OBJECT_WARN_INVALID_PROPERTY_ID(object, propId, paramSpec);
    }
}

static void webkitWebViewGetProperty(GObject* object, guint propId, GValue* value, GParamSpec* paramSpec)
{
    WebKitWebView* webView = WEBKIT_WEB_VIEW(object);

    switch (propId) {
#if PLATFORM(WPE)
    case PROP_BACKEND:
        g_value_set_static_boxed(value, webView->priv->backend.get());
        break;
#endif
    case PROP_WEB_CONTEXT:
        g_value_set_object(value, webView->priv->context.get());
        break;
    case PROP_SETTINGS:
        g_value_set_object(value, webkit_web_view_get_settings(webView));
        break;
    case PROP_USER_CONTENT_MANAGER:
        g_value_set_object(value, webkit_web_view_get_user_content_manager(webView));
        break;
#if ENABLE(2022_GLIB_API)
    case PROP_NETWORK_SESSION:
        g_value_set_object(value, webkit_web_view_get_network_session(webView));
        break;
#endif
    case PROP_TITLE:
        g_value_set_string(value, webView->priv->title.data());
        break;
    case PROP_ESTIMATED_LOAD_PROGRESS:
        g_value_set_double(value, webkit_web_view_get_estimated_load_progress(webView));
        break;
#if PLATFORM(GTK)
    case PROP_FAVICON:
#if USE(GTK4)
        g_value_set_object(value, webkit_web_view_get_favicon(webView));
#else
        g_value_set_pointer(value, webkit_web_view_get_favicon(webView));
#endif
        break;
#endif
    case PROP_URI:
        g_value_set_string(value, webkit_web_view_get_uri(webView));
        break;
    case PROP_ZOOM_LEVEL:
        g_value_set_double(value, webkit_web_view_get_zoom_level(webView));
        break;
    case PROP_IS_LOADING:
        g_value_set_boolean(value, webkit_web_view_is_loading(webView));
        break;
    case PROP_IS_PLAYING_AUDIO:
        g_value_set_boolean(value, webkit_web_view_is_playing_audio(webView));
        break;
#if !ENABLE(2022_GLIB_API)
    case PROP_IS_EPHEMERAL:
        g_value_set_boolean(value, webkit_web_view_is_ephemeral(webView));
        break;
#endif
    case PROP_IS_CONTROLLED_BY_AUTOMATION:
        g_value_set_boolean(value, webkit_web_view_is_controlled_by_automation(webView));
        break;
    case PROP_AUTOMATION_PRESENTATION_TYPE:
        g_value_set_enum(value, webkit_web_view_get_automation_presentation_type(webView));
        break;
    case PROP_EDITABLE:
        g_value_set_boolean(value, webkit_web_view_is_editable(webView));
        break;
    case PROP_PAGE_ID:
        g_value_set_uint64(value, webkit_web_view_get_page_id(webView));
        break;
    case PROP_IS_MUTED:
        g_value_set_boolean(value, webkit_web_view_get_is_muted(webView));
        break;
    case PROP_WEBSITE_POLICIES:
        g_value_set_object(value, webkit_web_view_get_website_policies(webView));
        break;
    case PROP_IS_WEB_PROCESS_RESPONSIVE:
        g_value_set_boolean(value, webkit_web_view_get_is_web_process_responsive(webView));
        break;
    case PROP_CAMERA_CAPTURE_STATE:
        g_value_set_enum(value, webkit_web_view_get_camera_capture_state(webView));
        break;
    case PROP_MICROPHONE_CAPTURE_STATE:
        g_value_set_enum(value, webkit_web_view_get_microphone_capture_state(webView));
        break;
    case PROP_DISPLAY_CAPTURE_STATE:
        g_value_set_enum(value, webkit_web_view_get_display_capture_state(webView));
        break;
    case PROP_WEB_EXTENSION_MODE:
        g_value_set_enum(value, webkit_web_view_get_web_extension_mode(webView));
        break;
    case PROP_DEFAULT_CONTENT_SECURITY_POLICY:
        g_value_set_string(value, webkit_web_view_get_default_content_security_policy(webView));
        break;
    default:
        G_OBJECT_WARN_INVALID_PROPERTY_ID(object, propId, paramSpec);
    }
}

static void webkitWebViewDispose(GObject* object)
{
    WebKitWebView* webView = WEBKIT_WEB_VIEW(object);

#if PLATFORM(GTK)
    webkitWebViewCancelFaviconRequest(webView);
    webView->priv->faviconChangedHandlerID = 0;
#endif

    webkitWebViewDisconnectSettingsSignalHandlers(webView);

    if (webView->priv->loadObserver) {
        getPage(webView).pageLoadState().removeObserver(*webView->priv->loadObserver);
        webView->priv->loadObserver.reset();

        // We notify the context here to ensure it's called only once. Ideally we should
        // call this in finalize, not dispose, but finalize is used internally and we don't
        // have access to the instance pointer from the private struct destructor.
        webkitWebContextWebViewDestroyed(webView->priv->context.get(), webView);
    }

    if (webView->priv->currentScriptDialog) {
        webkit_script_dialog_close(webView->priv->currentScriptDialog);
        ASSERT(!webView->priv->currentScriptDialog);
    }

#if PLATFORM(WPE)
    webView->priv->view->close();
#endif

    WebCore::setScreenDPIObserverHandler(nullptr, webView);

    G_OBJECT_CLASS(webkit_web_view_parent_class)->dispose(object);
}

static gboolean webkitWebViewAccumulatorObjectHandled(GSignalInvocationHint*, GValue* returnValue, const GValue* handlerReturn, gpointer)
{
    void* object = g_value_get_object(handlerReturn);
    if (object)
        g_value_set_object(returnValue, object);

    return !object;
}

static void webkit_web_view_class_init(WebKitWebViewClass* webViewClass)
{
    GObjectClass* gObjectClass = G_OBJECT_CLASS(webViewClass);

    gObjectClass->constructed = webkitWebViewConstructed;
    gObjectClass->set_property = webkitWebViewSetProperty;
    gObjectClass->get_property = webkitWebViewGetProperty;
    gObjectClass->dispose = webkitWebViewDispose;

    webViewClass->load_failed = webkitWebViewLoadFail;
    webViewClass->create = webkitWebViewCreate;
    webViewClass->script_dialog = webkitWebViewScriptDialog;
    webViewClass->decide_policy = webkitWebViewDecidePolicy;
    webViewClass->permission_request = webkitWebViewPermissionRequest;
    webViewClass->run_file_chooser = webkitWebViewRunFileChooser;
    webViewClass->authenticate = webkitWebViewAuthenticate;

#if PLATFORM(WPE)
    /**
     * WebKitWebView:backend:
     *
     * The #WebKitWebViewBackend of the view.
     *
     * since: 2.20
     */
    sObjProperties[PROP_BACKEND] =
        g_param_spec_boxed(
            "backend",
            nullptr, nullptr,
            WEBKIT_TYPE_WEB_VIEW_BACKEND,
            static_cast<GParamFlags>(WEBKIT_PARAM_READWRITE | G_PARAM_CONSTRUCT_ONLY));
#endif

    /**
     * WebKitWebView:web-context:
     *
     * The #WebKitWebContext of the view.
     */
    sObjProperties[PROP_WEB_CONTEXT] =
        g_param_spec_object(
            "web-context",
            nullptr, nullptr,
            WEBKIT_TYPE_WEB_CONTEXT,
            static_cast<GParamFlags>(WEBKIT_PARAM_READWRITE | G_PARAM_CONSTRUCT_ONLY));
    /**
     * WebKitWebView:related-view:
     *
     * The related #WebKitWebView used when creating the view to share the
     * same web process and network session. This property is not readable
     * because the related web view is only valid during the object construction.
     *
     * Since: 2.4
     */
    sObjProperties[PROP_RELATED_VIEW] =
        g_param_spec_object(
            "related-view",
            nullptr, nullptr,
            WEBKIT_TYPE_WEB_VIEW,
            static_cast<GParamFlags>(WEBKIT_PARAM_WRITABLE | G_PARAM_CONSTRUCT_ONLY));

    /**
     * WebKitWebView:settings:
     *
     * The #WebKitSettings of the view.
     *
     * Since: 2.6
     */
    sObjProperties[PROP_SETTINGS] =
        g_param_spec_object(
            "settings",
            nullptr, nullptr,
            WEBKIT_TYPE_SETTINGS,
            static_cast<GParamFlags>(WEBKIT_PARAM_WRITABLE | G_PARAM_CONSTRUCT));

    /**
     * WebKitWebView:user-content-manager:
     *
     * The #WebKitUserContentManager of the view.
     *
     * Since: 2.6
     */
    sObjProperties[PROP_USER_CONTENT_MANAGER] =
        g_param_spec_object(
            "user-content-manager",
            nullptr, nullptr,
            WEBKIT_TYPE_USER_CONTENT_MANAGER,
            static_cast<GParamFlags>(WEBKIT_PARAM_READWRITE | G_PARAM_CONSTRUCT_ONLY));

#if ENABLE(2022_GLIB_API)
    /**
     * WebKitWebView:network-session:
     *
     * The #WebKitNetworkSession of the view
     *
     * Since: 2.40
     */
    sObjProperties[PROP_NETWORK_SESSION]=
        g_param_spec_object(
            "network-session",
            nullptr, nullptr,
            WEBKIT_TYPE_NETWORK_SESSION,
            static_cast<GParamFlags>(WEBKIT_PARAM_READWRITE | G_PARAM_CONSTRUCT_ONLY));
#endif

    /**
     * WebKitWebView:title:
     *
     * The main frame document title of this #WebKitWebView. If
     * the title has not been received yet, it will be %NULL.
     */
    sObjProperties[PROP_TITLE] =
        g_param_spec_string(
            "title",
            nullptr, nullptr,
            nullptr,
            WEBKIT_PARAM_READABLE);

    /**
     * WebKitWebView:estimated-load-progress:
     *
     * An estimate of the percent completion for the current loading operation.
     * This value will range from 0.0 to 1.0 and, once a load completes,
     * will remain at 1.0 until a new load starts, at which point it
     * will be reset to 0.0.
     * The value is an estimate based on the total number of bytes expected
     * to be received for a document, including all its possible subresources
     * and child documents.
     */
    sObjProperties[PROP_ESTIMATED_LOAD_PROGRESS] =
        g_param_spec_double(
            "estimated-load-progress",
            nullptr, nullptr,
            0.0, 1.0, 0.0,
            WEBKIT_PARAM_READABLE);

#if PLATFORM(GTK)
    /**
     * WebKitWebView:favicon:
     *
     * The favicon currently associated to the #WebKitWebView.
     * See webkit_web_view_get_favicon() for more details.
     */
    sObjProperties[PROP_FAVICON] =
#if USE(GTK4)
        g_param_spec_object(
            "favicon",
            nullptr, nullptr,
            GDK_TYPE_TEXTURE,
            WEBKIT_PARAM_READABLE);
#else
        g_param_spec_pointer(
            "favicon",
            nullptr, nullptr,
            WEBKIT_PARAM_READABLE);
#endif
#endif

    /**
     * WebKitWebView:uri:
     *
     * The current active URI of the #WebKitWebView.
     * See webkit_web_view_get_uri() for more details.
     */
    sObjProperties[PROP_URI] =
        g_param_spec_string(
            "uri",
            nullptr, nullptr,
            nullptr,
            WEBKIT_PARAM_READABLE);

    /**
     * WebKitWebView:zoom-level:
     *
     * The zoom level of the #WebKitWebView content.
     * See webkit_web_view_set_zoom_level() for more details.
     */
    sObjProperties[PROP_ZOOM_LEVEL] =
        g_param_spec_double(
            "zoom-level",
            nullptr, nullptr,
            0, G_MAXDOUBLE, 1,
            WEBKIT_PARAM_READWRITE);

    /**
     * WebKitWebView:is-loading:
     *
     * Whether the #WebKitWebView is currently loading a page. This property becomes
     * %TRUE as soon as a new load operation is requested and before the
     * #WebKitWebView::load-changed signal is emitted with %WEBKIT_LOAD_STARTED and
     * at that point the active URI is the requested one.
     * When the load operation finishes the property is set to %FALSE before
     * #WebKitWebView::load-changed is emitted with %WEBKIT_LOAD_FINISHED.
     */
    sObjProperties[PROP_IS_LOADING] =
        g_param_spec_boolean(
            "is-loading",
            nullptr, nullptr,
            FALSE,
            WEBKIT_PARAM_READABLE);

    /**
     * WebKitWebView:is-playing-audio:
     *
     * Whether the #WebKitWebView is currently playing audio from a page.
     * This property becomes %TRUE as soon as web content starts playing any
     * kind of audio. When a page is no longer playing any kind of sound,
     * the property is set back to %FALSE.
     *
     * Since: 2.8
     */
    sObjProperties[PROP_IS_PLAYING_AUDIO] =
        g_param_spec_boolean(
            "is-playing-audio",
            nullptr, nullptr,
            FALSE,
            WEBKIT_PARAM_READABLE);

#if !ENABLE(2022_GLIB_API)
    /**
     * WebKitWebView:is-ephemeral:
     *
     * Whether the #WebKitWebView is ephemeral. An ephemeral web view never writes
     * website data to the client storage, no matter what #WebKitWebsiteDataManager
     * its context is using. This is normally used to implement private browsing mode.
     * This is a %G_PARAM_CONSTRUCT_ONLY property, so you have to create an ephemeral
     * #WebKitWebView and it can't be changed. The ephemeral #WebKitWebsiteDataManager
     * created for the #WebKitWebView will inherit the network settings from the
     * #WebKitWebContext<!-- -->'s #WebKitWebsiteDataManager. To use different settings
     * you can get the #WebKitWebsiteDataManager with webkit_web_view_get_website_data_manager()
     * and set the new ones.
     * Note that all #WebKitWebView<!-- -->s created with an ephemeral #WebKitWebContext
     * will be ephemeral automatically.
     * See also webkit_web_context_new_ephemeral().
     *
     * Since: 2.16
     */
    sObjProperties[PROP_IS_EPHEMERAL] =
        g_param_spec_boolean(
            "is-ephemeral",
            nullptr, nullptr,
            FALSE,
            static_cast<GParamFlags>(WEBKIT_PARAM_READWRITE | G_PARAM_CONSTRUCT_ONLY));
#endif

    /**
     * WebKitWebView:is-controlled-by-automation:
     *
     * Whether the #WebKitWebView is controlled by automation. This should only be used when
     * creating a new #WebKitWebView as a response to #WebKitAutomationSession::create-web-view
     * signal request.
     *
     * Since: 2.18
     */
    sObjProperties[PROP_IS_CONTROLLED_BY_AUTOMATION] =
        g_param_spec_boolean(
            "is-controlled-by-automation",
            nullptr, nullptr,
            FALSE,
            static_cast<GParamFlags>(WEBKIT_PARAM_READWRITE | G_PARAM_CONSTRUCT_ONLY));

    /**
     * WebKitWebView:automation-presentation-type:
     *
     * The #WebKitAutomationBrowsingContextPresentation of #WebKitWebView. This should only be used when
     * creating a new #WebKitWebView as a response to #WebKitAutomationSession::create-web-view
     * signal request. If the new WebView was added to a new tab of current browsing context window
     * %WEBKIT_AUTOMATION_BROWSING_CONTEXT_PRESENTATION_TAB should be used.
     *
     * Since: 2.28
     */
    sObjProperties[PROP_AUTOMATION_PRESENTATION_TYPE] =
        g_param_spec_enum(
            "automation-presentation-type",
            nullptr, nullptr,
            WEBKIT_TYPE_AUTOMATION_BROWSING_CONTEXT_PRESENTATION,
            WEBKIT_AUTOMATION_BROWSING_CONTEXT_PRESENTATION_WINDOW,
            static_cast<GParamFlags>(WEBKIT_PARAM_READWRITE | G_PARAM_CONSTRUCT_ONLY));

    /**
     * WebKitWebView:editable:
     *
     * Whether the pages loaded inside #WebKitWebView are editable. For more
     * information see webkit_web_view_set_editable().
     *
     * Since: 2.8
     */
    sObjProperties[PROP_EDITABLE] =
        g_param_spec_boolean(
            "editable",
            nullptr, nullptr,
            FALSE,
            WEBKIT_PARAM_READWRITE);

    /**
     * WebKitWebView:page-id:
     *
     * The identifier of the #WebKitWebPage corresponding to the #WebKitWebView.
     *
     * Since: 2.28
     */
    sObjProperties[PROP_PAGE_ID] =
        g_param_spec_uint64(
            "page-id",
            nullptr, nullptr,
            0, G_MAXUINT64, 0,
            WEBKIT_PARAM_READABLE);

    /**
     * WebKitWebView:is-muted:
     *
     * Whether the #WebKitWebView audio is muted. When %TRUE, audio is silenced.
     * It may still be playing, i.e. #WebKitWebView:is-playing-audio may be %TRUE.
     *
     * Since: 2.30
     */
    sObjProperties[PROP_IS_MUTED] =
        g_param_spec_boolean(
            "is-muted",
            nullptr, nullptr,
            FALSE,
            WEBKIT_PARAM_READWRITE);

    /**
     * WebKitWebView:website-policies:
     *
     * The #WebKitWebsitePolicies for the view.
     *
     * Since: 2.30
     */
    sObjProperties[PROP_WEBSITE_POLICIES] =
        g_param_spec_object(
            "website-policies",
            nullptr, nullptr,
            WEBKIT_TYPE_WEBSITE_POLICIES,
            static_cast<GParamFlags>(WEBKIT_PARAM_READWRITE | G_PARAM_CONSTRUCT_ONLY));

    /**
     * WebKitWebView:is-web-process-responsive:
     *
     * Whether the web process currently associated to the #WebKitWebView is responsive.
     *
     * Since: 2.34
     */
    sObjProperties[PROP_IS_WEB_PROCESS_RESPONSIVE] =
        g_param_spec_boolean(
            "is-web-process-responsive",
            nullptr, nullptr,
            TRUE,
            WEBKIT_PARAM_READABLE);

    /**
     * WebKitWebView:camera-capture-state:
     *
     * Capture state of the camera device. Whenever the user grants a media-request sent by the web
     * page, requesting video capture capabilities (`navigator.mediaDevices.getUserMedia({video:
     * true})`) this property will be set to %WEBKIT_MEDIA_CAPTURE_STATE_ACTIVE.
     *
     * The application can monitor this property and provide a visual indicator allowing to optionally
     * deactivate or mute the capture device by setting this property respectively to
     * %WEBKIT_MEDIA_CAPTURE_STATE_NONE or %WEBKIT_MEDIA_CAPTURE_STATE_MUTED.
     *
     * If the capture state of the device is set to %WEBKIT_MEDIA_CAPTURE_STATE_NONE the web-page
     * can still re-request the permission to the user. Permission desision caching is left to the
     * application.
     *
     * Since: 2.34
     */
    sObjProperties[PROP_CAMERA_CAPTURE_STATE] = g_param_spec_enum(
        "camera-capture-state",
        nullptr, nullptr,
        WEBKIT_TYPE_MEDIA_CAPTURE_STATE,
        WEBKIT_MEDIA_CAPTURE_STATE_NONE,
        WEBKIT_PARAM_READWRITE);

    /**
     * WebKitWebView:microphone-capture-state:
     *
     * Capture state of the microphone device. Whenever the user grants a media-request sent by the web
     * page, requesting audio capture capabilities (`navigator.mediaDevices.getUserMedia({audio:
     * true})`) this property will be set to %WEBKIT_MEDIA_CAPTURE_STATE_ACTIVE.
     *
     * The application can monitor this property and provide a visual indicator allowing to
     * optionally deactivate or mute the capture device by setting this property respectively to
     * %WEBKIT_MEDIA_CAPTURE_STATE_NONE or %WEBKIT_MEDIA_CAPTURE_STATE_MUTED.
     *
     * If the capture state of the device is set to %WEBKIT_MEDIA_CAPTURE_STATE_NONE the web-page
     * can still re-request the permission to the user. Permission desision caching is left to the
     * application.
     *
     * Since: 2.34
     */
    sObjProperties[PROP_MICROPHONE_CAPTURE_STATE] = g_param_spec_enum(
        "microphone-capture-state",
        nullptr, nullptr,
        WEBKIT_TYPE_MEDIA_CAPTURE_STATE,
        WEBKIT_MEDIA_CAPTURE_STATE_NONE,
        WEBKIT_PARAM_READWRITE);

    /**
     * WebKitWebView:display-capture-state:
     *
     * Capture state of the display device. Whenever the user grants a media-request sent by the web
     * page, requesting screencasting capabilities (`navigator.mediaDevices.getDisplayMedia() this
     * property will be set to %WEBKIT_MEDIA_CAPTURE_STATE_ACTIVE.
     *
     * The application can monitor this property and provide a visual indicator allowing to
     * optionally deactivate or mute the capture device by setting this property respectively to
     * %WEBKIT_MEDIA_CAPTURE_STATE_NONE or %WEBKIT_MEDIA_CAPTURE_STATE_MUTED.
     *
     * If the capture state of the device is set to %WEBKIT_MEDIA_CAPTURE_STATE_NONE the web-page
     * can still re-request the permission to the user. Permission desision caching is left to the
     * application.
     *
     * Since: 2.34
     */
    sObjProperties[PROP_DISPLAY_CAPTURE_STATE] = g_param_spec_enum(
        "display-capture-state",
        nullptr, nullptr,
        WEBKIT_TYPE_MEDIA_CAPTURE_STATE,
        WEBKIT_MEDIA_CAPTURE_STATE_NONE,
        WEBKIT_PARAM_READWRITE);

    /**
     * WebKitWebView:web-extension-mode:
     *
     * This configures @web_view to treat the content as a WebExtension.
     *
     * Note that this refers to the web standard [WebExtensions](https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions)
     * and not WebKitWebExtensions.
     *
     * In practice this limits the Content-Security-Policies that are allowed to be set. Some details can be found in
     * [Chrome's documentation](https://developer.chrome.com/docs/extensions/mv3/intro/mv3-migration/#content-security-policy).
     *
     * Since: 2.38
     */
    sObjProperties[PROP_WEB_EXTENSION_MODE] = g_param_spec_enum(
        "web-extension-mode",
        nullptr, nullptr,
        WEBKIT_TYPE_WEB_EXTENSION_MODE,
        WEBKIT_WEB_EXTENSION_MODE_NONE,
        static_cast<GParamFlags>(WEBKIT_PARAM_READWRITE | G_PARAM_CONSTRUCT_ONLY));

    /**
     * WebKitWebView:default-content-security-policy:
     *
     * The default Content-Security-Policy used by the webview as if it were set
     * by an HTTP header.
     *
     * This applies to all content loaded including through navigation or via the various
     * webkit_web_view_load_\* APIs. However do note that many WebKit APIs bypass
     * Content-Security-Policy in general such as #WebKitUserContentManager and
     * webkit_web_view_run_javascript().
     *
     * Policies are additive so if a website sets its own policy it still applies
     * on top of the policy set here.
     *
     * Since: 2.38
     */
    sObjProperties[PROP_DEFAULT_CONTENT_SECURITY_POLICY] = g_param_spec_string(
        "default-content-security-policy",
        nullptr, nullptr,
        nullptr,
        static_cast<GParamFlags>(WEBKIT_PARAM_READWRITE | G_PARAM_CONSTRUCT_ONLY));

    g_object_class_install_properties(gObjectClass, N_PROPERTIES, sObjProperties);

    /**
     * WebKitWebView::load-changed:
     * @web_view: the #WebKitWebView on which the signal is emitted
     * @load_event: the #WebKitLoadEvent
     *
     * Emitted when a load operation in @web_view changes.
     * The signal is always emitted with %WEBKIT_LOAD_STARTED when a
     * new load request is made and %WEBKIT_LOAD_FINISHED when the load
     * finishes successfully or due to an error. When the ongoing load
     * operation fails #WebKitWebView::load-failed signal is emitted
     * before #WebKitWebView::load-changed is emitted with
     * %WEBKIT_LOAD_FINISHED.
     * If a redirection is received from the server, this signal is emitted
     * with %WEBKIT_LOAD_REDIRECTED after the initial emission with
     * %WEBKIT_LOAD_STARTED and before %WEBKIT_LOAD_COMMITTED.
     * When the page content starts arriving the signal is emitted with
     * %WEBKIT_LOAD_COMMITTED event.
     *
     * You can handle this signal and use a switch to track any ongoing
     * load operation.
     *
     * ```c
     * static void web_view_load_changed (WebKitWebView  *web_view,
     *                                    WebKitLoadEvent load_event,
     *                                    gpointer        user_data)
     * {
     *     switch (load_event) {
     *     case WEBKIT_LOAD_STARTED:
     *         // New load, we have now a provisional URI
     *         provisional_uri = webkit_web_view_get_uri (web_view);
     *         // Here we could start a spinner or update the
     *         // location bar with the provisional URI
     *         break;
     *     case WEBKIT_LOAD_REDIRECTED:
     *         redirected_uri = webkit_web_view_get_uri (web_view);
     *         break;
     *     case WEBKIT_LOAD_COMMITTED:
     *         // The load is being performed. Current URI is
     *         // the final one and it won't change unless a new
     *         // load is requested or a navigation within the
     *         // same page is performed
     *         uri = webkit_web_view_get_uri (web_view);
     *         break;
     *     case WEBKIT_LOAD_FINISHED:
     *         // Load finished, we can now stop the spinner
     *         break;
     *     }
     * }
     * ```
     */
    signals[LOAD_CHANGED] =
        g_signal_new("load-changed",
                     G_TYPE_FROM_CLASS(webViewClass),
                     G_SIGNAL_RUN_LAST,
                     G_STRUCT_OFFSET(WebKitWebViewClass, load_changed),
                     0, 0,
                     g_cclosure_marshal_VOID__ENUM,
                     G_TYPE_NONE, 1,
                     WEBKIT_TYPE_LOAD_EVENT);

    /**
     * WebKitWebView::load-failed:
     * @web_view: the #WebKitWebView on which the signal is emitted
     * @load_event: the #WebKitLoadEvent of the load operation
     * @failing_uri: the URI that failed to load
     * @error: the #GError that was triggered
     *
     * Emitted when an error occurs during a load operation.
     * If the error happened when starting to load data for a page
     * @load_event will be %WEBKIT_LOAD_STARTED. If it happened while
     * loading a committed data source @load_event will be %WEBKIT_LOAD_COMMITTED.
     * Since a load error causes the load operation to finish, the signal
     * WebKitWebView::load-changed will always be emitted with
     * %WEBKIT_LOAD_FINISHED event right after this one.
     *
     * By default, if the signal is not handled, a stock error page will be displayed.
     * You need to handle the signal if you want to provide your own error page.
     *
     * Returns: %TRUE to stop other handlers from being invoked for the event.
     *    %FALSE to propagate the event further.
     */
    signals[LOAD_FAILED] =
        g_signal_new(
            "load-failed",
            G_TYPE_FROM_CLASS(webViewClass),
            G_SIGNAL_RUN_LAST,
            G_STRUCT_OFFSET(WebKitWebViewClass, load_failed),
            g_signal_accumulator_true_handled, 0,
            g_cclosure_marshal_generic,
            G_TYPE_BOOLEAN, 3,
            WEBKIT_TYPE_LOAD_EVENT,
            G_TYPE_STRING,
            G_TYPE_ERROR | G_SIGNAL_TYPE_STATIC_SCOPE);

    /**
     * WebKitWebView::load-failed-with-tls-errors:
     * @web_view: the #WebKitWebView on which the signal is emitted
     * @failing_uri: the URI that failed to load
     * @certificate: a #GTlsCertificate
     * @errors: a #GTlsCertificateFlags with the verification status of @certificate
     *
     * Emitted when a TLS error occurs during a load operation.
     * To allow an exception for this @certificate
     * and the host of @failing_uri use webkit_web_context_allow_tls_certificate_for_host().
     *
     * To handle this signal asynchronously you should call g_object_ref() on @certificate
     * and return %TRUE.
     *
     * If %FALSE is returned, #WebKitWebView::load-failed will be emitted. The load
     * will finish regardless of the returned value.
     *
     * Returns: %TRUE to stop other handlers from being invoked for the event.
     *   %FALSE to propagate the event further.
     *
     * Since: 2.6
     */
    signals[LOAD_FAILED_WITH_TLS_ERRORS] =
        g_signal_new("load-failed-with-tls-errors",
            G_TYPE_FROM_CLASS(webViewClass),
            G_SIGNAL_RUN_LAST,
            G_STRUCT_OFFSET(WebKitWebViewClass, load_failed_with_tls_errors),
            g_signal_accumulator_true_handled, 0 /* accumulator data */,
            g_cclosure_marshal_generic,
            G_TYPE_BOOLEAN, 3,
            G_TYPE_STRING,
            G_TYPE_TLS_CERTIFICATE,
            G_TYPE_TLS_CERTIFICATE_FLAGS);

    /**
     * WebKitWebView::create:
     * @web_view: the #WebKitWebView on which the signal is emitted
     * @navigation_action: a #WebKitNavigationAction
     *
     * Emitted when the creation of a new #WebKitWebView is requested.
     * If this signal is handled the signal handler should return the
     * newly created #WebKitWebView.
     *
     * The #WebKitNavigationAction parameter contains information about the
     * navigation action that triggered this signal.
     *
     * The new #WebKitWebView must be related to @web_view, see
     * #WebKitWebView:related-view for more details.
     *
     * The new #WebKitWebView should not be displayed to the user
     * until the #WebKitWebView::ready-to-show signal is emitted.
     *
     * Returns: (transfer full): a newly allocated #WebKitWebView widget
     *    or %NULL to propagate the event further.
     */
    signals[CREATE] = g_signal_new(
        "create",
        G_TYPE_FROM_CLASS(webViewClass),
        G_SIGNAL_RUN_LAST,
        G_STRUCT_OFFSET(WebKitWebViewClass, create),
        webkitWebViewAccumulatorObjectHandled, 0,
        g_cclosure_marshal_generic,
#if PLATFORM(GTK)
        GTK_TYPE_WIDGET,
#else
        WEBKIT_TYPE_WEB_VIEW,
#endif
        1,
        WEBKIT_TYPE_NAVIGATION_ACTION | G_SIGNAL_TYPE_STATIC_SCOPE);

    /**
     * WebKitWebView::ready-to-show:
     * @web_view: the #WebKitWebView on which the signal is emitted
     *
     * Emitted after #WebKitWebView::create on the newly created #WebKitWebView
     * when it should be displayed to the user. When this signal is emitted
     * all the information about how the window should look, including
     * size, position, whether the location, status and scrollbars
     * should be displayed, is already set on the #WebKitWindowProperties
     * of @web_view. See also webkit_web_view_get_window_properties().
     */
    signals[READY_TO_SHOW] =
        g_signal_new("ready-to-show",
                     G_TYPE_FROM_CLASS(webViewClass),
                     G_SIGNAL_RUN_LAST,
                     G_STRUCT_OFFSET(WebKitWebViewClass, ready_to_show),
                     0, 0,
                     g_cclosure_marshal_VOID__VOID,
                     G_TYPE_NONE, 0);

     /**
     * WebKitWebView::run-as-modal:
     * @web_view: the #WebKitWebView on which the signal is emitted
     *
     * Emitted after #WebKitWebView::ready-to-show on the newly
     * created #WebKitWebView when JavaScript code calls
     * <function>window.showModalDialog</function>. The purpose of
     * this signal is to allow the client application to prepare the
     * new view to behave as modal. Once the signal is emitted a new
     * main loop will be run to block user interaction in the parent
     * #WebKitWebView until the new dialog is closed.
     */
    signals[RUN_AS_MODAL] =
            g_signal_new("run-as-modal",
                         G_TYPE_FROM_CLASS(webViewClass),
                         G_SIGNAL_RUN_LAST,
                         G_STRUCT_OFFSET(WebKitWebViewClass, run_as_modal),
                         0, 0,
                         g_cclosure_marshal_VOID__VOID,
                         G_TYPE_NONE, 0);

    /**
     * WebKitWebView::close:
     * @web_view: the #WebKitWebView on which the signal is emitted
     *
     * Emitted when closing a #WebKitWebView is requested. This occurs when a
     * call is made from JavaScript's <function>window.close</function> function or
     * after trying to close the @web_view with webkit_web_view_try_close().
     * It is the owner's responsibility to handle this signal to hide or
     * destroy the #WebKitWebView, if necessary.
     */
    signals[CLOSE] =
        g_signal_new("close",
                     G_TYPE_FROM_CLASS(webViewClass),
                     G_SIGNAL_RUN_LAST,
                     G_STRUCT_OFFSET(WebKitWebViewClass, close),
                     0, 0,
                     g_cclosure_marshal_VOID__VOID,
                     G_TYPE_NONE, 0);

    /**
     * WebKitWebView::script-dialog:
     * @web_view: the #WebKitWebView on which the signal is emitted
     * @dialog: the #WebKitScriptDialog to show
     *
     * Emitted when JavaScript code calls <function>window.alert</function>,
     * <function>window.confirm</function> or <function>window.prompt</function>,
     * or when <function>onbeforeunload</function> event is fired.
     * The @dialog parameter should be used to build the dialog.
     * If the signal is not handled a different dialog will be built and shown depending
     * on the dialog type:
     * <itemizedlist>
     * <listitem><para>
     *  %WEBKIT_SCRIPT_DIALOG_ALERT: message dialog with a single Close button.
     * </para></listitem>
     * <listitem><para>
     *  %WEBKIT_SCRIPT_DIALOG_CONFIRM: message dialog with OK and Cancel buttons.
     * </para></listitem>
     * <listitem><para>
     *  %WEBKIT_SCRIPT_DIALOG_PROMPT: message dialog with OK and Cancel buttons and
     *  a text entry with the default text.
     * </para></listitem>
     * <listitem><para>
     *  %WEBKIT_SCRIPT_DIALOG_BEFORE_UNLOAD_CONFIRM: message dialog with Stay and Leave buttons.
     * </para></listitem>
     * </itemizedlist>
     *
     * It is possible to handle the script dialog request asynchronously, by simply
     * caling webkit_script_dialog_ref() on the @dialog argument and calling
     * webkit_script_dialog_close() when done.
     * If the last reference is removed on a #WebKitScriptDialog and the dialog has not been
     * closed, webkit_script_dialog_close() will be called.
     *
     * Returns: %TRUE to stop other handlers from being invoked for the event.
     *    %FALSE to propagate the event further.
     */
    signals[SCRIPT_DIALOG] = g_signal_new(
        "script-dialog",
        G_TYPE_FROM_CLASS(webViewClass),
        G_SIGNAL_RUN_LAST,
        G_STRUCT_OFFSET(WebKitWebViewClass, script_dialog),
        g_signal_accumulator_true_handled, nullptr,
        g_cclosure_marshal_generic,
        G_TYPE_BOOLEAN, 1,
        WEBKIT_TYPE_SCRIPT_DIALOG);

    /**
     * WebKitWebView::decide-policy:
     * @web_view: the #WebKitWebView on which the signal is emitted
     * @decision: the #WebKitPolicyDecision
     * @decision_type: a #WebKitPolicyDecisionType denoting the type of @decision
     *
     * This signal is emitted when WebKit is requesting the client to decide a policy
     * decision, such as whether to navigate to a page, open a new window or whether or
     * not to download a resource. The #WebKitNavigationPolicyDecision passed in the
     * @decision argument is a generic type, but should be casted to a more
     * specific type when making the decision. For example:
     *
     * ```c
     * static gboolean
     * decide_policy_cb (WebKitWebView *web_view,
     *                   WebKitPolicyDecision *decision,
     *                   WebKitPolicyDecisionType type)
     * {
     *     switch (type) {
     *     case WEBKIT_POLICY_DECISION_TYPE_NAVIGATION_ACTION: {
     *         WebKitNavigationPolicyDecision *navigation_decision = WEBKIT_NAVIGATION_POLICY_DECISION (decision);
     *         // Make a policy decision here
     *         break;
     *     }
     *     case WEBKIT_POLICY_DECISION_TYPE_NEW_WINDOW_ACTION: {
     *         WebKitNavigationPolicyDecision *navigation_decision = WEBKIT_NAVIGATION_POLICY_DECISION (decision);
     *         // Make a policy decision here
     *         break;
     *     }
     *     case WEBKIT_POLICY_DECISION_TYPE_RESPONSE:
     *         WebKitResponsePolicyDecision *response = WEBKIT_RESPONSE_POLICY_DECISION (decision);
     *         // Make a policy decision here
     *         break;
     *     default:
     *         // Making no decision results in webkit_policy_decision_use()
     *         return FALSE;
     *     }
     *     return TRUE;
     * }
     * ```
     *
     * It is possible to make policy decision asynchronously, by simply calling g_object_ref()
     * on the @decision argument and returning %TRUE to block the default signal handler.
     * If the last reference is removed on a #WebKitPolicyDecision and no decision has been
     * made explicitly, webkit_policy_decision_use() will be the default policy decision. The
     * default signal handler will simply call webkit_policy_decision_use(). Only the first
     * policy decision chosen for a given #WebKitPolicyDecision will have any affect.
     *
     * Returns: %TRUE to stop other handlers from being invoked for the event.
     *   %FALSE to propagate the event further.
     *
     */
    signals[DECIDE_POLICY] = g_signal_new(
        "decide-policy",
        G_TYPE_FROM_CLASS(webViewClass),
        G_SIGNAL_RUN_LAST,
        G_STRUCT_OFFSET(WebKitWebViewClass, decide_policy),
        g_signal_accumulator_true_handled, nullptr /* accumulator data */,
        g_cclosure_marshal_generic,
        G_TYPE_BOOLEAN, 2, /* number of parameters */
        WEBKIT_TYPE_POLICY_DECISION,
        WEBKIT_TYPE_POLICY_DECISION_TYPE);

    /**
     * WebKitWebView::permission-request:
     * @web_view: the #WebKitWebView on which the signal is emitted
     * @request: the #WebKitPermissionRequest
     *
     * This signal is emitted when WebKit is requesting the client to
     * decide about a permission request, such as allowing the browser
     * to switch to fullscreen mode, sharing its location or similar
     * operations.
     *
     * A possible way to use this signal could be through a dialog
     * allowing the user decide what to do with the request:
     *
     * ```c
     * static gboolean permission_request_cb (WebKitWebView *web_view,
     *                                        WebKitPermissionRequest *request,
     *                                        GtkWindow *parent_window)
     * {
     *     GtkWidget *dialog = gtk_message_dialog_new (parent_window,
     *                                                 GTK_DIALOG_MODAL,
     *                                                 GTK_MESSAGE_QUESTION,
     *                                                 GTK_BUTTONS_YES_NO,
     *                                                 "Allow Permission Request?");
     *     gtk_widget_show (dialog);
     *     gint result = gtk_dialog_run (GTK_DIALOG (dialog));
     *
     *     switch (result) {
     *     case GTK_RESPONSE_YES:
     *         webkit_permission_request_allow (request);
     *         break;
     *     default:
     *         webkit_permission_request_deny (request);
     *         break;
     *     }
     *     gtk_widget_destroy (dialog);
     *
     *     return TRUE;
     * }
     * ```
     *
     * It is possible to handle permission requests asynchronously, by
     * simply calling g_object_ref() on the @request argument and
     * returning %TRUE to block the default signal handler.  If the
     * last reference is removed on a #WebKitPermissionRequest and the
     * request has not been handled, webkit_permission_request_deny()
     * will be the default action.
     *
     * If the signal is not handled, the @request will be completed automatically
     * by the specific #WebKitPermissionRequest that could allow or deny it. Check the
     * documentation of classes implementing #WebKitPermissionRequest interface to know
     * their default action.
     *
     * Returns: %TRUE to stop other handlers from being invoked for the event.
     *   %FALSE to propagate the event further.
     *
     */
    signals[PERMISSION_REQUEST] = g_signal_new(
        "permission-request",
        G_TYPE_FROM_CLASS(webViewClass),
        G_SIGNAL_RUN_LAST,
        G_STRUCT_OFFSET(WebKitWebViewClass, permission_request),
        g_signal_accumulator_true_handled, nullptr /* accumulator data */,
        g_cclosure_marshal_generic,
        G_TYPE_BOOLEAN, 1, /* number of parameters */
        WEBKIT_TYPE_PERMISSION_REQUEST);
    /**
     * WebKitWebView::mouse-target-changed:
     * @web_view: the #WebKitWebView on which the signal is emitted
     * @hit_test_result: a #WebKitHitTestResult
     * @modifiers: a bitmask of #GdkModifierType
     *
     * This signal is emitted when the mouse cursor moves over an
     * element such as a link, image or a media element. To determine
     * what type of element the mouse cursor is over, a Hit Test is performed
     * on the current mouse coordinates and the result is passed in the
     * @hit_test_result argument. The @modifiers argument is a bitmask of
     * #GdkModifierType flags indicating the state of modifier keys.
     * The signal is emitted again when the mouse is moved out of the
     * current element with a new @hit_test_result.
     */
    signals[MOUSE_TARGET_CHANGED] = g_signal_new(
        "mouse-target-changed",
        G_TYPE_FROM_CLASS(webViewClass),
        G_SIGNAL_RUN_LAST,
        G_STRUCT_OFFSET(WebKitWebViewClass, mouse_target_changed),
        nullptr, nullptr,
        g_cclosure_marshal_generic,
        G_TYPE_NONE, 2,
        WEBKIT_TYPE_HIT_TEST_RESULT,
        G_TYPE_UINT);

#if PLATFORM(GTK)
    /**
     * WebKitWebView::print:
     * @web_view: the #WebKitWebView on which the signal is emitted
     * @print_operation: the #WebKitPrintOperation that will handle the print request
     *
     * Emitted when printing is requested on @web_view, usually by a JavaScript call,
     * before the print dialog is shown. This signal can be used to set the initial
     * print settings and page setup of @print_operation to be used as default values in
     * the print dialog. You can call webkit_print_operation_set_print_settings() and
     * webkit_print_operation_set_page_setup() and then return %FALSE to propagate the
     * event so that the print dialog is shown.
     *
     * You can connect to this signal and return %TRUE to cancel the print operation
     * or implement your own print dialog.
     *
     * Returns: %TRUE to stop other handlers from being invoked for the event.
     *    %FALSE to propagate the event further.
     */
    signals[PRINT] = g_signal_new(
        "print",
        G_TYPE_FROM_CLASS(webViewClass),
        G_SIGNAL_RUN_LAST,
        G_STRUCT_OFFSET(WebKitWebViewClass, print),
        g_signal_accumulator_true_handled, nullptr,
        g_cclosure_marshal_generic,
        G_TYPE_BOOLEAN, 1,
        WEBKIT_TYPE_PRINT_OPERATION);
#endif // PLATFORM(GTK)

    /**
     * WebKitWebView::resource-load-started:
     * @web_view: the #WebKitWebView on which the signal is emitted
     * @resource: a #WebKitWebResource
     * @request: a #WebKitURIRequest
     *
     * Emitted when a new resource is going to be loaded. The @request parameter
     * contains the #WebKitURIRequest that will be sent to the server.
     * You can monitor the load operation by connecting to the different signals
     * of @resource.
     */
    signals[RESOURCE_LOAD_STARTED] = g_signal_new(
        "resource-load-started",
        G_TYPE_FROM_CLASS(webViewClass),
        G_SIGNAL_RUN_LAST,
        G_STRUCT_OFFSET(WebKitWebViewClass, resource_load_started),
        nullptr, nullptr,
        g_cclosure_marshal_generic,
        G_TYPE_NONE, 2,
        WEBKIT_TYPE_WEB_RESOURCE,
                     WEBKIT_TYPE_URI_REQUEST);

    /**
     * WebKitWebView::enter-fullscreen:
     * @web_view: the #WebKitWebView on which the signal is emitted.
     *
     * Emitted when JavaScript code calls
     * <function>element.webkitRequestFullScreen</function>. If the
     * signal is not handled the #WebKitWebView will proceed to full screen
     * its top level window. This signal can be used by client code to
     * request permission to the user prior doing the full screen
     * transition and eventually prepare the top-level window
     * (e.g. hide some widgets that would otherwise be part of the
     * full screen window).
     *
     * Returns: %TRUE to stop other handlers from being invoked for the event.
     *    %FALSE to continue emission of the event.
     */
    signals[ENTER_FULLSCREEN] = g_signal_new(
        "enter-fullscreen",
        G_TYPE_FROM_CLASS(webViewClass),
        G_SIGNAL_RUN_LAST,
        G_STRUCT_OFFSET(WebKitWebViewClass, enter_fullscreen),
        g_signal_accumulator_true_handled, nullptr,
        g_cclosure_marshal_generic,
        G_TYPE_BOOLEAN, 0);

    /**
     * WebKitWebView::leave-fullscreen:
     * @web_view: the #WebKitWebView on which the signal is emitted.
     *
     * Emitted when the #WebKitWebView is about to restore its top level
     * window out of its full screen state. This signal can be used by
     * client code to restore widgets hidden during the
     * #WebKitWebView::enter-fullscreen stage for instance.
     *
     * Returns: %TRUE to stop other handlers from being invoked for the event.
     *    %FALSE to continue emission of the event.
     */
    signals[LEAVE_FULLSCREEN] = g_signal_new(
        "leave-fullscreen",
        G_TYPE_FROM_CLASS(webViewClass),
        G_SIGNAL_RUN_LAST,
        G_STRUCT_OFFSET(WebKitWebViewClass, leave_fullscreen),
        g_signal_accumulator_true_handled, nullptr,
        g_cclosure_marshal_generic,
        G_TYPE_BOOLEAN, 0);

     /**
     * WebKitWebView::run-file-chooser:
     * @web_view: the #WebKitWebView on which the signal is emitted
     * @request: a #WebKitFileChooserRequest
     *
     * This signal is emitted when the user interacts with a <input
     * type='file' /> HTML element, requesting from WebKit to show
     * a dialog to select one or more files to be uploaded. To let the
     * application know the details of the file chooser, as well as to
     * allow the client application to either cancel the request or
     * perform an actual selection of files, the signal will pass an
     * instance of the #WebKitFileChooserRequest in the @request
     * argument.
     *
     * The default signal handler will asynchronously run a regular
     * #GtkFileChooserDialog for the user to interact with.
     *
     * Returns: %TRUE to stop other handlers from being invoked for the event.
     *   %FALSE to propagate the event further.
     *
     */
    signals[RUN_FILE_CHOOSER] = g_signal_new(
        "run-file-chooser",
        G_TYPE_FROM_CLASS(webViewClass),
        G_SIGNAL_RUN_LAST,
        G_STRUCT_OFFSET(WebKitWebViewClass, run_file_chooser),
        g_signal_accumulator_true_handled, nullptr /* accumulator data */,
        g_cclosure_marshal_generic,
        G_TYPE_BOOLEAN, 1, /* number of parameters */
        WEBKIT_TYPE_FILE_CHOOSER_REQUEST);

    signals[CONTEXT_MENU] = createContextMenuSignal(webViewClass);

    /**
     * WebKitWebView::context-menu-dismissed:
     * @web_view: the #WebKitWebView on which the signal is emitted
     *
     * Emitted after #WebKitWebView::context-menu signal, if the context menu is shown,
     * to notify that the context menu is dismissed.
     */
    signals[CONTEXT_MENU_DISMISSED] =
        g_signal_new("context-menu-dismissed",
                     G_TYPE_FROM_CLASS(webViewClass),
                     G_SIGNAL_RUN_LAST,
                     G_STRUCT_OFFSET(WebKitWebViewClass, context_menu_dismissed),
                     0, 0,
                     g_cclosure_marshal_VOID__VOID,
                     G_TYPE_NONE, 0);

    /**
     * WebKitWebView::submit-form:
     * @web_view: the #WebKitWebView on which the signal is emitted
     * @request: a #WebKitFormSubmissionRequest
     *
     * This signal is emitted when a form is about to be submitted. The @request
     * argument passed contains information about the text fields of the form. This
     * is typically used to store login information that can be used later to
     * pre-fill the form.
     * The form will not be submitted until webkit_form_submission_request_submit() is called.
     *
     * It is possible to handle the form submission request asynchronously, by
     * simply calling g_object_ref() on the @request argument and calling
     * webkit_form_submission_request_submit() when done to continue with the form submission.
     * If the last reference is removed on a #WebKitFormSubmissionRequest and the
     * form has not been submitted, webkit_form_submission_request_submit() will be called.
     */
    signals[SUBMIT_FORM] =
        g_signal_new("submit-form",
                     G_TYPE_FROM_CLASS(webViewClass),
                     G_SIGNAL_RUN_LAST,
                     G_STRUCT_OFFSET(WebKitWebViewClass, submit_form),
                     0, 0,
                     g_cclosure_marshal_VOID__OBJECT,
                     G_TYPE_NONE, 1,
                     WEBKIT_TYPE_FORM_SUBMISSION_REQUEST);

    /**
     * WebKitWebView::insecure-content-detected:
     * @web_view: the #WebKitWebView on which the signal is emitted
     * @event: the #WebKitInsecureContentEvent
     *
     * This signal is emitted when insecure content has been detected
     * in a page loaded through a secure connection. This typically
     * means that a external resource from an unstrusted source has
     * been run or displayed, resulting in a mix of HTTPS and
     * non-HTTPS content.
     *
     * You can check the @event parameter to know exactly which kind
     * of event has been detected (see #WebKitInsecureContentEvent).
     */
    signals[INSECURE_CONTENT_DETECTED] =
        g_signal_new("insecure-content-detected",
            G_TYPE_FROM_CLASS(webViewClass),
            G_SIGNAL_RUN_LAST,
            G_STRUCT_OFFSET(WebKitWebViewClass, insecure_content_detected),
            0, 0,
            g_cclosure_marshal_VOID__ENUM,
            G_TYPE_NONE, 1,
            WEBKIT_TYPE_INSECURE_CONTENT_EVENT);

#if PLATFORM(GTK) && !USE(GTK4)
    /**
     * WebKitWebView::web-process-crashed:
     * @web_view: the #WebKitWebView
     *
     * This signal is emitted when the web process crashes.
     *
     * Returns: %TRUE to stop other handlers from being invoked for the event.
     *    %FALSE to propagate the event further.
     *
     * Deprecated: 2.20: Use WebKitWebView::web-process-terminated instead.
     */
    signals[WEB_PROCESS_CRASHED] = g_signal_new(
        "web-process-crashed",
        G_TYPE_FROM_CLASS(webViewClass),
        G_SIGNAL_RUN_LAST,
        G_STRUCT_OFFSET(WebKitWebViewClass, web_process_crashed),
        g_signal_accumulator_true_handled, nullptr,
        g_cclosure_marshal_generic,
        G_TYPE_BOOLEAN, 0);
#endif

    /**
     * WebKitWebView::web-process-terminated:
     * @web_view: the #WebKitWebView
     * @reason: the a #WebKitWebProcessTerminationReason
     *
     * This signal is emitted when the web process terminates abnormally due
     * to @reason.
     *
     * Since: 2.20
     */
    signals[WEB_PROCESS_TERMINATED] = g_signal_new(
        "web-process-terminated",
        G_TYPE_FROM_CLASS(webViewClass),
        G_SIGNAL_RUN_LAST,
        G_STRUCT_OFFSET(WebKitWebViewClass, web_process_terminated),
        0, 0,
        g_cclosure_marshal_VOID__ENUM,
        G_TYPE_NONE, 1,
        WEBKIT_TYPE_WEB_PROCESS_TERMINATION_REASON);

    /**
     * WebKitWebView::authenticate:
     * @web_view: the #WebKitWebView on which the signal is emitted
     * @request: a #WebKitAuthenticationRequest
     *
     * This signal is emitted when the user is challenged with HTTP
     * authentication. To let the  application access or supply
     * the credentials as well as to allow the client application
     * to either cancel the request or perform the authentication,
     * the signal will pass an instance of the
     * #WebKitAuthenticationRequest in the @request argument.
     * To handle this signal asynchronously you should keep a ref
     * of the request and return %TRUE. To disable HTTP authentication
     * entirely, connect to this signal and simply return %TRUE.
     *
     * The default signal handler will run a default authentication
     * dialog asynchronously for the user to interact with.
     *
     * Returns: %TRUE to stop other handlers from being invoked for the event.
     *   %FALSE to propagate the event further.
     *
     * Since: 2.2
     */
    signals[AUTHENTICATE] = g_signal_new(
        "authenticate",
        G_TYPE_FROM_CLASS(webViewClass),
        G_SIGNAL_RUN_LAST,
        G_STRUCT_OFFSET(WebKitWebViewClass, authenticate),
        g_signal_accumulator_true_handled, nullptr /* accumulator data */,
        g_cclosure_marshal_generic,
        G_TYPE_BOOLEAN, 1, /* number of parameters */
        WEBKIT_TYPE_AUTHENTICATION_REQUEST);

    /**
     * WebKitWebView::show-notification:
     * @web_view: the #WebKitWebView
     * @notification: a #WebKitNotification
     *
     * This signal is emitted when a notification should be presented to the
     * user. The @notification is kept alive until either: 1) the web page cancels it
     * or 2) a navigation happens.
     *
     * The default handler will emit a notification using libnotify, if built with
     * support for it.
     *
     * Returns: %TRUE to stop other handlers from being invoked. %FALSE otherwise.
     *
     * Since: 2.8
     */
    signals[SHOW_NOTIFICATION] = g_signal_new(
        "show-notification",
        G_TYPE_FROM_CLASS(gObjectClass),
        G_SIGNAL_RUN_LAST,
        G_STRUCT_OFFSET(WebKitWebViewClass, show_notification),
        g_signal_accumulator_true_handled, nullptr /* accumulator data */,
        g_cclosure_marshal_generic,
        G_TYPE_BOOLEAN, 1,
        WEBKIT_TYPE_NOTIFICATION);

#if PLATFORM(GTK)
     /**
      * WebKitWebView::run-color-chooser:
      * @web_view: the #WebKitWebView on which the signal is emitted
      * @request: a #WebKitColorChooserRequest
      *
      * This signal is emitted when the user interacts with a <input
      * type='color' /> HTML element, requesting from WebKit to show
      * a dialog to select a color. To let the application know the details of
      * the color chooser, as well as to allow the client application to either
      * cancel the request or perform an actual color selection, the signal will
      * pass an instance of the #WebKitColorChooserRequest in the @request
      * argument.
      *
      * It is possible to handle this request asynchronously by increasing the
      * reference count of the request.
      *
      * The default signal handler will asynchronously run a regular
      * #GtkColorChooser for the user to interact with.
      *
      * Returns: %TRUE to stop other handlers from being invoked for the event.
      *   %FALSE to propagate the event further.
      *
      * Since: 2.8
      */
    signals[RUN_COLOR_CHOOSER] = g_signal_new(
        "run-color-chooser",
        G_TYPE_FROM_CLASS(webViewClass),
        G_SIGNAL_RUN_LAST,
        G_STRUCT_OFFSET(WebKitWebViewClass, run_color_chooser),
        g_signal_accumulator_true_handled, nullptr,
        g_cclosure_marshal_generic,
        G_TYPE_BOOLEAN, 1,
        WEBKIT_TYPE_COLOR_CHOOSER_REQUEST);
#endif // PLATFORM(GTK)

    // This signal is different for WPE and GTK, so it's declared in
    // WebKitWebView[Gtk,WPE].cpp to ensure we don't break the introspection.
    signals[SHOW_OPTION_MENU] = createShowOptionMenuSignal(webViewClass);

    /**
     * WebKitWebView::user-message-received:
     * @web_view: the #WebKitWebView on which the signal is emitted
     * @message: the #WebKitUserMessage received
     *
     * This signal is emitted when a #WebKitUserMessage is received from the
     * #WebKitWebPage corresponding to @web_view. You can reply to the message
     * using webkit_user_message_send_reply().
     *
     * You can handle the user message asynchronously by calling g_object_ref() on
     * @message and returning %TRUE. If the last reference of @message is removed
     * and the message has not been replied to, the operation in the #WebKitWebPage will
     * finish with error %WEBKIT_USER_MESSAGE_UNHANDLED_MESSAGE.
     *
     * Returns: %TRUE if the message was handled, or %FALSE otherwise.
     *
     * Since: 2.28
     */
    signals[USER_MESSAGE_RECEIVED] = g_signal_new(
        "user-message-received",
        G_TYPE_FROM_CLASS(webViewClass),
        G_SIGNAL_RUN_LAST,
        G_STRUCT_OFFSET(WebKitWebViewClass, user_message_received),
        g_signal_accumulator_true_handled, nullptr,
        g_cclosure_marshal_generic,
        G_TYPE_BOOLEAN, 1,
        WEBKIT_TYPE_USER_MESSAGE);

    /**
     * WebKitWebView::query-permission-state:
     * @web_view: the #WebKitWebView on which the signal is emitted
     * @query: the #WebKitPermissionStateQuery
     *
     * This signal allows the User-Agent to respond to permission requests for powerful features, as
     * specified by the [Permissions W3C Specification](https://w3c.github.io/permissions/).
     * You can reply to the query using webkit_permission_state_query_finish().
     *
     * You can handle the query asynchronously by calling webkit_permission_state_query_ref() on
     * @query and returning %TRUE. If the last reference of @query is removed and the query has not
     * been handled, the query result will be set to %WEBKIT_QUERY_PERMISSION_PROMPT.
     *
     * Returns: %TRUE if the message was handled, or %FALSE otherwise.
     *
     * Since: 2.40
     */
    signals[QUERY_PERMISSION_STATE] = g_signal_new(
        "query-permission-state",
        G_TYPE_FROM_CLASS(webViewClass),
        G_SIGNAL_RUN_LAST,
        G_STRUCT_OFFSET(WebKitWebViewClass, query_permission_state),
        g_signal_accumulator_true_handled, nullptr /* accumulator data */,
        g_cclosure_marshal_generic,
        G_TYPE_BOOLEAN, 1, /* number of parameters */
        WEBKIT_TYPE_PERMISSION_STATE_QUERY);
}

static void webkitWebViewCompleteAuthenticationRequest(WebKitWebView* webView)
{
    WebKitWebViewPrivate* priv = webView->priv;
    if (!priv->authenticationRequest)
        return;

    if (priv->mainResource) {
        if (auto* response = webkit_web_resource_get_response(priv->mainResource.get())) {
            auto statusCode = webkit_uri_response_get_status_code(response);
            if (statusCode != SOUP_STATUS_UNAUTHORIZED && statusCode != SOUP_STATUS_PROXY_AUTHENTICATION_REQUIRED && statusCode < 500) {
                webkitAuthenticationRequestDidAuthenticate(priv->authenticationRequest.get());
                priv->authenticationRequest = nullptr;
                return;
            }
        }
    }

    webkit_authentication_request_cancel(priv->authenticationRequest.get());
    priv->authenticationRequest = nullptr;
}

void webkitWebViewCreatePage(WebKitWebView* webView, Ref<API::PageConfiguration>&& configuration)
{
#if PLATFORM(GTK)
    webkitWebViewBaseCreateWebPage(WEBKIT_WEB_VIEW_BASE(webView), WTFMove(configuration));
#elif PLATFORM(WPE)
    webView->priv->view.reset(WKWPE::View::create(webkit_web_view_backend_get_wpe_backend(webView->priv->backend.get()), configuration.get()));
#endif
}

WebPageProxy& webkitWebViewGetPage(WebKitWebView* webView)
{
    return getPage(webView);
}

void webkitWebViewWillStartLoad(WebKitWebView* webView)
{
    // Ignore the active URI changes happening before WEBKIT_LOAD_STARTED. If they are not user-initiated,
    // they could be a malicious attempt to trick users by loading an invalid URI on a trusted host, with the load
    // intended to stall, or perhaps be repeated. If we trust the URI here and display it to the user, then the user's
    // only indication that something is wrong would be a page loading indicator. If the load request is not
    // user-initiated, we must not trust it until WEBKIT_LOAD_COMMITTED. If the load is triggered by API
    // request, then the active URI is already the pending API request URL, so the blocking is harmless and the
    // client application will still see the URI update immediately. Otherwise, the URI update will be delayed a bit.
    webView->priv->isActiveURIChangeBlocked = true;

    // This is called before NavigationClient::didStartProvisionalNavigation(), the page load state hasn't been committed yet.
    auto& pageLoadState = getPage(webView).pageLoadState();
    if (pageLoadState.isFinished())
        return;

    GUniquePtr<GError> error(g_error_new_literal(WEBKIT_NETWORK_ERROR, WEBKIT_NETWORK_ERROR_CANCELLED, _("Load request cancelled")));
    webkitWebViewLoadFailed(webView, pageLoadState.isProvisional() ? WEBKIT_LOAD_STARTED : WEBKIT_LOAD_COMMITTED,
        pageLoadState.isProvisional() ? pageLoadState.provisionalURL().utf8().data() : pageLoadState.url().utf8().data(),
        error.get());
}

void webkitWebViewLoadChanged(WebKitWebView* webView, WebKitLoadEvent loadEvent)
{
    WebKitWebViewPrivate* priv = webView->priv;
    switch (loadEvent) {
    case WEBKIT_LOAD_STARTED:
#if PLATFORM(GTK)
        webkitWebViewCancelFaviconRequest(webView);
        webkitWebViewWatchForChangesInFavicon(webView);
#endif
        webkitWebViewCompleteAuthenticationRequest(webView);
        priv->mainResource = nullptr;
        webView->priv->isActiveURIChangeBlocked = false;
        break;
    case WEBKIT_LOAD_COMMITTED: {
        auto activeURL = getPage(webView).pageLoadState().activeURL().utf8();
        // Active URL is trusted now. If it's different to our active URI, due to the
        // update block before WEBKIT_LOAD_STARTED, we update it here to be in sync
        // again with the page load state.
        if (activeURL != priv->activeURI) {
            priv->activeURI = activeURL;
            g_object_notify_by_pspec(G_OBJECT(webView), sObjProperties[PROP_URI]);
        }
#if PLATFORM(GTK)
        if (auto* database = webkitWebViewGetFaviconDatabase(webView)) {
            GUniquePtr<char> faviconURI(webkit_favicon_database_get_favicon_uri(database, priv->activeURI.data()));
            webkitWebViewUpdateFaviconURI(webView, faviconURI.get());
        }
#endif
        break;
    }
    case WEBKIT_LOAD_FINISHED:
        webkitWebViewCompleteAuthenticationRequest(webView);
        break;
    default:
        break;
    }

    g_signal_emit(webView, signals[LOAD_CHANGED], 0, loadEvent);
}

void webkitWebViewLoadFailed(WebKitWebView* webView, WebKitLoadEvent loadEvent, const char* failingURI, GError *error)
{
    webkitWebViewCompleteAuthenticationRequest(webView);

    gboolean returnValue;
    g_signal_emit(webView, signals[LOAD_FAILED], 0, loadEvent, failingURI, error, &returnValue);
    g_signal_emit(webView, signals[LOAD_CHANGED], 0, WEBKIT_LOAD_FINISHED);
}

void webkitWebViewLoadFailedWithTLSErrors(WebKitWebView* webView, const char* failingURI, GError* error, GTlsCertificateFlags tlsErrors, GTlsCertificate* certificate)
{
    webkitWebViewCompleteAuthenticationRequest(webView);

#if ENABLE(2022_GLIB_API)
    WebKitTLSErrorsPolicy tlsErrorsPolicy = webkit_network_session_get_tls_errors_policy(webView->priv->networkSession.get());
#else
    auto* websiteDataManager = webkit_web_view_get_website_data_manager(webView);
    WebKitTLSErrorsPolicy tlsErrorsPolicy = webkit_website_data_manager_get_tls_errors_policy(websiteDataManager);
#endif
    if (tlsErrorsPolicy == WEBKIT_TLS_ERRORS_POLICY_FAIL) {
        gboolean returnValue;
        g_signal_emit(webView, signals[LOAD_FAILED_WITH_TLS_ERRORS], 0, failingURI, certificate, tlsErrors, &returnValue);
        if (!returnValue)
            g_signal_emit(webView, signals[LOAD_FAILED], 0, WEBKIT_LOAD_STARTED, failingURI, error, &returnValue);
    }

    g_signal_emit(webView, signals[LOAD_CHANGED], 0, WEBKIT_LOAD_FINISHED);
}

#if PLATFORM(GTK)
void webkitWebViewGetLoadDecisionForIcon(WebKitWebView* webView, const LinkIcon& icon, Function<void(bool)>&& completionHandler)
{
    // We only support favicons for now.
    if (icon.type != LinkIconType::Favicon) {
        completionHandler(false);
        return;
    }

    auto* database = webkitWebViewGetFaviconDatabase(webView);
    if (!database) {
        completionHandler(false);
        return;
    }

    webkitFaviconDatabaseGetLoadDecisionForIcon(database, icon, getPage(webView).pageLoadState().activeURL(), webkitWebViewIsEphemeral(webView), WTFMove(completionHandler));
}

void webkitWebViewSetIcon(WebKitWebView* webView, const LinkIcon& icon, API::Data& iconData)
{
    auto* database = webkitWebViewGetFaviconDatabase(webView);
    if (!database)
        return;

    webkitFaviconDatabaseSetIconForPageURL(database, icon, iconData, getPage(webView).pageLoadState().activeURL(), webkitWebViewIsEphemeral(webView));
}
#endif

RefPtr<WebPageProxy> webkitWebViewCreateNewPage(WebKitWebView* webView, const WindowFeatures& windowFeatures, WebKitNavigationAction* navigationAction)
{
    WebKitWebView* newWebView;
    g_signal_emit(webView, signals[CREATE], 0, navigationAction, &newWebView);
    if (!newWebView)
        return nullptr;

    if (&getPage(webView).process() != &getPage(newWebView).process()) {
        g_warning("WebKitWebView returned by WebKitWebView::create signal was not created with the related WebKitWebView");
        return nullptr;
    }

    webkitWindowPropertiesUpdateFromWebWindowFeatures(newWebView->priv->windowProperties.get(), windowFeatures);

    return &getPage(newWebView);
}

void webkitWebViewReadyToShowPage(WebKitWebView* webView)
{
    g_signal_emit(webView, signals[READY_TO_SHOW], 0, NULL);
}

void webkitWebViewRunAsModal(WebKitWebView* webView)
{
    g_signal_emit(webView, signals[RUN_AS_MODAL], 0, NULL);

    webView->priv->modalLoop = adoptGRef(g_main_loop_new(0, FALSE));

#if PLATFORM(GTK) && !USE(GTK4)
// This is to suppress warnings about gdk_threads_leave and gdk_threads_enter.
    ALLOW_DEPRECATED_DECLARATIONS_BEGIN
    gdk_threads_leave();
#endif

    g_main_loop_run(webView->priv->modalLoop.get());

#if PLATFORM(GTK) && !USE(GTK4)
    gdk_threads_enter();
    ALLOW_DEPRECATED_DECLARATIONS_END
#endif
}

void webkitWebViewClosePage(WebKitWebView* webView)
{
    g_signal_emit(webView, signals[CLOSE], 0, NULL);
}

void webkitWebViewRunJavaScriptAlert(WebKitWebView* webView, const CString& message, Function<void()>&& completionHandler)
{
    ASSERT(!webView->priv->currentScriptDialog);
    webView->priv->currentScriptDialog = webkitScriptDialogCreate(WEBKIT_SCRIPT_DIALOG_ALERT, message, { }, [webView, completionHandler = WTFMove(completionHandler)](bool, const String&) {
        completionHandler();
        webView->priv->currentScriptDialog = nullptr;
    });
    gboolean returnValue;
    g_signal_emit(webView, signals[SCRIPT_DIALOG], 0, webView->priv->currentScriptDialog, &returnValue);
    webkit_script_dialog_unref(webView->priv->currentScriptDialog);
}

void webkitWebViewRunJavaScriptConfirm(WebKitWebView* webView, const CString& message, Function<void(bool)>&& completionHandler)
{
    ASSERT(!webView->priv->currentScriptDialog);
    webView->priv->currentScriptDialog = webkitScriptDialogCreate(WEBKIT_SCRIPT_DIALOG_CONFIRM, message, { }, [webView, completionHandler = WTFMove(completionHandler)](bool result, const String&) {
        completionHandler(result);
        webView->priv->currentScriptDialog = nullptr;
    });
    gboolean returnValue;
    g_signal_emit(webView, signals[SCRIPT_DIALOG], 0, webView->priv->currentScriptDialog, &returnValue);
    webkit_script_dialog_unref(webView->priv->currentScriptDialog);
}

void webkitWebViewRunJavaScriptPrompt(WebKitWebView* webView, const CString& message, const CString& defaultText, Function<void(const String&)>&& completionHandler)
{
    ASSERT(!webView->priv->currentScriptDialog);
    webView->priv->currentScriptDialog = webkitScriptDialogCreate(WEBKIT_SCRIPT_DIALOG_PROMPT, message, defaultText, [webView, completionHandler = WTFMove(completionHandler)](bool, const String& result) {
        completionHandler(result);
        webView->priv->currentScriptDialog = nullptr;
    });
    gboolean returnValue;
    g_signal_emit(webView, signals[SCRIPT_DIALOG], 0, webView->priv->currentScriptDialog, &returnValue);
    webkit_script_dialog_unref(webView->priv->currentScriptDialog);
}

void webkitWebViewRunJavaScriptBeforeUnloadConfirm(WebKitWebView* webView, const CString& message, Function<void(bool)>&& completionHandler)
{
    ASSERT(!webView->priv->currentScriptDialog);
    webView->priv->currentScriptDialog = webkitScriptDialogCreate(WEBKIT_SCRIPT_DIALOG_BEFORE_UNLOAD_CONFIRM, message, { }, [webView, completionHandler = WTFMove(completionHandler)](bool result, const String&) {
        completionHandler(result);
        webView->priv->currentScriptDialog = nullptr;
    });
    gboolean returnValue;
    g_signal_emit(webView, signals[SCRIPT_DIALOG], 0, webView->priv->currentScriptDialog, &returnValue);
    webkit_script_dialog_unref(webView->priv->currentScriptDialog);
}

bool webkitWebViewIsShowingScriptDialog(WebKitWebView* webView)
{
    if (!webView->priv->currentScriptDialog)
        return false;

    // FIXME: Add API to ask the user in case default implementation is not being used.
    return webkitScriptDialogIsRunning(webView->priv->currentScriptDialog);
}

String webkitWebViewGetCurrentScriptDialogMessage(WebKitWebView* webView)
{
    if (!webView->priv->currentScriptDialog)
        return { };

    return String::fromUTF8(webView->priv->currentScriptDialog->message);
}

void webkitWebViewSetCurrentScriptDialogUserInput(WebKitWebView* webView, const String& userInput)
{
    if (!webView->priv->currentScriptDialog)
        return;

    if (webkitScriptDialogIsUserHandled(webView->priv->currentScriptDialog)) {
        // FIXME: Add API to ask the user in case default implementation is not being used.
        return;
    }

    if (webkitScriptDialogIsRunning(webView->priv->currentScriptDialog))
        webkitScriptDialogSetUserInput(webView->priv->currentScriptDialog, userInput);
}

void webkitWebViewAcceptCurrentScriptDialog(WebKitWebView* webView)
{
    if (!webView->priv->currentScriptDialog)
        return;

    if (webkitScriptDialogIsUserHandled(webView->priv->currentScriptDialog)) {
        // FIXME: Add API to ask the user in case default implementation is not being used.
        return;
    }

    if (webkitScriptDialogIsRunning(webView->priv->currentScriptDialog))
        webkitScriptDialogAccept(webView->priv->currentScriptDialog);
}

void webkitWebViewDismissCurrentScriptDialog(WebKitWebView* webView)
{
    if (!webView->priv->currentScriptDialog)
        return;

    if (webkitScriptDialogIsUserHandled(webView->priv->currentScriptDialog)) {
        // FIXME: Add API to ask the user in case default implementation is not being used.
        return;
    }

    if (webkitScriptDialogIsRunning(webView->priv->currentScriptDialog))
        webkitScriptDialogDismiss(webView->priv->currentScriptDialog);
}

std::optional<WebKitScriptDialogType> webkitWebViewGetCurrentScriptDialogType(WebKitWebView* webView)
{
    if (!webView->priv->currentScriptDialog)
        return std::nullopt;

    return static_cast<WebKitScriptDialogType>(webView->priv->currentScriptDialog->type);
}

void webkitWebViewMakePolicyDecision(WebKitWebView* webView, WebKitPolicyDecisionType type, WebKitPolicyDecision* decision)
{
    gboolean returnValue;
    g_signal_emit(webView, signals[DECIDE_POLICY], 0, decision, type, &returnValue);
}

void webkitWebViewMakePermissionRequest(WebKitWebView* webView, WebKitPermissionRequest* request)
{
    gboolean returnValue;
    g_signal_emit(webView, signals[PERMISSION_REQUEST], 0, request, &returnValue);
}

void webkitWebViewMouseTargetChanged(WebKitWebView* webView, const WebHitTestResultData& hitTestResult, OptionSet<WebEventModifier> modifiers)
{
#if PLATFORM(GTK)
    webkitWebViewBaseSetTooltipArea(WEBKIT_WEB_VIEW_BASE(webView), hitTestResult.elementBoundingBox);
    webkitWebViewBaseSetMouseIsOverScrollbar(WEBKIT_WEB_VIEW_BASE(webView), hitTestResult.isScrollbar);
#endif

    WebKitWebViewPrivate* priv = webView->priv;
    if (priv->mouseTargetHitTestResult
        && priv->mouseTargetModifiers == modifiers
        && webkitHitTestResultCompare(priv->mouseTargetHitTestResult.get(), hitTestResult))
        return;

    priv->mouseTargetModifiers = modifiers;
    priv->mouseTargetHitTestResult = adoptGRef(webkitHitTestResultCreate(hitTestResult));
    g_signal_emit(webView, signals[MOUSE_TARGET_CHANGED], 0, priv->mouseTargetHitTestResult.get(), toPlatformModifiers(modifiers));
}

#if PLATFORM(GTK)
void webkitWebViewPrintFrame(WebKitWebView* webView, WebFrameProxy* frame)
{
    auto printOperation = adoptGRef(webkit_print_operation_new(webView));
    webkitPrintOperationSetPrintMode(printOperation.get(), PrintInfo::PrintModeSync);
    gboolean returnValue;
    g_signal_emit(webView, signals[PRINT], 0, printOperation.get(), &returnValue);
    if (returnValue)
        return;

    WebKitPrintOperationResponse response = webkitPrintOperationRunDialogForFrame(printOperation.get(), 0, frame);
    if (response == WEBKIT_PRINT_OPERATION_RESPONSE_CANCEL)
        return;
    g_signal_connect(printOperation.leakRef(), "finished", G_CALLBACK(g_object_unref), 0);
}
#endif

WebKitWebResourceLoadManager* webkitWebViewGetWebResourceLoadManager(WebKitWebView* webView)
{
    return webView->priv->resourceLoadManager.get();
}

void webkitWebViewResourceLoadStarted(WebKitWebView* webView, WebKitWebResource* resource, ResourceRequest&& request)
{
    if (webkitWebResourceIsMainResource(resource))
        webView->priv->mainResource = resource;
    GRefPtr<WebKitURIRequest> uriRequest = adoptGRef(webkitURIRequestCreateForResourceRequest(request));
    g_signal_emit(webView, signals[RESOURCE_LOAD_STARTED], 0, resource, uriRequest.get());
}

void webkitWebViewEnterFullScreen(WebKitWebView* webView)
{
#if ENABLE(FULLSCREEN_API)
    gboolean returnValue;
    g_signal_emit(webView, signals[ENTER_FULLSCREEN], 0, &returnValue);
#if PLATFORM(GTK)
    if (!returnValue)
        webkitWebViewBaseEnterFullScreen(WEBKIT_WEB_VIEW_BASE(webView));
#endif
#endif
}

void webkitWebViewExitFullScreen(WebKitWebView* webView)
{
#if ENABLE(FULLSCREEN_API)
    gboolean returnValue;
    g_signal_emit(webView, signals[LEAVE_FULLSCREEN], 0, &returnValue);
#if PLATFORM(GTK)
    if (!returnValue)
        webkitWebViewBaseExitFullScreen(WEBKIT_WEB_VIEW_BASE(webView));
#endif
#endif
}

void webkitWebViewRunFileChooserRequest(WebKitWebView* webView, WebKitFileChooserRequest* request)
{
    gboolean returnValue;
    g_signal_emit(webView, signals[RUN_FILE_CHOOSER], 0, request, &returnValue);
}

#if PLATFORM(GTK)
void webkitWebViewPopulateContextMenu(WebKitWebView* webView, const Vector<WebContextMenuItemData>& proposedMenu, const WebHitTestResultData& hitTestResultData, GVariant* userData)
{
    WebKitWebViewBase* webViewBase = WEBKIT_WEB_VIEW_BASE(webView);
    WebContextMenuProxyGtk* contextMenuProxy = webkitWebViewBaseGetActiveContextMenuProxy(webViewBase);
    ASSERT(contextMenuProxy);

    GRefPtr<WebKitContextMenu> contextMenu = adoptGRef(webkitContextMenuCreate(proposedMenu));
    if (userData)
        webkit_context_menu_set_user_data(WEBKIT_CONTEXT_MENU(contextMenu.get()), userData);
    webkitContextMenuSetEvent(contextMenu.get(), webkitWebViewBaseTakeContextMenuEvent(webViewBase));

    GRefPtr<WebKitHitTestResult> hitTestResult = adoptGRef(webkitHitTestResultCreate(hitTestResultData));
    gboolean returnValue;
    g_signal_emit(webView, signals[CONTEXT_MENU], 0, contextMenu.get(),
#if !USE(GTK4)
        webkit_context_menu_get_event(contextMenu.get()),
#endif
        hitTestResult.get(), &returnValue);
    if (returnValue)
        return;

    Vector<WebContextMenuItemGlib> contextMenuItems;
    webkitContextMenuPopulate(contextMenu.get(), contextMenuItems);
    contextMenuProxy->populate(contextMenuItems);

    g_signal_connect(contextMenuProxy->gtkWidget(), WebContextMenuProxyGtk::widgetDismissedSignal, G_CALLBACK(+[](GtkWidget*, WebKitWebView* webView) {
        g_signal_emit(webView, signals[CONTEXT_MENU_DISMISSED], 0, nullptr);
    }), webView);

    // Clear the menu to make sure it's useless after signal emission.
    webkit_context_menu_remove_all(contextMenu.get());
}
#elif PLATFORM(WPE)
void webkitWebViewPopulateContextMenu(WebKitWebView* webView, const Vector<WebContextMenuItemData>& proposedMenu, const WebHitTestResultData& hitTestResultData, GVariant* userData)
{
    GRefPtr<WebKitContextMenu> contextMenu = adoptGRef(webkitContextMenuCreate(proposedMenu));
    if (userData)
        webkit_context_menu_set_user_data(WEBKIT_CONTEXT_MENU(contextMenu.get()), userData);
    GRefPtr<WebKitHitTestResult> hitTestResult = adoptGRef(webkitHitTestResultCreate(hitTestResultData));
    gboolean returnValue;
    g_signal_emit(webView, signals[CONTEXT_MENU], 0, contextMenu.get(),
#if !ENABLE(2022_GLIB_API)
        nullptr,
#endif
        hitTestResult.get(), &returnValue);
}
#endif

void webkitWebViewSubmitFormRequest(WebKitWebView* webView, WebKitFormSubmissionRequest* request)
{
    g_signal_emit(webView, signals[SUBMIT_FORM], 0, request);
}

void webkitWebViewHandleAuthenticationChallenge(WebKitWebView* webView, AuthenticationChallengeProxy* authenticationChallenge)
{
#if ENABLE(2022_GLIB_API)
    bool credentialStorageEnabled = webkit_network_session_get_persistent_credential_storage_enabled(webView->priv->networkSession.get());
#else
    auto* websiteDataManager = webkit_web_view_get_website_data_manager(webView);
    bool credentialStorageEnabled = webkit_website_data_manager_get_persistent_credential_storage_enabled(websiteDataManager);
#endif
    webView->priv->authenticationRequest = adoptGRef(webkitAuthenticationRequestCreate(authenticationChallenge, webkitWebViewIsEphemeral(webView), credentialStorageEnabled));
    gboolean returnValue;
    g_signal_emit(webView, signals[AUTHENTICATE], 0, webView->priv->authenticationRequest.get(), &returnValue);
}

void webkitWebViewInsecureContentDetected(WebKitWebView* webView, WebKitInsecureContentEvent type)
{
    g_signal_emit(webView, signals[INSECURE_CONTENT_DETECTED], 0, type);
}

bool webkitWebViewEmitShowNotification(WebKitWebView* webView, WebKitNotification* webNotification)
{
    gboolean handled;
    g_signal_emit(webView, signals[SHOW_NOTIFICATION], 0, webNotification, &handled);
    return handled;
}

#if PLATFORM(GTK)
bool webkitWebViewEmitRunColorChooser(WebKitWebView* webView, WebKitColorChooserRequest* request)
{
    gboolean handled;
    g_signal_emit(webView, signals[RUN_COLOR_CHOOSER], 0, request, &handled);
    return handled;
}
#endif

void webkitWebViewSelectionDidChange(WebKitWebView* webView)
{
    if (!webView->priv->editorState)
        return;

    webkitEditorStateChanged(webView->priv->editorState.get(), getPage(webView).editorState());
}

WebKitWebsiteDataManager* webkitWebViewGetWebsiteDataManager(WebKitWebView* webView)
{
#if ENABLE(2022_GLIB_API)
    return webkit_network_session_get_website_data_manager(webView->priv->networkSession.get());
#else
    return webView->priv->websiteDataManager.get();
#endif
}

#if PLATFORM(GTK)
bool webkitWebViewShowOptionMenu(WebKitWebView* webView, const IntRect& rect, WebKitOptionMenu* menu)
{
    GdkRectangle menuRect = rect;
    gboolean handled;
    g_signal_emit(webView, signals[SHOW_OPTION_MENU], 0, menu,
#if !USE(GTK4)
        webkit_option_menu_get_event(menu),
#endif
        &menuRect, &handled);
    return handled;
}
#endif

void webkitWebViewDidChangePageID(WebKitWebView* webView)
{
    g_object_notify_by_pspec(G_OBJECT(webView), sObjProperties[PROP_PAGE_ID]);
}

void webkitWebViewDidReceiveUserMessage(WebKitWebView* webView, UserMessage&& message, CompletionHandler<void(UserMessage&&)>&& completionHandler)
{
    // Sink the floating ref.
    GRefPtr<WebKitUserMessage> userMessage = webkitUserMessageCreate(WTFMove(message), WTFMove(completionHandler));
    gboolean returnValue;
    g_signal_emit(webView, signals[USER_MESSAGE_RECEIVED], 0, userMessage.get(), &returnValue);
}

#if ENABLE(POINTER_LOCK)
void webkitWebViewRequestPointerLock(WebKitWebView* webView)
{
#if PLATFORM(GTK)
    webkitWebViewBaseRequestPointerLock(WEBKIT_WEB_VIEW_BASE(webView));
#endif
}

void webkitWebViewDenyPointerLockRequest(WebKitWebView* webView)
{
    getPage(webView).didDenyPointerLock();
}

void webkitWebViewDidLosePointerLock(WebKitWebView* webView)
{
#if PLATFORM(GTK)
    webkitWebViewBaseDidLosePointerLock(WEBKIT_WEB_VIEW_BASE(webView));
#endif
}
#endif

static void webkitWebViewSynthesizeCompositionKeyPress(WebKitWebView* webView, const String& text, std::optional<Vector<CompositionUnderline>>&& underlines, std::optional<EditingRange>&& selectionRange)
{
#if PLATFORM(GTK)
    webkitWebViewBaseSynthesizeCompositionKeyPress(WEBKIT_WEB_VIEW_BASE(webView), text, WTFMove(underlines), WTFMove(selectionRange));
#elif PLATFORM(WPE)
    webView->priv->view->synthesizeCompositionKeyPress(text, WTFMove(underlines), WTFMove(selectionRange));
#endif
}

void webkitWebViewSetComposition(WebKitWebView* webView, const String& text, const Vector<CompositionUnderline>& underlines, EditingRange&& selectionRange)
{
    webkitWebViewSynthesizeCompositionKeyPress(webView, text, underlines, WTFMove(selectionRange));
}

void webkitWebViewConfirmComposition(WebKitWebView* webView, const String& text)
{
    webkitWebViewSynthesizeCompositionKeyPress(webView, text, std::nullopt, std::nullopt);
}

void webkitWebViewCancelComposition(WebKitWebView* webView, const String& text)
{
    getPage(webView).cancelComposition(text);
}

void webkitWebViewDeleteSurrounding(WebKitWebView* webView, int offset, unsigned characterCount)
{
    getPage(webView).deleteSurrounding(offset, characterCount);
}

#if PLATFORM(WPE)
bool webkitWebViewShowOptionMenu(WebKitWebView* webView, const IntRect& rect, WebKitOptionMenu* menu)
{
    WebKitRectangle rectangle { rect.x(), rect.y(), rect.width(), rect.height() };

    gboolean handled;
    g_signal_emit(webView, signals[SHOW_OPTION_MENU], 0, menu, &rectangle, &handled);
    return handled;
}
#endif

void webkitWebViewPermissionStateQuery(WebKitWebView* webView, WebKitPermissionStateQuery* query)
{
    gboolean result;
    g_signal_emit(webView, signals[QUERY_PERMISSION_STATE], 0, query, &result);
}

#if PLATFORM(WPE)
/**
 * webkit_web_view_get_backend:
 * @web_view: a #WebKitWebView
 *
 * Get the #WebKitWebViewBackend of @web_view
 *
 * Returns: (transfer none): the #WebKitWebViewBackend of @web_view
 *
 * Since: 2.20
 */
WebKitWebViewBackend* webkit_web_view_get_backend(WebKitWebView* webView)
{
    g_return_val_if_fail(WEBKIT_IS_WEB_VIEW(webView), nullptr);

    return webView->priv->backend.get();
}
#endif

/**
 * webkit_web_view_get_context:
 * @web_view: a #WebKitWebView
 *
 * Gets the web context of @web_view.
 *
 * Returns: (transfer none): the #WebKitWebContext of the view
 */
WebKitWebContext* webkit_web_view_get_context(WebKitWebView *webView)
{
    g_return_val_if_fail(WEBKIT_IS_WEB_VIEW(webView), 0);

    return webView->priv->context.get();
}

/**
 * webkit_web_view_get_user_content_manager:
 * @web_view: a #WebKitWebView
 *
 * Gets the user content manager associated to @web_view.
 *
 * Returns: (transfer none): the #WebKitUserContentManager associated with the view
 *
 * Since: 2.6
 */
WebKitUserContentManager* webkit_web_view_get_user_content_manager(WebKitWebView* webView)
{
    g_return_val_if_fail(WEBKIT_IS_WEB_VIEW(webView), nullptr);

    return webView->priv->userContentManager.get();
}

#if !ENABLE(2022_GLIB_API)
/**
 * webkit_web_view_is_ephemeral:
 * @web_view: a #WebKitWebView
 *
 * Get whether a #WebKitWebView is ephemeral.
 *
 * To create an ephemeral #WebKitWebView you need to
 * use g_object_new() and pass is-ephemeral property with %TRUE value. See
 * #WebKitWebView:is-ephemeral for more details.
 * If @web_view was created with a ephemeral #WebKitWebView:related-view or an
 * ephemeral #WebKitWebView:web-context it will also be ephemeral.
 *
 * Returns: %TRUE if @web_view is ephemeral or %FALSE otherwise.
 *
 * Since: 2.16
 */
gboolean webkit_web_view_is_ephemeral(WebKitWebView* webView)
{
    g_return_val_if_fail(WEBKIT_IS_WEB_VIEW(webView), FALSE);

    return webView->priv->isEphemeral;
}
#endif

/**
 * webkit_web_view_is_controlled_by_automation:
 * @web_view: a #WebKitWebView
 *
 * Get whether a #WebKitWebView was created with #WebKitWebView:is-controlled-by-automation
 * property enabled.
 *
 * Only #WebKitWebView<!-- -->s controlled by automation can be used in an
 * automation session.
 *
 * Returns: %TRUE if @web_view is controlled by automation, or %FALSE otherwise.
 *
 * Since: 2.18
 */
gboolean webkit_web_view_is_controlled_by_automation(WebKitWebView* webView)
{
    g_return_val_if_fail(WEBKIT_IS_WEB_VIEW(webView), FALSE);

    return webView->priv->isControlledByAutomation;
}

/**
 * webkit_web_view_get_automation_presentation_type:
 * @web_view: a #WebKitWebView
 *
 * Get the presentation type of #WebKitWebView when created for automation.
 *
 * Returns: a #WebKitAutomationBrowsingContextPresentation.
 *
 * Since: 2.28
 */
WebKitAutomationBrowsingContextPresentation webkit_web_view_get_automation_presentation_type(WebKitWebView* webView)
{
    g_return_val_if_fail(WEBKIT_IS_WEB_VIEW(webView), WEBKIT_AUTOMATION_BROWSING_CONTEXT_PRESENTATION_WINDOW);

    return webView->priv->automationPresentationType;
}

#if ENABLE(2022_GLIB_API)
/**
 * webkit_web_view_get_network_session:
 * @web_view: a #WebKitWebView
 *
 * Get the #WebKitNetworkSession associated to @web_view.
 *
 * Returns: (transfer none): a #WebKitNetworkSession
 *
 * Since: 2.40
 */
WebKitNetworkSession* webkit_web_view_get_network_session(WebKitWebView* webView)
{
    g_return_val_if_fail(WEBKIT_IS_WEB_VIEW(webView), nullptr);

    return webView->priv->networkSession.get();
}
#else
/**
 * webkit_web_view_get_website_data_manager:
 * @web_view: a #WebKitWebView
 *
 * Get the #WebKitWebsiteDataManager associated to @web_view.
 *
 * If @web_view is not ephemeral,
 * the returned #WebKitWebsiteDataManager will be the same as the #WebKitWebsiteDataManager
 * of @web_view's #WebKitWebContext.
 *
 * Returns: (transfer none): a #WebKitWebsiteDataManager
 *
 * Since: 2.16
 */
WebKitWebsiteDataManager* webkit_web_view_get_website_data_manager(WebKitWebView* webView)
{
    g_return_val_if_fail(WEBKIT_IS_WEB_VIEW(webView), nullptr);

    if (webView->priv->websiteDataManager)
        return webView->priv->websiteDataManager.get();

    return webkit_web_context_get_website_data_manager(webView->priv->context.get());
}
#endif

/**
 * webkit_web_view_try_close:
 * @web_view: a #WebKitWebView
 *
 * Tries to close the @web_view.
 *
 * This will fire the onbeforeunload event
 * to ask the user for confirmation to close the page. If there isn't an
 * onbeforeunload event handler or the user confirms to close the page,
 * the #WebKitWebView::close signal is emitted, otherwise nothing happens.
 *
 * Since: 2.12
 */
void webkit_web_view_try_close(WebKitWebView *webView)
{
    g_return_if_fail(WEBKIT_IS_WEB_VIEW(webView));
    if (getPage(webView).tryClose())
        webkitWebViewClosePage(webView);
}

/**
 * webkit_web_view_load_uri:
 * @web_view: a #WebKitWebView
 * @uri: an URI string
 *
 * Requests loading of the specified URI string.
 *
 * You can monitor the load operation by connecting to
 * #WebKitWebView::load-changed signal.
 */
void webkit_web_view_load_uri(WebKitWebView* webView, const gchar* uri)
{
    g_return_if_fail(WEBKIT_IS_WEB_VIEW(webView));
    g_return_if_fail(uri);

    getPage(webView).loadRequest(URL({ }, String::fromUTF8(uri)));
}

/**
 * webkit_web_view_load_html:
 * @web_view: a #WebKitWebView
 * @content: The HTML string to load
 * @base_uri: (allow-none): The base URI for relative locations or %NULL
 *
 * Load the given @content string with the specified @base_uri.
 *
 * If @base_uri is not %NULL, relative URLs in the @content will be
 * resolved against @base_uri and absolute local paths must be children of the @base_uri.
 * For security reasons absolute local paths that are not children of @base_uri
 * will cause the web process to terminate.
 * If you need to include URLs in @content that are local paths in a different
 * directory than @base_uri you can build a data URI for them. When @base_uri is %NULL,
 * it defaults to "about:blank". The mime type of the document will be "text/html".
 * You can monitor the load operation by connecting to #WebKitWebView::load-changed signal.
 */
void webkit_web_view_load_html(WebKitWebView* webView, const gchar* content, const gchar* baseURI)
{
    g_return_if_fail(WEBKIT_IS_WEB_VIEW(webView));
    g_return_if_fail(content);

    getPage(webView).loadData({ reinterpret_cast<const uint8_t*>(content), content ? strlen(content) : 0 }, "text/html"_s, "UTF-8"_s, String::fromUTF8(baseURI));
}

/**
 * webkit_web_view_load_alternate_html:
 * @web_view: a #WebKitWebView
 * @content: the new content to display as the main page of the @web_view
 * @content_uri: the URI for the alternate page content
 * @base_uri: (allow-none): the base URI for relative locations or %NULL
 *
 * Load the given @content string for the URI @content_uri.
 *
 * This allows clients to display page-loading errors in the #WebKitWebView itself.
 * When this method is called from #WebKitWebView::load-failed signal to show an
 * error page, then the back-forward list is maintained appropriately.
 * For everything else this method works the same way as webkit_web_view_load_html().
 */
void webkit_web_view_load_alternate_html(WebKitWebView* webView, const gchar* content, const gchar* contentURI, const gchar* baseURI)
{
    g_return_if_fail(WEBKIT_IS_WEB_VIEW(webView));
    g_return_if_fail(content);
    g_return_if_fail(contentURI);

    getPage(webView).loadAlternateHTML(WebCore::DataSegment::create(Vector<uint8_t>(reinterpret_cast<const uint8_t*>(content), content ? strlen(content) : 0)), "UTF-8"_s, URL { String::fromUTF8(baseURI) }, URL { String::fromUTF8(contentURI) });
}

/**
 * webkit_web_view_load_plain_text:
 * @web_view: a #WebKitWebView
 * @plain_text: The plain text to load
 *
 * Load the specified @plain_text string into @web_view.
 *
 * The mime type of document will be "text/plain". You can monitor the load
 * operation by connecting to #WebKitWebView::load-changed signal.
 */
void webkit_web_view_load_plain_text(WebKitWebView* webView, const gchar* plainText)
{
    g_return_if_fail(WEBKIT_IS_WEB_VIEW(webView));
    g_return_if_fail(plainText);

    getPage(webView).loadData({ reinterpret_cast<const uint8_t*>(plainText), plainText ? strlen(plainText) : 0 }, "text/plain"_s, "UTF-8"_s, aboutBlankURL().string());
}

/**
 * webkit_web_view_load_bytes:
 * @web_view: a #WebKitWebView
 * @bytes: input data to load
 * @mime_type: (allow-none): the MIME type of @bytes, or %NULL
 * @encoding: (allow-none): the character encoding of @bytes, or %NULL
 * @base_uri: (allow-none): the base URI for relative locations or %NULL
 *
 * Load the specified @bytes into @web_view using the given @mime_type and @encoding.
 *
 * When @mime_type is %NULL, it defaults to "text/html".
 * When @encoding is %NULL, it defaults to "UTF-8".
 * When @base_uri is %NULL, it defaults to "about:blank".
 * You can monitor the load operation by connecting to #WebKitWebView::load-changed signal.
 *
 * Since: 2.6
 */
void webkit_web_view_load_bytes(WebKitWebView* webView, GBytes* bytes, const char* mimeType, const char* encoding, const char* baseURI)
{
    g_return_if_fail(WEBKIT_IS_WEB_VIEW(webView));
    g_return_if_fail(bytes);

    gsize bytesDataSize;
    gconstpointer bytesData = g_bytes_get_data(bytes, &bytesDataSize);
    g_return_if_fail(bytesDataSize);

    getPage(webView).loadData({ reinterpret_cast<const uint8_t*>(bytesData), bytesDataSize }, mimeType ? String::fromUTF8(mimeType) : String::fromUTF8("text/html"),
        encoding ? String::fromUTF8(encoding) : String::fromUTF8("UTF-8"), String::fromUTF8(baseURI));
}

/**
 * webkit_web_view_load_request:
 * @web_view: a #WebKitWebView
 * @request: a #WebKitURIRequest to load
 *
 * Requests loading of the specified #WebKitURIRequest.
 *
 * You can monitor the load operation by connecting to
 * #WebKitWebView::load-changed signal.
 */
void webkit_web_view_load_request(WebKitWebView* webView, WebKitURIRequest* request)
{
    g_return_if_fail(WEBKIT_IS_WEB_VIEW(webView));
    g_return_if_fail(WEBKIT_IS_URI_REQUEST(request));

    ResourceRequest resourceRequest;
    webkitURIRequestGetResourceRequest(request, resourceRequest);
    getPage(webView).loadRequest(WTFMove(resourceRequest));
}

/**
 * webkit_web_view_get_page_id:
 * @web_view: a #WebKitWebView
 *
 * Get the identifier of the #WebKitWebPage corresponding to
 * the #WebKitWebView
 *
 * Returns: the page ID of @web_view.
 */
guint64 webkit_web_view_get_page_id(WebKitWebView* webView)
{
    g_return_val_if_fail(WEBKIT_IS_WEB_VIEW(webView), 0);

    return getPage(webView).webPageID().toUInt64();
}

/**
 * webkit_web_view_get_title:
 * @web_view: a #WebKitWebView
 *
 * Gets the value of the #WebKitWebView:title property.
 *
 * You can connect to notify::title signal of @web_view to
 * be notified when the title has been received.
 *
 * Returns: The main frame document title of @web_view.
 */
const gchar* webkit_web_view_get_title(WebKitWebView* webView)
{
    g_return_val_if_fail(WEBKIT_IS_WEB_VIEW(webView), 0);

    return webView->priv->title.data();
}

/**
 * webkit_web_view_reload:
 * @web_view: a #WebKitWebView
 *
 * Reloads the current contents of @web_view.
 *
 * See also webkit_web_view_reload_bypass_cache().
 */
void webkit_web_view_reload(WebKitWebView* webView)
{
    g_return_if_fail(WEBKIT_IS_WEB_VIEW(webView));

    getPage(webView).reload({ });
}

/**
 * webkit_web_view_reload_bypass_cache:
 * @web_view: a #WebKitWebView
 *
 * Reloads the current contents of @web_view without
 * using any cached data.
 */
void webkit_web_view_reload_bypass_cache(WebKitWebView* webView)
{
    g_return_if_fail(WEBKIT_IS_WEB_VIEW(webView));

    getPage(webView).reload(ReloadOption::FromOrigin);
}

/**
 * webkit_web_view_stop_loading:
 * @web_view: a #WebKitWebView
 *
 * Stops any ongoing loading operation in @web_view.
 *
 * This method does nothing if no content is being loaded.
 * If there is a loading operation in progress, it will be cancelled and
 * #WebKitWebView::load-failed signal will be emitted with
 * %WEBKIT_NETWORK_ERROR_CANCELLED error.
 */
void webkit_web_view_stop_loading(WebKitWebView* webView)
{
    g_return_if_fail(WEBKIT_IS_WEB_VIEW(webView));

    getPage(webView).stopLoading();
}

/**
 * webkit_web_view_is_loading:
 * @web_view: a #WebKitWebView
 *
 * Gets the value of the #WebKitWebView:is-loading property.
 *
 * You can monitor when a #WebKitWebView is loading a page by connecting to
 * notify::is-loading signal of @web_view. This is useful when you are
 * interesting in knowing when the view is loading something but not in the
 * details about the status of the load operation, for example to start a spinner
 * when the view is loading a page and stop it when it finishes.
 *
 * Returns: %TRUE if @web_view is loading a page or %FALSE otherwise.
 */
gboolean webkit_web_view_is_loading(WebKitWebView* webView)
{
    g_return_val_if_fail(WEBKIT_IS_WEB_VIEW(webView), FALSE);

    return webView->priv->isLoading;
}

/**
 * webkit_web_view_is_playing_audio:
 * @web_view: a #WebKitWebView
 *
 * Gets the value of the #WebKitWebView:is-playing-audio property.
 *
 * You can monitor when a page in a #WebKitWebView is playing audio by
 * connecting to the notify::is-playing-audio signal of @web_view. This
 * is useful when the application wants to provide visual feedback when a
 * page is producing sound.
 *
 * Returns: %TRUE if a page in @web_view is playing audio or %FALSE otherwise.
 *
 * Since: 2.8
 */
gboolean webkit_web_view_is_playing_audio(WebKitWebView* webView)
{
    g_return_val_if_fail(WEBKIT_IS_WEB_VIEW(webView), FALSE);

    return getPage(webView).isPlayingAudio();
}

/**
 * webkit_web_view_set_is_muted:
 * @web_view: a #WebKitWebView
 * @muted: mute flag
 *
 * Sets the mute state of @web_view.
 *
 * Since: 2.30
 */
void webkit_web_view_set_is_muted(WebKitWebView* webView, gboolean muted)
{
    g_return_if_fail(WEBKIT_IS_WEB_VIEW(webView));

    if (webkit_web_view_get_is_muted (webView) == muted)
        return;

    WebCore::MediaProducer::MutedStateFlags audioMutedFlag;
    if (muted)
        audioMutedFlag.add(WebCore::MediaProducer::MutedState::AudioIsMuted);
    getPage(webView).setMuted(audioMutedFlag);
    g_object_notify_by_pspec(G_OBJECT(webView), sObjProperties[PROP_IS_MUTED]);
}

/**
 * webkit_web_view_get_is_muted:
 * @web_view: a #WebKitWebView
 *
 * Gets the mute state of @web_view.
 *
 * Returns: %TRUE if @web_view audio is muted or %FALSE is audio is not muted.
 *
 * Since: 2.30
 */
gboolean webkit_web_view_get_is_muted(WebKitWebView* webView)
{
    g_return_val_if_fail(WEBKIT_IS_WEB_VIEW(webView), FALSE);

    return getPage(webView).isAudioMuted();
}

/**
 * webkit_web_view_go_back:
 * @web_view: a #WebKitWebView
 *
 * Loads the previous history item.
 *
 * You can monitor the load operation by connecting to
 * #WebKitWebView::load-changed signal.
 */
void webkit_web_view_go_back(WebKitWebView* webView)
{
    g_return_if_fail(WEBKIT_IS_WEB_VIEW(webView));

    getPage(webView).goBack();
}

/**
 * webkit_web_view_can_go_back:
 * @web_view: a #WebKitWebView
 *
 * Determines whether @web_view has a previous history item.
 *
 * Returns: %TRUE if able to move back or %FALSE otherwise.
 */
gboolean webkit_web_view_can_go_back(WebKitWebView* webView)
{
    g_return_val_if_fail(WEBKIT_IS_WEB_VIEW(webView), FALSE);

    return !!getPage(webView).backForwardList().backItem();
}

/**
 * webkit_web_view_go_forward:
 * @web_view: a #WebKitWebView
 *
 * Loads the next history item.
 *
 * You can monitor the load operation by connecting to
 * #WebKitWebView::load-changed signal.
 */
void webkit_web_view_go_forward(WebKitWebView* webView)
{
    g_return_if_fail(WEBKIT_IS_WEB_VIEW(webView));

    getPage(webView).goForward();
}

/**
 * webkit_web_view_can_go_forward:
 * @web_view: a #WebKitWebView
 *
 * Determines whether @web_view has a next history item.
 *
 * Returns: %TRUE if able to move forward or %FALSE otherwise.
 */
gboolean webkit_web_view_can_go_forward(WebKitWebView* webView)
{
    g_return_val_if_fail(WEBKIT_IS_WEB_VIEW(webView), FALSE);

    return !!getPage(webView).backForwardList().forwardItem();
}

/**
 * webkit_web_view_get_uri:
 * @web_view: a #WebKitWebView
 *
 * Returns the current active URI of @web_view.
 *
 * The active URI might change during
 * a load operation:
 *
 * <orderedlist>
 * <listitem><para>
 *   When nothing has been loaded yet on @web_view the active URI is %NULL.
 * </para></listitem>
 * <listitem><para>
 *   When a new load operation starts the active URI is the requested URI:
 *   <itemizedlist>
 *   <listitem><para>
 *     If the load operation was started by webkit_web_view_load_uri(),
 *     the requested URI is the given one.
 *   </para></listitem>
 *   <listitem><para>
 *     If the load operation was started by webkit_web_view_load_html(),
 *     the requested URI is "about:blank".
 *   </para></listitem>
 *   <listitem><para>
 *     If the load operation was started by webkit_web_view_load_alternate_html(),
 *     the requested URI is content URI provided.
 *   </para></listitem>
 *   <listitem><para>
 *     If the load operation was started by webkit_web_view_go_back() or
 *     webkit_web_view_go_forward(), the requested URI is the original URI
 *     of the previous/next item in the #WebKitBackForwardList of @web_view.
 *   </para></listitem>
 *   <listitem><para>
 *     If the load operation was started by
 *     webkit_web_view_go_to_back_forward_list_item(), the requested URI
 *     is the opriginal URI of the given #WebKitBackForwardListItem.
 *   </para></listitem>
 *   </itemizedlist>
 * </para></listitem>
 * <listitem><para>
 *   If there is a server redirection during the load operation,
 *   the active URI is the redirected URI. When the signal
 *   #WebKitWebView::load-changed is emitted with %WEBKIT_LOAD_REDIRECTED
 *   event, the active URI is already updated to the redirected URI.
 * </para></listitem>
 * <listitem><para>
 *   When the signal #WebKitWebView::load-changed is emitted
 *   with %WEBKIT_LOAD_COMMITTED event, the active URI is the final
 *   one and it will not change unless a new load operation is started
 *   or a navigation action within the same page is performed.
 * </para></listitem>
 * </orderedlist>
 *
 * You can monitor the active URI by connecting to the notify::uri
 * signal of @web_view.
 *
 * Returns: the current active URI of @web_view or %NULL
 *    if nothing has been loaded yet.
 */
const gchar* webkit_web_view_get_uri(WebKitWebView* webView)
{
    g_return_val_if_fail(WEBKIT_IS_WEB_VIEW(webView), 0);

    return webView->priv->activeURI.data();
}

#if PLATFORM(GTK)
/**
 * webkit_web_view_get_favicon:
 * @web_view: a #WebKitWebView
 *
 * Returns favicon currently associated to @web_view.
 *
 * Returns favicon currently associated to @web_view, if any. You can
 * connect to notify::favicon signal of @web_view to be notified when
 * the favicon is available.
 *
 * Returns: (transfer none): the favicon image or %NULL if there's no
 *    icon associated with @web_view.
 */
#if USE(GTK4)
GdkTexture* webkit_web_view_get_favicon(WebKitWebView* webView)
#else
cairo_surface_t* webkit_web_view_get_favicon(WebKitWebView* webView)
#endif
{
    g_return_val_if_fail(WEBKIT_IS_WEB_VIEW(webView), 0);
    if (webView->priv->activeURI.isNull())
        return 0;

    return webView->priv->favicon.get();
}
#endif

/**
 * webkit_web_view_get_custom_charset:
 * @web_view: a #WebKitWebView
 *
 * Returns the current custom character encoding name of @web_view.
 *
 * Returns: the current custom character encoding name or %NULL if no
 *    custom character encoding has been set.
 */
const gchar* webkit_web_view_get_custom_charset(WebKitWebView* webView)
{
    g_return_val_if_fail(WEBKIT_IS_WEB_VIEW(webView), 0);

    String customTextEncoding = getPage(webView).customTextEncodingName();
    if (customTextEncoding.isEmpty())
        return 0;

    webView->priv->customTextEncoding = customTextEncoding.utf8();
    return webView->priv->customTextEncoding.data();
}

/**
 * webkit_web_view_set_custom_charset:
 * @web_view: a #WebKitWebView
 * @charset: (allow-none): a character encoding name or %NULL
 *
 * Sets the current custom character encoding override of @web_view.
 *
 * The custom character encoding will override any text encoding detected via HTTP headers or
 * META tags. Calling this method will stop any current load operation and reload the
 * current page. Setting the custom character encoding to %NULL removes the character
 * encoding override.
 */
void webkit_web_view_set_custom_charset(WebKitWebView* webView, const gchar* charset)
{
    g_return_if_fail(WEBKIT_IS_WEB_VIEW(webView));

    getPage(webView).setCustomTextEncodingName(String::fromUTF8(charset));
}

/**
 * webkit_web_view_get_estimated_load_progress:
 * @web_view: a #WebKitWebView
 *
 * Gets the value of the #WebKitWebView:estimated-load-progress property.
 *
 * You can monitor the estimated progress of a load operation by
 * connecting to the notify::estimated-load-progress signal of @web_view.
 *
 * Returns: an estimate of the of the percent complete for a document
 *     load as a range from 0.0 to 1.0.
 */
gdouble webkit_web_view_get_estimated_load_progress(WebKitWebView* webView)
{
    g_return_val_if_fail(WEBKIT_IS_WEB_VIEW(webView), 0);
    return getPage(webView).pageLoadState().estimatedProgress();
}

/**
 * webkit_web_view_get_back_forward_list:
 * @web_view: a #WebKitWebView
 *
 * Obtains the #WebKitBackForwardList associated with the given #WebKitWebView.
 *
 * The #WebKitBackForwardList is owned by the #WebKitWebView.
 *
 * Returns: (transfer none): the #WebKitBackForwardList
 */
WebKitBackForwardList* webkit_web_view_get_back_forward_list(WebKitWebView* webView)
{
    g_return_val_if_fail(WEBKIT_IS_WEB_VIEW(webView), 0);

    return webView->priv->backForwardList.get();
}

/**
 * webkit_web_view_go_to_back_forward_list_item:
 * @web_view: a #WebKitWebView
 * @list_item: a #WebKitBackForwardListItem
 *
 * Loads the specific history item @list_item.
 *
 * You can monitor the load operation by connecting to
 * #WebKitWebView::load-changed signal.
 */
void webkit_web_view_go_to_back_forward_list_item(WebKitWebView* webView, WebKitBackForwardListItem* listItem)
{
    g_return_if_fail(WEBKIT_IS_WEB_VIEW(webView));
    g_return_if_fail(WEBKIT_IS_BACK_FORWARD_LIST_ITEM(listItem));

    getPage(webView).goToBackForwardItem(*webkitBackForwardListItemGetItem(listItem));
}

/**
 * webkit_web_view_set_settings:
 * @web_view: a #WebKitWebView
 * @settings: a #WebKitSettings
 *
 * Sets the #WebKitSettings to be applied to @web_view.
 *
 * The
 * existing #WebKitSettings of @web_view will be replaced by
 * @settings. New settings are applied immediately on @web_view.
 * The same #WebKitSettings object can be shared
 * by multiple #WebKitWebView<!-- -->s.
 */
void webkit_web_view_set_settings(WebKitWebView* webView, WebKitSettings* settings)
{
    g_return_if_fail(WEBKIT_IS_WEB_VIEW(webView));
    g_return_if_fail(WEBKIT_IS_SETTINGS(settings));

    if (webView->priv->settings == settings)
        return;

    // The "settings" property is set on construction, and in that
    // case webkit_web_view_set_settings() will be called *before*
    // any settings have been assigned. In that case there are no
    // signal handlers to disconnect.
    if (webView->priv->settings)
        webkitWebViewDisconnectSettingsSignalHandlers(webView);

    webView->priv->settings = settings;
    webkitWebViewUpdateSettings(webView);
    g_object_notify_by_pspec(G_OBJECT(webView), sObjProperties[PROP_SETTINGS]);
}

/**
 * webkit_web_view_get_settings:
 * @web_view: a #WebKitWebView
 *
 * Gets the #WebKitSettings currently applied to @web_view.
 *
 * If no other #WebKitSettings have been explicitly applied to
 * @web_view with webkit_web_view_set_settings(), the default
 * #WebKitSettings will be returned. This method always returns
 * a valid #WebKitSettings object.
 * To modify any of the @web_view settings, you can either create
 * a new #WebKitSettings object with webkit_settings_new(), setting
 * the desired preferences, and then replace the existing @web_view
 * settings with webkit_web_view_set_settings() or get the existing
 * @web_view settings and update it directly. #WebKitSettings objects
 * can be shared by multiple #WebKitWebView<!-- -->s, so modifying
 * the settings of a #WebKitWebView would affect other
 * #WebKitWebView<!-- -->s using the same #WebKitSettings.
 *
 * Returns: (transfer none): the #WebKitSettings attached to @web_view
 */
WebKitSettings* webkit_web_view_get_settings(WebKitWebView* webView)
{
    g_return_val_if_fail(WEBKIT_IS_WEB_VIEW(webView), nullptr);
    return webView->priv->settings.get();
}

/**
 * webkit_web_view_get_window_properties:
 * @web_view: a #WebKitWebView
 *
 * Get the #WebKitWindowProperties object.
 *
 * Get the #WebKitWindowProperties object containing the properties
 * that the window containing @web_view should have.
 *
 * Returns: (transfer none): the #WebKitWindowProperties of @web_view
 */
WebKitWindowProperties* webkit_web_view_get_window_properties(WebKitWebView* webView)
{
    g_return_val_if_fail(WEBKIT_IS_WEB_VIEW(webView), 0);

    return webView->priv->windowProperties.get();
}

/**
 * webkit_web_view_set_zoom_level:
 * @web_view: a #WebKitWebView
 * @zoom_level: the zoom level
 *
 * Set the zoom level of @web_view.
 *
 * Set the zoom level of @web_view, i.e. the factor by which the
 * view contents are scaled with respect to their original size.
 */
void webkit_web_view_set_zoom_level(WebKitWebView* webView, gdouble zoomLevel)
{
    g_return_if_fail(WEBKIT_IS_WEB_VIEW(webView));

    if (webkit_web_view_get_zoom_level(webView) == zoomLevel)
        return;

    auto& page = getPage(webView);
    if (webkit_settings_get_zoom_text_only(webView->priv->settings.get()))
        page.setTextZoomFactor(zoomLevel * webView->priv->textScaleFactor);
    else
        page.setPageZoomFactor(zoomLevel);
    g_object_notify_by_pspec(G_OBJECT(webView), sObjProperties[PROP_ZOOM_LEVEL]);
}

/**
 * webkit_web_view_get_zoom_level:
 * @web_view: a #WebKitWebView
 *
 * Set the zoom level of @web_view.
 *
 * Get the zoom level of @web_view, i.e. the factor by which the
 * view contents are scaled with respect to their original size.
 *
 * Returns: the current zoom level of @web_view
 */
gdouble webkit_web_view_get_zoom_level(WebKitWebView* webView)
{
    g_return_val_if_fail(WEBKIT_IS_WEB_VIEW(webView), 1);

    auto& page = getPage(webView);
    gboolean zoomTextOnly = webkit_settings_get_zoom_text_only(webView->priv->settings.get());
    return zoomTextOnly ? page.textZoomFactor() / webView->priv->textScaleFactor : page.pageZoomFactor();
}

/**
 * webkit_web_view_can_execute_editing_command:
 * @web_view: a #WebKitWebView
 * @command: the command to check
 * @cancellable: (allow-none): a #GCancellable or %NULL to ignore
 * @callback: (scope async): a #GAsyncReadyCallback to call when the request is satisfied
 * @user_data: the data to pass to callback function
 *
 * Asynchronously check if it is possible to execute the given editing command.
 *
 * When the operation is finished, @callback will be called. You can then call
 * webkit_web_view_can_execute_editing_command_finish() to get the result of the operation.
 */
void webkit_web_view_can_execute_editing_command(WebKitWebView* webView, const char* command, GCancellable* cancellable, GAsyncReadyCallback callback, gpointer userData)
{
    g_return_if_fail(WEBKIT_IS_WEB_VIEW(webView));
    g_return_if_fail(command);

    GRefPtr<GTask> task = adoptGRef(g_task_new(webView, cancellable, callback, userData));
    getPage(webView).validateCommand(String::fromUTF8(command), [task = WTFMove(task)](bool isEnabled, int32_t) {
        g_task_return_boolean(task.get(), isEnabled);
    });
}

/**
 * webkit_web_view_can_execute_editing_command_finish:
 * @web_view: a #WebKitWebView
 * @result: a #GAsyncResult
 * @error: return location for error or %NULL to ignore
 *
 * Finish an asynchronous operation started with webkit_web_view_can_execute_editing_command().
 *
 * Returns: %TRUE if the editing command can be executed or %FALSE otherwise
 */
gboolean webkit_web_view_can_execute_editing_command_finish(WebKitWebView* webView, GAsyncResult* result, GError** error)
{
    g_return_val_if_fail(WEBKIT_IS_WEB_VIEW(webView), FALSE);
    g_return_val_if_fail(g_task_is_valid(result, webView), FALSE);

    return g_task_propagate_boolean(G_TASK(result), error);
}

/**
 * webkit_web_view_execute_editing_command:
 * @web_view: a #WebKitWebView
 * @command: the command to execute
 *
 * Request to execute the given @command for @web_view.
 *
 * You can use webkit_web_view_can_execute_editing_command() to check whether
 * it's possible to execute the command.
 */
void webkit_web_view_execute_editing_command(WebKitWebView* webView, const char* command)
{
    g_return_if_fail(WEBKIT_IS_WEB_VIEW(webView));
    g_return_if_fail(command);

    getPage(webView).executeEditCommand(String::fromUTF8(command));
}

/**
 * webkit_web_view_execute_editing_command_with_argument:
 * @web_view: a #WebKitWebView
 * @command: the command to execute
 * @argument: the command argument
 *
 * Request to execute the given @command with @argument for @web_view.
 *
 * You can use
 * webkit_web_view_can_execute_editing_command() to check whether
 * it's possible to execute the command.
 *
 * Since: 2.10
 */
void webkit_web_view_execute_editing_command_with_argument(WebKitWebView* webView, const char* command, const char* argument)
{
    g_return_if_fail(WEBKIT_IS_WEB_VIEW(webView));
    g_return_if_fail(command);
    g_return_if_fail(argument);

    getPage(webView).executeEditCommand(String::fromUTF8(command), String::fromUTF8(argument));
}

/**
 * webkit_web_view_get_find_controller:
 * @web_view: the #WebKitWebView
 *
 * Gets the #WebKitFindController.
 *
 * Gets the #WebKitFindController that will allow the caller to query
 * the #WebKitWebView for the text to look for.
 *
 * Returns: (transfer none): the #WebKitFindController associated to
 * this particular #WebKitWebView.
 */
WebKitFindController* webkit_web_view_get_find_controller(WebKitWebView* webView)
{
    g_return_val_if_fail(WEBKIT_IS_WEB_VIEW(webView), 0);

    if (!webView->priv->findController)
        webView->priv->findController = adoptGRef(WEBKIT_FIND_CONTROLLER(g_object_new(WEBKIT_TYPE_FIND_CONTROLLER, "web-view", webView, NULL)));

    return webView->priv->findController.get();
}

#if PLATFORM(GTK) && !USE(GTK4)
/**
 * webkit_web_view_get_javascript_global_context: (skip)
 * @web_view: a #WebKitWebView
 *
 * Get the global JavaScript context.
 *
 * Get the global JavaScript context used by @web_view to deserialize the
 * result values of scripts executed with webkit_web_view_run_javascript().
 *
 * Returns: the JSGlobalContextRef used by @web_view to deserialize
 *    the result values of scripts.
 *
 * Deprecated: 2.22: Use jsc_value_get_context() instead.
 */
JSGlobalContextRef webkit_web_view_get_javascript_global_context(WebKitWebView* webView)
{
    g_return_val_if_fail(WEBKIT_IS_WEB_VIEW(webView), nullptr);

    // We keep a reference to the js context in the view only when this method is called
    // for backwards compatibility.
    if (!webView->priv->jsContext)
        webView->priv->jsContext = API::SerializedScriptValue::sharedJSCContext();
    return jscContextGetJSContext(webView->priv->jsContext.get());
}
#endif

enum class RunJavascriptReturnType {
    JSCValue,
#if !ENABLE(2022_GLIB_API)
    WebKitJavascriptResult
#endif
};

static void webkitWebViewRunJavaScriptWithParams(WebKitWebView* webView, RunJavaScriptParameters&& params, const char* worldName, RunJavascriptReturnType returnType, GRefPtr<GTask>&& task)
{
    auto world = worldName ? API::ContentWorld::sharedWorldWithName(String::fromUTF8(worldName)) : Ref<API::ContentWorld> { API::ContentWorld::pageContentWorld() };
    getPage(webView).runJavaScriptInFrameInScriptWorld(WTFMove(params), std::nullopt, world.get(), [task = WTFMove(task), returnType] (auto&& result) {
        if (g_task_return_error_if_cancelled(task.get()))
            return;

        if (result.has_value()) {
            if (!result.value())
                g_task_return_new_error(task.get(), WEBKIT_JAVASCRIPT_ERROR, WEBKIT_JAVASCRIPT_ERROR_INVALID_RESULT, "Unsupported result type");
            else {
#if ENABLE(2022_GLIB_API)
                ASSERT_UNUSED(returnType, returnType == RunJavascriptReturnType::JSCValue);
                g_task_return_pointer(task.get(), API::SerializedScriptValue::deserialize(result.value()->internalRepresentation()).leakRef(),
                    reinterpret_cast<GDestroyNotify>(g_object_unref));
#else
                if (returnType == RunJavascriptReturnType::JSCValue) {
                    g_task_return_pointer(task.get(), API::SerializedScriptValue::deserialize(result.value()->internalRepresentation()).leakRef(),
                        reinterpret_cast<GDestroyNotify>(g_object_unref));
                } else {
                    ASSERT(returnType == RunJavascriptReturnType::WebKitJavascriptResult);
                    g_task_return_pointer(task.get(), webkitJavascriptResultCreate(result.value()->internalRepresentation()),
                        reinterpret_cast<GDestroyNotify>(webkit_javascript_result_unref));
                }
#endif
            }
        } else {
            ExceptionDetails exceptionDetails = WTFMove(result.error());
            StringBuilder builder;
            if (!exceptionDetails.sourceURL.isEmpty()) {
                builder.append(exceptionDetails.sourceURL);
                if (exceptionDetails.lineNumber > 0) {
                    builder.append(':', exceptionDetails.lineNumber);
                    if (exceptionDetails.columnNumber > 0)
                        builder.append(':', exceptionDetails.columnNumber);
                }
                builder.append(": ");
            }
            builder.append(exceptionDetails.message);
            g_task_return_new_error(task.get(), WEBKIT_JAVASCRIPT_ERROR, WEBKIT_JAVASCRIPT_ERROR_SCRIPT_FAILED,
                "%s", builder.toString().utf8().data());
        }
    });
}

void webkitWebViewRunJavascriptWithoutForcedUserGestures(WebKitWebView* webView, const gchar* script, GCancellable* cancellable, GAsyncReadyCallback callback, gpointer userData)
{
    g_return_if_fail(WEBKIT_IS_WEB_VIEW(webView));
    g_return_if_fail(script);

    RunJavaScriptParameters params = { String::fromUTF8(script), URL { }, RunAsAsyncFunction::No, std::nullopt, ForceUserGesture::No, RemoveTransientActivation::Yes };
    webkitWebViewRunJavaScriptWithParams(webView, WTFMove(params), nullptr, RunJavascriptReturnType::JSCValue, adoptGRef(g_task_new(webView, cancellable, callback, userData)));
}

static void webkitWebViewEvaluateJavascriptInternal(WebKitWebView* webView, const char* script, gssize length, const char* worldName, const char* sourceURI, RunJavascriptReturnType returnType, GCancellable* cancellable, GAsyncReadyCallback callback, gpointer userData)
{
    g_return_if_fail(WEBKIT_IS_WEB_VIEW(webView));
    g_return_if_fail(script);

    RunJavaScriptParameters params = { String::fromUTF8(script, length < 0 ? strlen(script) : length), URL({ }, String::fromUTF8(sourceURI)), RunAsAsyncFunction::No, std::nullopt, ForceUserGesture::Yes, RemoveTransientActivation::Yes };
    webkitWebViewRunJavaScriptWithParams(webView, WTFMove(params), worldName, returnType, adoptGRef(g_task_new(webView, cancellable, callback, userData)));
}

/**
 * webkit_web_view_evaluate_javascript:
 * @web_view: a #WebKitWebView
 * @script: the script to evaluate
 * @length: length of @script, or -1 if @script is a nul-terminated string
 * @world_name: (nullable): the name of a #WebKitScriptWorld or %NULL to use the default
 * @source_uri: (nullable): the source URI
 * @cancellable: (nullable): a #GCancellable or %NULL to ignore
 * @callback: (scope async): a #GAsyncReadyCallback to call when the script finished
 * @user_data: the data to pass to callback function
 *
 * Asynchronously evaluate @script in the script world with name @world_name of the main frame current context in @web_view.
 * If @world_name is %NULL, the default world is used. Any value that is not %NULL is a distinct world.
 * The @source_uri will be shown in exceptions and doesn't affect the behavior of the script.
 * When not provided, the document URL is used.
 *
 * Note that if #WebKitSettings:enable-javascript is %FALSE, this method will do nothing.
 * If you want to use this method but still prevent web content from executing its own
 * JavaScript, then use #WebKitSettings:enable-javascript-markup.
 *
 * When the operation is finished, @callback will be called. You can then call
 * webkit_web_view_evaluate_javascript_finish() to get the result of the operation.
 *
 * This is an example of using webkit_web_view_evaluate_javascript() with a script returning
 * a string:
 *
 * ```c
 * static void
 * web_view_javascript_finished (GObject      *object,
 *                               GAsyncResult *result,
 *                               gpointer      user_data)
 * {
 *     JSCValue               *value;
 *     GError                 *error = NULL;
 *
 *     value = webkit_web_view_evaluate_javascript_finish (WEBKIT_WEB_VIEW (object), result, &error);
 *     if (!value) {
 *         g_warning ("Error running javascript: %s", error->message);
 *         g_error_free (error);
 *         return;
 *     }
 *
 *     if (jsc_value_is_string (value)) {
 *         gchar        *str_value = jsc_value_to_string (value);
 *         JSCException *exception = jsc_context_get_exception (jsc_value_get_context (value));
 *         if (exception)
 *             g_warning ("Error running javascript: %s", jsc_exception_get_message (exception));
 *         else
 *             g_print ("Script result: %s\n", str_value);
 *         g_free (str_value);
 *     } else {
 *         g_warning ("Error running javascript: unexpected return value");
 *     }
 *     webkit_javascript_result_unref (js_result);
 * }
 *
 * static void
 * web_view_get_link_url (WebKitWebView *web_view,
 *                        const gchar   *link_id)
 * {
 *     gchar *script = g_strdup_printf ("window.document.getElementById('%s').href;", link_id);
 *     webkit_web_view_evaluate_javascript (web_view, script, -1, NULL, NULL, NULL, web_view_javascript_finished, NULL);
 *     g_free (script);
 * }
 * ```
 *
 * Since: 2.40
 */
void webkit_web_view_evaluate_javascript(WebKitWebView* webView, const char* script, gssize length, const char* worldName, const char* sourceURI, GCancellable* cancellable, GAsyncReadyCallback callback, gpointer userData)
{
    webkitWebViewEvaluateJavascriptInternal(webView, script, length, worldName, sourceURI, RunJavascriptReturnType::JSCValue, cancellable, callback, userData);
}

/**
 * webkit_web_view_evaluate_javascript_finish:
 * @web_view: a #WebKitWebView
 * @result: a #GAsyncResult
 * @error: return location for error or %NULL to ignore
 *
 * Finish an asynchronous operation started with webkit_web_view_evaluate_javascript().
 *
 * Returns: (transfer full): a #JSCValue with the result of the last executed statement in script
 *    or %NULL in case of error
 *
 * Since: 2.40
 */
JSCValue* webkit_web_view_evaluate_javascript_finish(WebKitWebView* webView, GAsyncResult* result, GError** error)
{
    g_return_val_if_fail(WEBKIT_IS_WEB_VIEW(webView), nullptr);
    g_return_val_if_fail(g_task_is_valid(result, webView), nullptr);

    return static_cast<JSCValue*>(g_task_propagate_pointer(G_TASK(result), error));
}

static ArgumentWireBytesMap parseAsyncFunctionArguments(GVariant* arguments, GError** error)
{
    if (!arguments)
        return { };

    ArgumentWireBytesMap argumentsMap;
    GVariantIter iter;
    g_variant_iter_init(&iter, arguments);
    const char* key;
    GVariant* value;
    while (g_variant_iter_loop(&iter, "{&sv}", &key, &value)) {
        if (!key)
            continue;

        auto serializedValue = API::SerializedScriptValue::createFromGVariant(value);
        if (!serializedValue) {
            *error = g_error_new(WEBKIT_JAVASCRIPT_ERROR, WEBKIT_JAVASCRIPT_ERROR_INVALID_PARAMETER, "Invalid parameter %s passed as argument of async function call", key);
            return { };
        }
        argumentsMap.set(String::fromUTF8(key), serializedValue->internalRepresentation().wireBytes());
    }

    return argumentsMap;
}

static void webkitWebViewCallAsyncJavascriptFunctionInternal(WebKitWebView* webView, const char* body, gssize length, GVariant* arguments, const char* worldName, const char* sourceURI, RunJavascriptReturnType returnType, GCancellable* cancellable, GAsyncReadyCallback callback, gpointer userData)
{
    g_return_if_fail(WEBKIT_IS_WEB_VIEW(webView));
    g_return_if_fail(body);
    g_return_if_fail(!arguments || g_variant_is_of_type(arguments, G_VARIANT_TYPE("a{sv}")));

    GError* error = nullptr;
    auto argumentsMap = parseAsyncFunctionArguments(arguments, &error);
    if (error) {
        g_task_report_error(webView, callback, userData, nullptr, error);
        return;
    }

    RunJavaScriptParameters params = { String::fromUTF8(body, length < 0 ? strlen(body) : length), URL({ }, String::fromUTF8(sourceURI)), RunAsAsyncFunction::Yes, WTFMove(argumentsMap), ForceUserGesture::Yes, RemoveTransientActivation::Yes };
    webkitWebViewRunJavaScriptWithParams(webView, WTFMove(params), worldName, returnType, adoptGRef(g_task_new(webView, cancellable, callback, userData)));
}

/**
 * webkit_web_view_call_async_javascript_function:
 * @web_view: a #WebKitWebView
 * @body: the function body
 * @length: length of @body, or -1 if @body is a nul-terminated string
 * @arguments: (nullable): a #GVariant with format `a{sv}` storing the function arguments, or %NULL
 * @world_name: (nullable): the name of a #WebKitScriptWorld or %NULL to use the default
 * @source_uri: (nullable): the source URI
 * @cancellable: (nullable): a #GCancellable or %NULL to ignore
 * @callback: (scope async): a #GAsyncReadyCallback to call when the script finished
 * @user_data: the data to pass to callback function
 *
 * Asynchronously call @body with @arguments in the script world with name @world_name of the main frame current context in @web_view.
 * The @arguments values must be one of the following types, or contain only the following GVariant types: number, string and dictionary.
 * The result of the operation can be a Promise that will be properly passed to the callback.
 * If @world_name is %NULL, the default world is used. Any value that is not %NULL is a distin ct world.
 * The @source_uri will be shown in exceptions and doesn't affect the behavior of the script.
 * When not provided, the document URL is used.
 *
 * Note that if #WebKitSettings:enable-javascript is %FALSE, this method will do nothing.
 * If you want to use this method but still prevent web content from executing its own
 * JavaScript, then use #WebKitSettings:enable-javascript-markup.
 *
 * When the operation is finished, @callback will be called. You can then call
 * webkit_web_view_call_async_javascript_function_finish() to get the result of the operation.
 *
 * This is an example that shows how to pass arguments to a JS function that returns a Promise
 * that resolves with the passed argument:
 *
 * ```c
 * static void
 * web_view_javascript_finished (GObject      *object,
 *                               GAsyncResult *result,
 *                               gpointer      user_data)
 * {
 *     JSCValue               *value;
 *     GError                 *error = NULL;
 *
 *     value = webkit_web_view_call_async_javascript_function_finish (WEBKIT_WEB_VIEW (object), result, &error);
 *     if (!value) {
 *         g_warning ("Error running javascript: %s", error->message);
 *         g_error_free (error);
 *         return;
 *     }
 *
 *     if (jsc_value_is_number (value)) {
 *         gint32        int_value = jsc_value_to_string (value);
 *         JSCException *exception = jsc_context_get_exception (jsc_value_get_context (value));
 *         if (exception)
 *             g_warning ("Error running javascript: %s", jsc_exception_get_message (exception));
 *         else
 *             g_print ("Script result: %d\n", int_value);
 *         g_free (str_value);
 *     } else {
 *         g_warning ("Error running javascript: unexpected return value");
 *     }
 *     webkit_javascript_result_unref (js_result);
 * }
 *
 * static void
 * web_view_evaluate_promise (WebKitWebView *web_view)
 * {
 *     GVariantDict dict;
 *     g_variant_dict_init (&dict, NULL);
 *     g_variant_dict_insert (&dict, "count", "u", 42);
 *     GVariant *args = g_variant_dict_end (&dict);
 *     const gchar *body = "return new Promise((resolve) => { resolve(count); });";
 *     webkit_web_view_call_async_javascript_function (web_view, body, -1, arguments, NULL, NULL, NULL, web_view_javascript_finished, NULL);
 * }
 * ```
 *
 * Since: 2.40
 */
void webkit_web_view_call_async_javascript_function(WebKitWebView* webView, const char* body, gssize length, GVariant* arguments, const char* worldName, const char* sourceURI, GCancellable* cancellable, GAsyncReadyCallback callback, gpointer userData)
{
    webkitWebViewCallAsyncJavascriptFunctionInternal(webView, body, length, arguments, worldName, sourceURI, RunJavascriptReturnType::JSCValue, cancellable, callback, userData);
}

/**
 * webkit_web_view_call_async_javascript_function_finish:
 * @web_view: a #WebKitWebView
 * @result: a #GAsyncResult
 * @error: return location for error or %NULL to ignore
 *
 * Finish an asynchronous operation started with webkit_web_view_call_async_javascript_function().
 *
 * Returns: (transfer full): a #JSCValue with the return value of the async function
 *    or %NULL in case of error
 *
 * Since: 2.40
 */
JSCValue* webkit_web_view_call_async_javascript_function_finish(WebKitWebView* webView, GAsyncResult* result, GError** error)
{
    g_return_val_if_fail(WEBKIT_IS_WEB_VIEW(webView), nullptr);
    g_return_val_if_fail(g_task_is_valid(result, webView), nullptr);

    return static_cast<JSCValue*>(g_task_propagate_pointer(G_TASK(result), error));
}

#if !ENABLE(2022_GLIB_API)
/**
 * webkit_web_view_run_javascript:
 * @web_view: a #WebKitWebView
 * @script: the script to run
 * @cancellable: (allow-none): a #GCancellable or %NULL to ignore
 * @callback: (scope async): a #GAsyncReadyCallback to call when the script finished
 * @user_data: the data to pass to callback function
 *
 * Asynchronously run @script in the context of the current page in @web_view.
 *
 * If WebKitSettings:enable-javascript is FALSE, this method will do nothing.
 *
 * When the operation is finished, @callback will be called. You can then call
 * webkit_web_view_run_javascript_finish() to get the result of the operation.
 *
 * Deprecated: 2.40: Use webkit_web_view_evaluate_javascript() instead.
 */
void webkit_web_view_run_javascript(WebKitWebView* webView, const gchar* script, GCancellable* cancellable, GAsyncReadyCallback callback, gpointer userData)
{
    webkitWebViewEvaluateJavascriptInternal(webView, script, -1, nullptr, nullptr, RunJavascriptReturnType::WebKitJavascriptResult, cancellable, callback, userData);
}

/**
 * webkit_web_view_run_javascript_finish:
 * @web_view: a #WebKitWebView
 * @result: a #GAsyncResult
 * @error: return location for error or %NULL to ignore
 *
 * Finish an asynchronous operation started with webkit_web_view_run_javascript().
 *
 * This is an example of using webkit_web_view_run_javascript() with a script returning
 * a string:
 *
 * ```c
 * static void
 * web_view_javascript_finished (GObject      *object,
 *                               GAsyncResult *result,
 *                               gpointer      user_data)
 * {
 *     WebKitJavascriptResult *js_result;
 *     JSCValue               *value;
 *     GError                 *error = NULL;
 *
 *     js_result = webkit_web_view_run_javascript_finish (WEBKIT_WEB_VIEW (object), result, &error);
 *     if (!js_result) {
 *         g_warning ("Error running javascript: %s", error->message);
 *         g_error_free (error);
 *         return;
 *     }
 *
 *     value = webkit_javascript_result_get_js_value (js_result);
 *     if (jsc_value_is_string (value)) {
 *         gchar        *str_value = jsc_value_to_string (value);
 *         JSCException *exception = jsc_context_get_exception (jsc_value_get_context (value));
 *         if (exception)
 *             g_warning ("Error running javascript: %s", jsc_exception_get_message (exception));
 *         else
 *             g_print ("Script result: %s\n", str_value);
 *         g_free (str_value);
 *     } else {
 *         g_warning ("Error running javascript: unexpected return value");
 *     }
 *     webkit_javascript_result_unref (js_result);
 * }
 *
 * static void
 * web_view_get_link_url (WebKitWebView *web_view,
 *                        const gchar   *link_id)
 * {
 *     gchar *script = g_strdup_printf ("window.document.getElementById('%s').href;", link_id);
 *     webkit_web_view_run_javascript (web_view, script, NULL, web_view_javascript_finished, NULL);
 *     g_free (script);
 * }
 * ```
 *
 * Returns: (transfer full): a #WebKitJavascriptResult with the result of the last executed statement in @script
 *    or %NULL in case of error
 *
 * Deprecated: 2.40: Use webkit_web_view_evaluate_javascript_finish() instead.
 */
WebKitJavascriptResult* webkit_web_view_run_javascript_finish(WebKitWebView* webView, GAsyncResult* result, GError** error)
{
    g_return_val_if_fail(WEBKIT_IS_WEB_VIEW(webView), nullptr);
    g_return_val_if_fail(g_task_is_valid(result, webView), nullptr);

    return static_cast<WebKitJavascriptResult*>(g_task_propagate_pointer(G_TASK(result), error));
}

/**
 * webkit_web_view_run_javascript_in_world:
 * @web_view: a #WebKitWebView
 * @script: the script to run
 * @world_name: the name of a #WebKitScriptWorld
 * @cancellable: (allow-none): a #GCancellable or %NULL to ignore
 * @callback: (scope async): a #GAsyncReadyCallback to call when the script finished
 * @user_data: the data to pass to callback function
 *
 * Asynchronously run @script in the script world.
 *
 * Asynchronously run @script in the script world with name @world_name of the current page context in @web_view.
 * If WebKitSettings:enable-javascript is FALSE, this method will do nothing.
 *
 * When the operation is finished, @callback will be called. You can then call
 * webkit_web_view_run_javascript_in_world_finish() to get the result of the operation.
 *
 * Since: 2.22
 *
 * Deprecated: 2.40: Use webkit_web_view_evaluate_javascript() instead.
 */
void webkit_web_view_run_javascript_in_world(WebKitWebView* webView, const gchar* script, const char* worldName, GCancellable* cancellable, GAsyncReadyCallback callback, gpointer userData)
{
    g_return_if_fail(worldName);

    webkitWebViewEvaluateJavascriptInternal(webView, script, -1, worldName, nullptr, RunJavascriptReturnType::WebKitJavascriptResult, cancellable, callback, userData);
}

/**
 * webkit_web_view_run_async_javascript_function_in_world:
 * @web_view: a #WebKitWebView
 * @body: the JavaScript function body
 * @arguments: a #GVariant with format `{&sv}` storing the function arguments. Function argument values must be one of the following types, or contain only the following GVariant types: number, string, array, and dictionary.
 * @world_name (nullable): the name of a #WebKitScriptWorld, if no name (i.e. %NULL) is provided, the default world is used. Any value that is not %NULL is a distinct world.
 * @cancellable: (allow-none): a #GCancellable or %NULL to ignore
 * @callback: (scope async): a #GAsyncReadyCallback to call when the script finished
 * @user_data: the data to pass to callback function
 *
 * Asynchronously run @body in the script world with name @world_name of the current page context in
 * @web_view. If WebKitSettings:enable-javascript is FALSE, this method will do nothing. This API
 * differs from webkit_web_view_run_javascript_in_world() in that the JavaScript function can return a
 * Promise and its result will be properly passed to the callback.
 *
 * When the operation is finished, @callback will be called. You can then call
 * webkit_web_view_run_javascript_in_world_finish() to get the result of the operation.
 *
 * For instance here is a dummy example that shows how to pass arguments to a JS function that
 * returns a Promise that resolves with the passed argument:
 *
 * ```c
 * static void
 * web_view_javascript_finished (GObject      *object,
 *                               GAsyncResult *result,
 *                               gpointer      user_data)
 * {
 *     WebKitJavascriptResult *js_result;
 *     JSCValue               *value;
 *     GError                 *error = NULL;
 *
 *     js_result = webkit_web_view_run_javascript_finish (WEBKIT_WEB_VIEW (object), result, &error);
 *     if (!js_result) {
 *         g_warning ("Error running javascript: %s", error->message);
 *         g_error_free (error);
 *         return;
 *     }
 *
 *     value = webkit_javascript_result_get_js_value (js_result);
 *     if (jsc_value_is_number (value)) {
 *         gint32        int_value = jsc_value_to_string (value);
 *         JSCException *exception = jsc_context_get_exception (jsc_value_get_context (value));
 *         if (exception)
 *             g_warning ("Error running javascript: %s", jsc_exception_get_message (exception));
 *         else
 *             g_print ("Script result: %d\n", int_value);
 *         g_free (str_value);
 *     } else {
 *         g_warning ("Error running javascript: unexpected return value");
 *     }
 *     webkit_javascript_result_unref (js_result);
 * }
 *
 * static void
 * web_view_evaluate_promise (WebKitWebView *web_view)
 * {
 *     GVariantDict dict;
 *     g_variant_dict_init (&dict, NULL);
 *     g_variant_dict_insert (&dict, "count", "u", 42);
 *     GVariant *args = g_variant_dict_end (&dict);
 *     const gchar *body = "return new Promise((resolve) => { resolve(count); });";
 *     webkit_web_view_run_async_javascript_function_in_world (web_view, body, arguments, NULL, NULL, web_view_javascript_finished, NULL);
 * }
 * ```
 *
 * Since: 2.38
 *
 * Deprecated: 2.40: Use webkit_web_view_call_async_javascript_function() instead.
 */
void webkit_web_view_run_async_javascript_function_in_world(WebKitWebView* webView, const gchar* body, GVariant* arguments, const char* worldName, GCancellable* cancellable, GAsyncReadyCallback callback, gpointer userData)
{
    webkitWebViewCallAsyncJavascriptFunctionInternal(webView, body, -1, arguments, worldName, nullptr, RunJavascriptReturnType::WebKitJavascriptResult, cancellable, callback, userData);
}

/**
 * webkit_web_view_run_javascript_in_world_finish:
 * @web_view: a #WebKitWebView
 * @result: a #GAsyncResult
 * @error: return location for error or %NULL to ignore
 *
 * Finish an asynchronous operation started with webkit_web_view_run_javascript_in_world().
 *
 * Returns: (transfer full): a #WebKitJavascriptResult with the result of the last executed statement in @script
 *    or %NULL in case of error
 *
 * Since: 2.22
 *
 * Deprecated: 2.40: Use webkit_web_view_call_async_javascript_function_finish() instead.
 */
WebKitJavascriptResult* webkit_web_view_run_javascript_in_world_finish(WebKitWebView* webView, GAsyncResult* result, GError** error)
{
    g_return_val_if_fail(WEBKIT_IS_WEB_VIEW(webView), nullptr);
    g_return_val_if_fail(g_task_is_valid(result, webView), nullptr);

    return static_cast<WebKitJavascriptResult*>(g_task_propagate_pointer(G_TASK(result), error));
}

static void resourcesStreamReadCallback(GObject* object, GAsyncResult* result, gpointer userData)
{
    GRefPtr<GTask> task = adoptGRef(G_TASK(userData));

    GError* error = nullptr;
    g_output_stream_splice_finish(G_OUTPUT_STREAM(object), result, &error);
    if (error) {
        g_task_return_error(task.get(), error);
        return;
    }

    WebKitWebView* webView = WEBKIT_WEB_VIEW(g_task_get_source_object(task.get()));
    gpointer outputStreamData = g_memory_output_stream_get_data(G_MEMORY_OUTPUT_STREAM(object));
    RunJavaScriptParameters params = { String::fromUTF8(reinterpret_cast<const gchar*>(outputStreamData)), URL { }, RunAsAsyncFunction::No, std::nullopt, ForceUserGesture::Yes, RemoveTransientActivation::Yes };
    webkitWebViewRunJavaScriptWithParams(webView, WTFMove(params), nullptr, RunJavascriptReturnType::WebKitJavascriptResult, WTFMove(task));
}

/**
 * webkit_web_view_run_javascript_from_gresource:
 * @web_view: a #WebKitWebView
 * @resource: the location of the resource to load
 * @cancellable: (allow-none): a #GCancellable or %NULL to ignore
 * @callback: (scope async): a #GAsyncReadyCallback to call when the script finished
 * @user_data: the data to pass to callback function
 *
 * Asynchronously run the script from @resource.
 *
 * Asynchronously run the script from @resource in the context of the
 * current page in @web_view.
 *
 * When the operation is finished, @callback will be called. You can
 * then call webkit_web_view_run_javascript_from_gresource_finish() to get the result
 * of the operation.
 *
 * Deprecated: 2.40: Use webkit_web_view_evaluate_javascript() instead.
 */
void webkit_web_view_run_javascript_from_gresource(WebKitWebView* webView, const gchar* resource, GCancellable* cancellable, GAsyncReadyCallback callback, gpointer userData)
{
    g_return_if_fail(WEBKIT_IS_WEB_VIEW(webView));
    g_return_if_fail(resource);

    GError* error = 0;
    GRefPtr<GInputStream> inputStream = adoptGRef(g_resources_open_stream(resource, G_RESOURCE_LOOKUP_FLAGS_NONE, &error));
    if (error) {
        g_task_report_error(webView, callback, userData, 0, error);
        return;
    }

    GTask* task = g_task_new(webView, cancellable, callback, userData);
    GRefPtr<GOutputStream> outputStream = adoptGRef(g_memory_output_stream_new(0, 0, fastRealloc, fastFree));
    g_output_stream_splice_async(outputStream.get(), inputStream.get(),
        static_cast<GOutputStreamSpliceFlags>(G_OUTPUT_STREAM_SPLICE_CLOSE_SOURCE | G_OUTPUT_STREAM_SPLICE_CLOSE_TARGET),
        G_PRIORITY_DEFAULT, cancellable, resourcesStreamReadCallback, task);
}

/**
 * webkit_web_view_run_javascript_from_gresource_finish:
 * @web_view: a #WebKitWebView
 * @result: a #GAsyncResult
 * @error: return location for error or %NULL to ignore
 *
 * Finish an asynchronous operation started with webkit_web_view_run_javascript_from_gresource().
 *
 * Check webkit_web_view_run_javascript_finish() for a usage example.
 *
 * Returns: (transfer full): a #WebKitJavascriptResult with the result of the last executed statement in @script
 *    or %NULL in case of error
 *
 * Deprecated: 2.40: Use webkit_web_view_evaluate_javascript_finish() instead.
 */
WebKitJavascriptResult* webkit_web_view_run_javascript_from_gresource_finish(WebKitWebView* webView, GAsyncResult* result, GError** error)
{
    g_return_val_if_fail(WEBKIT_IS_WEB_VIEW(webView), 0);
    g_return_val_if_fail(g_task_is_valid(result, webView), 0);

    return static_cast<WebKitJavascriptResult*>(g_task_propagate_pointer(G_TASK(result), error));
}
#endif

/**
 * webkit_web_view_get_main_resource:
 * @web_view: a #WebKitWebView
 *
 * Return the main resource of @web_view.
 *
 * Returns: (transfer none): the main #WebKitWebResource of the view
 *    or %NULL if nothing has been loaded.
 */
WebKitWebResource* webkit_web_view_get_main_resource(WebKitWebView* webView)
{
    g_return_val_if_fail(WEBKIT_IS_WEB_VIEW(webView), 0);

    return webView->priv->mainResource.get();
}

#if PLATFORM(GTK)
/**
 * webkit_web_view_get_inspector:
 * @web_view: a #WebKitWebView
 *
 * Get the #WebKitWebInspector associated to @web_view
 *
 * Returns: (transfer none): the #WebKitWebInspector of @web_view
 */
WebKitWebInspector* webkit_web_view_get_inspector(WebKitWebView* webView)
{
    g_return_val_if_fail(WEBKIT_IS_WEB_VIEW(webView), 0);

    if (!webView->priv->inspector)
        webView->priv->inspector = adoptGRef(webkitWebInspectorCreate(getPage(webView).inspector()));

    return webView->priv->inspector.get();
}
#endif

/**
 * webkit_web_view_can_show_mime_type:
 * @web_view: a #WebKitWebView
 * @mime_type: a MIME type
 *
 * Whether or not a MIME type can be displayed in @web_view.
 *
 * Returns: %TRUE if the MIME type @mime_type can be displayed or %FALSE otherwise
 */
gboolean webkit_web_view_can_show_mime_type(WebKitWebView* webView, const char* mimeType)
{
    g_return_val_if_fail(WEBKIT_IS_WEB_VIEW(webView), FALSE);
    g_return_val_if_fail(mimeType, FALSE);

    return getPage(webView).canShowMIMEType(String::fromUTF8(mimeType));
}

struct ViewSaveAsyncData {
    WTF_MAKE_STRUCT_FAST_ALLOCATED;
    RefPtr<API::Data> webData;
    GRefPtr<GFile> file;
};
WEBKIT_DEFINE_ASYNC_DATA_STRUCT(ViewSaveAsyncData)

static void fileReplaceContentsCallback(GObject* object, GAsyncResult* result, gpointer data)
{
    GRefPtr<GTask> task = adoptGRef(G_TASK(data));
    GError* error = 0;
    if (!g_file_replace_contents_finish(G_FILE(object), result, 0, &error)) {
        g_task_return_error(task.get(), error);
        return;
    }

    g_task_return_boolean(task.get(), TRUE);
}

static void getContentsAsMHTMLDataCallback(API::Data* wkData, GTask* taskPtr)
{
    auto task = adoptGRef(taskPtr);
    if (g_task_return_error_if_cancelled(task.get()))
        return;

    ViewSaveAsyncData* data = static_cast<ViewSaveAsyncData*>(g_task_get_task_data(task.get()));
    // We need to retain the data until the asyncronous process
    // initiated by the user has finished completely.
    data->webData = wkData;

    // If we are saving to a file we need to write the data on disk before finishing.
    if (g_task_get_source_tag(task.get()) == webkit_web_view_save_to_file) {
        ASSERT(G_IS_FILE(data->file.get()));
        GCancellable* cancellable = g_task_get_cancellable(task.get());
        g_file_replace_contents_async(data->file.get(), reinterpret_cast<const gchar*>(data->webData->bytes()), data->webData->size(),
            0, FALSE, G_FILE_CREATE_REPLACE_DESTINATION, cancellable, fileReplaceContentsCallback, task.leakRef());
        return;
    }

    g_task_return_boolean(task.get(), TRUE);
}

/**
 * webkit_web_view_save:
 * @web_view: a #WebKitWebView
 * @save_mode: the #WebKitSaveMode specifying how the web page should be saved.
 * @cancellable: (allow-none): a #GCancellable or %NULL to ignore
 * @callback: (scope async): a #GAsyncReadyCallback to call when the request is satisfied
 * @user_data: the data to pass to callback function
 *
 * Asynchronously save the current web page.
 *
 * Asynchronously save the current web page associated to the
 * #WebKitWebView into a self-contained format using the mode
 * specified in @save_mode.
 *
 * When the operation is finished, @callback will be called. You can
 * then call webkit_web_view_save_finish() to get the result of the
 * operation.
 */
void webkit_web_view_save(WebKitWebView* webView, WebKitSaveMode saveMode, GCancellable* cancellable, GAsyncReadyCallback callback, gpointer userData)
{
    g_return_if_fail(WEBKIT_IS_WEB_VIEW(webView));

    // We only support MHTML at the moment.
    g_return_if_fail(saveMode == WEBKIT_SAVE_MODE_MHTML);

    GTask* task = g_task_new(webView, cancellable, callback, userData);
    g_task_set_source_tag(task, reinterpret_cast<gpointer>(webkit_web_view_save));
    g_task_set_task_data(task, createViewSaveAsyncData(), reinterpret_cast<GDestroyNotify>(destroyViewSaveAsyncData));
    getPage(webView).getContentsAsMHTMLData([task](API::Data* data) {
        getContentsAsMHTMLDataCallback(data, task);
    });
}

/**
 * webkit_web_view_save_finish:
 * @web_view: a #WebKitWebView
 * @result: a #GAsyncResult
 * @error: return location for error or %NULL to ignore
 *
 * Finish an asynchronous operation started with webkit_web_view_save().
 *
 * Returns: (transfer full): a #GInputStream with the result of saving
 *    the current web page or %NULL in case of error.
 */
GInputStream* webkit_web_view_save_finish(WebKitWebView* webView, GAsyncResult* result, GError** error)
{
    g_return_val_if_fail(WEBKIT_IS_WEB_VIEW(webView), 0);
    g_return_val_if_fail(g_task_is_valid(result, webView), 0);

    GTask* task = G_TASK(result);
    if (!g_task_propagate_boolean(task, error))
        return 0;

    GInputStream* dataStream = g_memory_input_stream_new();
    ViewSaveAsyncData* data = static_cast<ViewSaveAsyncData*>(g_task_get_task_data(task));
    gsize length = data->webData->size();
    if (length)
        g_memory_input_stream_add_data(G_MEMORY_INPUT_STREAM(dataStream), fastMemDup(data->webData->bytes(), length), length, fastFree);

    return dataStream;
}

/**
 * webkit_web_view_save_to_file:
 * @web_view: a #WebKitWebView
 * @file: the #GFile where the current web page should be saved to.
 * @save_mode: the #WebKitSaveMode specifying how the web page should be saved.
 * @cancellable: (allow-none): a #GCancellable or %NULL to ignore
 * @callback: (scope async): a #GAsyncReadyCallback to call when the request is satisfied
 * @user_data: the data to pass to callback function
 *
 * Asynchronously save the current web page.
 *
 * Asynchronously save the current web page associated to the
 * #WebKitWebView into a self-contained format using the mode
 * specified in @save_mode and writing it to @file.
 *
 * When the operation is finished, @callback will be called. You can
 * then call webkit_web_view_save_to_file_finish() to get the result of the
 * operation.
 */
void webkit_web_view_save_to_file(WebKitWebView* webView, GFile* file, WebKitSaveMode saveMode, GCancellable* cancellable, GAsyncReadyCallback callback, gpointer userData)
{
    g_return_if_fail(WEBKIT_IS_WEB_VIEW(webView));
    g_return_if_fail(G_IS_FILE(file));

    // We only support MHTML at the moment.
    g_return_if_fail(saveMode == WEBKIT_SAVE_MODE_MHTML);

    GTask* task = g_task_new(webView, cancellable, callback, userData);
    g_task_set_source_tag(task, reinterpret_cast<gpointer>(webkit_web_view_save_to_file));
    ViewSaveAsyncData* data = createViewSaveAsyncData();
    data->file = file;
    g_task_set_task_data(task, data, reinterpret_cast<GDestroyNotify>(destroyViewSaveAsyncData));

    getPage(webView).getContentsAsMHTMLData([task](API::Data* data) {
        getContentsAsMHTMLDataCallback(data, task);
    });
}

/**
 * webkit_web_view_save_to_file_finish:
 * @web_view: a #WebKitWebView
 * @result: a #GAsyncResult
 * @error: return location for error or %NULL to ignore
 *
 * Finish an asynchronous operation started with webkit_web_view_save_to_file().
 *
 * Returns: %TRUE if the web page was successfully saved to a file or %FALSE otherwise.
 */
gboolean webkit_web_view_save_to_file_finish(WebKitWebView* webView, GAsyncResult* result, GError** error)
{
    g_return_val_if_fail(WEBKIT_IS_WEB_VIEW(webView), FALSE);
    g_return_val_if_fail(g_task_is_valid(result, webView), FALSE);

    return g_task_propagate_boolean(G_TASK(result), error);
}

/**
 * webkit_web_view_download_uri:
 * @web_view: a #WebKitWebView
 * @uri: the URI to download
 *
 * Requests downloading of the specified URI string for @web_view.
 *
 * Returns: (transfer full): a new #WebKitDownload representing
 *    the download operation.
 */
WebKitDownload* webkit_web_view_download_uri(WebKitWebView* webView, const char* uri)
{
    g_return_val_if_fail(WEBKIT_IS_WEB_VIEW(webView), nullptr);
    g_return_val_if_fail(uri, nullptr);

    auto& page = getPage(webView);
    auto downloadProxy = page.process().processPool().download(page.websiteDataStore(), &page, ResourceRequest { String::fromUTF8(uri) });
    auto download = webkitDownloadCreate(downloadProxy, webView);
#if ENABLE(2022_GLIB_API)
    downloadProxy->setDidStartCallback([session = GRefPtr<WebKitNetworkSession> { webView->priv->networkSession }, download = download.get()](auto* downloadProxy) {
#else
    downloadProxy->setDidStartCallback([context = GRefPtr<WebKitWebContext> { webView->priv->context }, download = download.get()](auto* downloadProxy) {
#endif
        if (!downloadProxy)
            return;

        webkitDownloadStarted(download);
#if ENABLE(2022_GLIB_API)
        webkitNetworkSessionDownloadStarted(session.get(), download);
#else
        webkitWebContextDownloadStarted(context.get(), download);
#endif
    });

    return download.leakRef();
}

/**
 * webkit_web_view_get_tls_info:
 * @web_view: a #WebKitWebView
 * @certificate: (out) (transfer none): return location for a #GTlsCertificate
 * @errors: (out): return location for a #GTlsCertificateFlags the verification status of @certificate
 *
 * Retrieves the #GTlsCertificate associated with the main resource of @web_view.
 *
 * Retrieves the #GTlsCertificate associated with the main resource of @web_view,
 * and the #GTlsCertificateFlags showing what problems, if any, have been found
 * with that certificate.
 * If the connection is not HTTPS, this function returns %FALSE.
 * This function should be called after a response has been received from the
 * server, so you can connect to #WebKitWebView::load-changed and call this function
 * when it's emitted with %WEBKIT_LOAD_COMMITTED event.
 *
 * Note that this function provides no information about the security of the web
 * page if the current #WebKitTLSErrorsPolicy is %WEBKIT_TLS_ERRORS_POLICY_IGNORE,
 * as subresources of the page may be controlled by an attacker. This function
 * may safely be used to determine the security status of the current page only
 * if the current #WebKitTLSErrorsPolicy is %WEBKIT_TLS_ERRORS_POLICY_FAIL, in
 * which case subresources that fail certificate verification will be blocked.
 *
 * Returns: %TRUE if the @web_view connection uses HTTPS and a response has been received
 *    from the server, or %FALSE otherwise.
 */
gboolean webkit_web_view_get_tls_info(WebKitWebView* webView, GTlsCertificate** certificate, GTlsCertificateFlags* errors)
{
    g_return_val_if_fail(WEBKIT_IS_WEB_VIEW(webView), FALSE);

    WebFrameProxy* mainFrame = getPage(webView).mainFrame();
    if (!mainFrame)
        return FALSE;

    const auto& certificateInfo = mainFrame->certificateInfo();
    if (certificate)
        *certificate = certificateInfo.certificate().get();
    if (errors)
        *errors = certificateInfo.tlsErrors();

    return !!certificateInfo.certificate();
}

#if PLATFORM(GTK)
/**
 * webkit_web_view_get_snapshot:
 * @web_view: a #WebKitWebView
 * @region: the #WebKitSnapshotRegion for this snapshot
 * @options: #WebKitSnapshotOptions for the snapshot
 * @cancellable: (allow-none): a #GCancellable
 * @callback: (scope async): a #GAsyncReadyCallback
 * @user_data: user data
 *
 * Asynchronously retrieves a snapshot of @web_view for @region.
 *
 * @options specifies how the snapshot should be rendered.
 *
 * When the operation is finished, @callback will be called. You must
 * call webkit_web_view_get_snapshot_finish() to get the result of the
 * operation.
 */
void webkit_web_view_get_snapshot(WebKitWebView* webView, WebKitSnapshotRegion region, WebKitSnapshotOptions options, GCancellable* cancellable, GAsyncReadyCallback callback, gpointer userData)
{
    g_return_if_fail(WEBKIT_IS_WEB_VIEW(webView));

    SnapshotOptions snapshotOptions = 0;
    switch (region) {
    case WEBKIT_SNAPSHOT_REGION_VISIBLE:
        snapshotOptions |= SnapshotOptionsVisibleContentRect;
        break;
    case WEBKIT_SNAPSHOT_REGION_FULL_DOCUMENT:
        snapshotOptions |= SnapshotOptionsFullContentRect;
        break;
    }

    if (!(options & WEBKIT_SNAPSHOT_OPTIONS_INCLUDE_SELECTION_HIGHLIGHTING))
        snapshotOptions |= SnapshotOptionsExcludeSelectionHighlighting;
    if (options & WEBKIT_SNAPSHOT_OPTIONS_TRANSPARENT_BACKGROUND)
        snapshotOptions |= SnapshotOptionsTransparentBackground;

    GRefPtr<GTask> task = adoptGRef(g_task_new(webView, cancellable, callback, userData));
    getPage(webView).takeSnapshot({ }, { }, snapshotOptions, [task = WTFMove(task)](ShareableBitmap::Handle&& handle) {
        if (!handle.isNull()) {
            if (auto bitmap = ShareableBitmap::create(WTFMove(handle), SharedMemory::Protection::ReadOnly)) {
                if (auto surface = bitmap->createCairoSurface()) {
                    g_task_return_pointer(task.get(), surface.leakRef(), reinterpret_cast<GDestroyNotify>(cairo_surface_destroy));
                    return;
                }
            }
        }
        g_task_return_new_error(task.get(), WEBKIT_SNAPSHOT_ERROR, WEBKIT_SNAPSHOT_ERROR_FAILED_TO_CREATE, _("There was an error creating the snapshot"));
    });
}

/**
 * webkit_web_view_get_snapshot_finish:
 * @web_view: a #WebKitWebView
 * @result: a #GAsyncResult
 * @error: return location for error or %NULL to ignore
 *
 * Finishes an asynchronous operation started with webkit_web_view_get_snapshot().
 *
 * Returns: (transfer full): an image with the retrieved snapshot, or %NULL in case of error.
 */
#if USE(GTK4)
GdkTexture* webkit_web_view_get_snapshot_finish(WebKitWebView* webView, GAsyncResult* result, GError** error)
#else
cairo_surface_t* webkit_web_view_get_snapshot_finish(WebKitWebView* webView, GAsyncResult* result, GError** error)
#endif
{
    g_return_val_if_fail(WEBKIT_IS_WEB_VIEW(webView), nullptr);
    g_return_val_if_fail(g_task_is_valid(result, webView), nullptr);

#if USE(GTK4)
    auto image = adoptRef(static_cast<cairo_surface_t*>(g_task_propagate_pointer(G_TASK(result), error)));
    return image ? cairoSurfaceToGdkTexture(image.get()).leakRef() : nullptr;
#else
    return static_cast<cairo_surface_t*>(g_task_propagate_pointer(G_TASK(result), error));
#endif
}
#endif

void webkitWebViewWebProcessTerminated(WebKitWebView* webView, WebKitWebProcessTerminationReason reason)
{
#if PLATFORM(GTK) && !USE(GTK4)
    if (reason == WEBKIT_WEB_PROCESS_CRASHED) {
        gboolean returnValue;
        g_signal_emit(webView, signals[WEB_PROCESS_CRASHED], 0, &returnValue);
    }
#endif
    g_signal_emit(webView, signals[WEB_PROCESS_TERMINATED], 0, reason);

    // Reset the state of the responsiveness property.
    webkitWebViewSetIsWebProcessResponsive(webView, true);
}

/**
 * webkit_web_view_is_editable:
 * @web_view: a #WebKitWebView
 *
 * Gets whether the user is allowed to edit the HTML document.
 *
 * When @web_view is not editable an element in the HTML document can only be edited if the
 * CONTENTEDITABLE attribute has been set on the element or one of its parent
 * elements. By default a #WebKitWebView is not editable.
 *
 * Returns: %TRUE if the user is allowed to edit the HTML document, or %FALSE otherwise.
 *
 * Since: 2.8
 */
gboolean webkit_web_view_is_editable(WebKitWebView* webView)
{
    g_return_val_if_fail(WEBKIT_IS_WEB_VIEW(webView), FALSE);

    return getPage(webView).isEditable();
}

/**
 * webkit_web_view_set_editable:
 * @web_view: a #WebKitWebView
 * @editable: a #gboolean indicating the editable state
 *
 * Sets whether the user is allowed to edit the HTML document.
 *
 * If @editable is %TRUE, @web_view allows the user to edit the HTML document. If
 * @editable is %FALSE, an element in @web_view's document can only be edited if the
 * CONTENTEDITABLE attribute has been set on the element or one of its parent
 * elements. By default a #WebKitWebView is not editable.
 *
 * Normally, a HTML document is not editable unless the elements within the
 * document are editable. This function provides a way to make the contents
 * of a #WebKitWebView editable without altering the document or DOM structure.
 *
 * Since: 2.8
 */
void webkit_web_view_set_editable(WebKitWebView* webView, gboolean editable)
{
    g_return_if_fail(WEBKIT_IS_WEB_VIEW(webView));

    if (editable == getPage(webView).isEditable())
        return;

    getPage(webView).setEditable(editable);

    g_object_notify_by_pspec(G_OBJECT(webView), sObjProperties[PROP_EDITABLE]);
}

/**
 * webkit_web_view_get_editor_state:
 * @web_view: a #WebKitWebView
 *
 * Gets the web editor state of @web_view.
 *
 * Returns: (transfer none): the #WebKitEditorState of the view
 *
 * Since: 2.10
 */
WebKitEditorState* webkit_web_view_get_editor_state(WebKitWebView *webView)
{
    g_return_val_if_fail(WEBKIT_IS_WEB_VIEW(webView), nullptr);

    if (!webView->priv->editorState)
        webView->priv->editorState = adoptGRef(webkitEditorStateCreate(getPage(webView)));

    return webView->priv->editorState.get();
}

/**
 * webkit_web_view_get_session_state:
 * @web_view: a #WebKitWebView
 *
 * Gets the current session state of @web_view
 *
 * Returns: (transfer full): a #WebKitWebViewSessionState
 *
 * Since: 2.12
 */
WebKitWebViewSessionState* webkit_web_view_get_session_state(WebKitWebView* webView)
{
    g_return_val_if_fail(WEBKIT_IS_WEB_VIEW(webView), nullptr);

    SessionState sessionState = getPage(webView).sessionState(nullptr);
    return webkitWebViewSessionStateCreate(WTFMove(sessionState));
}

/**
 * webkit_web_view_restore_session_state:
 * @web_view: a #WebKitWebView
 * @state: a #WebKitWebViewSessionState
 *
 * Restore the @web_view session state from @state
 *
 * Since: 2.12
 */
void webkit_web_view_restore_session_state(WebKitWebView* webView, WebKitWebViewSessionState* state)
{
    g_return_if_fail(WEBKIT_IS_WEB_VIEW(webView));
    g_return_if_fail(state);

    getPage(webView).restoreFromSessionState(webkitWebViewSessionStateGetSessionState(state), false);
}

#if PLATFORM(WPE)
/**
 * webkit_web_view_add_frame_displayed_callback:
 * @web_view: a #WebKitWebView
 * @callback: (scope notified): a #WebKitFrameDisplayedCallback
 * @user_data: user data to pass to @callback
 * @destroy_notify: (nullable): destroy notifier for @user_data
 *
 * Add a callback to be called when the backend notifies that a frame has been displayed in @web_view.
 *
 * Returns: an identifier that should be passed to webkit_web_view_remove_frame_displayed_callback()
 *    to remove the callback.
 *
 * Since: 2.24
 */
unsigned webkit_web_view_add_frame_displayed_callback(WebKitWebView* webView, WebKitFrameDisplayedCallback callback, gpointer userData, GDestroyNotify destroyNotify)
{
    g_return_val_if_fail(WEBKIT_IS_WEB_VIEW(webView), 0);
    g_return_val_if_fail(callback, 0);

    webView->priv->frameDisplayedCallbacks.append(FrameDisplayedCallback(callback, userData, destroyNotify));
    return webView->priv->frameDisplayedCallbacks.last().id;
}

/**
 * webkit_web_view_remove_frame_displayed_callback:
 * @web_view: a #WebKitWebView
 * @id: an identifier
 *
 * Removes a #WebKitFrameDisplayedCallback previously added to @web_view with
 * webkit_web_view_add_frame_displayed_callback().
 *
 * Since: 2.24
 */
void webkit_web_view_remove_frame_displayed_callback(WebKitWebView* webView, unsigned id)
{
    g_return_if_fail(WEBKIT_IS_WEB_VIEW(webView));
    g_return_if_fail(id);

    Function<bool(const FrameDisplayedCallback&)> matchFunction = [id](const auto& item) {
        return item.id == id;
    };

    if (webView->priv->inFrameDisplayed) {
        auto index = webView->priv->frameDisplayedCallbacks.findIf(matchFunction);
        if (index != notFound)
            webView->priv->frameDisplayedCallbacksToRemove.add(id);
    } else
        webView->priv->frameDisplayedCallbacks.removeFirstMatching(matchFunction);
}
#endif // PLATFORM(WPE)

/**
 * webkit_web_view_send_message_to_page:
 * @web_view: a #WebKitWebView
 * @message: a #WebKitUserMessage
 * @cancellable: (nullable): a #GCancellable or %NULL to ignore
 * @callback: (scope async): (nullable): A #GAsyncReadyCallback to call when the request is satisfied or %NULL
 * @user_data: the data to pass to callback function
 *
 * Send @message to the #WebKitWebPage corresponding to @web_view.
 *
 * If @message is floating, it's consumed.
 * If you don't expect any reply, or you simply want to ignore it, you can pass %NULL as @callback.
 * When the operation is finished, @callback will be called. You can then call
 * webkit_web_view_send_message_to_page_finish() to get the message reply.
 *
 * Since: 2.28
 */
void webkit_web_view_send_message_to_page(WebKitWebView* webView, WebKitUserMessage* message, GCancellable* cancellable, GAsyncReadyCallback callback, gpointer userData)
{
    g_return_if_fail(WEBKIT_IS_WEB_VIEW(webView));
    g_return_if_fail(WEBKIT_IS_USER_MESSAGE(message));

    // We sink the reference in case of being floating.
    GRefPtr<WebKitUserMessage> adoptedMessage = message;
    auto& page = getPage(webView);
    if (!callback) {
        page.ensureRunningProcess().send(Messages::WebPage::SendMessageToWebProcessExtension(webkitUserMessageGetMessage(message)), page.webPageID().toUInt64());
        return;
    }

    GRefPtr<GTask> task = adoptGRef(g_task_new(webView, cancellable, callback, userData));
    CompletionHandler<void(UserMessage&&)> completionHandler = [task = WTFMove(task)](UserMessage&& replyMessage) {
        switch (replyMessage.type) {
        case UserMessage::Type::Null:
            g_task_return_new_error(task.get(), G_IO_ERROR, G_IO_ERROR_CANCELLED, _("Operation was cancelled"));
            break;
        case UserMessage::Type::Message:
            g_task_return_pointer(task.get(), g_object_ref_sink(webkitUserMessageCreate(WTFMove(replyMessage))), static_cast<GDestroyNotify>(g_object_unref));
            break;
        case UserMessage::Type::Error:
            g_task_return_new_error(task.get(), WEBKIT_USER_MESSAGE_ERROR, replyMessage.errorCode, _("Message %s was not handled"), replyMessage.name.data());
            break;
        }
    };
    page.ensureRunningProcess().sendWithAsyncReply(Messages::WebPage::SendMessageToWebProcessExtensionWithReply(webkitUserMessageGetMessage(message)),
        WTFMove(completionHandler), page.webPageID().toUInt64());
}

/**
 * webkit_web_view_send_message_to_page_finish:
 * @web_view: a #WebKitWebView
 * @result: a #GAsyncResult
 * @error: return location for error or %NULL to ignor
 *
 * Finish an asynchronous operation started with webkit_web_view_send_message_to_page().
 *
 * Returns: (transfer full): a #WebKitUserMessage with the reply or %NULL in case of error.
 *
 * Since: 2.28
 */
WebKitUserMessage* webkit_web_view_send_message_to_page_finish(WebKitWebView* webView, GAsyncResult* result, GError** error)
{
    g_return_val_if_fail(WEBKIT_IS_WEB_VIEW(webView), nullptr);
    g_return_val_if_fail(g_task_is_valid(result, webView), nullptr);

    return WEBKIT_USER_MESSAGE(g_task_propagate_pointer(G_TASK(result), error));
}

/**
 * webkit_web_view_set_input_method_context:
 * @web_view: a #WebKitWebView
 * @context: (nullable): the #WebKitInputMethodContext to set, or %NULL
 *
 * Set the #WebKitInputMethodContext to be used by @web_view.
 *
 * Set the #WebKitInputMethodContext to be used by @web_view, or %NULL to not use any input method.
 * Note that the same #WebKitInputMethodContext can't be set on more than one #WebKitWebView at the same time.
 *
 * Since: 2.28
 */
void webkit_web_view_set_input_method_context(WebKitWebView* webView, WebKitInputMethodContext* context)
{
    g_return_if_fail(WEBKIT_IS_WEB_VIEW(webView));
    g_return_if_fail(!context || WEBKIT_IS_INPUT_METHOD_CONTEXT(context));

    if (context) {
        if (auto* currentWebView = webkitInputMethodContextGetWebView(context)) {
            if (currentWebView != webView) {
                g_warning("Trying to set a WebKitInputMethodContext to a WebKitWebView, but the WebKitInputMethodContext "
                    "was already set to a different WebKitWebView. It's not possible to use a WebKitInputMethodContext "
                    "with more than one WebKitWebView at the same time.");
            }
            return;
        }
        webkitInputMethodContextSetWebView(context, webView);
    }
#if PLATFORM(GTK)
    webkitWebViewBaseSetInputMethodContext(WEBKIT_WEB_VIEW_BASE(webView), context);
#elif PLATFORM(WPE)
    webView->priv->view->setInputMethodContext(context);
#endif
}

/**
 * webkit_web_view_get_input_method_context:
 * @web_view: a #WebKitWebView
 *
 * Get the #WebKitInputMethodContext currently in use by @web_view.
 *
 * Get the #WebKitInputMethodContext currently in use by @web_view, or %NULL if no input method is being used.
 *
 * Returns: (nullable) (transfer none): a #WebKitInputMethodContext, or %NULL
 *
 * Since: 2.28
 */
WebKitInputMethodContext* webkit_web_view_get_input_method_context(WebKitWebView* webView)
{
    g_return_val_if_fail(WEBKIT_IS_WEB_VIEW(webView), nullptr);

#if PLATFORM(GTK)
    return webkitWebViewBaseGetInputMethodContext(WEBKIT_WEB_VIEW_BASE(webView));
#elif PLATFORM(WPE)
    return webView->priv->view->inputMethodContext();
#endif

}

/**
 * webkit_web_view_get_website_policies:
 * @web_view: a #WebKitWebView
 *
 * Gets the default website policies.
 *
 * Gets the default website policies set on construction in the
 * @web_view. These can be overridden on a per-origin basis via the
 * #WebKitWebView::decide-policy signal handler.
 *
 * See also webkit_policy_decision_use_with_policies().
 *
 * Returns: (transfer none): the default #WebKitWebsitePolicies
 *     associated with the view.
 *
 * Since: 2.30
 */
WebKitWebsitePolicies* webkit_web_view_get_website_policies(WebKitWebView* webView)
{
    g_return_val_if_fail(WEBKIT_IS_WEB_VIEW(webView), nullptr);

    return webView->priv->websitePolicies.get();
}

void webkitWebViewSetIsWebProcessResponsive(WebKitWebView* webView, bool isResponsive)
{
    if (webView->priv->isWebProcessResponsive == isResponsive)
        return;

    webView->priv->isWebProcessResponsive = isResponsive;
    g_object_notify_by_pspec(G_OBJECT(webView), sObjProperties[PROP_IS_WEB_PROCESS_RESPONSIVE]);
}

/**
 * webkit_web_view_get_is_web_process_responsive:
 * @web_view: a #WebKitWebView
 *
 * Get whether the current web process of a #WebKitWebView is responsive.
 *
 * Returns: %TRUE if the web process attached to @web_view is responsive, or %FALSE otherwise.
 *
 * Since: 2.34
 */
gboolean webkit_web_view_get_is_web_process_responsive(WebKitWebView* webView)
{
    g_return_val_if_fail(WEBKIT_IS_WEB_VIEW(webView), FALSE);

    return webView->priv->isWebProcessResponsive;
}

/**
 * webkit_web_view_terminate_web_process:
 * @web_view: a #WebKitWebView
 *
 * Terminates the web process associated to @web_view.
 *
 * When the web process gets terminated
 * using this method, the #WebKitWebView::web-process-terminated signal is emitted with
 * %WEBKIT_WEB_PROCESS_TERMINATED_BY_API as the reason for termination.
 *
 * Since: 2.34
 */
void webkit_web_view_terminate_web_process(WebKitWebView* webView)
{
    g_return_if_fail(WEBKIT_IS_WEB_VIEW(webView));

    auto& page = getPage(webView);

    Ref<WebKit::WebProcessProxy> protectedProcessProxy(page.process());
    protectedProcessProxy->requestTermination(WebKit::ProcessTerminationReason::RequestedByClient);

    if (auto* provisionalPageProxy = page.provisionalPageProxy()) {
        Ref<WebKit::WebProcessProxy> protectedProcessProxy(provisionalPageProxy->process());
        protectedProcessProxy->requestTermination(WebKit::ProcessTerminationReason::RequestedByClient);
    }
}

/**
 * webkit_web_view_set_cors_allowlist:
 * @web_view: a #WebKitWebView
 * @allowlist: (array zero-terminated=1) (element-type utf8) (transfer none) (nullable): an allowlist of URI patterns, or %NULL
 *
 * Sets the @allowlist for CORS.
 *
 * Sets the @allowlist for which
 * [Cross-Origin Resource Sharing](https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS)
 * checks are disabled in @web_view. URI patterns must be of the form
 * `[protocol]://[host]/[path]`, each component may contain the wildcard
 * character (`*`) to represent zero or more other characters. All three
 * components are required and must not be omitted from the URI
 * patterns.
 *
 * Disabling CORS checks permits resources from other origins to load
 * allowlisted resources. It does not permit the allowlisted resources
 * to load resources from other origins.
 *
 * If this function is called multiple times, only the allowlist set by
 * the most recent call will be effective.
 *
 * Since: 2.34
 */
void webkit_web_view_set_cors_allowlist(WebKitWebView* webView, const gchar* const* allowList)
{
    g_return_if_fail(WEBKIT_IS_WEB_VIEW(webView));

    Vector<String> allowListVector;
    if (allowList) {
        for (auto str = allowList; *str; ++str)
            allowListVector.append(String::fromUTF8(*str));
    }

    getPage(webView).setCORSDisablingPatterns(WTFMove(allowListVector));
}

static void webkitWebViewConfigureMediaCapture(WebKitWebView* webView, WebCore::MediaProducerMediaCaptureKind captureKind, WebKitMediaCaptureState captureState)
{
    auto& page = getPage(webView);
    auto mutedState = page.mutedStateFlags();

    switch (captureState) {
    case WEBKIT_MEDIA_CAPTURE_STATE_NONE:
        page.stopMediaCapture(captureKind, [webView, captureKind] {
            switch (captureKind) {
            case WebCore::MediaProducerMediaCaptureKind::Microphone:
                g_object_notify_by_pspec(G_OBJECT(webView), sObjProperties[PROP_MICROPHONE_CAPTURE_STATE]);
                break;
            case WebCore::MediaProducerMediaCaptureKind::Display:
                break;
            case WebCore::MediaProducerMediaCaptureKind::Camera:
                g_object_notify_by_pspec(G_OBJECT(webView), sObjProperties[PROP_CAMERA_CAPTURE_STATE]);
                break;
            case WebCore::MediaProducerMediaCaptureKind::SystemAudio:
            case WebCore::MediaProducerMediaCaptureKind::EveryKind:
                ASSERT_NOT_REACHED();
                return;
            }
        });
        break;
    case WEBKIT_MEDIA_CAPTURE_STATE_ACTIVE:
        switch (captureKind) {
        case WebCore::MediaProducerMediaCaptureKind::Microphone:
            mutedState.remove(WebCore::MediaProducer::MutedState::AudioCaptureIsMuted);
            break;
        case WebCore::MediaProducerMediaCaptureKind::Camera:
            mutedState.remove(WebCore::MediaProducer::MutedState::VideoCaptureIsMuted);
            break;
        case WebCore::MediaProducerMediaCaptureKind::Display:
            mutedState.remove(WebCore::MediaProducer::MutedState::ScreenCaptureIsMuted);
            break;
        case WebCore::MediaProducerMediaCaptureKind::SystemAudio:
        case WebCore::MediaProducerMediaCaptureKind::EveryKind:
            ASSERT_NOT_REACHED();
            return;
        }
        page.setMuted(mutedState);
        break;
    case WEBKIT_MEDIA_CAPTURE_STATE_MUTED:
        switch (captureKind) {
        case WebCore::MediaProducerMediaCaptureKind::Microphone:
            mutedState.add(WebCore::MediaProducer::MutedState::AudioCaptureIsMuted);
            break;
        case WebCore::MediaProducerMediaCaptureKind::Camera:
            mutedState.add(WebCore::MediaProducer::MutedState::VideoCaptureIsMuted);
            break;
        case WebCore::MediaProducerMediaCaptureKind::Display:
            mutedState.add(WebCore::MediaProducer::MutedState::ScreenCaptureIsMuted);
            break;
        case WebCore::MediaProducerMediaCaptureKind::SystemAudio:
        case WebCore::MediaProducerMediaCaptureKind::EveryKind:
            ASSERT_NOT_REACHED();
            return;
        }
        page.setMuted(mutedState);
        break;
    }
}

/**
 * webkit_web_view_get_camera_capture_state:
 * @web_view: a #WebKitWebView
 *
 * Get the camera capture state of a #WebKitWebView.
 *
 * Returns: The #WebKitMediaCaptureState of the camera device. If #WebKitSettings:enable-mediastream
 * is %FALSE, this method will return %WEBKIT_MEDIA_CAPTURE_STATE_NONE.
 *
 * Since: 2.34
 */
WebKitMediaCaptureState webkit_web_view_get_camera_capture_state(WebKitWebView* webView)
{
    auto state = getPage(webView).reportedMediaState();
    if (state & WebCore::MediaProducer::MediaState::HasActiveVideoCaptureDevice)
        return WEBKIT_MEDIA_CAPTURE_STATE_ACTIVE;
    if (state & WebCore::MediaProducer::MediaState::HasMutedVideoCaptureDevice)
        return WEBKIT_MEDIA_CAPTURE_STATE_MUTED;
    return WEBKIT_MEDIA_CAPTURE_STATE_NONE;
}

/**
 * webkit_web_view_set_camera_capture_state:
 * @web_view: a #WebKitWebView
 * @state: a #WebKitMediaCaptureState
 *
 * Set the camera capture state of a #WebKitWebView.
 *
 * If #WebKitSettings:enable-mediastream is %FALSE, this method will have no visible effect. Once the
 * state of the device has been set to %WEBKIT_MEDIA_CAPTURE_STATE_NONE it cannot be changed
 * anymore. The page can however request capture again using the mediaDevices API.
 *
 * Since: 2.34
 */
void webkit_web_view_set_camera_capture_state(WebKitWebView* webView, WebKitMediaCaptureState state)
{
    if (webkit_web_view_get_camera_capture_state(webView) == WEBKIT_MEDIA_CAPTURE_STATE_NONE)
        return;

    webkitWebViewConfigureMediaCapture(webView, WebCore::MediaProducerMediaCaptureKind::Camera, state);
}

/**
 * webkit_web_view_get_microphone_capture_state:
 * @web_view: a #WebKitWebView
 *
 * Get the microphone capture state of a #WebKitWebView.
 *
 * Returns: The #WebKitMediaCaptureState of the microphone device. If #WebKitSettings:enable-mediastream
 * is %FALSE, this method will return %WEBKIT_MEDIA_CAPTURE_STATE_NONE.
 *
 * Since: 2.34
 */
WebKitMediaCaptureState webkit_web_view_get_microphone_capture_state(WebKitWebView* webView)
{
    auto state = getPage(webView).reportedMediaState();
    if (state & WebCore::MediaProducer::MediaState::HasActiveAudioCaptureDevice)
        return WEBKIT_MEDIA_CAPTURE_STATE_ACTIVE;
    if (state & WebCore::MediaProducer::MediaState::HasMutedAudioCaptureDevice)
        return WEBKIT_MEDIA_CAPTURE_STATE_MUTED;
    return WEBKIT_MEDIA_CAPTURE_STATE_NONE;
}

/**
 * webkit_web_view_set_microphone_capture_state:
 * @web_view: a #WebKitWebView
 * @state: a #WebKitMediaCaptureState
 *
 * Set the microphone capture state of a #WebKitWebView.
 *
 * If #WebKitSettings:enable-mediastream is %FALSE, this method will have no visible effect. Once the
 * state of the device has been set to %WEBKIT_MEDIA_CAPTURE_STATE_NONE it cannot be changed
 * anymore. The page can however request capture again using the mediaDevices API.
 *
 * Since: 2.34
 */
void webkit_web_view_set_microphone_capture_state(WebKitWebView* webView, WebKitMediaCaptureState state)
{
    if (webkit_web_view_get_microphone_capture_state(webView) == WEBKIT_MEDIA_CAPTURE_STATE_NONE)
        return;

    webkitWebViewConfigureMediaCapture(webView, WebCore::MediaProducerMediaCaptureKind::Microphone, state);
}

/**
 * webkit_web_view_get_display_capture_state:
 * @web_view: a #WebKitWebView
 *
 * Get the display capture state of a #WebKitWebView.
 *
 * Returns: The #WebKitMediaCaptureState of the display device. If #WebKitSettings:enable-mediastream
 * is %FALSE, this method will return %WEBKIT_MEDIA_CAPTURE_STATE_NONE.
 *
 * Since: 2.34
 */
WebKitMediaCaptureState webkit_web_view_get_display_capture_state(WebKitWebView* webView)
{
    auto state = getPage(webView).reportedMediaState();
    if (state & WebCore::MediaProducer::MediaState::HasActiveScreenCaptureDevice)
        return WEBKIT_MEDIA_CAPTURE_STATE_ACTIVE;
    if (state & WebCore::MediaProducer::MediaState::HasMutedScreenCaptureDevice)
        return WEBKIT_MEDIA_CAPTURE_STATE_MUTED;
    return WEBKIT_MEDIA_CAPTURE_STATE_NONE;
}

/**
 * webkit_web_view_set_display_capture_state:
 * @web_view: a #WebKitWebView
 * @state: a #WebKitMediaCaptureState
 *
 * Set the display capture state of a #WebKitWebView.
 *
 * If #WebKitSettings:enable-mediastream is %FALSE, this method will have no visible effect. Once the
 * state of the device has been set to %WEBKIT_MEDIA_CAPTURE_STATE_NONE it cannot be changed
 * anymore. The page can however request capture again using the mediaDevices API.
 *
 * Since: 2.34
 */
void webkit_web_view_set_display_capture_state(WebKitWebView* webView, WebKitMediaCaptureState state)
{
    if (webkit_web_view_get_display_capture_state(webView) == WEBKIT_MEDIA_CAPTURE_STATE_NONE)
        return;

    webkitWebViewConfigureMediaCapture(webView, WebCore::MediaProducerMediaCaptureKind::Display, state);
}

void webkitWebViewForceRepaintForTesting(WebKitWebView* webView, ForceRepaintCallback callback, gpointer userData)
{
    g_return_if_fail(WEBKIT_IS_WEB_VIEW(webView));

    getPage(webView).forceRepaint([callback, userData]() {
        callback(userData);
    });
}

void webkitSetCachedProcessSuspensionDelayForTesting(double seconds)
{
    WebKit::WebsiteDataStore::setCachedProcessSuspensionDelayForTesting(Seconds(seconds));
}

/**
 * webkit_web_view_get_web_extension_mode:
 * @web_view: a #WebKitWebView
 *
 * Get the view's #WebKitWebExtensionMode.
 *
 * Returns: the #WebKitWebExtensionMode
 *
 * Since: 2.38
 */
WebKitWebExtensionMode webkit_web_view_get_web_extension_mode(WebKitWebView* webView)
{
    g_return_val_if_fail(WEBKIT_IS_WEB_VIEW(webView), WEBKIT_WEB_EXTENSION_MODE_NONE);

    return webView->priv->webExtensionMode;
}

/**
 * webkit_web_view_get_default_content_security_policy:
 * @web_view: a #WebKitWebView
 *
 * Gets the configured default Content-Security-Policy.
 *
 * Returns: (nullable): The default policy or %NULL
 *
 * Since: 2.38
 */
const gchar*
webkit_web_view_get_default_content_security_policy(WebKitWebView* webView)
{
    g_return_val_if_fail(WEBKIT_IS_WEB_VIEW(webView), nullptr);

    if (webView->priv->defaultContentSecurityPolicy.isNull())
        return nullptr;

    return webView->priv->defaultContentSecurityPolicy.data();
}