summaryrefslogtreecommitdiff
path: root/src/xwidget.c
blob: 45879b15cbeaebbb373c8ab0a7c4398782b38550 (plain)
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
/* Support for embedding graphical components in a buffer.

Copyright (C) 2011-2022 Free Software Foundation, Inc.

This file is part of GNU Emacs.

GNU Emacs is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or (at
your option) any later version.

GNU Emacs 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 General Public License for more details.

You should have received a copy of the GNU General Public License
along with GNU Emacs.  If not, see <https://www.gnu.org/licenses/>.  */

#include <config.h>

#include "buffer.h"
#include "coding.h"
#include "xwidget.h"

#include "lisp.h"
#include "blockinput.h"
#include "dispextern.h"
#include "frame.h"
#include "keyboard.h"
#include "gtkutil.h"
#include "sysstdio.h"
#include "termhooks.h"
#include "window.h"
#include "process.h"

/* Include xwidget bottom end headers.  */
#ifdef USE_GTK
#include <webkit2/webkit2.h>
#include <JavaScriptCore/JavaScript.h>
#include <cairo.h>
#ifndef HAVE_PGTK
#include <X11/Xlib.h>
#else
#include <gtk/gtk.h>
#endif
#ifdef HAVE_XINPUT2
#include <X11/extensions/XInput2.h>
#endif
#elif defined NS_IMPL_COCOA
#include "nsxwidget.h"
#endif

#include <math.h>

static Lisp_Object id_to_xwidget_map;
static Lisp_Object internal_xwidget_view_list;
static Lisp_Object internal_xwidget_list;
static uint32_t xwidget_counter = 0;

#ifdef USE_GTK
#ifdef HAVE_X_WINDOWS
static Lisp_Object x_window_to_xwv_map;
#endif
static gboolean offscreen_damage_event (GtkWidget *, GdkEvent *, gpointer);
static void synthesize_focus_in_event (GtkWidget *);
static GdkDevice *find_suitable_keyboard (struct frame *);
static gboolean webkit_script_dialog_cb (WebKitWebView *, WebKitScriptDialog *,
					 gpointer);
static void record_osr_embedder (struct xwidget_view *);
static void from_embedder (GdkWindow *, double, double, gpointer, gpointer, gpointer);
static void to_embedder (GdkWindow *, double, double, gpointer, gpointer, gpointer);
static GdkWindow *pick_embedded_child (GdkWindow *, double, double, gpointer);
#endif

static struct xwidget *
allocate_xwidget (void)
{
  return ALLOCATE_PSEUDOVECTOR (struct xwidget, script_callbacks, PVEC_XWIDGET);
}

static struct xwidget_view *
allocate_xwidget_view (void)
{
  return ALLOCATE_PSEUDOVECTOR (struct xwidget_view, w, PVEC_XWIDGET_VIEW);
}

#define XSETXWIDGET(a, b) XSETPSEUDOVECTOR (a, b, PVEC_XWIDGET)
#define XSETXWIDGET_VIEW(a, b) XSETPSEUDOVECTOR (a, b, PVEC_XWIDGET_VIEW)

static struct xwidget_view *xwidget_view_lookup (struct xwidget *,
						 struct window *);
static void kill_xwidget (struct xwidget *);

#ifdef USE_GTK
static void webkit_view_load_changed_cb (WebKitWebView *,
                                         WebKitLoadEvent,
                                         gpointer);
static void webkit_javascript_finished_cb (GObject *,
                                           GAsyncResult *,
                                           gpointer);
static gboolean webkit_download_cb (WebKitWebContext *, WebKitDownload *, gpointer);
static GtkWidget *webkit_create_cb (WebKitWebView *, WebKitNavigationAction *, gpointer);
static gboolean
webkit_decide_policy_cb (WebKitWebView *,
                         WebKitPolicyDecision *,
                         WebKitPolicyDecisionType,
                         gpointer);
static GtkWidget *find_widget_at_pos (GtkWidget *, int, int, int *, int *);
static gboolean run_file_chooser_cb (WebKitWebView *,
				     WebKitFileChooserRequest *,
				     gpointer);

struct widget_search_data
{
  int x;
  int y;
  bool foundp;
  bool first;
  GtkWidget *data;
};

static void find_widget (GtkWidget *t, struct widget_search_data *);
static void mouse_target_changed (WebKitWebView *, WebKitHitTestResult *, guint,
				  gpointer);
#endif

#ifdef HAVE_PGTK
static int
xw_forward_event_translate (GdkEvent *event, struct xwidget_view *xv,
			    struct xwidget *xw)
{
  GtkWidget *widget;
  int new_x, new_y;

  switch (event->type)
    {
    case GDK_BUTTON_PRESS:
    case GDK_BUTTON_RELEASE:
    case GDK_2BUTTON_PRESS:
    case GDK_3BUTTON_PRESS:
      widget = find_widget_at_pos (xw->widgetwindow_osr,
				   lrint (event->button.x - xv->clip_left),
				   lrint (event->button.y - xv->clip_top),
				   &new_x, &new_y);
      if (widget)
	{
	  event->any.window = gtk_widget_get_window (widget);
	  event->button.x = new_x;
	  event->button.y = new_y;
	  return 1;
	}
      return 0;
    case GDK_SCROLL:
      widget = find_widget_at_pos (xw->widgetwindow_osr,
				   lrint (event->scroll.x - xv->clip_left),
				   lrint (event->scroll.y - xv->clip_top),
				   &new_x, &new_y);
      if (widget)
	{
	  event->any.window = gtk_widget_get_window (widget);
	  event->scroll.x = new_x;
	  event->scroll.y = new_y;
	  return 1;
	}
      return 0;
    case GDK_MOTION_NOTIFY:
      widget = find_widget_at_pos (xw->widgetwindow_osr,
				   lrint (event->motion.x - xv->clip_left),
				   lrint (event->motion.y - xv->clip_top),
				   &new_x, &new_y);
      if (widget)
	{
	  event->any.window = gtk_widget_get_window (widget);
	  event->motion.x = new_x;
	  event->motion.y = new_y;
	  return 1;
	}
      return 0;
    case GDK_ENTER_NOTIFY:
    case GDK_LEAVE_NOTIFY:
      widget = find_widget_at_pos (xw->widgetwindow_osr,
				   lrint (event->crossing.x - xv->clip_left),
				   lrint (event->crossing.y - xv->clip_top),
				   &new_x, &new_y);
      if (widget)
	{
	  event->any.window = gtk_widget_get_window (widget);
	  event->crossing.x = new_x;
	  event->crossing.y = new_y;
	  return 1;
	}
      return 0;
    default:
      return 0;
    }
}

static gboolean
xw_forward_event_from_view (GtkWidget *widget, GdkEvent *event,
			    gpointer user_data)
{
  struct xwidget_view *xv = user_data;
  struct xwidget *xw = XXWIDGET (xv->model);
  GdkEvent *eventcopy;
  bool translated_p;

  if (NILP (xw->buffer))
    return TRUE;

  eventcopy = gdk_event_copy (event);
  translated_p = xw_forward_event_translate (eventcopy, xv, xw);
  record_osr_embedder (xv);

  g_object_ref (eventcopy->any.window);
  if (translated_p)
    gtk_main_do_event (eventcopy);
  gdk_event_free (eventcopy);

  /* Don't propagate this event further.  */
  return TRUE;
}
#endif

#ifdef HAVE_X_WINDOWS
static guint
xw_translate_x_modifiers (struct x_display_info *dpyinfo,
			  unsigned int modifiers)
{
  guint mods = 0;

  if (modifiers & dpyinfo->meta_mod_mask)
    {
      /* GDK always assumes Mod1 is alt, but that's no reason for
	 us to make that mistake as well.  */
      if (!dpyinfo->alt_mod_mask)
	mods |= GDK_MOD1_MASK;
      else
	mods |= GDK_META_MASK;
    }

  if (modifiers & dpyinfo->alt_mod_mask)
    mods |= GDK_MOD1_MASK;
  if (modifiers & dpyinfo->super_mod_mask)
    mods |= GDK_SUPER_MASK;
  if (modifiers & dpyinfo->hyper_mod_mask)
    mods |= GDK_HYPER_MASK;
  if (modifiers & ControlMask)
    mods |= GDK_CONTROL_MASK;
  if (modifiers & ShiftMask)
    mods |= GDK_SHIFT_MASK;

  return mods;
}
#endif

DEFUN ("make-xwidget",
       Fmake_xwidget, Smake_xwidget,
       4, 7, 0,
       doc: /* Make an xwidget of TYPE.
If BUFFER is nil, use the current buffer.
If BUFFER is a string and no such buffer exists, create it.
TYPE is a symbol which can take one of the following values:

- webkit

RELATED is nil, or an xwidget.  When constructing a WebKit widget, it
will share the same settings and internal subprocess as RELATED.
Returns the newly constructed xwidget, or nil if construction
fails.  */)
  (Lisp_Object type,
   Lisp_Object title, Lisp_Object width, Lisp_Object height,
   Lisp_Object arguments, Lisp_Object buffer, Lisp_Object related)
{
#ifdef USE_GTK
  if (!xg_gtk_initialized)
    error ("make-xwidget: GTK has not been initialized");
#endif
  CHECK_SYMBOL (type);
  CHECK_FIXNAT (width);
  CHECK_FIXNAT (height);

  if (!EQ (type, Qwebkit))
    error ("Bad xwidget type");

  Frequire (Qxwidget, Qnil, Qnil);

  struct xwidget *xw = allocate_xwidget ();
  Lisp_Object val;
  xw->type = type;
  xw->title = title;
  xw->buffer = (NILP (buffer) ? Fcurrent_buffer ()
		: Fget_buffer_create (buffer, Qnil));
  xw->height = XFIXNAT (height);
  xw->width = XFIXNAT (width);
  xw->kill_without_query = false;
  XSETXWIDGET (val, xw);
  internal_xwidget_list = Fcons (val, internal_xwidget_list);
  Vxwidget_list = Fcopy_sequence (internal_xwidget_list);
  xw->plist = Qnil;
  xw->xwidget_id = ++xwidget_counter;
  xw->find_text = NULL;

  Fputhash (make_fixnum (xw->xwidget_id), val, id_to_xwidget_map);

#ifdef USE_GTK
  xw->widgetwindow_osr = NULL;
  xw->widget_osr = NULL;
  xw->hit_result = 0;
  if (EQ (xw->type, Qwebkit))
    {
      block_input ();
      WebKitSettings *settings;
      WebKitWebContext *webkit_context = webkit_web_context_get_default ();

# if WEBKIT_CHECK_VERSION (2, 26, 0)
      if (!webkit_web_context_get_sandbox_enabled (webkit_context))
	webkit_web_context_set_sandbox_enabled (webkit_context, TRUE);
# endif

      xw->widgetwindow_osr = gtk_offscreen_window_new ();
      gtk_window_resize (GTK_WINDOW (xw->widgetwindow_osr), xw->width,
                         xw->height);
      gtk_container_check_resize (GTK_CONTAINER (xw->widgetwindow_osr));

      if (EQ (xw->type, Qwebkit))
        {
	  WebKitWebView *related_view;

	  if (NILP (related)
	      || !XWIDGETP (related)
	      || !EQ (XXWIDGET (related)->type, Qwebkit))
	    {
	      WebKitWebContext *ctx = webkit_web_context_new ();
	      xw->widget_osr = webkit_web_view_new_with_context (ctx);
	      g_object_unref (ctx);

	      g_signal_connect (G_OBJECT (ctx),
				"download-started",
				G_CALLBACK (webkit_download_cb), xw);

	      webkit_web_view_load_uri (WEBKIT_WEB_VIEW (xw->widget_osr),
					"about:blank");
	      /* webkitgtk uses GSubprocess which sets sigaction causing
		 Emacs to not catch SIGCHLD with its usual handle setup in
		 'catch_child_signal'.  This resets the SIGCHLD sigaction.  */
	      catch_child_signal ();
	    }
	  else
	    {
	      related_view = WEBKIT_WEB_VIEW (XXWIDGET (related)->widget_osr);
	      xw->widget_osr = webkit_web_view_new_with_related_view (related_view);
	    }

	  /* Enable the developer extras.  */
	  settings = webkit_web_view_get_settings (WEBKIT_WEB_VIEW (xw->widget_osr));
	  g_object_set (G_OBJECT (settings), "enable-developer-extras", TRUE, NULL);
	}

      gtk_widget_set_size_request (GTK_WIDGET (xw->widget_osr), xw->width,
                                   xw->height);
      gtk_widget_queue_allocate (GTK_WIDGET (xw->widget_osr));

      if (EQ (xw->type, Qwebkit))
        {
          gtk_container_add (GTK_CONTAINER (xw->widgetwindow_osr),
                             GTK_WIDGET (WEBKIT_WEB_VIEW (xw->widget_osr)));
        }
      else
        {
          gtk_container_add (GTK_CONTAINER (xw->widgetwindow_osr),
                             xw->widget_osr);
        }

      gtk_widget_show (xw->widget_osr);
      gtk_widget_show (xw->widgetwindow_osr);
#if !defined HAVE_XINPUT2 && !defined HAVE_PGTK
      synthesize_focus_in_event (xw->widgetwindow_osr);
#endif

      g_signal_connect (G_OBJECT (gtk_widget_get_window (xw->widgetwindow_osr)),
			"from-embedder", G_CALLBACK (from_embedder), NULL);
      g_signal_connect (G_OBJECT (gtk_widget_get_window (xw->widgetwindow_osr)),
			"to-embedder", G_CALLBACK (to_embedder), NULL);
      g_signal_connect (G_OBJECT (gtk_widget_get_window (xw->widgetwindow_osr)),
			"pick-embedded-child", G_CALLBACK (pick_embedded_child), NULL);

      /* Store some xwidget data in the gtk widgets for convenient
         retrieval in the event handlers.  */
      g_object_set_data (G_OBJECT (xw->widget_osr), XG_XWIDGET, xw);
      g_object_set_data (G_OBJECT (xw->widgetwindow_osr), XG_XWIDGET, xw);

      /* signals */
      if (EQ (xw->type, Qwebkit))
        {
          g_signal_connect (G_OBJECT (xw->widget_osr),
                            "load-changed",
                            G_CALLBACK (webkit_view_load_changed_cb), xw);

          g_signal_connect (G_OBJECT (xw->widget_osr),
                            "decide-policy",
                            G_CALLBACK
                            (webkit_decide_policy_cb),
                            xw);

	  g_signal_connect (G_OBJECT (xw->widget_osr),
			    "mouse-target-changed",
			    G_CALLBACK (mouse_target_changed),
			    xw);
	  g_signal_connect (G_OBJECT (xw->widget_osr),
			    "create",
			    G_CALLBACK (webkit_create_cb),
			    xw);
	  g_signal_connect (G_OBJECT (xw->widget_osr),
			    "script-dialog",
			    G_CALLBACK (webkit_script_dialog_cb),
			    NULL);
	  g_signal_connect (G_OBJECT (xw->widget_osr),
			    "run-file-chooser",
			    G_CALLBACK (run_file_chooser_cb),
			    NULL);
        }

      g_signal_connect (G_OBJECT (xw->widgetwindow_osr), "damage-event",
			G_CALLBACK (offscreen_damage_event), xw);

      unblock_input ();
    }
#elif defined NS_IMPL_COCOA
  nsxwidget_init (xw);
#endif

  return val;
}

DEFUN ("xwidget-live-p", Fxwidget_live_p, Sxwidget_live_p,
       1, 1, 0, doc: /* Return t if OBJECT is an xwidget that has not been killed.
Value is nil if OBJECT is not an xwidget or if it has been killed.  */)
  (Lisp_Object object)
{
  return ((XWIDGETP (object)
	   && !NILP (XXWIDGET (object)->buffer))
	  ? Qt : Qnil);
}

#ifdef USE_GTK
static void
set_widget_if_text_view (GtkWidget *widget, void *data)
{
  GtkWidget **pointer = data;

  if (GTK_IS_TEXT_VIEW (widget))
    *pointer = widget;
}
#endif

DEFUN ("xwidget-perform-lispy-event",
       Fxwidget_perform_lispy_event, Sxwidget_perform_lispy_event,
       2, 3, 0, doc: /* Send a lispy event to XWIDGET.
EVENT should be the event that will be sent.  FRAME should be the
frame which generated the event, and defaults to the selected frame.
On X11, modifier keys will not be processed if FRAME is nil and the
selected frame is not an X-Windows frame.  */)
  (Lisp_Object xwidget, Lisp_Object event, Lisp_Object frame)
{
  struct xwidget *xw;
  struct frame *f = NULL;
  int character = -1, keycode = -1;
  int modifiers = 0;

#ifdef USE_GTK
  GdkEvent *xg_event;
  GtkContainerClass *klass;
  GtkWidget *widget;
  GtkWidget *temp = NULL;
#ifdef HAVE_XINPUT2
  GdkWindow *embedder;
  GdkWindow *osw;
#endif
#endif

  CHECK_LIVE_XWIDGET (xwidget);
  xw = XXWIDGET (xwidget);

  if (!NILP (frame))
    f = decode_window_system_frame (frame);
  else if (FRAME_WINDOW_P (SELECTED_FRAME ()))
    f = SELECTED_FRAME ();

#ifdef USE_GTK
#ifdef HAVE_XINPUT2
  /* XI2 GDK devices crash if we try this without an embedder set.  */
  if (!f)
    return Qnil;

  block_input ();
  osw = gtk_widget_get_window (xw->widgetwindow_osr);
  embedder = gtk_widget_get_window (FRAME_GTK_OUTER_WIDGET (f));

  gdk_offscreen_window_set_embedder (osw, embedder);
  unblock_input ();
#endif
  widget = gtk_window_get_focus (GTK_WINDOW (xw->widgetwindow_osr));

  if (!widget)
    widget = xw->widget_osr;

  if (RANGED_FIXNUMP (0, event, INT_MAX))
    {
      character = XFIXNUM (event);

      if (character < 32)
	modifiers |= ctrl_modifier;

      modifiers |= character & meta_modifier;
      modifiers |= character & hyper_modifier;
      modifiers |= character & super_modifier;
      modifiers |= character & shift_modifier;
      modifiers |= character & ctrl_modifier;

      character = character & ~(1 << 21);

      if (character < 32)
	character += '_';

#ifndef HAVE_PGTK
      if (f)
	modifiers = x_emacs_to_x_modifiers (FRAME_DISPLAY_INFO (f), modifiers);
      else
	modifiers = 0;
#else
      if (f)
	modifiers = pgtk_emacs_to_gtk_modifiers (FRAME_DISPLAY_INFO (f), modifiers);
      else
	modifiers = 0;
#endif
    }
  else if (SYMBOLP (event))
    {
      Lisp_Object decoded = parse_modifiers (event);
      Lisp_Object decoded_name = SYMBOL_NAME (XCAR (decoded));

      int off = 0;
      bool found = false;

      while (off < 256)
	{
	  if (lispy_function_keys[off]
	      && !strcmp (lispy_function_keys[off],
			  SSDATA (decoded_name)))
	    {
	      found = true;
	      break;
	    }
	  ++off;
	}

#ifndef HAVE_PGTK
      if (f)
	modifiers = x_emacs_to_x_modifiers (FRAME_DISPLAY_INFO (f),
					    XFIXNUM (XCAR (XCDR (decoded))));
      else
	modifiers = 0;
#else
      if (f)
	modifiers = pgtk_emacs_to_gtk_modifiers (FRAME_DISPLAY_INFO (f),
						 XFIXNUM (XCAR (XCDR (decoded))));
      else
	modifiers = 0;
#endif

      if (found)
	keycode = off + 0xff00;
    }

  if (character == -1 && keycode == -1)
    {
#ifdef HAVE_XINPUT2
      block_input ();
      if (xw->embedder_view)
	record_osr_embedder (xw->embedder_view);
      else
	gdk_offscreen_window_set_embedder (osw, NULL);
      unblock_input ();
#endif
      return Qnil;
    }

  block_input ();
  xg_event = gdk_event_new (GDK_KEY_PRESS);
  xg_event->any.window = gtk_widget_get_window (xw->widget_osr);
  g_object_ref (xg_event->any.window);

  if (character > -1)
    keycode = gdk_unicode_to_keyval (character);

  xg_event->key.keyval = keycode;
#ifndef HAVE_X_WINDOWS
  xg_event->key.state = modifiers;
#else
  if (f)
    xg_event->key.state = xw_translate_x_modifiers (FRAME_DISPLAY_INFO (f),
						    modifiers);
#endif

  if (keycode > -1)
    {
      /* WebKitGTK internals abuse follows.  */
      if (WEBKIT_IS_WEB_VIEW (widget))
	{
	  /* WebKitGTK relies on an internal GtkTextView object to
	     "translate" keys such as backspace.  We must find that
	     widget and activate its binding to this key if any.  */
	  klass = GTK_CONTAINER_CLASS (G_OBJECT_GET_CLASS (widget));

	  klass->forall (GTK_CONTAINER (xw->widget_osr), TRUE,
			 set_widget_if_text_view, &temp);

	  if (GTK_IS_WIDGET (temp))
	    {
	      if (!gtk_widget_get_realized (temp))
		gtk_widget_realize (temp);

	      gtk_bindings_activate (G_OBJECT (temp), keycode, modifiers);
	    }
	}
    }

  if (f)
    gdk_event_set_device (xg_event,
			  find_suitable_keyboard (SELECTED_FRAME ()));

  gtk_main_do_event (xg_event);
  xg_event->type = GDK_KEY_RELEASE;
  gtk_main_do_event (xg_event);
  gdk_event_free (xg_event);

#ifdef HAVE_XINPUT2
  if (xw->embedder_view)
    record_osr_embedder (xw->embedder_view);
  else
    gdk_offscreen_window_set_embedder (osw, NULL);
#endif
  unblock_input ();
#endif

  return Qnil;
}

DEFUN ("get-buffer-xwidgets", Fget_buffer_xwidgets, Sget_buffer_xwidgets,
       1, 1, 0,
       doc: /* Return a list of xwidgets associated with BUFFER.
BUFFER may be a buffer or the name of one.  */)
  (Lisp_Object buffer)
{
  Lisp_Object xw, tail, xw_list;

  if (NILP (buffer))
    return Qnil;
  buffer = Fget_buffer (buffer);
  if (NILP (buffer))
    return Qnil;

  xw_list = Qnil;

  for (tail = internal_xwidget_list; CONSP (tail); tail = XCDR (tail))
    {
      xw = XCAR (tail);
      if (XWIDGETP (xw) && EQ (Fxwidget_buffer (xw), buffer))
        xw_list = Fcons (xw, xw_list);
    }
  return xw_list;
}

static bool
xwidget_hidden (struct xwidget_view *xv)
{
  return xv->hidden;
}

struct xwidget *
xwidget_from_id (uint32_t id)
{
  Lisp_Object key = make_fixnum (id);
  Lisp_Object xwidget = Fgethash (key, id_to_xwidget_map, Qnil);

  if (NILP (xwidget))
    emacs_abort ();

  return XXWIDGET (xwidget);
}

#ifdef USE_GTK
static GdkWindow *
pick_embedded_child (GdkWindow *window, double x, double y,
		     gpointer user_data)
{
  GtkWidget *widget;
  GtkWidget *child;
  GdkEvent event;
  int xout, yout;

  event.any.window = window;
  event.any.type = GDK_NOTHING;

  widget = gtk_get_event_widget (&event);

  if (!widget)
    return NULL;

  child = find_widget_at_pos (widget, lrint (x), lrint (y),
			      &xout, &yout);

  if (!child)
    return NULL;

  return gtk_widget_get_window (child);
}

static void
record_osr_embedder (struct xwidget_view *view)
{
  struct xwidget *xw;
  GdkWindow *window, *embedder;

  xw = XXWIDGET (view->model);
  window = gtk_widget_get_window (xw->widgetwindow_osr);
#ifndef HAVE_PGTK
  embedder = gtk_widget_get_window (FRAME_GTK_OUTER_WIDGET (view->frame));
#else
  embedder = gtk_widget_get_window (view->widget);
#endif
  gdk_offscreen_window_set_embedder (window, embedder);
  xw->embedder = view->frame;
  xw->embedder_view = view;
}

static struct xwidget *
find_xwidget_for_offscreen_window (GdkWindow *window)
{
  Lisp_Object tem;
  struct xwidget *xw;
  GdkWindow *w;

  for (tem = internal_xwidget_list; CONSP (tem); tem = XCDR (tem))
    {
      if (XWIDGETP (XCAR (tem)))
	{
	  xw = XXWIDGET (XCAR (tem));
	  w = gtk_widget_get_window (xw->widgetwindow_osr);

	  if (w == window)
	    return xw;
	}
    }

  return NULL;
}

static void
from_embedder (GdkWindow *window, double x, double y,
	       gpointer x_out_ptr, gpointer y_out_ptr,
	       gpointer user_data)
{
  double *xout = x_out_ptr;
  double *yout = y_out_ptr;
#ifndef HAVE_PGTK
  struct xwidget *xw = find_xwidget_for_offscreen_window (window);
  struct xwidget_view *xvw;
  gint xoff, yoff;

  if (!xw)
    emacs_abort ();

  xvw = xw->embedder_view;

  if (!xvw)
    {
      *xout = x;
      *yout = y;
    }
  else
    {
      gtk_widget_translate_coordinates (FRAME_GTK_WIDGET (xvw->frame),
					FRAME_GTK_OUTER_WIDGET (xvw->frame),
					0, 0, &xoff, &yoff);

      *xout = x - xvw->x - xoff;
      *yout = y - xvw->y - yoff;
    }
#else
  *xout = x;
  *yout = y;
#endif
}

static void
to_embedder (GdkWindow *window, double x, double y,
	     gpointer x_out_ptr, gpointer y_out_ptr,
	     gpointer user_data)
{
  double *xout = x_out_ptr;
  double *yout = y_out_ptr;
#ifndef HAVE_PGTK
  struct xwidget *xw = find_xwidget_for_offscreen_window (window);
  struct xwidget_view *xvw;
  gint xoff, yoff;

  if (!xw)
    emacs_abort ();

  xvw = xw->embedder_view;

  if (!xvw)
    {
      *xout = x;
      *yout = y;
    }
  else
    {
      gtk_widget_translate_coordinates (FRAME_GTK_WIDGET (xvw->frame),
					FRAME_GTK_OUTER_WIDGET (xvw->frame),
					0, 0, &xoff, &yoff);

      *xout = x + xvw->x + xoff;
      *yout = y + xvw->y + yoff;
    }
#else
  *xout = x;
  *yout = y;
#endif
}

static GdkDevice *
find_suitable_pointer (struct frame *f)
{
  GdkSeat *seat = gdk_display_get_default_seat
    (gtk_widget_get_display (FRAME_GTK_WIDGET (f)));

  if (!seat)
    return NULL;

  return gdk_seat_get_pointer (seat);
}

static GdkDevice *
find_suitable_keyboard (struct frame *f)
{
  GdkSeat *seat = gdk_display_get_default_seat
    (gtk_widget_get_display (FRAME_GTK_WIDGET (f)));

  if (!seat)
    return NULL;

  return gdk_seat_get_keyboard (seat);
}

static void
find_widget_cb (GtkWidget *widget, void *user)
{
  find_widget (widget, user);
}

static void
find_widget (GtkWidget *widget,
	     struct widget_search_data *data)
{
  GtkAllocation new_allocation;
  GdkWindow *window;
  int x_offset = 0;
  int y_offset = 0;

  gtk_widget_get_allocation (widget, &new_allocation);

  if (gtk_widget_get_has_window (widget))
    {
      new_allocation.x = 0;
      new_allocation.y = 0;
    }

  if (gtk_widget_get_parent (widget) && !data->first)
    {
      window = gtk_widget_get_window (widget);
      while (window != gtk_widget_get_window (gtk_widget_get_parent (widget)))
	{
	  gint tx, ty, twidth, theight;

	  if (!window)
	    return;

	  twidth = gdk_window_get_width (window);
	  theight = gdk_window_get_height (window);

	  if (new_allocation.x < 0)
	    {
	      new_allocation.width += new_allocation.x;
	      new_allocation.x = 0;
	    }

	  if (new_allocation.y < 0)
	    {
	      new_allocation.height += new_allocation.y;
	      new_allocation.y = 0;
	    }

	  if (new_allocation.x + new_allocation.width > twidth)
	    new_allocation.width = twidth - new_allocation.x;
	  if (new_allocation.y + new_allocation.height > theight)
	    new_allocation.height = theight - new_allocation.y;

	  gdk_window_get_position (window, &tx, &ty);
	  new_allocation.x += tx;
	  x_offset += tx;
	  new_allocation.y += ty;
	  y_offset += ty;

	  window = gdk_window_get_parent (window);
	}
    }

  if ((data->x >= new_allocation.x) && (data->y >= new_allocation.y) &&
      (data->x < new_allocation.x + new_allocation.width) &&
      (data->y < new_allocation.y + new_allocation.height))
    {
      /* First, check if the drag is in a valid drop site in one of
	 our children.	*/
      if (GTK_IS_CONTAINER (widget))
	{
	  struct widget_search_data new_data = *data;

	  new_data.x -= x_offset;
	  new_data.y -= y_offset;
	  new_data.foundp = false;
	  new_data.first = false;

	  gtk_container_forall (GTK_CONTAINER (widget),
				find_widget_cb, &new_data);

	  data->foundp = new_data.foundp;
	  if (data->foundp)
	    data->data = new_data.data;
	}

      /* If not, and this widget is registered as a drop site, check
	 to emit "drag_motion" to check if we are actually in a drop
	 site.	*/
      if (!data->foundp)
	{
	  data->foundp = true;
	  data->data = widget;
	}
    }
}

static GtkWidget *
find_widget_at_pos (GtkWidget *w, int x, int y,
		    int *new_x, int *new_y)
{
  struct widget_search_data data;

  data.x = x;
  data.y = y;
  data.foundp = false;
  data.first = true;

  find_widget (w, &data);

  if (data.foundp)
    {
      gtk_widget_translate_coordinates (w, data.data, x,
					y, new_x, new_y);
      return data.data;
    }

  *new_x = x;
  *new_y = y;

  return NULL;
}

static Emacs_Cursor
cursor_for_hit (guint result, struct frame *frame)
{
  Emacs_Cursor cursor = FRAME_OUTPUT_DATA (frame)->nontext_cursor;

  if ((result & WEBKIT_HIT_TEST_RESULT_CONTEXT_EDITABLE)
      || (result & WEBKIT_HIT_TEST_RESULT_CONTEXT_SELECTION)
      || (result & WEBKIT_HIT_TEST_RESULT_CONTEXT_DOCUMENT))
    cursor = FRAME_X_OUTPUT (frame)->text_cursor;

  if (result & WEBKIT_HIT_TEST_RESULT_CONTEXT_SCROLLBAR)
    cursor = FRAME_X_OUTPUT (frame)->vertical_drag_cursor;

  if (result & WEBKIT_HIT_TEST_RESULT_CONTEXT_LINK)
    cursor = FRAME_X_OUTPUT (frame)->hand_cursor;

  return cursor;
}

static void
define_cursors (struct xwidget *xw, WebKitHitTestResult *res)
{
  struct xwidget_view *xvw;
#ifdef HAVE_PGTK
  GdkWindow *wdesc;
#endif

  xw->hit_result = webkit_hit_test_result_get_context (res);

  for (Lisp_Object tem = internal_xwidget_view_list; CONSP (tem);
       tem = XCDR (tem))
    {
      if (XWIDGET_VIEW_P (XCAR (tem)))
	{
	  xvw = XXWIDGET_VIEW (XCAR (tem));

	  if (XXWIDGET (xvw->model) == xw)
	    {
	      xvw->cursor = cursor_for_hit (xw->hit_result, xvw->frame);
#ifdef HAVE_X_WINDOWS
	      if (xvw->wdesc != None)
		XDefineCursor (xvw->dpy, xvw->wdesc, xvw->cursor);
#else
	      if (gtk_widget_get_realized (xvw->widget))
		{
		  wdesc = gtk_widget_get_window (xvw->widget);
		  gdk_window_set_cursor (wdesc, xvw->cursor);
		}
#endif
	    }
	}
    }
}

static void
mouse_target_changed (WebKitWebView *webview,
		      WebKitHitTestResult *hitresult,
		      guint modifiers, gpointer xw)
{
  define_cursors (xw, hitresult);
}

static gboolean
run_file_chooser_cb (WebKitWebView *webview,
		     WebKitFileChooserRequest *request,
		     gpointer user_data)
{
  struct frame *f = SELECTED_FRAME ();
  GtkFileChooserNative *chooser;
  GtkFileFilter *filter;
  bool select_multiple_p;
  guint response;
  GSList *filenames;
  GSList *tem;
  int i, len;
  gchar **files;

  /* Return TRUE to prevent WebKit from showing the default script
     dialog in the offscreen window, which runs a nested main loop
     Emacs can't respond to, and as such can't pass X events to.  */
  if (!FRAME_WINDOW_P (f))
    return TRUE;

  chooser = gtk_file_chooser_native_new ("Select file",
					 GTK_WINDOW (FRAME_GTK_OUTER_WIDGET (f)),
					 GTK_FILE_CHOOSER_ACTION_OPEN, "Select",
					 "Cancel");
  filter = webkit_file_chooser_request_get_mime_types_filter (request);
  select_multiple_p = webkit_file_chooser_request_get_select_multiple (request);

  gtk_file_chooser_set_select_multiple (GTK_FILE_CHOOSER (chooser),
					select_multiple_p);
  gtk_file_chooser_add_filter (GTK_FILE_CHOOSER (chooser), filter);
  response = gtk_native_dialog_run (GTK_NATIVE_DIALOG (chooser));

  if (response != GTK_RESPONSE_ACCEPT)
    {
      gtk_native_dialog_destroy (GTK_NATIVE_DIALOG (chooser));
      webkit_file_chooser_request_cancel (request);

      return TRUE;
    }

  filenames = gtk_file_chooser_get_filenames (GTK_FILE_CHOOSER (chooser));
  len = g_slist_length (filenames);
  files = alloca (sizeof *files * (len + 1));

  for (tem = filenames, i = 0; tem; tem = tem->next, ++i)
    files[i] = tem->data;
  files[len] = NULL;

  g_slist_free (filenames);
  webkit_file_chooser_request_select_files (request, (const gchar **) files);

  for (i = 0; i < len; ++i)
    g_free (files[i]);

  gtk_native_dialog_destroy (GTK_NATIVE_DIALOG (chooser));

  return TRUE;
}

#ifdef HAVE_X_WINDOWS

static void
xwidget_button_1 (struct xwidget_view *view,
		  bool down_p, int x, int y, int button,
		  int modifier_state, Time time)
{
  GdkEvent *xg_event = gdk_event_new (down_p ? GDK_BUTTON_PRESS : GDK_BUTTON_RELEASE);
  struct xwidget *model = XXWIDGET (view->model);
  GtkWidget *target;

  /* X and Y should be relative to the origin of view->wdesc.  */
  x += view->clip_left;
  y += view->clip_top;

  target = find_widget_at_pos (model->widgetwindow_osr, x, y, &x, &y);

  if (!target)
    target = model->widget_osr;

  xg_event->any.window = gtk_widget_get_window (target);
  g_object_ref (xg_event->any.window); /* The window will be unrefed
					  later by gdk_event_free.  */

  xg_event->button.x = x;
  xg_event->button.x_root = x;
  xg_event->button.y = y;
  xg_event->button.y_root = y;
  xg_event->button.button = button;
  xg_event->button.state = modifier_state;
  xg_event->button.time = time;
  xg_event->button.device = find_suitable_pointer (view->frame);

  gtk_main_do_event (xg_event);
  gdk_event_free (xg_event);
}

void
xwidget_button (struct xwidget_view *view,
		bool down_p, int x, int y, int button,
		int modifier_state, Time time)
{
  if (NILP (XXWIDGET (view->model)->buffer))
    return;

  record_osr_embedder (view);

  if (button < 4 || button > 8)
    xwidget_button_1 (view, down_p, x, y, button, modifier_state, time);
#ifndef HAVE_XINPUT2
  else
#else
  else if (!FRAME_DISPLAY_INFO (view->frame)->supports_xi2
	   || FRAME_DISPLAY_INFO (view->frame)->xi2_version < 1)
#endif
    {
      GdkEvent *xg_event = gdk_event_new (GDK_SCROLL);
      struct xwidget *model = XXWIDGET (view->model);
      GtkWidget *target;

      x += view->clip_left;
      y += view->clip_top;

      target = find_widget_at_pos (model->widgetwindow_osr, x, y, &x, &y);

      if (!target)
	target = model->widget_osr;

      xg_event->any.window = gtk_widget_get_window (target);
      g_object_ref (xg_event->any.window); /* The window will be unrefed
					      later by gdk_event_free.  */
      if (button == 4)
	xg_event->scroll.direction = GDK_SCROLL_UP;
      else if (button == 5)
	xg_event->scroll.direction = GDK_SCROLL_DOWN;
      else if (button == 6)
	xg_event->scroll.direction = GDK_SCROLL_LEFT;
      else
	xg_event->scroll.direction = GDK_SCROLL_RIGHT;

      xg_event->scroll.device = find_suitable_pointer (view->frame);

      xg_event->scroll.x = x;
      xg_event->scroll.x_root = x;
      xg_event->scroll.y = y;
      xg_event->scroll.y_root = y;
      xg_event->scroll.state = modifier_state;
      xg_event->scroll.time = time;

      xg_event->scroll.delta_x = 0;
      xg_event->scroll.delta_y = 0;

      gtk_main_do_event (xg_event);
      gdk_event_free (xg_event);
    }
}

#ifdef HAVE_XINPUT2
void
xwidget_motion_notify (struct xwidget_view *view,
		       double x, double y,
		       double root_x, double root_y,
		       uint state, Time time)
{
  GdkEvent *xg_event;
  GtkWidget *target;
  struct xwidget *model = XXWIDGET (view->model);
  int target_x, target_y;

  if (NILP (model->buffer))
    return;

  record_osr_embedder (view);

  target = find_widget_at_pos (model->widgetwindow_osr,
			       lrint (x + view->clip_left),
			       lrint (y + view->clip_top),
			       &target_x, &target_y);

  if (!target)
    {
      target_x = lrint (x);
      target_y = lrint (y);
      target = model->widget_osr;
    }

  xg_event = gdk_event_new (GDK_MOTION_NOTIFY);
  xg_event->any.window = gtk_widget_get_window (target);
  xg_event->motion.x = target_x;
  xg_event->motion.y = target_y;
  xg_event->motion.x_root = root_x;
  xg_event->motion.y_root = root_y;
  xg_event->motion.time = time;
  xg_event->motion.state = state;
  xg_event->motion.device = find_suitable_pointer (view->frame);

  g_object_ref (xg_event->any.window);

  gtk_main_do_event (xg_event);
  gdk_event_free (xg_event);
}

void
xwidget_scroll (struct xwidget_view *view, double x, double y,
		double dx, double dy, uint state, Time time,
		bool stop_p)
{
  GdkEvent *xg_event;
  GtkWidget *target;
  struct xwidget *model = XXWIDGET (view->model);
  int target_x, target_y;

  if (NILP (model->buffer))
    return;

  record_osr_embedder (view);

  target = find_widget_at_pos (model->widgetwindow_osr,
			       lrint (x + view->clip_left),
			       lrint (y + view->clip_top),
			       &target_x, &target_y);

  if (!target)
    {
      target_x = lrint (x);
      target_y = lrint (y);
      target = model->widget_osr;
    }

  xg_event = gdk_event_new (GDK_SCROLL);
  xg_event->any.window = gtk_widget_get_window (target);
  xg_event->scroll.direction = GDK_SCROLL_SMOOTH;
  xg_event->scroll.x = target_x;
  xg_event->scroll.y = target_y;
  xg_event->scroll.x_root = lrint (x);
  xg_event->scroll.y_root = lrint (y);
  xg_event->scroll.time = time;
  xg_event->scroll.state = state;
  xg_event->scroll.delta_x = dx;
  xg_event->scroll.delta_y = dy;
  xg_event->scroll.device = find_suitable_pointer (view->frame);
  xg_event->scroll.is_stop = stop_p;

  g_object_ref (xg_event->any.window);

  gtk_main_do_event (xg_event);
  gdk_event_free (xg_event);
}

#ifdef HAVE_USABLE_XI_GESTURE_PINCH_EVENT
void
xwidget_pinch (struct xwidget_view *view, XIGesturePinchEvent *xev)
{
#if GTK_CHECK_VERSION (3, 18, 0)
  GdkEvent *xg_event;
  GtkWidget *target;
  struct xwidget *model = XXWIDGET (view->model);
  int target_x, target_y;
  double x = xev->event_x;
  double y = xev->event_y;

  if (NILP (model->buffer))
    return;

  record_osr_embedder (view);

  target = find_widget_at_pos (model->widgetwindow_osr,
			       lrint (x + view->clip_left),
			       lrint (y + view->clip_top),
			       &target_x, &target_y);

  if (!target)
    {
      target_x = lrint (x);
      target_y = lrint (y);
      target = model->widget_osr;
    }

  xg_event = gdk_event_new (GDK_TOUCHPAD_PINCH);
  xg_event->any.window = gtk_widget_get_window (target);
  xg_event->touchpad_pinch.x = target_x;
  xg_event->touchpad_pinch.y = target_y;
  xg_event->touchpad_pinch.dx = xev->delta_x;
  xg_event->touchpad_pinch.dy = xev->delta_y;
  xg_event->touchpad_pinch.angle_delta = xev->delta_angle;
  xg_event->touchpad_pinch.scale = xev->scale;
  xg_event->touchpad_pinch.x_root = xev->root_x;
  xg_event->touchpad_pinch.y_root = xev->root_y;
  xg_event->touchpad_pinch.state = xev->mods.effective;
  xg_event->touchpad_pinch.n_fingers = 2;

  switch (xev->evtype)
    {
    case XI_GesturePinchBegin:
      xg_event->touchpad_pinch.phase = GDK_TOUCHPAD_GESTURE_PHASE_BEGIN;
      break;
    case XI_GesturePinchUpdate:
      xg_event->touchpad_pinch.phase = GDK_TOUCHPAD_GESTURE_PHASE_UPDATE;
      break;
    case XI_GesturePinchEnd:
      xg_event->touchpad_pinch.phase = GDK_TOUCHPAD_GESTURE_PHASE_END;
      break;
    }

  gdk_event_set_device (xg_event, find_suitable_pointer (view->frame));

  g_object_ref (xg_event->any.window);
  gtk_main_do_event (xg_event);
  gdk_event_free (xg_event);
#endif
}
#endif
#endif

#ifdef HAVE_XINPUT2
static GdkNotifyType
xi_translate_notify_detail (int detail)
{
  switch (detail)
    {
    case XINotifyInferior:
      return GDK_NOTIFY_INFERIOR;
    case XINotifyAncestor:
      return GDK_NOTIFY_ANCESTOR;
    case XINotifyVirtual:
      return GDK_NOTIFY_VIRTUAL;
    case XINotifyNonlinear:
      return GDK_NOTIFY_NONLINEAR;
    case XINotifyNonlinearVirtual:
      return GDK_NOTIFY_NONLINEAR_VIRTUAL;
    default:
      emacs_abort ();
    }
}
#endif

void
xwidget_motion_or_crossing (struct xwidget_view *view, const XEvent *event)
{
  GdkEvent *xg_event;
  struct xwidget *model = XXWIDGET (view->model);
  int x;
  int y;
  GtkWidget *target;
#ifdef HAVE_XINPUT2
  XIEnterEvent *xev = NULL;
#endif

  if (NILP (model->buffer))
    return;

#ifdef HAVE_XINPUT2
  if (event->type != GenericEvent)
#endif
    {
      xg_event = gdk_event_new (event->type == MotionNotify
				? GDK_MOTION_NOTIFY
				: (event->type == LeaveNotify
				   ? GDK_LEAVE_NOTIFY
				   : GDK_ENTER_NOTIFY));
      target = find_widget_at_pos (model->widgetwindow_osr,
				   (event->type == MotionNotify
				    ? event->xmotion.x + view->clip_left
				    : event->xcrossing.x + view->clip_left),
				   (event->type == MotionNotify
				    ? event->xmotion.y + view->clip_top
				    : event->xcrossing.y + view->clip_top),
				   &x, &y);
    }
#ifdef HAVE_XINPUT2
  else
    {
      eassert (event->xcookie.evtype == XI_Enter
	       || event->xcookie.evtype == XI_Leave);

      xev = (XIEnterEvent *) event->xcookie.data;
      xg_event = gdk_event_new (event->type == XI_Enter
				? GDK_ENTER_NOTIFY
				: GDK_LEAVE_NOTIFY);
      target = find_widget_at_pos (model->widgetwindow_osr,
				   lrint (xev->event_x + view->clip_left),
				   lrint (xev->event_y + view->clip_top),
				   &x, &y);
    }
#endif

  if (!target)
    target = model->widget_osr;

  record_osr_embedder (view);
  xg_event->any.window = gtk_widget_get_window (target);
  g_object_ref (xg_event->any.window); /* The window will be unrefed
					  later by gdk_event_free.  */

  if (event->type == MotionNotify)
    {
      xg_event->motion.x = x;
      xg_event->motion.y = y;
      xg_event->motion.x_root = event->xmotion.x_root;
      xg_event->motion.y_root = event->xmotion.y_root;
      xg_event->motion.time = event->xmotion.time;
      xg_event->motion.state = event->xmotion.state;
      xg_event->motion.device = find_suitable_pointer (view->frame);
    }
#ifdef HAVE_XINPUT2
  else if (event->type == GenericEvent)
    {
      xg_event->crossing.x = x;
      xg_event->crossing.y = y;
      xg_event->crossing.x_root = (gdouble) xev->root_x;
      xg_event->crossing.y_root = (gdouble) xev->root_y;
      xg_event->crossing.time = xev->time;
      xg_event->crossing.focus = xev->focus;
      xg_event->crossing.mode = xev->mode;
      xg_event->crossing.detail = xi_translate_notify_detail (xev->detail);
      xg_event->crossing.state = xev->mods.effective;

      if (xev->buttons.mask_len)
	{
	  if (XIMaskIsSet (xev->buttons.mask, 1))
	    xg_event->crossing.state |= GDK_BUTTON1_MASK;
	  if (XIMaskIsSet (xev->buttons.mask, 2))
	    xg_event->crossing.state |= GDK_BUTTON2_MASK;
	  if (XIMaskIsSet (xev->buttons.mask, 3))
	    xg_event->crossing.state |= GDK_BUTTON3_MASK;
	}

      gdk_event_set_device (xg_event, find_suitable_pointer (view->frame));
    }
#endif
  else
    {
      xg_event->crossing.detail = min (5, event->xcrossing.detail);
      xg_event->crossing.time = event->xcrossing.time;
      xg_event->crossing.x = x;
      xg_event->crossing.y = y;
      xg_event->crossing.x_root = event->xcrossing.x_root;
      xg_event->crossing.y_root = event->xcrossing.y_root;
      xg_event->crossing.focus = event->xcrossing.focus;
      gdk_event_set_device (xg_event, find_suitable_pointer (view->frame));
    }

  gtk_main_do_event (xg_event);
  gdk_event_free (xg_event);
}

#endif /* HAVE_X_WINDOWS */

static void
synthesize_focus_in_event (GtkWidget *offscreen_window)
{
  GdkWindow *wnd;
  GdkEvent *focus_event;

  if (!gtk_widget_get_realized (offscreen_window))
    gtk_widget_realize (offscreen_window);

  wnd = gtk_widget_get_window (offscreen_window);

  focus_event = gdk_event_new (GDK_FOCUS_CHANGE);
  focus_event->focus_change.window = wnd;
  focus_event->focus_change.in = TRUE;

  if (FRAME_WINDOW_P (SELECTED_FRAME ()))
    gdk_event_set_device (focus_event,
			  find_suitable_pointer (SELECTED_FRAME ()));

  g_object_ref (wnd);

  gtk_main_do_event (focus_event);
  gdk_event_free (focus_event);
}

#ifdef HAVE_X_WINDOWS
struct xwidget_view *
xwidget_view_from_window (Window wdesc)
{
  Lisp_Object key = make_fixnum (wdesc);
  Lisp_Object xwv = Fgethash (key, x_window_to_xwv_map, Qnil);

  if (NILP (xwv))
    return NULL;

  return XXWIDGET_VIEW (xwv);
}
#endif

static void
xwidget_show_view (struct xwidget_view *xv)
{
  xv->hidden = false;
#ifdef HAVE_X_WINDOWS
  XMoveWindow (xv->dpy, xv->wdesc,
	       xv->x + xv->clip_left,
	       xv->y + xv->clip_top);
  XMapWindow (xv->dpy, xv->wdesc);
  XFlush (xv->dpy);
#else
  gtk_fixed_move (GTK_FIXED (FRAME_GTK_WIDGET (xv->frame)),
		  xv->widget, xv->x + xv->clip_left,
		  xv->y + xv->clip_top);
  gtk_widget_show_all (xv->widget);
#endif
}

/* Hide an xwidget view.  */
static void
xwidget_hide_view (struct xwidget_view *xv)
{
  xv->hidden = true;
#ifdef HAVE_X_WINDOWS
  XUnmapWindow (xv->dpy, xv->wdesc);
  XFlush (xv->dpy);
#else
  gtk_widget_hide (xv->widget);
#endif
}

#ifndef HAVE_PGTK
static void
xv_do_draw (struct xwidget_view *xw, struct xwidget *w)
{
  GtkOffscreenWindow *wnd;
  cairo_surface_t *surface;

  if (xw->just_resized)
    return;

  if (NILP (w->buffer))
    {
      XClearWindow (xw->dpy, xw->wdesc);
      return;
    }

  block_input ();
  wnd = GTK_OFFSCREEN_WINDOW (w->widgetwindow_osr);
  surface = gtk_offscreen_window_get_surface (wnd);

  cairo_save (xw->cr_context);
  if (surface)
    {
      cairo_translate (xw->cr_context, -xw->clip_left, -xw->clip_top);
      cairo_set_source_surface (xw->cr_context, surface, 0, 0);
      cairo_set_operator (xw->cr_context, CAIRO_OPERATOR_SOURCE);
      cairo_paint (xw->cr_context);
    }
  cairo_restore (xw->cr_context);

  unblock_input ();
}
#else
static void
xwidget_view_draw_cb (GtkWidget *widget, cairo_t *cr,
		      gpointer data)
{
  struct xwidget_view *view = data;
  struct xwidget *w = XXWIDGET (view->model);
  GtkOffscreenWindow *wnd;
  cairo_surface_t *surface;

  if (NILP (w->buffer))
    return;

  block_input ();
  wnd = GTK_OFFSCREEN_WINDOW (w->widgetwindow_osr);
  surface = gtk_offscreen_window_get_surface (wnd);

  cairo_save (cr);
  if (surface)
    {
      cairo_translate (cr, -view->clip_left,
		       -view->clip_top);
      cairo_set_source_surface (cr, surface, 0, 0);
      cairo_set_operator (cr, CAIRO_OPERATOR_SOURCE);
      cairo_paint (cr);
    }
  cairo_restore (cr);

  unblock_input ();
}
#endif

/* When the off-screen webkit master view changes this signal is called.
   It copies the bitmap from the off-screen instance.  */
static gboolean
offscreen_damage_event (GtkWidget *widget, GdkEvent *event,
                        gpointer xwidget)
{
  block_input ();

  for (Lisp_Object tail = internal_xwidget_view_list; CONSP (tail);
       tail = XCDR (tail))
    {
      if (XWIDGET_VIEW_P (XCAR (tail)))
	{
	  struct xwidget_view *view = XXWIDGET_VIEW (XCAR (tail));
#ifdef HAVE_X_WINDOWS
	  if (view->wdesc && XXWIDGET (view->model) == xwidget)
	    xv_do_draw (view, XXWIDGET (view->model));
#else
	  gtk_widget_queue_draw (view->widget);
#endif
	}
    }

  unblock_input ();

  return FALSE;
}

#ifdef HAVE_X_WINDOWS
void
xwidget_expose (struct xwidget_view *xv)
{
  struct xwidget *xw = XXWIDGET (xv->model);

  xv_do_draw (xv, xw);
}
#endif
#endif /* USE_GTK */

void
store_xwidget_event_string (struct xwidget *xw, const char *eventname,
                            const char *eventstr)
{
  struct input_event event;
  Lisp_Object xwl;
  XSETXWIDGET (xwl, xw);
  EVENT_INIT (event);
  event.kind = XWIDGET_EVENT;
  event.frame_or_window = Qnil;
  event.arg = list3 (intern (eventname), xwl, build_string (eventstr));
  kbd_buffer_store_event (&event);
}

void
store_xwidget_download_callback_event (struct xwidget *xw,
                                       const char *url,
                                       const char *mimetype,
                                       const char *filename)
{
  struct input_event event;
  Lisp_Object xwl;
  XSETXWIDGET (xwl, xw);
  EVENT_INIT (event);
  event.kind = XWIDGET_EVENT;
  event.frame_or_window = Qnil;
  event.arg = list5 (intern ("download-callback"),
                     xwl,
                     build_string (url),
                     build_string (mimetype),
                     build_string (filename));
  kbd_buffer_store_event (&event);
}

void
store_xwidget_js_callback_event (struct xwidget *xw,
                                 Lisp_Object proc,
                                 Lisp_Object argument)
{
  struct input_event event;
  Lisp_Object xwl;
  XSETXWIDGET (xwl, xw);
  EVENT_INIT (event);
  event.kind = XWIDGET_EVENT;
  event.frame_or_window = Qnil;
  event.arg = list4 (intern ("javascript-callback"), xwl, proc, argument);
  kbd_buffer_store_event (&event);
}


#ifdef USE_GTK
static void
store_xwidget_display_event (struct xwidget *xw,
			     struct xwidget *src)
{
  struct input_event evt;
  Lisp_Object val, src_val;

  XSETXWIDGET (val, xw);
  XSETXWIDGET (src_val, src);
  EVENT_INIT (evt);
  evt.kind = XWIDGET_DISPLAY_EVENT;
  evt.frame_or_window = Qnil;
  evt.arg = list2 (val, src_val);
  kbd_buffer_store_event (&evt);
}

static void
webkit_ready_to_show (WebKitWebView *new_view,
		      gpointer user_data)
{
  Lisp_Object tem;
  struct xwidget *xw;
  struct xwidget *src;

  src = find_xwidget_for_offscreen_window (GDK_WINDOW (user_data));

  for (tem = internal_xwidget_list; CONSP (tem); tem = XCDR (tem))
    {
      if (XWIDGETP (XCAR (tem)))
	{
	  xw = XXWIDGET (XCAR (tem));

	  if (EQ (xw->type, Qwebkit)
	      && WEBKIT_WEB_VIEW (xw->widget_osr) == new_view)
	    {
	      /* The source widget was destroyed before we had a
		 chance to display the new widget.  */
	      if (!src)
		kill_xwidget (xw);
	      else
		store_xwidget_display_event (xw, src);
	    }
	}
    }
}

static GtkWidget *
webkit_create_cb_1 (WebKitWebView *webview,
		    struct xwidget *xv)
{
  Lisp_Object related;
  Lisp_Object xwidget;
  GtkWidget *widget;

  XSETXWIDGET (related, xv);
  xwidget = Fmake_xwidget (Qwebkit, Qnil, make_fixnum (0),
			   make_fixnum (0), Qnil,
			   build_string (" *detached xwidget buffer*"),
			   related);

  if (NILP (xwidget))
    return NULL;

  widget = XXWIDGET (xwidget)->widget_osr;

  g_signal_connect (G_OBJECT (widget), "ready-to-show",
		    G_CALLBACK (webkit_ready_to_show),
		    gtk_widget_get_window (xv->widgetwindow_osr));

  return widget;
}

static GtkWidget *
webkit_create_cb (WebKitWebView *webview,
		  WebKitNavigationAction *nav_action,
		  gpointer user_data)
{
  switch (webkit_navigation_action_get_navigation_type (nav_action))
    {
    case WEBKIT_NAVIGATION_TYPE_OTHER:
      return webkit_create_cb_1 (webview, user_data);

    case WEBKIT_NAVIGATION_TYPE_BACK_FORWARD:
    case WEBKIT_NAVIGATION_TYPE_RELOAD:
    case WEBKIT_NAVIGATION_TYPE_FORM_SUBMITTED:
    case WEBKIT_NAVIGATION_TYPE_FORM_RESUBMITTED:
    case WEBKIT_NAVIGATION_TYPE_LINK_CLICKED:
    default:
      return NULL;
    }
}

void
webkit_view_load_changed_cb (WebKitWebView *webkitwebview,
                             WebKitLoadEvent load_event,
                             gpointer data)
{
  struct xwidget *xw = g_object_get_data (G_OBJECT (webkitwebview),
					  XG_XWIDGET);

  switch (load_event)
    {
    case WEBKIT_LOAD_FINISHED:
      store_xwidget_event_string (xw, "load-changed", "load-finished");
      break;
    case WEBKIT_LOAD_STARTED:
      store_xwidget_event_string (xw, "load-changed", "load-started");
      break;
    case WEBKIT_LOAD_REDIRECTED:
      store_xwidget_event_string (xw, "load-changed", "load-redirected");
      break;
    case WEBKIT_LOAD_COMMITTED:
      store_xwidget_event_string (xw, "load-changed", "load-committed");
      break;
    }
}

/* Recursively convert a JavaScript value to a Lisp value. */
static Lisp_Object
webkit_js_to_lisp (JSCValue *value)
{
  if (jsc_value_is_string (value))
    {
      gchar *str_value = jsc_value_to_string (value);
      Lisp_Object ret = build_string (str_value);
      g_free (str_value);

      return ret;
    }
  else if (jsc_value_is_boolean (value))
    {
      return (jsc_value_to_boolean (value)) ? Qt : Qnil;
    }
  else if (jsc_value_is_number (value))
    {
      return make_fixnum (jsc_value_to_int32 (value));
    }
  else if (jsc_value_is_array (value))
    {
      JSCValue *len = jsc_value_object_get_property (value, "length");
      const gint32 dlen = jsc_value_to_int32 (len);

      Lisp_Object obj;
      if (! (0 <= dlen && dlen < PTRDIFF_MAX + 1.0))
	memory_full (SIZE_MAX);

      ptrdiff_t n = dlen;
      struct Lisp_Vector *p = allocate_nil_vector (n);

      for (ptrdiff_t i = 0; i < n; ++i)
	{
	  p->contents[i] =
	    webkit_js_to_lisp (jsc_value_object_get_property_at_index (value, i));
	}
      XSETVECTOR (obj, p);
      return obj;
    }
  else if (jsc_value_is_object (value))
    {
      char **properties_names = jsc_value_object_enumerate_properties (value);
      guint n = g_strv_length (properties_names);

      Lisp_Object obj;
      if (PTRDIFF_MAX < n)
	memory_full (n);
      struct Lisp_Vector *p = allocate_nil_vector (n);

      for (ptrdiff_t i = 0; i < n; ++i)
	{
	  const char *name = properties_names[i];
	  JSCValue *property = jsc_value_object_get_property (value, name);

	  p->contents[i] =
	    Fcons (build_string (name), webkit_js_to_lisp (property));
	}

      g_strfreev (properties_names);

      XSETVECTOR (obj, p);
      return obj;
    }

  return Qnil;
}

static void
webkit_javascript_finished_cb (GObject      *webview,
                               GAsyncResult *result,
                               gpointer      arg)
{
  GError *error = NULL;
  struct xwidget *xw = g_object_get_data (G_OBJECT (webview), XG_XWIDGET);

  ptrdiff_t script_idx = (intptr_t) arg;
  Lisp_Object script_callback = AREF (xw->script_callbacks, script_idx);
  ASET (xw->script_callbacks, script_idx, Qnil);
  if (!NILP (script_callback))
    xfree (xmint_pointer (XCAR (script_callback)));

  WebKitJavascriptResult *js_result =
    webkit_web_view_run_javascript_finish
    (WEBKIT_WEB_VIEW (webview), result, &error);

  if (!js_result)
    {
      if (error)
	g_error_free (error);
      return;
    }

  if (!NILP (script_callback) && !NILP (XCDR (script_callback)))
    {
      JSCValue *value = webkit_javascript_result_get_js_value (js_result);

      Lisp_Object lisp_value = webkit_js_to_lisp (value);

      /* Register an xwidget event here, which then runs the callback.
	 This ensures that the callback runs in sync with the Emacs
	 event loop.  */
      store_xwidget_js_callback_event (xw, XCDR (script_callback), lisp_value);
    }

  webkit_javascript_result_unref (js_result);
}


gboolean
webkit_download_cb (WebKitWebContext *webkitwebcontext,
                    WebKitDownload *arg1,
                    gpointer data)
{
  WebKitWebView *view = webkit_download_get_web_view(arg1);
  WebKitURIRequest *request = webkit_download_get_request(arg1);
  struct xwidget *xw = g_object_get_data (G_OBJECT (view),
                                          XG_XWIDGET);

  store_xwidget_event_string (xw, "download-started",
                              webkit_uri_request_get_uri(request));
  return FALSE;
}

static gboolean
webkit_decide_policy_cb (WebKitWebView *webView,
                         WebKitPolicyDecision *decision,
                         WebKitPolicyDecisionType type,
                         gpointer user_data)
{
  switch (type) {
  case WEBKIT_POLICY_DECISION_TYPE_RESPONSE:
    /* This function makes webkit send a download signal for all unknown
       mime types.  TODO: Defer the decision to Lisp, so that it's
       possible to make Emacs handle mime text for instance.  */
    {
      WebKitResponsePolicyDecision *response =
        WEBKIT_RESPONSE_POLICY_DECISION (decision);
      if (!webkit_response_policy_decision_is_mime_type_supported (response))
        {
          webkit_policy_decision_download (decision);
          return TRUE;
        }
      else
        return FALSE;
      break;
    }
  case WEBKIT_POLICY_DECISION_TYPE_NEW_WINDOW_ACTION:
    {
      WebKitNavigationPolicyDecision *navigation_decision =
        WEBKIT_NAVIGATION_POLICY_DECISION (decision);
      WebKitNavigationAction *navigation_action =
        webkit_navigation_policy_decision_get_navigation_action (navigation_decision);
      WebKitURIRequest *request =
        webkit_navigation_action_get_request (navigation_action);
      WebKitWebView *newview;
      struct xwidget *xw = g_object_get_data (G_OBJECT (webView), XG_XWIDGET);
      Lisp_Object val, new_xwidget;

      XSETXWIDGET (val, xw);

      new_xwidget = Fmake_xwidget (Qwebkit, Qnil, make_fixnum (0),
				   make_fixnum (0), Qnil,
				   build_string (" *detached xwidget buffer*"),
				   val);

      if (NILP (new_xwidget))
	return FALSE;

      newview = WEBKIT_WEB_VIEW (XXWIDGET (new_xwidget)->widget_osr);
      webkit_web_view_load_request (newview, request);

      store_xwidget_display_event (XXWIDGET (new_xwidget), xw);
      return TRUE;
    }
  case WEBKIT_POLICY_DECISION_TYPE_NAVIGATION_ACTION:
    {
      WebKitNavigationPolicyDecision *navigation_decision =
        WEBKIT_NAVIGATION_POLICY_DECISION (decision);
      WebKitNavigationAction *navigation_action =
        webkit_navigation_policy_decision_get_navigation_action (navigation_decision);
      WebKitURIRequest *request =
        webkit_navigation_action_get_request (navigation_action);

      struct xwidget *xw = g_object_get_data (G_OBJECT (webView), XG_XWIDGET);
      store_xwidget_event_string (xw, "decide-policy",
                                  webkit_uri_request_get_uri (request));
      return FALSE;
      break;
    }
  default:
    return FALSE;
  }
}

static gboolean
webkit_script_dialog_cb (WebKitWebView *webview,
			 WebKitScriptDialog *script_dialog,
			 gpointer user)
{
  struct frame *f = SELECTED_FRAME ();
  WebKitScriptDialogType type;
  GtkWidget *widget;
  GtkWidget *dialog;
  GtkWidget *entry;
  GtkWidget *content_area;
  GtkWidget *box;
  GtkWidget *label;
  const gchar *content;
  const gchar *message;
  gint result;

  /* Return TRUE to prevent WebKit from showing the default script
     dialog in the offscreen window, which runs a nested main loop
     Emacs can't respond to, and as such can't pass X events to.  */
  if (!FRAME_WINDOW_P (f))
    return TRUE;

  type = webkit_script_dialog_get_dialog_type (script_dialog);;
  widget = FRAME_GTK_OUTER_WIDGET (f);
  content = webkit_script_dialog_get_message (script_dialog);

  if (type == WEBKIT_SCRIPT_DIALOG_ALERT)
    dialog = gtk_dialog_new_with_buttons ("Alert", GTK_WINDOW (widget),
					  GTK_DIALOG_MODAL,
					  "Dismiss", 1, NULL);
  else
    dialog = gtk_dialog_new_with_buttons ("Question", GTK_WINDOW (widget),
					  GTK_DIALOG_MODAL,
					  "OK", 0, "Cancel", 1, NULL);

  box = gtk_box_new (GTK_ORIENTATION_VERTICAL, 8);
  label = gtk_label_new (content);
  content_area = gtk_dialog_get_content_area (GTK_DIALOG (dialog));
  gtk_container_add (GTK_CONTAINER (content_area), box);

  gtk_widget_show (box);
  gtk_widget_show (label);

  gtk_box_pack_start (GTK_BOX (box), label, TRUE, TRUE, 0);

  if (type == WEBKIT_SCRIPT_DIALOG_PROMPT)
    {
      entry = gtk_entry_new ();
      message = webkit_script_dialog_prompt_get_default_text (script_dialog);

      gtk_widget_show (entry);
      gtk_entry_set_text (GTK_ENTRY (entry), message);
      gtk_box_pack_end (GTK_BOX (box), entry, TRUE, TRUE, 0);
    }

  result = gtk_dialog_run (GTK_DIALOG (dialog));

  if (type == WEBKIT_SCRIPT_DIALOG_CONFIRM
      || type == WEBKIT_SCRIPT_DIALOG_BEFORE_UNLOAD_CONFIRM)
    webkit_script_dialog_confirm_set_confirmed (script_dialog, result == 0);

  if (type == WEBKIT_SCRIPT_DIALOG_PROMPT)
    webkit_script_dialog_prompt_set_text (script_dialog,
					  gtk_entry_get_text (GTK_ENTRY (entry)));

  gtk_widget_destroy (GTK_WIDGET (dialog));

  return TRUE;
}
#endif /* USE_GTK */


/* Initializes and does initial placement of an xwidget view on screen.  */
static struct xwidget_view *
xwidget_init_view (struct xwidget *xww,
                   struct glyph_string *s,
                   int x, int y)
{

#ifdef USE_GTK
  if (!xg_gtk_initialized)
    error ("xwidget_init_view: GTK has not been initialized");
#endif

  struct xwidget_view *xv = allocate_xwidget_view ();
  Lisp_Object val;

  XSETXWIDGET_VIEW (val, xv);
  internal_xwidget_view_list = Fcons (val, internal_xwidget_view_list);
  Vxwidget_view_list = Fcopy_sequence (internal_xwidget_view_list);

  XSETWINDOW (xv->w, s->w);
  XSETXWIDGET (xv->model, xww);

#ifdef HAVE_X_WINDOWS
  xv->dpy = FRAME_X_DISPLAY (s->f);

  xv->x = x;
  xv->y = y;

  xv->clip_left = 0;
  xv->clip_right = xww->width;
  xv->clip_top = 0;
  xv->clip_bottom = xww->height;

  xv->wdesc = None;
  xv->frame = s->f;
  xv->cursor = cursor_for_hit (xww->hit_result, s->f);
  xv->just_resized = false;
#elif defined HAVE_PGTK
  xv->dpyinfo = FRAME_DISPLAY_INFO (s->f);
  xv->widget = gtk_drawing_area_new ();
  gtk_widget_set_app_paintable (xv->widget, TRUE);
  gtk_widget_add_events (xv->widget, GDK_ALL_EVENTS_MASK);
  gtk_container_add (GTK_CONTAINER (FRAME_GTK_WIDGET (s->f)),
		     xv->widget);

  g_signal_connect (xv->widget, "draw",
		    G_CALLBACK (xwidget_view_draw_cb), xv);
  g_signal_connect (xv->widget, "event",
		    G_CALLBACK (xw_forward_event_from_view), xv);

  g_object_set_data (G_OBJECT (xv->widget), XG_XWIDGET_VIEW, xv);

  xv->x = x;
  xv->y = y;

  xv->clip_left = 0;
  xv->clip_right = xww->width;
  xv->clip_top = 0;
  xv->clip_bottom = xww->height;

  xv->frame = s->f;
  xv->cursor = cursor_for_hit (xww->hit_result, s->f);
  xv->just_resized = false;
#elif defined NS_IMPL_COCOA
  nsxwidget_init_view (xv, xww, s, x, y);
  nsxwidget_resize_view(xv, xww->width, xww->height);
#endif

  return xv;
}

void
x_draw_xwidget_glyph_string (struct glyph_string *s)
{
  /* This method is called by the redisplay engine and places the
     xwidget on screen.  Moving and clipping is done here.  Also view
     initialization.  */
  struct xwidget *xww = s->xwidget;
  struct xwidget_view *xv = xwidget_view_lookup (xww, s->w);
  int text_area_x, text_area_y, text_area_width, text_area_height;
  int clip_right;
  int clip_bottom;
  int clip_top;
  int clip_left;

  int x = s->x;
  int y = s->y + (s->height / 2) - (xww->height / 2);

  /* Do initialization here in the display loop because there is no
     other time to know things like window placement etc.  Do not
     create a new view if we have found one that is usable.  */
#ifdef USE_GTK
  if (!xv)
    xv = xwidget_init_view (xww, s, x, y);

  xv->just_resized = false;
#elif defined NS_IMPL_COCOA
  if (!xv)
    {
      /* Enforce 1 to 1, model and view for macOS Cocoa webkit2.  */
      if (xww->xv)
        {
          if (xwidget_hidden (xww->xv))
            {
              Lisp_Object xvl;
              XSETXWIDGET_VIEW (xvl, xww->xv);
              Fdelete_xwidget_view (xvl);
            }
          else
            {
              message ("You can't share an xwidget (webkit2) among windows.");
              return;
            }
        }
      xv = xwidget_init_view (xww, s, x, y);
    }
#endif

  xv->area = s->area;

  window_box (s->w, xv->area, &text_area_x, &text_area_y,
              &text_area_width, &text_area_height);

  clip_left = max (0, text_area_x - x);
  clip_right = max (clip_left,
		    min (xww->width, text_area_x + text_area_width - x));
  clip_top = max (0, text_area_y - y);
  clip_bottom = max (clip_top,
		     min (xww->height, text_area_y + text_area_height - y));

  /* We are concerned with movement of the onscreen area.  The area
     might sit still when the widget actually moves.  This happens
     when an Emacs window border moves across a widget window.  So, if
     any corner of the outer widget clipping window moves, that counts
     as movement here, even if it looks like no movement happens
     because the widget sits still inside the clipping area.  The
     widget can also move inside the clipping area, which happens
     later.  */
  bool moved = (xv->x + xv->clip_left != x + clip_left
		|| xv->y + xv->clip_top != y + clip_top);

#ifdef HAVE_X_WINDOWS
  bool wdesc_was_none = xv->wdesc == None;
#endif
  xv->x = x;
  xv->y = y;

#ifdef HAVE_X_WINDOWS
  block_input ();
  if (xv->wdesc == None)
    {
      Lisp_Object xvw;
      XSETXWIDGET_VIEW (xvw, xv);
      XSetWindowAttributes a;
      a.event_mask = (ExposureMask | ButtonPressMask | ButtonReleaseMask
		      | PointerMotionMask | EnterWindowMask | LeaveWindowMask);

      if (clip_right - clip_left <= 0
	  || clip_bottom - clip_top <= 0)
	{
	  unblock_input ();
	  return;
	}

      xv->wdesc = XCreateWindow (xv->dpy, FRAME_X_WINDOW (s->f),
				 x + clip_left, y + clip_top,
				 clip_right - clip_left,
				 clip_bottom - clip_top, 0,
				 CopyFromParent, CopyFromParent,
				 CopyFromParent, CWEventMask, &a);
#ifdef HAVE_XINPUT2
      XIEventMask mask;
      ptrdiff_t l = XIMaskLen (XI_LASTEVENT);
      unsigned char *m;

      if (FRAME_DISPLAY_INFO (s->f)->supports_xi2)
	{
	  mask.mask = m = alloca (l);
	  memset (m, 0, l);
	  mask.mask_len = l;
	  mask.deviceid = XIAllMasterDevices;

	  XISetMask (m, XI_Motion);
	  XISetMask (m, XI_ButtonPress);
	  XISetMask (m, XI_ButtonRelease);
	  XISetMask (m, XI_Enter);
	  XISetMask (m, XI_Leave);
#ifdef XI_GesturePinchBegin
	  if (FRAME_DISPLAY_INFO (s->f)->xi2_version >= 4)
	    {
	      XISetMask (m, XI_GesturePinchBegin);
	      XISetMask (m, XI_GesturePinchUpdate);
	      XISetMask (m, XI_GesturePinchEnd);
	    }
#endif
	  XISelectEvents (xv->dpy, xv->wdesc, &mask, 1);
	}
#endif
      XLowerWindow (xv->dpy, xv->wdesc);
      XDefineCursor (xv->dpy, xv->wdesc, xv->cursor);
      xv->cr_surface = cairo_xlib_surface_create (xv->dpy,
						  xv->wdesc,
						  FRAME_DISPLAY_INFO (s->f)->visual,
						  clip_right - clip_left,
						  clip_bottom - clip_top);
      xv->cr_context = cairo_create (xv->cr_surface);
      Fputhash (make_fixnum (xv->wdesc), xvw, x_window_to_xwv_map);

      moved = false;
    }
#endif
#ifdef HAVE_PGTK
  block_input ();
#endif

  /* Has it moved?  */
  if (moved)
    {
#ifdef HAVE_X_WINDOWS
      XMoveResizeWindow (xv->dpy, xv->wdesc, x + clip_left, y + clip_top,
			 clip_right - clip_left, clip_bottom - clip_top);
      XFlush (xv->dpy);
      cairo_xlib_surface_set_size (xv->cr_surface, clip_right - clip_left,
				   clip_bottom - clip_top);
#elif defined HAVE_PGTK
      gtk_widget_set_size_request (xv->widget, clip_right - clip_left,
				   clip_bottom - clip_top);
      gtk_fixed_move (GTK_FIXED (FRAME_GTK_WIDGET (xv->frame)),
		      xv->widget, x + clip_left, y + clip_top);
      gtk_widget_queue_allocate (xv->widget);
#elif defined NS_IMPL_COCOA
      nsxwidget_move_view (xv, x + clip_left, y + clip_top);
#endif
    }

  /* Clip the widget window if some parts happen to be outside
     drawable area.  An Emacs window is not a gtk window.  A gtk window
     covers the entire frame.  Clipping might have changed even if we
     haven't actually moved; try to figure out when we need to reclip
     for real.  */
#ifndef HAVE_PGTK
  if (xv->clip_right != clip_right
      || xv->clip_bottom != clip_bottom
      || xv->clip_top != clip_top || xv->clip_left != clip_left)
#endif
    {
#ifdef USE_GTK
#ifdef HAVE_X_WINDOWS
      if (!wdesc_was_none && !moved)
	{
	  if (clip_right - clip_left <= 0
	      || clip_bottom - clip_top <= 0)
	    {
	      XUnmapWindow (xv->dpy, xv->wdesc);
	      xv->hidden = true;
	    }
	  else
	    {
	      XResizeWindow (xv->dpy, xv->wdesc, clip_right - clip_left,
			     clip_bottom - clip_top);
	    }
	  XFlush (xv->dpy);
	  cairo_xlib_surface_set_size (xv->cr_surface, clip_right - clip_left,
				       clip_bottom - clip_top);
	}
#else
      gtk_widget_set_size_request (xv->widget, clip_right - clip_left,
				   clip_bottom - clip_top);
      gtk_fixed_move (GTK_FIXED (FRAME_GTK_WIDGET (xv->frame)),
		      xv->widget, x + clip_left, y + clip_top);
      gtk_widget_queue_allocate (xv->widget);
#endif
#elif defined NS_IMPL_COCOA
      nsxwidget_resize_view (xv, clip_right - clip_left,
                             clip_bottom - clip_top);
      nsxwidget_move_widget_in_view (xv, -clip_left, -clip_top);
#endif

      xv->clip_right = clip_right;
      xv->clip_bottom = clip_bottom;
      xv->clip_top = clip_top;
      xv->clip_left = clip_left;
    }

  /* If emacs wants to repaint the area where the widget lives, queue
     a redraw.  It seems its possible to get out of sync with emacs
     redraws so emacs background sometimes shows up instead of the
     xwidgets background.  It's just a visual glitch though.  */
  /* When xww->buffer is nil, that means the xwidget has been killed.  */
  if (!NILP (xww->buffer))
    {
      if (!xwidget_hidden (xv))
	{
#ifdef USE_GTK
	  gtk_widget_queue_draw (xww->widget_osr);
#elif defined NS_IMPL_COCOA
	  nsxwidget_set_needsdisplay (xv);
#endif
	}
    }
#ifdef HAVE_X_WINDOWS
  else
    {
      XSetWindowBackground (xv->dpy, xv->wdesc,
			    FRAME_BACKGROUND_PIXEL (s->f));
    }
#endif

#if defined HAVE_XINPUT2 || defined HAVE_PGTK
  record_osr_embedder (xv);
  synthesize_focus_in_event (xww->widget_osr);
#endif

#ifdef USE_GTK
  unblock_input ();
#endif
}

#define CHECK_WEBKIT_WIDGET(xw)				\
  if (NILP (xw->buffer) || !EQ (xw->type, Qwebkit))	\
    error ("Not a WebKit widget")

/* Macro that checks xwidget hold webkit web view first.  */
#define WEBKIT_FN_INIT()						\
  CHECK_LIVE_XWIDGET (xwidget);						\
  struct xwidget *xw = XXWIDGET (xwidget);				\
  CHECK_WEBKIT_WIDGET (xw)

DEFUN ("xwidget-webkit-uri",
       Fxwidget_webkit_uri, Sxwidget_webkit_uri,
       1, 1, 0,
       doc: /* Get the current URL of XWIDGET webkit.  */)
  (Lisp_Object xwidget)
{
  WEBKIT_FN_INIT ();
#ifdef USE_GTK
  WebKitWebView *wkwv = WEBKIT_WEB_VIEW (xw->widget_osr);
  const gchar *uri = webkit_web_view_get_uri (wkwv);
  if (!uri)
    return build_string ("");
  return build_string (uri);
#elif defined NS_IMPL_COCOA
  return nsxwidget_webkit_uri (xw);
#endif
}

DEFUN ("xwidget-webkit-title",
       Fxwidget_webkit_title, Sxwidget_webkit_title,
       1, 1, 0,
       doc: /* Get the current title of XWIDGET webkit.  */)
  (Lisp_Object xwidget)
{
  WEBKIT_FN_INIT ();
#ifdef USE_GTK
  WebKitWebView *wkwv = WEBKIT_WEB_VIEW (xw->widget_osr);
  const gchar *title = webkit_web_view_get_title (wkwv);

  return build_string (title ? title : "");
#elif defined NS_IMPL_COCOA
  return nsxwidget_webkit_title (xw);
#endif
}

DEFUN ("xwidget-webkit-goto-uri",
       Fxwidget_webkit_goto_uri, Sxwidget_webkit_goto_uri,
       2, 2, 0,
       doc: /* Make the xwidget webkit instance referenced by XWIDGET browse URI.  */)
  (Lisp_Object xwidget, Lisp_Object uri)
{
  WEBKIT_FN_INIT ();
  CHECK_STRING (uri);
  uri = ENCODE_FILE (uri);
#ifdef USE_GTK
  webkit_web_view_load_uri (WEBKIT_WEB_VIEW (xw->widget_osr), SSDATA (uri));
  catch_child_signal ();
#elif defined NS_IMPL_COCOA
  nsxwidget_webkit_goto_uri (xw, SSDATA (uri));
#endif
  return Qnil;
}

DEFUN ("xwidget-webkit-goto-history",
       Fxwidget_webkit_goto_history, Sxwidget_webkit_goto_history,
       2, 2, 0,
       doc: /* Make the XWIDGET webkit the REL-POSth element in load history.

If REL-POS is 0, the widget will be just reload the current element in
history.  If REL-POS is more or less than 0, the widget will load the
REL-POSth element around the current spot in the load history. */)
  (Lisp_Object xwidget, Lisp_Object rel_pos)
{
  WEBKIT_FN_INIT ();
  CHECK_FIXNUM (rel_pos);

#ifdef USE_GTK
  WebKitWebView *wkwv = WEBKIT_WEB_VIEW (xw->widget_osr);
  WebKitBackForwardList *list;
  WebKitBackForwardListItem *it;

  if (XFIXNUM (rel_pos) == 0)
    webkit_web_view_reload (wkwv);
  else
    {
      list = webkit_web_view_get_back_forward_list (wkwv);
      it = webkit_back_forward_list_get_nth_item (list, XFIXNUM (rel_pos));

      if (!it)
	error ("There is no item at this index");

      webkit_web_view_go_to_back_forward_list_item (wkwv, it);
    }
#elif defined NS_IMPL_COCOA
  nsxwidget_webkit_goto_history (xw, XFIXNAT (rel_pos));
#endif
  return Qnil;
}

DEFUN ("xwidget-webkit-zoom",
       Fxwidget_webkit_zoom, Sxwidget_webkit_zoom,
       2, 2, 0,
       doc: /* Change the zoom factor of the xwidget webkit instance referenced by XWIDGET.  */)
  (Lisp_Object xwidget, Lisp_Object factor)
{
  WEBKIT_FN_INIT ();
  if (FLOATP (factor))
    {
      double zoom_change = XFLOAT_DATA (factor);
#ifdef USE_GTK
      webkit_web_view_set_zoom_level
        (WEBKIT_WEB_VIEW (xw->widget_osr),
         webkit_web_view_get_zoom_level
         (WEBKIT_WEB_VIEW (xw->widget_osr)) + zoom_change);
#elif defined NS_IMPL_COCOA
      nsxwidget_webkit_zoom (xw, zoom_change);
#endif
    }
  return Qnil;
}

#ifdef USE_GTK
/* Save script and fun in the script/callback save vector and return
   its index.  */
static ptrdiff_t
save_script_callback (struct xwidget *xw, Lisp_Object script, Lisp_Object fun)
{
  Lisp_Object cbs = xw->script_callbacks;
  if (NILP (cbs))
    xw->script_callbacks = cbs = make_nil_vector (32);

  /* Find first free index.  */
  ptrdiff_t idx;
  for (idx = 0; !NILP (AREF (cbs, idx)); idx++)
    if (idx + 1 == ASIZE (cbs))
      {
	xw->script_callbacks = cbs = larger_vector (cbs, 1, -1);
	break;
      }

  ASET (cbs, idx, Fcons (make_mint_ptr (xlispstrdup (script)), fun));
  return idx;
}
#endif

DEFUN ("xwidget-webkit-execute-script",
       Fxwidget_webkit_execute_script, Sxwidget_webkit_execute_script,
       2, 3, 0,
       doc: /* Make the Webkit XWIDGET execute JavaScript SCRIPT.
If FUN is provided, feed the JavaScript return value to the single
argument procedure FUN.*/)
  (Lisp_Object xwidget, Lisp_Object script, Lisp_Object fun)
{
  WEBKIT_FN_INIT ();
  CHECK_STRING (script);
  if (!NILP (fun) && !FUNCTIONP (fun))
    wrong_type_argument (Qinvalid_function, fun);

  script = ENCODE_SYSTEM (script);

#ifdef USE_GTK
  /* Protect script and fun during GC.  */
  intptr_t idx = save_script_callback (xw, script, fun);

  /* JavaScript execution happens asynchronously.  If an elisp
     callback function is provided we pass it to the C callback
     procedure that retrieves the return value.  */
  gchar *script_string
    = xmint_pointer (XCAR (AREF (xw->script_callbacks, idx)));
  webkit_web_view_run_javascript (WEBKIT_WEB_VIEW (xw->widget_osr),
				  script_string,
                                  NULL, /* cancelable */
                                  webkit_javascript_finished_cb,
				  (gpointer) idx);
#elif defined NS_IMPL_COCOA
  nsxwidget_webkit_execute_script (xw, SSDATA (script), fun);
#endif
  return Qnil;
}

DEFUN ("xwidget-resize", Fxwidget_resize, Sxwidget_resize, 3, 3, 0,
       doc: /* Resize XWIDGET to NEW_WIDTH, NEW_HEIGHT.  */ )
  (Lisp_Object xwidget, Lisp_Object new_width, Lisp_Object new_height)
{
  CHECK_LIVE_XWIDGET (xwidget);
  int w = check_integer_range (new_width, 0, INT_MAX);
  int h = check_integer_range (new_height, 0, INT_MAX);
  struct xwidget *xw = XXWIDGET (xwidget);

  xw->width = w;
  xw->height = h;

  block_input ();

  for (Lisp_Object tail = internal_xwidget_view_list; CONSP (tail);
       tail = XCDR (tail))
    {
      if (XWIDGET_VIEW_P (XCAR (tail)))
        {
          struct xwidget_view *xv = XXWIDGET_VIEW (XCAR (tail));
          if (XXWIDGET (xv->model) == xw)
            {
#ifdef USE_GTK
	      xv->just_resized = true;
	      SET_FRAME_GARBAGED (xv->frame);
#else
	      wset_redisplay (XWINDOW (xv->w));
#endif
            }
        }
    }

  redisplay ();

  /* If there is an offscreen widget resize it first.  */
#ifdef USE_GTK
  if (xw->widget_osr)
    {
      gtk_window_resize (GTK_WINDOW (xw->widgetwindow_osr), xw->width,
                         xw->height);
      gtk_widget_set_size_request (GTK_WIDGET (xw->widget_osr), xw->width,
                                   xw->height);

      gtk_widget_queue_allocate (GTK_WIDGET (xw->widget_osr));
    }
#elif defined NS_IMPL_COCOA
  nsxwidget_resize (xw);
#endif
  unblock_input ();

  return Qnil;
}




DEFUN ("xwidget-size-request",
       Fxwidget_size_request, Sxwidget_size_request,
       1, 1, 0,
       doc: /* Return the desired size of the XWIDGET.
This can be used to read the xwidget desired size, and resizes the
Emacs allocated area accordingly.  */)
  (Lisp_Object xwidget)
{
  CHECK_LIVE_XWIDGET (xwidget);
#ifdef USE_GTK
  GtkRequisition requisition;
  gtk_widget_size_request (XXWIDGET (xwidget)->widget_osr, &requisition);
  return list2i (requisition.width, requisition.height);
#elif defined NS_IMPL_COCOA
  return nsxwidget_get_size (XXWIDGET (xwidget));
#endif
}

DEFUN ("xwidgetp",
       Fxwidgetp, Sxwidgetp,
       1, 1, 0,
       doc: /* Return t if OBJECT is an xwidget.  */)
  (Lisp_Object object)
{
  return XWIDGETP (object) ? Qt : Qnil;
}

DEFUN ("xwidget-view-p",
       Fxwidget_view_p, Sxwidget_view_p,
       1, 1, 0,
       doc: /* Return t if OBJECT is an xwidget-view.  */)
  (Lisp_Object object)
{
  return XWIDGET_VIEW_P (object) ? Qt : Qnil;
}

DEFUN ("xwidget-info",
       Fxwidget_info, Sxwidget_info,
       1, 1, 0,
       doc: /* Return XWIDGET properties in a vector.
Currently [TYPE TITLE WIDTH HEIGHT].  */)
  (Lisp_Object xwidget)
{
  CHECK_LIVE_XWIDGET (xwidget);
  struct xwidget *xw = XXWIDGET (xwidget);
  return CALLN (Fvector, xw->type, xw->title,
		make_fixed_natnum (xw->width), make_fixed_natnum (xw->height));
}

DEFUN ("xwidget-view-info",
       Fxwidget_view_info, Sxwidget_view_info,
       1, 1, 0,
       doc: /* Return properties of XWIDGET-VIEW in a vector.
Currently [X Y CLIP_RIGHT CLIP_BOTTOM CLIP_TOP CLIP_LEFT].  */)
  (Lisp_Object xwidget_view)
{
  CHECK_XWIDGET_VIEW (xwidget_view);
  struct xwidget_view *xv = XXWIDGET_VIEW (xwidget_view);
  return CALLN (Fvector, make_fixnum (xv->x), make_fixnum (xv->y),
		make_fixnum (xv->clip_right), make_fixnum (xv->clip_bottom),
		make_fixnum (xv->clip_top), make_fixnum (xv->clip_left));
}

DEFUN ("xwidget-view-model",
       Fxwidget_view_model, Sxwidget_view_model,
       1, 1, 0,
       doc:  /* Return the model associated with XWIDGET-VIEW.  */)
  (Lisp_Object xwidget_view)
{
  CHECK_XWIDGET_VIEW (xwidget_view);
  return XXWIDGET_VIEW (xwidget_view)->model;
}

DEFUN ("xwidget-view-window",
       Fxwidget_view_window, Sxwidget_view_window,
       1, 1, 0,
       doc:  /* Return the window of XWIDGET-VIEW.  */)
  (Lisp_Object xwidget_view)
{
  CHECK_XWIDGET_VIEW (xwidget_view);
  return XXWIDGET_VIEW (xwidget_view)->w;
}


DEFUN ("delete-xwidget-view",
       Fdelete_xwidget_view, Sdelete_xwidget_view,
       1, 1, 0,
       doc:  /* Delete the XWIDGET-VIEW.  */)
  (Lisp_Object xwidget_view)
{
  CHECK_XWIDGET_VIEW (xwidget_view);
  struct xwidget_view *xv = XXWIDGET_VIEW (xwidget_view);

  block_input ();
#ifdef USE_GTK
  struct xwidget *xw = XXWIDGET (xv->model);
  GdkWindow *w;
#ifdef HAVE_X_WINDOWS
  if (xv->wdesc != None)
    {
      cairo_destroy (xv->cr_context);
      cairo_surface_destroy (xv->cr_surface);
      XDestroyWindow (xv->dpy, xv->wdesc);
      Fremhash (make_fixnum (xv->wdesc), x_window_to_xwv_map);
    }
#else
  gtk_widget_destroy (xv->widget);
#endif

  if (xw->embedder_view == xv && !NILP (xw->buffer))
    {
      w = gtk_widget_get_window (xw->widgetwindow_osr);

      XXWIDGET (xv->model)->embedder_view = NULL;
      XXWIDGET (xv->model)->embedder = NULL;

      gdk_offscreen_window_set_embedder (w, NULL);
    }
#elif defined NS_IMPL_COCOA
  nsxwidget_delete_view (xv);
#endif

  internal_xwidget_view_list = Fdelq (xwidget_view, internal_xwidget_view_list);
  Vxwidget_view_list = Fcopy_sequence (internal_xwidget_view_list);
  unblock_input ();
  return Qnil;
}

DEFUN ("xwidget-view-lookup",
       Fxwidget_view_lookup, Sxwidget_view_lookup,
       1, 2, 0,
       doc: /* Return the xwidget-view associated with XWIDGET in WINDOW.
If WINDOW is unspecified or nil, use the selected window.
Return nil if no association is found.  */)
  (Lisp_Object xwidget, Lisp_Object window)
{
  CHECK_XWIDGET (xwidget);

  if (NILP (window))
    window = Fselected_window ();
  CHECK_WINDOW (window);

  for (Lisp_Object tail = internal_xwidget_view_list; CONSP (tail);
       tail = XCDR (tail))
    {
      Lisp_Object xwidget_view = XCAR (tail);
      if (EQ (Fxwidget_view_model (xwidget_view), xwidget)
          && EQ (Fxwidget_view_window (xwidget_view), window))
        return xwidget_view;
    }

  return Qnil;
}

DEFUN ("xwidget-plist",
       Fxwidget_plist, Sxwidget_plist,
       1, 1, 0,
       doc: /* Return the plist of XWIDGET.  */)
  (Lisp_Object xwidget)
{
  CHECK_LIVE_XWIDGET (xwidget);
  return XXWIDGET (xwidget)->plist;
}

DEFUN ("xwidget-buffer",
       Fxwidget_buffer, Sxwidget_buffer,
       1, 1, 0,
       doc: /* Return the buffer of XWIDGET.  */)
  (Lisp_Object xwidget)
{
  CHECK_XWIDGET (xwidget);
  return XXWIDGET (xwidget)->buffer;
}

DEFUN ("set-xwidget-buffer",
       Fset_xwidget_buffer, Sset_xwidget_buffer,
       2, 2, 0,
       doc: /* Set XWIDGET's buffer to BUFFER.  */)
  (Lisp_Object xwidget, Lisp_Object buffer)
{
  CHECK_LIVE_XWIDGET (xwidget);
  CHECK_BUFFER (buffer);

  XXWIDGET (xwidget)->buffer = buffer;
  return Qnil;
}

DEFUN ("set-xwidget-plist",
       Fset_xwidget_plist, Sset_xwidget_plist,
       2, 2, 0,
       doc: /* Replace the plist of XWIDGET with PLIST.
Returns PLIST.  */)
  (Lisp_Object xwidget, Lisp_Object plist)
{
  CHECK_LIVE_XWIDGET (xwidget);
  CHECK_LIST (plist);

  XXWIDGET (xwidget)->plist = plist;
  return plist;
}

DEFUN ("set-xwidget-query-on-exit-flag",
       Fset_xwidget_query_on_exit_flag, Sset_xwidget_query_on_exit_flag,
       2, 2, 0,
       doc: /* Specify if query is needed for XWIDGET when Emacs is exited.
If the second argument FLAG is non-nil, Emacs will query the user before
exiting or killing a buffer if XWIDGET is running.
This function returns FLAG.  */)
  (Lisp_Object xwidget, Lisp_Object flag)
{
  CHECK_LIVE_XWIDGET (xwidget);
  XXWIDGET (xwidget)->kill_without_query = NILP (flag);
  return flag;
}

DEFUN ("xwidget-query-on-exit-flag",
       Fxwidget_query_on_exit_flag, Sxwidget_query_on_exit_flag,
       1, 1, 0,
       doc: /* Return the current value of the query-on-exit flag for XWIDGET.  */)
  (Lisp_Object xwidget)
{
  CHECK_LIVE_XWIDGET (xwidget);
  return (XXWIDGET (xwidget)->kill_without_query ? Qnil : Qt);
}

DEFUN ("xwidget-webkit-search", Fxwidget_webkit_search, Sxwidget_webkit_search,
       2, 5, 0,
       doc: /* Begin an incremental search operation in an xwidget.
QUERY should be a string containing the text to search for.  XWIDGET
should be a WebKit xwidget where the search will take place.  When the
search operation is complete, callers should also call
`xwidget-webkit-finish-search' to complete the search operation.

CASE-INSENSITIVE, when non-nil, will cause the search to ignore the
case of characters inside QUERY.  BACKWARDS, when non-nil, will cause
the search to proceed towards the beginning of the widget's contents.
WRAP-AROUND, when nil, will cause the search to stop upon hitting the
end of the widget's contents.

It is OK to call this function even when a search is already in
progress.  In that case, the previous search query will be replaced
with QUERY.  */)
  (Lisp_Object query, Lisp_Object xwidget, Lisp_Object case_insensitive,
   Lisp_Object backwards, Lisp_Object wrap_around)
{
#ifdef USE_GTK
  WebKitWebView *webview;
  WebKitFindController *controller;
  WebKitFindOptions opt;
  struct xwidget *xw;
  gchar *g_query;
#endif

  CHECK_STRING (query);
  CHECK_LIVE_XWIDGET (xwidget);

#ifdef USE_GTK
  xw = XXWIDGET (xwidget);
  CHECK_WEBKIT_WIDGET (xw);

  webview = WEBKIT_WEB_VIEW (xw->widget_osr);
  query = ENCODE_UTF_8 (query);
  opt = WEBKIT_FIND_OPTIONS_NONE;
  g_query = xstrdup (SSDATA (query));

  if (!NILP (case_insensitive))
    opt |= WEBKIT_FIND_OPTIONS_CASE_INSENSITIVE;
  if (!NILP (backwards))
    opt |= WEBKIT_FIND_OPTIONS_BACKWARDS;
  if (!NILP (wrap_around))
    opt |= WEBKIT_FIND_OPTIONS_WRAP_AROUND;

  if (xw->find_text)
    xfree (xw->find_text);
  xw->find_text = g_query;

  block_input ();
  controller = webkit_web_view_get_find_controller (webview);
  webkit_find_controller_search (controller, g_query, opt, G_MAXUINT);
  unblock_input ();
#endif

  return Qnil;
}

DEFUN ("xwidget-webkit-next-result", Fxwidget_webkit_next_result,
       Sxwidget_webkit_next_result, 1, 1, 0,
       doc: /* Show the next result matching the current search query.

XWIDGET should be an xwidget that currently has a search query.
Before calling this function, you should start a search operation
using `xwidget-webkit-search'.  */)
  (Lisp_Object xwidget)
{
  struct xwidget *xw;
#ifdef USE_GTK
  WebKitWebView *webview;
  WebKitFindController *controller;
#endif

  CHECK_LIVE_XWIDGET (xwidget);
  xw = XXWIDGET (xwidget);
  CHECK_WEBKIT_WIDGET (xw);

  if (!xw->find_text)
    error ("Widget has no ongoing search operation");

#ifdef USE_GTK
  block_input ();
  webview = WEBKIT_WEB_VIEW (xw->widget_osr);
  controller = webkit_web_view_get_find_controller (webview);
  webkit_find_controller_search_next (controller);
  unblock_input ();
#endif

  return Qnil;
}

DEFUN ("xwidget-webkit-previous-result", Fxwidget_webkit_previous_result,
       Sxwidget_webkit_previous_result, 1, 1, 0,
       doc: /* Show the previous result matching the current search query.

XWIDGET should be an xwidget that currently has a search query.
Before calling this function, you should start a search operation
using `xwidget-webkit-search'.  */)
  (Lisp_Object xwidget)
{
  struct xwidget *xw;
#ifdef USE_GTK
  WebKitWebView *webview;
  WebKitFindController *controller;
#endif

  CHECK_LIVE_XWIDGET (xwidget);
  xw = XXWIDGET (xwidget);
  CHECK_WEBKIT_WIDGET (xw);

  if (!xw->find_text)
    error ("Widget has no ongoing search operation");

#ifdef USE_GTK
  block_input ();
  webview = WEBKIT_WEB_VIEW (xw->widget_osr);
  controller = webkit_web_view_get_find_controller (webview);
  webkit_find_controller_search_previous (controller);
  unblock_input ();
#endif

  return Qnil;
}

DEFUN ("xwidget-webkit-finish-search", Fxwidget_webkit_finish_search,
       Sxwidget_webkit_finish_search, 1, 1, 0,
       doc: /* Finish XWIDGET's search operation.

XWIDGET should be an xwidget that currently has a search query.
Before calling this function, you should start a search operation
using `xwidget-webkit-search'.  */)
  (Lisp_Object xwidget)
{
  struct xwidget *xw;
#ifdef USE_GTK
  WebKitWebView *webview;
  WebKitFindController *controller;
#endif

  CHECK_LIVE_XWIDGET (xwidget);
  xw = XXWIDGET (xwidget);
  CHECK_WEBKIT_WIDGET (xw);

  if (!xw->find_text)
    error ("Widget has no ongoing search operation");

#ifdef USE_GTK
  block_input ();
  webview = WEBKIT_WEB_VIEW (xw->widget_osr);
  controller = webkit_web_view_get_find_controller (webview);
  webkit_find_controller_search_finish (controller);

  if (xw->find_text)
    {
      xfree (xw->find_text);
      xw->find_text = NULL;
    }
  unblock_input ();
#endif

  return Qnil;
}

DEFUN ("kill-xwidget", Fkill_xwidget, Skill_xwidget,
       1, 1, 0,
       doc: /* Kill the specified XWIDGET.
This releases all window system resources associated with XWIDGET,
removes it from `xwidget-list', and detaches it from its buffer.  */)
  (Lisp_Object xwidget)
{
  struct xwidget *xw;

  CHECK_LIVE_XWIDGET (xwidget);
  xw = XXWIDGET (xwidget);

  block_input ();
  kill_xwidget (xw);
  unblock_input ();

  return Qnil;
}

#ifdef USE_GTK
DEFUN ("xwidget-webkit-load-html", Fxwidget_webkit_load_html,
       Sxwidget_webkit_load_html, 2, 3, 0,
       doc: /* Make XWIDGET's WebKit widget render TEXT.
XWIDGET should be a WebKit xwidget, that will receive TEXT.  TEXT
should be a string that will be displayed by XWIDGET as HTML markup.
BASE-URI should be a string containing a URI that is used to locate
resources with relative URLs, and if not specified, defaults
to "about:blank".  */)
  (Lisp_Object xwidget, Lisp_Object text, Lisp_Object base_uri)
{
  struct xwidget *xw;
  WebKitWebView *webview;
  char *data, *uri;

  CHECK_LIVE_XWIDGET (xwidget);
  CHECK_STRING (text);
  if (NILP (base_uri))
    base_uri = build_string ("about:blank");
  else
    CHECK_STRING (base_uri);

  base_uri = ENCODE_UTF_8 (base_uri);
  text = ENCODE_UTF_8 (text);
  xw = XXWIDGET (xwidget);
  CHECK_WEBKIT_WIDGET (xw);

  data = SSDATA (text);
  uri = SSDATA (base_uri);
  webview = WEBKIT_WEB_VIEW (xw->widget_osr);

  block_input ();
  webkit_web_view_load_html (webview, data, uri);
  unblock_input ();

  return Qnil;
}

DEFUN ("xwidget-webkit-back-forward-list", Fxwidget_webkit_back_forward_list,
       Sxwidget_webkit_back_forward_list, 1, 2, 0,
       doc: /* Return the navigation history of XWIDGET, a WebKit xwidget.

Return the history as a list of the form (BACK HERE FORWARD), where
HERE is the current navigation item, while BACK and FORWARD are lists
of history items of the form (IDX TITLE URI).  Here, IDX is an index
that can be passed to `xwidget-webkit-goto-history', TITLE is a string
containing the human-readable title of the history item, and URI is
the URI of the history item.

BACK, HERE, and FORWARD can all be nil depending on the state of the
navigation history.

BACK and FORWARD will each not contain more elements than LIMIT.  If
LIMIT is not specified or nil, it is treated as `50'.  */)
  (Lisp_Object xwidget, Lisp_Object limit)
{
  struct xwidget *xw;
  Lisp_Object back, here, forward;
  WebKitWebView *webview;
  WebKitBackForwardList *list;
  WebKitBackForwardListItem *item;
  GList *parent, *tem;
  int i;
  unsigned int lim;
  Lisp_Object title, uri;
  const gchar *item_title, *item_uri;

  back = Qnil;
  here = Qnil;
  forward = Qnil;

  if (NILP (limit))
    limit = make_fixnum (50);
  else
    CHECK_FIXNAT (limit);

  CHECK_LIVE_XWIDGET (xwidget);
  xw = XXWIDGET (xwidget);

  webview = WEBKIT_WEB_VIEW (xw->widget_osr);
  list = webkit_web_view_get_back_forward_list (webview);
  item = webkit_back_forward_list_get_current_item (list);
  lim = XFIXNAT (limit);

  if (item)
    {
      item_title = webkit_back_forward_list_item_get_title (item);
      item_uri = webkit_back_forward_list_item_get_uri (item);
      here = list3 (make_fixnum (0),
		    build_string_from_utf8 (item_title ? item_title : ""),
		    build_string_from_utf8 (item_uri ? item_uri : ""));
    }
  parent = webkit_back_forward_list_get_back_list_with_limit (list, lim);

  if (parent)
    {
      for (i = 1, tem = parent; tem; tem = tem->next, ++i)
	{
	  item = tem->data;
	  item_title = webkit_back_forward_list_item_get_title (item);
	  item_uri = webkit_back_forward_list_item_get_uri (item);
	  title = build_string_from_utf8 (item_title ? item_title : "");
	  uri = build_string_from_utf8 (item_uri ? item_uri : "");
	  back = Fcons (list3 (make_fixnum (-i), title, uri), back);
	}
    }

  back = Fnreverse (back);
  g_list_free (parent);

  parent = webkit_back_forward_list_get_forward_list_with_limit (list, lim);

  if (parent)
    {
      for (i = 1, tem = parent; tem; tem = tem->next, ++i)
	{
	  item = tem->data;
	  item_title = webkit_back_forward_list_item_get_title (item);
	  item_uri = webkit_back_forward_list_item_get_uri (item);
	  title = build_string_from_utf8 (item_title ? item_title : "");
	  uri = build_string_from_utf8 (item_uri ? item_uri : "");
	  forward = Fcons (list3 (make_fixnum (i), title, uri), forward);
	}
    }

  forward = Fnreverse (forward);
  g_list_free (parent);

  return list3 (back, here, forward);
}

DEFUN ("xwidget-webkit-estimated-load-progress",
       Fxwidget_webkit_estimated_load_progress, Sxwidget_webkit_estimated_load_progress,
       1, 1, 0, doc: /* Get the estimated load progress of XWIDGET, a WebKit widget.
Return a value ranging from 0.0 to 1.0, based on how close XWIDGET
is to completely loading its page.  */)
  (Lisp_Object xwidget)
{
  struct xwidget *xw;
  WebKitWebView *webview;
  double value;

  CHECK_LIVE_XWIDGET (xwidget);
  xw = XXWIDGET (xwidget);
  CHECK_WEBKIT_WIDGET (xw);

  block_input ();
  webview = WEBKIT_WEB_VIEW (xw->widget_osr);
  value = webkit_web_view_get_estimated_load_progress (webview);
  unblock_input ();

  return make_float (value);
}
#endif

DEFUN ("xwidget-webkit-set-cookie-storage-file",
       Fxwidget_webkit_set_cookie_storage_file, Sxwidget_webkit_set_cookie_storage_file,
       2, 2, 0, doc: /* Make the WebKit widget XWIDGET load and store cookies in FILE.

Cookies will be stored as plain text in FILE, which must be an
absolute file name.  All xwidgets related to XWIDGET will also
store cookies in FILE and load them from there.  */)
  (Lisp_Object xwidget, Lisp_Object file)
{
#ifdef USE_GTK
  struct xwidget *xw;
  WebKitWebView *webview;
  WebKitWebContext *context;
  WebKitCookieManager *manager;

  CHECK_LIVE_XWIDGET (xwidget);
  xw = XXWIDGET (xwidget);
  CHECK_WEBKIT_WIDGET (xw);
  CHECK_STRING (file);

  block_input ();
  webview = WEBKIT_WEB_VIEW (xw->widget_osr);
  context = webkit_web_view_get_context (webview);
  manager = webkit_web_context_get_cookie_manager (context);
  webkit_cookie_manager_set_persistent_storage (manager,
						SSDATA (ENCODE_UTF_8 (file)),
						WEBKIT_COOKIE_PERSISTENT_STORAGE_TEXT);
  unblock_input ();
#endif

  return Qnil;
}

DEFUN ("xwidget-webkit-stop-loading", Fxwidget_webkit_stop_loading,
       Sxwidget_webkit_stop_loading,
       1, 1, 0, doc: /* Stop loading data in the WebKit widget XWIDGET.
This will stop any data transfer that may still be in progress inside
XWIDGET as part of loading a page.  */)
  (Lisp_Object xwidget)
{
#ifdef USE_GTK
  struct xwidget *xw;
  WebKitWebView *webview;

  CHECK_LIVE_XWIDGET (xwidget);
  xw = XXWIDGET (xwidget);
  CHECK_WEBKIT_WIDGET (xw);

  block_input ();
  webview = WEBKIT_WEB_VIEW (xw->widget_osr);
  webkit_web_view_stop_loading (webview);
  unblock_input ();
#endif

  return Qnil;
}

void
syms_of_xwidget (void)
{
  defsubr (&Smake_xwidget);
  defsubr (&Sxwidgetp);
  defsubr (&Sxwidget_live_p);
  DEFSYM (Qxwidgetp, "xwidgetp");
  DEFSYM (Qxwidget_live_p, "xwidget-live-p");
  defsubr (&Sxwidget_view_p);
  DEFSYM (Qxwidget_view_p, "xwidget-view-p");
  defsubr (&Sxwidget_info);
  defsubr (&Sxwidget_view_info);
  defsubr (&Sxwidget_resize);
  defsubr (&Sget_buffer_xwidgets);
  defsubr (&Sxwidget_view_model);
  defsubr (&Sxwidget_view_window);
  defsubr (&Sxwidget_view_lookup);
  defsubr (&Sxwidget_query_on_exit_flag);
  defsubr (&Sset_xwidget_query_on_exit_flag);

  defsubr (&Sxwidget_webkit_uri);
  defsubr (&Sxwidget_webkit_title);
  defsubr (&Sxwidget_webkit_goto_uri);
  defsubr (&Sxwidget_webkit_goto_history);
  defsubr (&Sxwidget_webkit_zoom);
  defsubr (&Sxwidget_webkit_execute_script);
  DEFSYM (Qwebkit, "webkit");

  defsubr (&Sxwidget_size_request);
  defsubr (&Sdelete_xwidget_view);

  defsubr (&Sxwidget_plist);
  defsubr (&Sxwidget_buffer);
  defsubr (&Sset_xwidget_plist);
  defsubr (&Sxwidget_perform_lispy_event);
  defsubr (&Sxwidget_webkit_search);
  defsubr (&Sxwidget_webkit_finish_search);
  defsubr (&Sxwidget_webkit_next_result);
  defsubr (&Sxwidget_webkit_previous_result);
  defsubr (&Sset_xwidget_buffer);
  defsubr (&Sxwidget_webkit_set_cookie_storage_file);
  defsubr (&Sxwidget_webkit_stop_loading);
#ifdef USE_GTK
  defsubr (&Sxwidget_webkit_load_html);
  defsubr (&Sxwidget_webkit_back_forward_list);
  defsubr (&Sxwidget_webkit_estimated_load_progress);
#endif
  defsubr (&Skill_xwidget);

  DEFSYM (QCxwidget, ":xwidget");
  DEFSYM (QCtitle, ":title");

  /* Do not forget to update the docstring of make-xwidget if you add
     new types.  */

  DEFSYM (Qvertical, "vertical");
  DEFSYM (Qhorizontal, "horizontal");

  DEFSYM (QCplist, ":plist");

  DEFVAR_LISP ("xwidget-list", Vxwidget_list,
               doc: /* List of all xwidgets that have not been killed.  */);
  Vxwidget_list = Qnil;

  DEFVAR_LISP ("xwidget-view-list", Vxwidget_view_list,
	       doc: /* List of all xwidget views.  */);
  Vxwidget_view_list = Qnil;

  Fprovide (intern ("xwidget-internal"), Qnil);

  id_to_xwidget_map = CALLN (Fmake_hash_table, QCtest, Qeq,
			     QCweakness, Qvalue);
  staticpro (&id_to_xwidget_map);

  internal_xwidget_list = Qnil;
  staticpro (&internal_xwidget_list);
  internal_xwidget_view_list = Qnil;
  staticpro (&internal_xwidget_view_list);

#ifdef HAVE_X_WINDOWS
  x_window_to_xwv_map = CALLN (Fmake_hash_table, QCtest, Qeq);

  staticpro (&x_window_to_xwv_map);
#endif
}


/* Value is non-zero if OBJECT is a valid Lisp xwidget specification.  A
   valid xwidget specification is a list whose car is the symbol
   `xwidget', and whose rest is a property list.  The property list must
   contain a value for key `:type'.  That value must be the name of a
   supported xwidget type.  The rest of the property list depends on the
   xwidget type.  */

bool
valid_xwidget_spec_p (Lisp_Object object)
{
  return CONSP (object) && EQ (XCAR (object), Qxwidget);
}


/* Find a value associated with key in spec.  */
static Lisp_Object
xwidget_spec_value (Lisp_Object spec, Lisp_Object key)
{
  Lisp_Object tail;

  eassert (valid_xwidget_spec_p (spec));

  for (tail = XCDR (spec);
       CONSP (tail) && CONSP (XCDR (tail)); tail = XCDR (XCDR (tail)))
    {
      if (EQ (XCAR (tail), key))
	return XCAR (XCDR (tail));
    }

  return Qnil;
}


void
xwidget_view_delete_all_in_window (struct window *w)
{
  struct xwidget_view *xv = NULL;
  for (Lisp_Object tail = internal_xwidget_view_list; CONSP (tail);
       tail = XCDR (tail))
    {
      if (XWIDGET_VIEW_P (XCAR (tail)))
        {
          xv = XXWIDGET_VIEW (XCAR (tail));
          if (XWINDOW (xv->w) == w)
            {
              Fdelete_xwidget_view (XCAR (tail));
            }
        }
    }
}

static struct xwidget_view *
xwidget_view_lookup (struct xwidget *xw, struct window *w)
{
  Lisp_Object xwidget, window, ret;
  XSETXWIDGET (xwidget, xw);
  XSETWINDOW (window, w);

  ret = Fxwidget_view_lookup (xwidget, window);

  return NILP (ret) ? NULL : XXWIDGET_VIEW (ret);
}

struct xwidget *
lookup_xwidget (Lisp_Object spec)
{
  /* When a xwidget lisp spec is found initialize the C struct that is
     used in the C code.  This is done by redisplay so values change
     if the spec changes.  So, take special care of one-shot events.  */
  Lisp_Object value;
  struct xwidget *xw;

  value = xwidget_spec_value (spec, QCxwidget);
  xw = XXWIDGET (value);

  return xw;
}

/* Set up detection of touched xwidget.  */
static void
xwidget_start_redisplay (void)
{
  for (Lisp_Object tail = internal_xwidget_view_list; CONSP (tail);
       tail = XCDR (tail))
    {
      if (XWIDGET_VIEW_P (XCAR (tail)))
        XXWIDGET_VIEW (XCAR (tail))->redisplayed = false;
    }
}

/* The xwidget was touched during redisplay, so it isn't a candidate
   for hiding.  */
static void
xwidget_touch (struct xwidget_view *xv)
{
  xv->redisplayed = true;
}

static bool
xwidget_touched (struct xwidget_view *xv)
{
  return xv->redisplayed;
}

/* Redisplay has ended, now we should hide untouched xwidgets.  */
void
xwidget_end_redisplay (struct window *w, struct glyph_matrix *matrix)
{
  int i;
  int area;

  xwidget_start_redisplay ();
  /* Iterate desired glyph matrix of window here, hide gtk widgets
     not in the desired matrix.

     This only takes care of xwidgets in active windows.  If a window
     goes away from the screen, xwidget views must be deleted.

     dump_glyph_matrix (matrix, 2);  */
  for (i = 0; i < matrix->nrows; ++i)
    {
      /* dump_glyph_row (MATRIX_ROW (matrix, i), i, glyphs); */
      struct glyph_row *row;
      row = MATRIX_ROW (matrix, i);
      if (row->enabled_p)
	for (area = LEFT_MARGIN_AREA; area < LAST_AREA; ++area)
	  {
	    struct glyph *glyph = row->glyphs[area];
	    struct glyph *glyph_end = glyph + row->used[area];
	    for (; glyph < glyph_end; ++glyph)
	      if (glyph->type == XWIDGET_GLYPH)
		{
		  /* The only call to xwidget_end_redisplay is in dispnew.
		     xwidget_end_redisplay (w->current_matrix);  */
		  struct xwidget_view *xv
		    = xwidget_view_lookup (xwidget_from_id (glyph->u.xwidget), w);

		  /* In NS xwidget, xv can be NULL for the second or
                     later views for a model, the result of 1 to 1
                     model view relation enforcement.  `xwidget_view_lookup'
		     has also been observed to return NULL here on X-Windows
		     at least once, so stay safe and only touch it if it's
		     not NULL.  */

                  if (xv)
                    xwidget_touch (xv);
		}
	  }
    }

  for (Lisp_Object tail = internal_xwidget_view_list; CONSP (tail);
       tail = XCDR (tail))
    {
      if (XWIDGET_VIEW_P (XCAR (tail)))
        {
          struct xwidget_view *xv = XXWIDGET_VIEW (XCAR (tail));

          /* "touched" is only meaningful for the current window, so
             disregard other views.  */
          if (XWINDOW (xv->w) == w)
            {
              if (xwidget_touched (xv))
                {
#ifdef USE_GTK
                  xwidget_show_view (xv);
#elif defined NS_IMPL_COCOA
                  nsxwidget_show_view (xv);
#endif
                }
              else
                {
#ifdef USE_GTK
                  xwidget_hide_view (xv);
#elif defined NS_IMPL_COCOA
                  nsxwidget_hide_view (xv);
#endif
                }
            }
        }
    }
}

#ifdef HAVE_X_WINDOWS
void
lower_frame_xwidget_views (struct frame *f)
{
  struct xwidget_view *xv;

  for (Lisp_Object tail = internal_xwidget_view_list; CONSP (tail);
       tail = XCDR (tail))
    {
      xv = XXWIDGET_VIEW (XCAR (tail));
      if (xv->frame == f && xv->wdesc != None)
	XLowerWindow (xv->dpy, xv->wdesc);
    }
}
#endif

#ifndef NS_IMPL_COCOA
void
kill_frame_xwidget_views (struct frame *f)
{
  Lisp_Object rem = Qnil;

  for (Lisp_Object tail = internal_xwidget_view_list; CONSP (tail);
       tail = XCDR (tail))
    {
      if (XWIDGET_VIEW_P (XCAR (tail))
	  && XXWIDGET_VIEW (XCAR (tail))->frame == f)
	rem = Fcons (XCAR (tail), rem);
    }

  for (; CONSP (rem); rem = XCDR (rem))
    Fdelete_xwidget_view (XCAR (rem));
}
#endif

static void
kill_xwidget (struct xwidget *xw)
{
  Lisp_Object val;
  XSETXWIDGET (val, xw);

  internal_xwidget_list = Fdelq (val, internal_xwidget_list);
  Vxwidget_list = Fcopy_sequence (internal_xwidget_list);
#ifdef USE_GTK
  xw->buffer = Qnil;

  if (xw->widget_osr && xw->widgetwindow_osr)
    {
      gtk_widget_destroy (xw->widget_osr);
      gtk_widget_destroy (xw->widgetwindow_osr);
    }

  if (xw->find_text)
    xfree (xw->find_text);

  if (!NILP (xw->script_callbacks))
    {
      for (ptrdiff_t idx = 0; idx < ASIZE (xw->script_callbacks); idx++)
	{
	  Lisp_Object cb = AREF (xw->script_callbacks, idx);
	  if (!NILP (cb))
	    xfree (xmint_pointer (XCAR (cb)));
	  ASET (xw->script_callbacks, idx, Qnil);
	}
    }

  xw->widget_osr = NULL;
  xw->widgetwindow_osr = NULL;
  xw->find_text = NULL;

  catch_child_signal ();
#elif defined NS_IMPL_COCOA
  nsxwidget_kill (xw);
#endif
}

/* Kill all xwidget in BUFFER.  */
void
kill_buffer_xwidgets (Lisp_Object buffer)
{
  Lisp_Object tail, xwidget;
  for (tail = Fget_buffer_xwidgets (buffer); CONSP (tail); tail = XCDR (tail))
    {
      xwidget = XCAR (tail);
      {
        CHECK_LIVE_XWIDGET (xwidget);
        struct xwidget *xw = XXWIDGET (xwidget);

	kill_xwidget (xw);
      }
    }

  catch_child_signal ();
}