summaryrefslogtreecommitdiff
path: root/gdk/win32/gdkevents-win32.c
blob: 24c300f9320fa486378a388e1f29aae3ff1dbbdc (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
/* GDK - The GIMP Drawing Kit
 * Copyright (C) 1995-1997 Peter Mattis, Spencer Kimball and Josh MacDonald
 * Copyright (C) 1998-2002 Tor Lillqvist
 * Copyright (C) 2001,2009 Hans Breuer
 * Copyright (C) 2007-2009 Cody Russell
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.	 See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library. If not, see <http://www.gnu.org/licenses/>.
 */

/*
 * Modified by the GTK+ Team and others 1997-2000.  See the AUTHORS
 * file for a list of people on the GTK+ Team.  See the ChangeLog
 * files for a list of changes.  These files are distributed with
 * GTK+ at ftp://ftp.gtk.org/pub/gtk/.
 */

/* Cannot use TrackMouseEvent, as the stupid WM_MOUSELEAVE message
 * doesn’t tell us where the mouse has gone. Thus we cannot use it to
 * generate a correct GdkNotifyType. Pity, as using TrackMouseEvent
 * otherwise would make it possible to reliably generate
 * GDK_LEAVE_NOTIFY events, which would help get rid of those pesky
 * tooltips sometimes popping up in the wrong place.
 *
 * Update: a combination of TrackMouseEvent, GetCursorPos and
 * GetWindowPos can and is actually used to get rid of those
 * pesky tooltips. It should be possible to use this for the
 * whole ENTER/LEAVE NOTIFY handling but some platforms may
 * not have TrackMouseEvent at all (?) --hb
 */

#include "config.h"

#include "gdkprivate-win32.h"

#include <glib/gprintf.h>
#include <cairo-win32.h>

#include "gdk.h"
#include "gdkdisplayprivate.h"
#include "gdkmonitorprivate.h"
#include "gdkwin32.h"
#include "gdkkeysyms.h"
#include "gdkglcontext-win32.h"
#include "gdkdevicemanager-win32.h"
#include "gdkdisplay-win32.h"
#include "gdkdeviceprivate.h"
#include "gdkdevice-wintab.h"
#include "gdkwin32dnd.h"
#include "gdkwin32dnd-private.h"
#include "gdkdisplay-win32.h"
//#include "gdkselection-win32.h"
#include "gdkdragprivate.h"

#include <windowsx.h>

#ifdef G_WITH_CYGWIN
#include <fcntl.h>
#include <errno.h>
#endif

#include <objbase.h>

#include <imm.h>

#define GDK_MOD2_MASK (1 << 4)

#ifndef XBUTTON1
#define XBUTTON1 1
#define XBUTTON2 2
#endif

#ifndef VK_XBUTTON1
#define VK_XBUTTON1 5
#define VK_XBUTTON2 6
#endif

#ifndef MK_XBUTTON1
#define MK_XBUTTON1 32
#define MK_XBUTTON2 64
#endif

/* Undefined flags: */
#define SWP_NOCLIENTSIZE 0x0800
#define SWP_NOCLIENTMOVE 0x1000
#define SWP_STATECHANGED 0x8000
/*
 * Private function declarations
 */

#define SYNAPSIS_ICON_WINDOW_CLASS "SynTrackCursorWindowClass"

static gboolean gdk_event_translate (MSG        *msg,
				     int        *ret_valp);
static gboolean gdk_event_prepare  (GSource     *source,
				    int         *timeout);
static gboolean gdk_event_check    (GSource     *source);
static gboolean gdk_event_dispatch (GSource     *source,
				    GSourceFunc  callback,
				    gpointer     user_data);

/* Private variable declarations
 */

extern int        _gdk_input_ignore_core;

typedef struct
{
  GSource source;

  GdkDisplay *display;
  GPollFD event_poll_fd;
} GdkWin32EventSource;

static GSourceFuncs event_funcs = {
  gdk_event_prepare,
  gdk_event_check,
  gdk_event_dispatch,
  NULL
};

/* Whenever we do an implicit grab (call SetCapture() after
 * a mouse button is held down), we ref the capturing surface
 * and keep that ref here. When mouse buttons are released,
 * we remove the implicit grab and synthesize a crossing
 * event from the grab surface to whatever surface is now
 * under cursor.
 */
static GdkSurface *implicit_grab_surface = NULL;

static GdkSurface *mouse_window = NULL;
static GdkSurface *mouse_window_ignored_leave = NULL;
static int current_x, current_y;
static int current_root_x, current_root_y;

static UINT got_gdk_events_message;
static HWND modal_win32_dialog = NULL;

#if 0
static HKL latin_locale = NULL;
#endif

static gboolean in_ime_composition = FALSE;
static UINT     modal_timer;
static UINT     sync_timer = 0;

static int debug_indent = 0;

static int both_shift_pressed[2]; /* to store keycodes for shift keys */

/* low-level keyboard hook handle */
static HHOOK keyboard_hook = NULL;
static UINT aerosnap_message;

static void
track_mouse_event (DWORD dwFlags,
		   HWND  hwnd)
{
  TRACKMOUSEEVENT tme;

  tme.cbSize = sizeof(TRACKMOUSEEVENT);
  tme.dwFlags = dwFlags;
  tme.hwndTrack = hwnd;
  tme.dwHoverTime = HOVER_DEFAULT; /* not used */

  if (!TrackMouseEvent (&tme))
    WIN32_API_FAILED ("TrackMouseEvent");
  else if (dwFlags == TME_LEAVE)
    GDK_NOTE (EVENTS, g_print(" (TrackMouseEvent %p)", hwnd));
  else if (dwFlags == TME_CANCEL)
    GDK_NOTE (EVENTS, g_print(" (cancel TrackMouseEvent %p)", hwnd));
}

gulong
_gdk_win32_get_next_tick (gulong suggested_tick)
{
  static gulong cur_tick = 0;

  if (suggested_tick == 0)
    suggested_tick = GetTickCount ();
  /* Ticks eventually wrap around.
   * This works as long as the interval between ticks is < 2147483648ms */
  if (suggested_tick <= cur_tick && ((cur_tick - suggested_tick) < 0x7FFFFFFF))
    return cur_tick;
  else
    return cur_tick = suggested_tick;
}

static void
generate_focus_event (GdkDeviceManagerWin32 *device_manager,
                      GdkSurface        *window,
                      gboolean          in)
{
  GdkDevice *device;
  GdkEvent *event;

  device = GDK_DEVICE_MANAGER_WIN32 (device_manager)->core_keyboard;

  event = gdk_focus_event_new (window, device, in);

  _gdk_win32_append_event (event);
}

static void
generate_grab_broken_event (GdkDeviceManagerWin32 *device_manager,
                            GdkSurface        *window,
                            gboolean          keyboard,
                            GdkSurface        *grab_window)
{
  GdkEvent *event;
  GdkDevice *device;

  if (keyboard)
    device = device_manager->core_keyboard;
  else
    device = device_manager->core_pointer;

  event = gdk_grab_broken_event_new (window,
                                     device,
                                     grab_window,
                                     FALSE);

  _gdk_win32_append_event (event);
}

static LRESULT
inner_window_procedure (HWND   hwnd,
			UINT   message,
			WPARAM wparam,
			LPARAM lparam)
{
  MSG msg;
  DWORD pos;
  int ret_val = 0;

  msg.hwnd = hwnd;
  msg.message = message;
  msg.wParam = wparam;
  msg.lParam = lparam;
  msg.time = _gdk_win32_get_next_tick (0);
  pos = GetMessagePos ();
  msg.pt.x = GET_X_LPARAM (pos);
  msg.pt.y = GET_Y_LPARAM (pos);

  if (gdk_event_translate (&msg, &ret_val))
    {
      /* If gdk_event_translate() returns TRUE, we return ret_val from
       * the window procedure.
       */
      if (modal_win32_dialog)
	PostMessageW (modal_win32_dialog, got_gdk_events_message,
		      (WPARAM) 1, 0);
      return ret_val;
    }
  else
    {
      /* Otherwise call DefWindowProcW(). */
      GDK_NOTE (EVENTS, g_print (" DefWindowProcW"));
      return DefWindowProcW (hwnd, message, wparam, lparam);
    }
}

LRESULT CALLBACK
_gdk_win32_surface_procedure (HWND   hwnd,
                             UINT   message,
                             WPARAM wparam,
                             LPARAM lparam)
{
  LRESULT retval;

  GDK_NOTE (EVENTS, g_print ("%s%*s%s %p %#" G_GINTPTR_MODIFIER "x %#" G_GINTPTR_MODIFIER "x",
			     (debug_indent > 0 ? "\n" : ""),
			     debug_indent, "",
			     _gdk_win32_message_to_string (message), hwnd,
			     wparam, lparam));
  debug_indent += 2;
  retval = inner_window_procedure (hwnd, message, wparam, lparam);
  debug_indent -= 2;

  GDK_NOTE (EVENTS, g_print (" => %" G_GINT64_FORMAT "%s", (gint64) retval, (debug_indent == 0 ? "\n" : "")));

  return retval;
}

static LRESULT
low_level_keystroke_handler (WPARAM message,
                                       KBDLLHOOKSTRUCT *kbdhook,
                                       GdkSurface *window)
{
  GdkSurface *toplevel = window;
  static DWORD last_keydown = 0;

  if (message == WM_KEYDOWN &&
      !GDK_SURFACE_DESTROYED (toplevel) &&
      _gdk_win32_surface_lacks_wm_decorations (toplevel) && /* For CSD only */
      last_keydown != kbdhook->vkCode &&
      ((GetKeyState (VK_LWIN) & 0x8000) ||
      (GetKeyState (VK_RWIN) & 0x8000)))
	{
	  GdkWin32AeroSnapCombo combo = GDK_WIN32_AEROSNAP_COMBO_NOTHING;
	  gboolean lshiftdown = GetKeyState (VK_LSHIFT) & 0x8000;
          gboolean rshiftdown = GetKeyState (VK_RSHIFT) & 0x8000;
          gboolean oneshiftdown = (lshiftdown || rshiftdown) && !(lshiftdown && rshiftdown);
          gboolean maximized = gdk_toplevel_get_state (GDK_TOPLEVEL (toplevel)) & GDK_TOPLEVEL_STATE_MAXIMIZED;

	  switch (kbdhook->vkCode)
	    {
	    case VK_UP:
	      combo = GDK_WIN32_AEROSNAP_COMBO_UP;
	      break;
	    case VK_DOWN:
	      combo = GDK_WIN32_AEROSNAP_COMBO_DOWN;
	      break;
	    case VK_LEFT:
	      combo = GDK_WIN32_AEROSNAP_COMBO_LEFT;
	      break;
	    case VK_RIGHT:
	      combo = GDK_WIN32_AEROSNAP_COMBO_RIGHT;
	      break;
	    }

	  if (oneshiftdown && combo != GDK_WIN32_AEROSNAP_COMBO_NOTHING)
	    combo += 4;

	  /* These are the only combos that Windows WM does handle for us */
	  if (combo == GDK_WIN32_AEROSNAP_COMBO_SHIFTLEFT ||
              combo == GDK_WIN32_AEROSNAP_COMBO_SHIFTRIGHT)
            combo = GDK_WIN32_AEROSNAP_COMBO_NOTHING;

          /* On Windows 10 the WM will handle this specific combo */
          if (combo == GDK_WIN32_AEROSNAP_COMBO_DOWN && maximized &&
              g_win32_check_windows_version (6, 4, 0, G_WIN32_OS_ANY))
            combo = GDK_WIN32_AEROSNAP_COMBO_NOTHING;

	  if (combo != GDK_WIN32_AEROSNAP_COMBO_NOTHING)
            PostMessage (GDK_SURFACE_HWND (toplevel), aerosnap_message, (WPARAM) combo, 0);
	}

  if (message == WM_KEYDOWN)
    last_keydown = kbdhook->vkCode;
  else if (message == WM_KEYUP && last_keydown == kbdhook->vkCode)
    last_keydown = 0;

  return 0;
}

static LRESULT CALLBACK
low_level_keyboard_proc (int    code,
                         WPARAM wParam,
                         LPARAM lParam)
{
  KBDLLHOOKSTRUCT *kbdhook;
  HWND kbd_focus_owner;
  GdkSurface *gdk_kbd_focus_owner;
  LRESULT chain;

  do
  {
    if (code < 0)
      break;

    kbd_focus_owner = GetFocus ();

    if (kbd_focus_owner == NULL)
      break;

    gdk_kbd_focus_owner = gdk_win32_handle_table_lookup (kbd_focus_owner);

    if (gdk_kbd_focus_owner == NULL)
      break;

    kbdhook = (KBDLLHOOKSTRUCT *) lParam;
    chain = low_level_keystroke_handler (wParam, kbdhook, gdk_kbd_focus_owner);

    if (chain != 0)
      return chain;
  } while (FALSE);

  return CallNextHookEx (0, code, wParam, lParam);
}

static void
set_up_low_level_keyboard_hook (void)
{
  HHOOK hook_handle;

  if (keyboard_hook != NULL)
    return;

  hook_handle = SetWindowsHookEx (WH_KEYBOARD_LL,
                                  (HOOKPROC) low_level_keyboard_proc,
                                  _gdk_dll_hinstance,
                                  0);

  if (hook_handle != NULL)
    keyboard_hook = hook_handle;
  else
    WIN32_API_FAILED ("SetWindowsHookEx");

  aerosnap_message = RegisterWindowMessage ("GDK_WIN32_AEROSNAP_MESSAGE");
}

void
_gdk_events_init (GdkDisplay *display)
{
  GSource *source;
  GdkWin32EventSource *event_source;

#if 0
  int i, j, n;

  /* List of languages that use a latin keyboard. Somewhat sorted in
   * "order of least surprise", in case we have to load one of them if
   * the user only has arabic loaded, for instance.
   */
  static int latin_languages[] = {
    LANG_ENGLISH,
    LANG_SPANISH,
    LANG_PORTUGUESE,
    LANG_FRENCH,
    LANG_GERMAN,
    /* Rest in numeric order */
    LANG_CZECH,
    LANG_DANISH,
    LANG_FINNISH,
    LANG_HUNGARIAN,
    LANG_ICELANDIC,
    LANG_ITALIAN,
    LANG_DUTCH,
    LANG_NORWEGIAN,
    LANG_POLISH,
    LANG_ROMANIAN,
    LANG_SLOVAK,
    LANG_ALBANIAN,
    LANG_SWEDISH,
    LANG_TURKISH,
    LANG_INDONESIAN,
    LANG_SLOVENIAN,
    LANG_ESTONIAN,
    LANG_LATVIAN,
    LANG_LITHUANIAN,
    LANG_VIETNAMESE,
    LANG_AFRIKAANS,
    LANG_FAEROESE
#ifdef LANG_SWAHILI
   ,LANG_SWAHILI
#endif
  };
#endif

  got_gdk_events_message = RegisterWindowMessage ("GDK_WIN32_GOT_EVENTS");

#if 0
  /* Check if we have some input locale identifier loaded that uses a
   * latin keyboard, to be able to get the virtual-key code for the
   * latin characters corresponding to ASCII control characters.
   */
  if ((n = GetKeyboardLayoutList (0, NULL)) == 0)
    WIN32_API_FAILED ("GetKeyboardLayoutList");
  else
    {
      HKL *hkl_list = g_new (HKL, n);
      if (GetKeyboardLayoutList (n, hkl_list) == 0)
	WIN32_API_FAILED ("GetKeyboardLayoutList");
      else
	{
	  for (i = 0; latin_locale == NULL && i < n; i++)
	    for (j = 0; j < G_N_ELEMENTS (latin_languages); j++)
	      if (PRIMARYLANGID (LOWORD (hkl_list[i])) == latin_languages[j])
		{
		  latin_locale = hkl_list [i];
		  break;
		}
	}
      g_free (hkl_list);
    }

  if (latin_locale == NULL)
    {
      /* Try to load a keyboard layout with latin characters then.
       */
      i = 0;
      while (latin_locale == NULL && i < G_N_ELEMENTS (latin_languages))
	{
	  char id[9];
	  g_sprintf (id, "%08x", MAKELANGID (latin_languages[i++], SUBLANG_DEFAULT));
	  latin_locale = LoadKeyboardLayout (id, KLF_NOTELLSHELL|KLF_SUBSTITUTE_OK);
	}
    }

  GDK_NOTE (EVENTS, g_print ("latin_locale = %08x\n", (guint) latin_locale));
#endif

  source = g_source_new (&event_funcs, sizeof (GdkWin32EventSource));
  g_source_set_name (source, "GDK Win32 event source");
  g_source_set_priority (source, GDK_PRIORITY_EVENTS);

  event_source = (GdkWin32EventSource *)source;
  event_source->display = display;
#ifdef G_WITH_CYGWIN
  event_source->event_poll_fd.fd = open ("/dev/windows", O_RDONLY);
  if (event_source->event_poll_fd.fd == -1)
    g_error ("can't open \"/dev/windows\": %s", g_strerror (errno));
#else
  event_source->event_poll_fd.fd = G_WIN32_MSG_HANDLE;
#endif
  event_source->event_poll_fd.events = G_IO_IN;

  g_source_add_poll (source, &event_source->event_poll_fd);
  g_source_set_can_recurse (source, TRUE);
  g_source_attach (source, NULL);

  set_up_low_level_keyboard_hook ();
}

gboolean
_gdk_win32_display_has_pending (GdkDisplay *display)
{
  return (_gdk_event_queue_find_first (display) ||
	  (modal_win32_dialog == NULL &&
	   GetQueueStatus (QS_ALLINPUT) != 0));
}

#if 0 /* Unused, but might be useful to re-introduce in some debugging output? */

static char *
event_mask_string (GdkEventMask mask)
{
  static char bfr[500];
  char *p = bfr;

  *p = '\0';
#define BIT(x) \
  if (mask & GDK_##x##_MASK) \
    p += g_sprintf (p, "%s" #x, (p > bfr ? " " : ""))
  BIT (EXPOSURE);
  BIT (POINTER_MOTION);
  BIT (POINTER_MOTION_HINT);
  BIT (BUTTON_MOTION);
  BIT (BUTTON1_MOTION);
  BIT (BUTTON2_MOTION);
  BIT (BUTTON3_MOTION);
  BIT (BUTTON_PRESS);
  BIT (BUTTON_RELEASE);
  BIT (KEY_PRESS);
  BIT (KEY_RELEASE);
  BIT (ENTER_NOTIFY);
  BIT (LEAVE_NOTIFY);
  BIT (FOCUS_CHANGE);
  BIT (STRUCTURE);
  BIT (PROPERTY_CHANGE);
  BIT (VISIBILITY_NOTIFY);
  BIT (PROXIMITY_IN);
  BIT (PROXIMITY_OUT);
  BIT (SUBSTRUCTURE);
  BIT (SCROLL);
#undef BIT

  return bfr;
}

#endif

static GdkSurface *
find_window_for_mouse_event (GdkSurface* reported_window,
			     MSG*       msg)
{
  POINT pt;
  GdkDisplay *display;
  GdkDeviceManagerWin32 *device_manager;
  GdkSurface *event_surface;
  HWND hwnd;
  RECT rect;
  GdkDeviceGrabInfo *grab;

  display = gdk_display_get_default ();
  device_manager = GDK_DEVICE_MANAGER_WIN32 (_gdk_device_manager);

  grab = _gdk_display_get_last_device_grab (display, device_manager->core_pointer);
  if (grab == NULL)
    return reported_window;

  pt = msg->pt;

  if (!grab->owner_events)
    event_surface = grab->surface;
  else
    {
      event_surface = NULL;
      hwnd = WindowFromPoint (pt);
      if (hwnd != NULL)
	{
	  POINT client_pt = pt;

	  ScreenToClient (hwnd, &client_pt);
	  GetClientRect (hwnd, &rect);
	  if (PtInRect (&rect, client_pt))
	    event_surface = gdk_win32_handle_table_lookup (hwnd);
	}
      if (event_surface == NULL)
	event_surface = grab->surface;
    }

  /* need to also adjust the coordinates to the new window */
  ScreenToClient (GDK_SURFACE_HWND (event_surface), &pt);

  /* ATTENTION: need to update client coords */
  msg->lParam = MAKELPARAM (pt.x, pt.y);

  return event_surface;
}

static GdkModifierType
build_key_event_state (BYTE *key_state)
{
  GdkModifierType state;
  GdkWin32Keymap *keymap;

  state = 0;

  if (key_state[VK_SHIFT] & 0x80)
    state |= GDK_SHIFT_MASK;

  if (key_state[VK_CAPITAL] & 0x01)
    state |= GDK_LOCK_MASK;

  if (key_state[VK_LBUTTON] & 0x80)
    state |= GDK_BUTTON1_MASK;
  if (key_state[VK_MBUTTON] & 0x80)
    state |= GDK_BUTTON2_MASK;
  if (key_state[VK_RBUTTON] & 0x80)
    state |= GDK_BUTTON3_MASK;
  if (key_state[VK_XBUTTON1] & 0x80)
    state |= GDK_BUTTON4_MASK;
  if (key_state[VK_XBUTTON2] & 0x80)
    state |= GDK_BUTTON5_MASK;

  keymap = GDK_WIN32_KEYMAP (_gdk_win32_display_get_keymap (_gdk_display));

  if (_gdk_win32_keymap_has_altgr (keymap) &&
      (key_state[VK_LCONTROL] & 0x80) &&
      (key_state[VK_RMENU] & 0x80))
    {
      state |= GDK_MOD2_MASK;
      if (key_state[VK_RCONTROL] & 0x80)
	state |= GDK_CONTROL_MASK;
      if (key_state[VK_LMENU] & 0x80)
	state |= GDK_ALT_MASK;
    }
  else
    {
      if (key_state[VK_CONTROL] & 0x80)
	state |= GDK_CONTROL_MASK;
      if (key_state[VK_MENU] & 0x80)
	state |= GDK_ALT_MASK;
    }

  return state;
}

static guint8
get_active_group (void)
{
  GdkWin32Keymap *keymap;

  keymap = GDK_WIN32_KEYMAP (_gdk_win32_display_get_keymap (_gdk_display));

  return _gdk_win32_keymap_get_active_group (keymap);
}

static int
build_pointer_event_state (MSG *msg)
{
  int state;

  state = 0;

  if (msg->wParam & MK_CONTROL)
    state |= GDK_CONTROL_MASK;

  if ((msg->message != WM_LBUTTONDOWN &&
       (msg->wParam & MK_LBUTTON)) ||
      msg->message == WM_LBUTTONUP)
    state |= GDK_BUTTON1_MASK;

  if ((msg->message != WM_MBUTTONDOWN &&
       (msg->wParam & MK_MBUTTON)) ||
      msg->message == WM_MBUTTONUP)
    state |= GDK_BUTTON2_MASK;

  if ((msg->message != WM_RBUTTONDOWN &&
       (msg->wParam & MK_RBUTTON)) ||
      msg->message == WM_RBUTTONUP)
    state |= GDK_BUTTON3_MASK;

  if (((msg->message != WM_XBUTTONDOWN || HIWORD (msg->wParam) != XBUTTON1) &&
       (msg->wParam & MK_XBUTTON1)) ||
      (msg->message == WM_XBUTTONUP && HIWORD (msg->wParam) == XBUTTON1))
    state |= GDK_BUTTON4_MASK;

  if (((msg->message != WM_XBUTTONDOWN || HIWORD (msg->wParam) != XBUTTON2) &&
       (msg->wParam & MK_XBUTTON2)) ||
      (msg->message == WM_XBUTTONUP && HIWORD (msg->wParam) == XBUTTON2))
    state |= GDK_BUTTON5_MASK;

  if (msg->wParam & MK_SHIFT)
    state |= GDK_SHIFT_MASK;

  if (GetKeyState (VK_MENU) < 0)
    state |= GDK_ALT_MASK;

  if (GetKeyState (VK_CAPITAL) & 0x1)
    state |= GDK_LOCK_MASK;

  return state;
}

#ifdef G_ENABLE_DEBUG

static void
print_event_state (guint state)
{
#define CASE(bit) if (state & GDK_ ## bit ## _MASK) g_print (#bit " ");
  CASE (SHIFT);
  CASE (LOCK);
  CASE (CONTROL);
  CASE (ALT);
  CASE (MOD2);
  CASE (BUTTON1);
  CASE (BUTTON2);
  CASE (BUTTON3);
  CASE (BUTTON4);
  CASE (BUTTON5);
#undef CASE
}

void
_gdk_win32_print_event (GdkEvent *event)
{
  const char *kvname;
  double x, y;
  GdkCrossingMode mode;
  GdkNotifyType detail;
  GdkScrollDirection direction;

  g_print ("%s%*s===> ", (debug_indent > 0 ? "\n" : ""), debug_indent, "");
  switch (gdk_event_get_event_type (event))
    {
#define CASE(x) case x: g_print (#x); break;
    CASE (GDK_DELETE);
    CASE (GDK_MOTION_NOTIFY);
    CASE (GDK_BUTTON_PRESS);
    CASE (GDK_BUTTON_RELEASE);
    CASE (GDK_KEY_PRESS);
    CASE (GDK_KEY_RELEASE);
    CASE (GDK_ENTER_NOTIFY);
    CASE (GDK_LEAVE_NOTIFY);
    CASE (GDK_FOCUS_CHANGE);
    CASE (GDK_PROXIMITY_IN);
    CASE (GDK_PROXIMITY_OUT);
    CASE (GDK_DRAG_ENTER);
    CASE (GDK_DRAG_LEAVE);
    CASE (GDK_DRAG_MOTION);
    CASE (GDK_DROP_START);
    CASE (GDK_SCROLL);
    CASE (GDK_GRAB_BROKEN);
#undef CASE
    default: g_assert_not_reached ();
    }

  g_print (" %p @ %ums ",
           GDK_SURFACE_HWND (gdk_event_get_surface (event)),
           gdk_event_get_time (event));

  switch (gdk_event_get_event_type (event))
    {
    case GDK_MOTION_NOTIFY:
      gdk_event_get_position (event, &x, &y);
      g_print ("(%.4g,%.4g) ", x, y);
      print_event_state (gdk_event_get_modifier_state (event));
      break;
    case GDK_BUTTON_PRESS:
    case GDK_BUTTON_RELEASE:
      gdk_event_get_position (event, &x, &y);
      g_print ("%d (%.4g,%.4g) ", gdk_button_event_get_button (event), x, y);
      print_event_state (gdk_event_get_modifier_state (event));
      break;
    case GDK_KEY_PRESS:
    case GDK_KEY_RELEASE:
      kvname = gdk_keyval_name (gdk_key_event_get_keyval (event));
      g_print ("%#.02x group:%d %s",
               gdk_key_event_get_keycode (event),
               gdk_key_event_get_layout (event),
	       (kvname ? kvname : "??"));
      print_event_state (gdk_event_get_modifier_state (event));
      break;
    case GDK_ENTER_NOTIFY:
    case GDK_LEAVE_NOTIFY:
      gdk_event_get_position (event, &x, &y);
      mode = gdk_crossing_event_get_mode (event);
      detail = gdk_crossing_event_get_detail (event);
      g_print ("(%.4g,%.4g) %s %s",
	       x, y,
	       (mode == GDK_CROSSING_NORMAL ? "NORMAL" :
		(mode == GDK_CROSSING_GRAB ? "GRAB" :
		 (mode == GDK_CROSSING_UNGRAB ? "UNGRAB" :
		  "???"))),
	       (detail == GDK_NOTIFY_ANCESTOR ? "ANCESTOR" :
		(detail == GDK_NOTIFY_VIRTUAL ? "VIRTUAL" :
		 (detail == GDK_NOTIFY_INFERIOR ? "INFERIOR" :
		  (detail == GDK_NOTIFY_NONLINEAR ? "NONLINEAR" :
		   (detail == GDK_NOTIFY_NONLINEAR_VIRTUAL ? "NONLINEAR_VIRTUAL" :
		    (detail == GDK_NOTIFY_UNKNOWN ? "UNKNOWN" :
		     "???")))))));
      print_event_state (gdk_event_get_modifier_state (event));
      break;
    case GDK_FOCUS_CHANGE:
      g_print ("%s", (gdk_focus_event_get_in (event) ? "IN" : "OUT"));
      break;
    case GDK_DRAG_ENTER:
    case GDK_DRAG_LEAVE:
    case GDK_DRAG_MOTION:
    case GDK_DROP_START:
      g_print ("DND");
      break;
    case GDK_SCROLL:
      direction = gdk_scroll_event_get_direction (event);
      g_print (" %s ",
	       (direction == GDK_SCROLL_UP ? "UP" :
		(direction == GDK_SCROLL_DOWN ? "DOWN" :
		 (direction == GDK_SCROLL_LEFT ? "LEFT" :
		  (direction == GDK_SCROLL_RIGHT ? "RIGHT" :
		   "???")))));
      print_event_state (gdk_event_get_modifier_state (event));
      break;
    case GDK_GRAB_BROKEN:
      g_print ("Grab broken");
    default:
      /* Nothing */
      break;
    }
  g_print ("%s", (debug_indent == 0 ? "\n" : ""));
}

static char *
decode_key_lparam (LPARAM lParam)
{
  static char buf[100];
  char *p = buf;

  if (HIWORD (lParam) & KF_UP)
    p += g_sprintf (p, "KF_UP ");
  if (HIWORD (lParam) & KF_REPEAT)
    p += g_sprintf (p, "KF_REPEAT ");
  if (HIWORD (lParam) & KF_ALTDOWN)
    p += g_sprintf (p, "KF_ALTDOWN ");
  if (HIWORD (lParam) & KF_EXTENDED)
    p += g_sprintf (p, "KF_EXTENDED ");
  p += g_sprintf (p, "sc:%d rep:%d", LOBYTE (HIWORD (lParam)), LOWORD (lParam));

  return buf;
}

#endif

static void
fixup_event (GdkEvent *event)
{
  if (event->surface)
    g_object_ref (event->surface);
}

void
_gdk_win32_append_event (GdkEvent *event)
{
  GdkDisplay *display;
  GList *link;

  display = gdk_display_get_default ();

  fixup_event (event);
#if 1
  link = _gdk_event_queue_append (display, event);
  GDK_NOTE (EVENTS, _gdk_win32_print_event (event));
  /* event morphing, the passed in may not be valid afterwards */
  _gdk_windowing_got_event (display, link, event, 0);
#else
  _gdk_event_queue_append (display, event);
  GDK_NOTE (EVENTS, _gdk_win32_print_event (event));
#endif
}

static GdkWin32MessageFilterReturn
apply_message_filters (GdkDisplay *display,
                       MSG        *msg,
                       int        *ret_valp,
                       GList     **filters)
{
  GdkWin32MessageFilterReturn result = GDK_WIN32_MESSAGE_FILTER_CONTINUE;
  GList *tmp_list;

  tmp_list = *filters;
  while (tmp_list)
    {
      GdkWin32MessageFilter *filter = (GdkWin32MessageFilter *) tmp_list->data;
      GList *node;

      if (filter->removed)
        {
          tmp_list = tmp_list->next;
          continue;
        }

      filter->ref_count++;
      result = filter->function (GDK_WIN32_DISPLAY (display), msg, ret_valp, filter->data);

      /* get the next node after running the function since the
         function may add or remove a next node */
      node = tmp_list;
      tmp_list = tmp_list->next;

      filter->ref_count--;
      if (filter->ref_count == 0)
        {
          *filters = g_list_remove_link (*filters, node);
          g_list_free_1 (node);
          g_free (filter);
        }

      if (result != GDK_WIN32_MESSAGE_FILTER_CONTINUE)
	break;
    }

  return result;
}

/*
 * On Windows, transient windows will not have their own taskbar entries.
 * Because of this, we must hide and restore groups of transients in both
 * directions.  That is, all transient children must be hidden or restored
 * with this window, but if this window’s transient owner also has a
 * transient owner then this window’s transient owner must be hidden/restored
 * with this one.  And etc, up the chain until we hit an ancestor that has no
 * transient owner.
 *
 * It would be a good idea if applications don’t chain transient windows
 * together.  There’s a limit to how much evil GTK can try to shield you
 * from.
 */
static void
show_window_recurse (GdkSurface *window, gboolean hide_window)
{
  GdkWin32Surface *impl = GDK_WIN32_SURFACE (window);
  GSList *children = impl->transient_children;
  GdkSurface *child = NULL;

  if (!impl->changing_state)
    {
      impl->changing_state = TRUE;

      if (children != NULL)
	{
	  while (children != NULL)
	    {
	      child = children->data;
	      show_window_recurse (child, hide_window);

	      children = children->next;
	    }
	}

      if (GDK_SURFACE_IS_MAPPED (window))
	{
	  if (!hide_window)
	    {
	      if (gdk_toplevel_get_state (GDK_TOPLEVEL (window)) & GDK_TOPLEVEL_STATE_MINIMIZED)
		{
		  if (gdk_toplevel_get_state (GDK_TOPLEVEL (window)) & GDK_TOPLEVEL_STATE_MAXIMIZED)
		    {
		      GtkShowWindow (window, SW_SHOWMAXIMIZED);
		    }
		  else
		    {
		      GtkShowWindow (window, SW_RESTORE);
		    }
		}
	    }
	  else
	    {
	      GtkShowWindow (window, SW_MINIMIZE);
	    }
	}

      impl->changing_state = FALSE;
    }
}

static void
do_show_window (GdkSurface *window, gboolean hide_window)
{
  GdkSurface *tmp_window = NULL;
  GdkWin32Surface *tmp_impl = GDK_WIN32_SURFACE (window);

  if (!tmp_impl->changing_state)
    {
      /* Find the top-level window in our transient chain. */
      while (tmp_impl->transient_owner != NULL)
	{
	  tmp_window = tmp_impl->transient_owner;
	  tmp_impl = GDK_WIN32_SURFACE (tmp_window);
	}

      /* If we couldn't find one, use the window provided. */
      if (tmp_window == NULL)
	{
	  tmp_window = window;
	}

      /* Recursively show/hide every window in the chain. */
      if (tmp_window != window)
	{
	  show_window_recurse (tmp_window, hide_window);
	}
    }
}

static void
send_crossing_event (GdkDisplay                 *display,
		     GdkSurface                  *window,
		     GdkEventType                type,
		     GdkCrossingMode             mode,
		     GdkNotifyType               notify_type,
		     GdkSurface                  *subwindow,
		     POINT                      *screen_pt,
		     GdkModifierType             mask,
		     guint32                     time_)
{
  GdkEvent *event;
  GdkDeviceGrabInfo *grab;
  GdkDeviceManagerWin32 *device_manager;
  POINT pt;
  GdkWin32Surface *impl = GDK_WIN32_SURFACE (window);

  device_manager = _gdk_device_manager;

  grab = _gdk_display_has_device_grab (display, device_manager->core_pointer, 0);

  if (grab != NULL &&
      !grab->owner_events &&
      mode != GDK_CROSSING_UNGRAB)
    {
      /* !owner_event => only report events wrt grab window, ignore rest */
      if ((GdkSurface *)window != grab->surface)
	return;
    }

  pt = *screen_pt;
  ScreenToClient (GDK_SURFACE_HWND (window), &pt);

  event = gdk_crossing_event_new (type,
                                  window,
                                  device_manager->core_pointer,
                                  _gdk_win32_get_next_tick (time_),
                                  mask,
                                  pt.x / impl->surface_scale,
                                  pt.y / impl->surface_scale,
                                  mode,
                                  notify_type);
          
  _gdk_win32_append_event (event);
}

static GdkSurface *
find_common_ancestor (GdkSurface *win1,
		      GdkSurface *win2)
{
  GdkSurface *tmp;
  GList *path1 = NULL, *path2 = NULL;
  GList *list1, *list2;

  tmp = win1;
  while (tmp != NULL)
    {
      path1 = g_list_prepend (path1, tmp);
      tmp = tmp->parent;
    }

  tmp = win2;
  while (tmp != NULL)
    {
      path2 = g_list_prepend (path2, tmp);
      tmp = tmp->parent;
    }

  list1 = path1;
  list2 = path2;
  tmp = NULL;
  while (list1 && list2 && (list1->data == list2->data))
    {
      tmp = (GdkSurface *)list1->data;
      list1 = list1->next;
      list2 = list2->next;
    }
  g_list_free (path1);
  g_list_free (path2);

  return tmp;
}

void
synthesize_crossing_events (GdkDisplay                 *display,
			    GdkSurface                  *src,
			    GdkSurface                  *dest,
			    GdkCrossingMode             mode,
			    POINT                      *screen_pt,
			    GdkModifierType             mask,
			    guint32                     time_,
			    gboolean                    non_linear)
{
  GdkSurface *c;
  GdkSurface *win, *last, *next;
  GList *path, *list;
  GdkSurface *a;
  GdkSurface *b;
  GdkNotifyType notify_type;

  a = src;
  b = dest;
  if (a == b)
    return; /* No crossings generated between src and dest */

  c = find_common_ancestor (a, b);

  non_linear |= (c != a) && (c != b);

  if (a) /* There might not be a source (i.e. if no previous pointer_in_window) */
    {
      /* Traverse up from a to (excluding) c sending leave events */
      if (non_linear)
	notify_type = GDK_NOTIFY_NONLINEAR;
      else if (c == a)
	notify_type = GDK_NOTIFY_INFERIOR;
      else
	notify_type = GDK_NOTIFY_ANCESTOR;
      send_crossing_event (display,
			   a, GDK_LEAVE_NOTIFY,
			   mode,
			   notify_type,
			   NULL,
			   screen_pt,
			   mask, time_);

      if (c != a)
	{
	  if (non_linear)
	    notify_type = GDK_NOTIFY_NONLINEAR_VIRTUAL;
	  else
	    notify_type = GDK_NOTIFY_VIRTUAL;

	  last = a;
	  win = a->parent;
	  while (win != c && win != NULL)
	    {
	      send_crossing_event (display,
				   win, GDK_LEAVE_NOTIFY,
				   mode,
				   notify_type,
				   (GdkSurface *)last,
				   screen_pt,
				   mask, time_);

	      last = win;
	      win = win->parent;
	    }
	}
    }

  if (b) /* Might not be a dest, e.g. if we're moving out of the window */
    {
      /* Traverse down from c to b */
      if (c != b)
	{
	  path = NULL;
	  win = b->parent;
	  while (win != c && win != NULL)
	    {
	      path = g_list_prepend (path, win);
	      win = win->parent;
	    }

	  if (non_linear)
	    notify_type = GDK_NOTIFY_NONLINEAR_VIRTUAL;
	  else
	    notify_type = GDK_NOTIFY_VIRTUAL;

	  list = path;
	  while (list)
	    {
	      win = (GdkSurface *)list->data;
	      list = list->next;
	      if (list)
		next = (GdkSurface *)list->data;
	      else
		next = b;

	      send_crossing_event (display,
				   win, GDK_ENTER_NOTIFY,
				   mode,
				   notify_type,
				   next,
				   screen_pt,
				   mask, time_);
	    }
	  g_list_free (path);
	}


      if (non_linear)
	notify_type = GDK_NOTIFY_NONLINEAR;
      else if (c == a)
	notify_type = GDK_NOTIFY_ANCESTOR;
      else
	notify_type = GDK_NOTIFY_INFERIOR;

      send_crossing_event (display,
			   b, GDK_ENTER_NOTIFY,
			   mode,
			   notify_type,
			   NULL,
			   screen_pt,
			   mask, time_);
    }
}

/* Acquires actual client area size of the underlying native window.
 * Rectangle is in GDK screen coordinates (_gdk_offset_* is added).
 * Returns FALSE if configure events should be inhibited,
 * TRUE otherwise.
 */
gboolean
_gdk_win32_get_window_rect (GdkSurface *window,
                            RECT      *rect)
{
  RECT client_rect;
  POINT point;
  HWND hwnd;
  GdkWin32Surface *impl = GDK_WIN32_SURFACE (window);

  hwnd = GDK_SURFACE_HWND (window);

  GetClientRect (hwnd, &client_rect);
  point.x = client_rect.left; /* always 0 */
  point.y = client_rect.top;

  /* top level windows need screen coords */
  if (GDK_IS_TOPLEVEL (window))
    {
      ClientToScreen (hwnd, &point);
      point.x += _gdk_offset_x * impl->surface_scale;
      point.y += _gdk_offset_y * impl->surface_scale;
    }

  rect->left = point.x;
  rect->top = point.y;
  rect->right = point.x + client_rect.right - client_rect.left;
  rect->bottom = point.y + client_rect.bottom - client_rect.top;

  return !impl->inhibit_configure;
}

void
_gdk_win32_do_emit_configure_event (GdkSurface *surface,
                                    RECT       rect)
{
  GdkWin32Surface *impl = GDK_WIN32_SURFACE (surface);

  impl->unscaled_width = rect.right - rect.left;
  impl->unscaled_height = rect.bottom - rect.top;
  surface->width = (impl->unscaled_width + impl->surface_scale - 1) / impl->surface_scale;
  surface->height = (impl->unscaled_height + impl->surface_scale - 1) / impl->surface_scale;
  surface->x = rect.left / impl->surface_scale;
  surface->y = rect.top / impl->surface_scale;

  _gdk_surface_update_size (surface);

  g_signal_emit_by_name (surface, "size-changed", surface->width, surface->height);
}

void
_gdk_win32_emit_configure_event (GdkSurface *surface)
{
  RECT rect;

  if (!_gdk_win32_get_window_rect (surface, &rect))
    return;

  _gdk_win32_do_emit_configure_event (surface, rect);
}

cairo_region_t *
_gdk_win32_hrgn_to_region (HRGN  hrgn,
                           guint scale)
{
  RGNDATA *rgndata;
  RECT *rects;
  cairo_region_t *result;
  int nbytes;
  guint i;

  if ((nbytes = GetRegionData (hrgn, 0, NULL)) == 0)
    {
      WIN32_GDI_FAILED ("GetRegionData");
      return NULL;
    }

  rgndata = (RGNDATA *) g_malloc (nbytes);

  if (GetRegionData (hrgn, nbytes, rgndata) == 0)
    {
      WIN32_GDI_FAILED ("GetRegionData");
      g_free (rgndata);
      return NULL;
    }

  result = cairo_region_create ();
  rects = (RECT *) rgndata->Buffer;
  for (i = 0; i < rgndata->rdh.nCount; i++)
    {
      GdkRectangle r;

      r.x = rects[i].left;
      r.y = rects[i].top;
      r.width = (rects[i].right - r.x) / scale;
      r.height = (rects[i].bottom - r.y) / scale;

      cairo_region_union_rectangle (result, &r);
    }

  g_free (rgndata);

  return result;
}

static void
handle_wm_paint (MSG        *msg,
		 GdkSurface  *window)
{
  HRGN hrgn = CreateRectRgn (0, 0, 0, 0);
  HDC hdc;
  PAINTSTRUCT paintstruct;
  cairo_region_t *update_region;
  GdkWin32Surface *impl = GDK_WIN32_SURFACE (window);

  if (GetUpdateRgn (msg->hwnd, hrgn, FALSE) == ERROR)
    {
      WIN32_GDI_FAILED ("GetUpdateRgn");
      DeleteObject (hrgn);
      return;
    }

  hdc = BeginPaint (msg->hwnd, &paintstruct);

  GDK_NOTE (EVENTS, g_print (" %s %s dc %p",
			     _gdk_win32_rect_to_string (&paintstruct.rcPaint),
			     (paintstruct.fErase ? "erase" : ""),
			     hdc));

  EndPaint (msg->hwnd, &paintstruct);

  if ((paintstruct.rcPaint.right == paintstruct.rcPaint.left) ||
      (paintstruct.rcPaint.bottom == paintstruct.rcPaint.top))
    {
      GDK_NOTE (EVENTS, g_print (" (empty paintstruct, ignored)"));
      DeleteObject (hrgn);
      return;
    }

  update_region = _gdk_win32_hrgn_to_region (hrgn, impl->surface_scale);
  if (!cairo_region_is_empty (update_region))
    gdk_surface_invalidate_region (window, update_region);
  cairo_region_destroy (update_region);

  DeleteObject (hrgn);
}

static VOID CALLBACK
modal_timer_proc (HWND     hwnd,
		  UINT     msg,
		  UINT_PTR id,
		  DWORD    time)
{
  int arbitrary_limit = 10;

  while (_modal_operation_in_progress != GDK_WIN32_MODAL_OP_NONE &&
	 g_main_context_pending (NULL) &&
	 arbitrary_limit--)
    g_main_context_iteration (NULL, FALSE);
}

void
_gdk_win32_begin_modal_call (GdkWin32ModalOpKind kind)
{
  GdkWin32ModalOpKind was = _modal_operation_in_progress;
  g_assert (!(_modal_operation_in_progress & kind));

  _modal_operation_in_progress |= kind;

  if (was == GDK_WIN32_MODAL_OP_NONE)
    {
      modal_timer = SetTimer (NULL, 0, 10, modal_timer_proc);

      if (modal_timer == 0)
	WIN32_API_FAILED ("SetTimer");
    }
}

void
_gdk_win32_end_modal_call (GdkWin32ModalOpKind kind)
{
  g_assert (_modal_operation_in_progress & kind);

  _modal_operation_in_progress &= ~kind;

  if (_modal_operation_in_progress == GDK_WIN32_MODAL_OP_NONE &&
      modal_timer != 0)
    {
      API_CALL (KillTimer, (NULL, modal_timer));
      modal_timer = 0;
    }
}

static VOID CALLBACK
sync_timer_proc (HWND     hwnd,
		 UINT     msg,
		 UINT_PTR id,
		 DWORD    time)
{
  MSG message;
  if (PeekMessageW (&message, hwnd, WM_PAINT, WM_PAINT, PM_REMOVE))
    {
      return;
    }

  RedrawWindow (hwnd, NULL, NULL, RDW_INVALIDATE|RDW_UPDATENOW|RDW_ALLCHILDREN);

  KillTimer (hwnd, sync_timer);
}

static gboolean
handle_nchittest (HWND hwnd,
                  GdkSurface *window,
                  gint16 screen_x,
                  gint16 screen_y,
                  int *ret_valp)
{
  RECT rect;
  GdkWin32Surface *impl;

  if (window == NULL || window->input_region == NULL)
    return FALSE;

  /* If the window has decorations, DefWindowProc() will take
   * care of NCHITTEST.
   */
  if (!_gdk_win32_surface_lacks_wm_decorations (window))
    return FALSE;

  if (!GetWindowRect (hwnd, &rect))
    return FALSE;

  impl = GDK_WIN32_SURFACE (window);
  rect.left = screen_x - rect.left;
  rect.top = screen_y - rect.top;

  /* If it's inside the rect, return FALSE and let DefWindowProc() handle it */
  if (cairo_region_contains_point (window->input_region,
                                   rect.left / impl->surface_scale,
                                   rect.top / impl->surface_scale))
    return FALSE;

  /* Otherwise override DefWindowProc() and tell WM that the point is not
   * within the window
   */
  *ret_valp = HTNOWHERE;
  return TRUE;
}

static void
handle_dpi_changed (GdkSurface *window,
                    MSG       *msg)
{
  GdkWin32Surface *impl = GDK_WIN32_SURFACE (window);
  GdkDisplay *display = gdk_display_get_default ();
  GdkWin32Display *win32_display = GDK_WIN32_DISPLAY (display);
  RECT *rect = (RECT *)msg->lParam;
  guint old_scale = impl->surface_scale;

  /* MSDN for WM_DPICHANGED: dpi_x == dpi_y here, so LOWORD (msg->wParam) == HIWORD (msg->wParam) */
  guint dpi = LOWORD (msg->wParam);

  /* Don't bother if we use a fixed scale */
  if (win32_display->has_fixed_scale)
    return;

  impl->surface_scale = dpi / USER_DEFAULT_SCREEN_DPI;

  /* Don't bother if scales did not change in the end */
  if (old_scale == impl->surface_scale)
    return;

  if (!IsIconic (msg->hwnd) &&
      !GDK_SURFACE_DESTROYED (window))
    {
      GdkMonitor *monitor;

      monitor = gdk_display_get_monitor_at_surface (display, window);
      gdk_monitor_set_scale_factor (monitor, impl->surface_scale);

      if (impl->layered)
        {
          /* We only need to set the cairo surface device scale here ourselves for layered windows */
          if (impl->cache_surface != NULL)
            cairo_surface_set_device_scale (impl->cache_surface,
                                            impl->surface_scale,
                                            impl->surface_scale);
        }
    }

  _gdk_win32_adjust_client_rect (window, rect);

  if (impl->drag_move_resize_context.op != GDK_WIN32_DRAGOP_NONE)
    gdk_win32_surface_move_resize (window,
                                   window->x, window->y,
                                   window->width, window->height);
  else
    gdk_win32_surface_resize (window, window->width, window->height);
}

static void
generate_button_event (GdkEventType      type,
                       int               button,
                       GdkSurface        *window,
                       MSG              *msg)
{
  GdkEvent *event;
  GdkDeviceManagerWin32 *device_manager;
  GdkWin32Surface *impl = GDK_WIN32_SURFACE (window);

  if (_gdk_input_ignore_core > 0)
    return;

  device_manager = GDK_DEVICE_MANAGER_WIN32 (_gdk_device_manager);

  current_x = (gint16) GET_X_LPARAM (msg->lParam) / impl->surface_scale;
  current_y = (gint16) GET_Y_LPARAM (msg->lParam) / impl->surface_scale;

  event = gdk_button_event_new (type,
                                window,
                                device_manager->core_pointer,
                                NULL,
                                _gdk_win32_get_next_tick (msg->time),
                                build_pointer_event_state (msg),
                                button,
                                current_x,
                                current_y,
                                NULL);
                                
  _gdk_win32_append_event (event);
}

static gboolean
handle_wm_sysmenu (GdkSurface *window, MSG *msg, int *ret_valp)
{
  GdkWin32Surface *impl;
  LONG_PTR style, tmp_style;
  LONG_PTR additional_styles;

  impl = GDK_WIN32_SURFACE (window);

  style = GetWindowLongPtr (msg->hwnd, GWL_STYLE);

  additional_styles = 0;

  if (!(style & WS_SYSMENU))
    additional_styles |= WS_SYSMENU;

  if (!(style & WS_MAXIMIZEBOX))
    additional_styles |= WS_MAXIMIZEBOX;

  if (!(style & WS_MINIMIZEBOX))
    additional_styles |= WS_MINIMIZEBOX;

  if (!(style & WS_SIZEBOX))
    additional_styles |= WS_SIZEBOX;

  if (!(style & WS_DLGFRAME))
    additional_styles |= WS_DLGFRAME;

  if (!(style & WS_BORDER))
    additional_styles |= WS_BORDER;

  if (additional_styles == 0)
    /* The caller will eventually pass this to DefWindowProc (),
     * only without the style dance, which isn't needed, as it turns out.
     */
    return FALSE;

  /* Note: This code will enable resizing, maximizing and minimizing windows
   * via window menu even if these are non-CSD windows that were explicitly
   * forbidden from doing this by removing the appropriate styles,
   * or if these are CSD windows that were explicitly forbidden from doing
   * this by removing appropriate decorations from the headerbar and/or
   * changing hints or properties.
   *
   * If doing this for non-CSD windows is not desired,
   * do a _gdk_win32_surface_lacks_wm_decorations() check and return FALSE
   * if it doesn't pass.
   *
   * If doing this for CSD windows with disabled decorations is not desired,
   * tough luck - GDK can't know which CSD decorations are enabled, and which
   * are not.
   *
   * If doing this for CSD windows with particular hints is not desired,
   * check window hints here and return FALSE (DefWindowProc() will return
   * FALSE later) or set *ret_valp to 0 and return TRUE.
   */
  tmp_style = style | additional_styles;
  GDK_NOTE (EVENTS, g_print (" Handling WM_SYSMENU: style 0x%" G_GINTPTR_MODIFIER "x -> 0x%" G_GINTPTR_MODIFIER "x\n", style, tmp_style));
  impl->have_temp_styles = TRUE;
  impl->temp_styles = additional_styles;
  SetWindowLongPtr (msg->hwnd, GWL_STYLE, tmp_style);

  *ret_valp = DefWindowProc (msg->hwnd, msg->message, msg->wParam, msg->lParam);

  tmp_style = GetWindowLongPtr (msg->hwnd, GWL_STYLE);
  style = tmp_style & ~additional_styles;

  GDK_NOTE (EVENTS, g_print (" Handling WM_SYSMENU: style 0x%" G_GINTPTR_MODIFIER "x <- 0x%" G_GINTPTR_MODIFIER "x\n", style, tmp_style));
  SetWindowLongPtr (msg->hwnd, GWL_STYLE, style);
  impl->have_temp_styles = FALSE;

  return TRUE;
}

gboolean
_gdk_win32_surface_fill_min_max_info (GdkSurface  *window,
                                     MINMAXINFO *mmi)
{
  GdkWin32Surface *impl;
  RECT rect;

  if (GDK_SURFACE_DESTROYED (window))
    return FALSE;

  impl = GDK_WIN32_SURFACE (window);

  if (impl->hint_flags & GDK_HINT_MIN_SIZE)
    {
      rect.left = rect.top = 0;
      rect.right = impl->hints.min_width * impl->surface_scale;
      rect.bottom = impl->hints.min_height * impl->surface_scale;

      _gdk_win32_adjust_client_rect (window, &rect);

      mmi->ptMinTrackSize.x = rect.right - rect.left;
      mmi->ptMinTrackSize.y = rect.bottom - rect.top;
    }

  if (impl->hint_flags & GDK_HINT_MAX_SIZE)
    {
      int maxw, maxh;

      rect.left = rect.top = 0;
      rect.right = impl->hints.max_width * impl->surface_scale;
      rect.bottom = impl->hints.max_height * impl->surface_scale;

      _gdk_win32_adjust_client_rect (window, &rect);

      /* at least on win9x we have the 16 bit trouble */
      maxw = rect.right - rect.left;
      maxh = rect.bottom - rect.top;
      mmi->ptMaxTrackSize.x = maxw > 0 && maxw < G_MAXSHORT ? maxw : G_MAXSHORT;
      mmi->ptMaxTrackSize.y = maxh > 0 && maxh < G_MAXSHORT ? maxh : G_MAXSHORT;
    }
  else
    {
      /* According to "How does the window manager adjust ptMaxSize and
       * ptMaxPosition for multiple monitors?" article
       * https://blogs.msdn.microsoft.com/oldnewthing/20150501-00/?p=44964
       * if ptMaxSize >= primary_monitor_size, then it will be adjusted by
       * WM to account for the monitor size differences if the window gets
       * maximized on a non-primary monitor, by simply adding the size
       * difference (i.e. if non-primary monitor is larger by 100px, then
       * window will be made larger exactly by 100px).
       * If ptMaxSize < primary_monitor_size at least in one direction,
       * nothing is adjusted.
       * Therefore, if primary monitor is smaller than the actual monitor,
       * then it is not possible to give window a size that is larger than
       * the primary monitor and smaller than the non-primary monitor,
       * because WM will always enlarge the window.
       * Therefore, it is impossible to account for taskbar size.
       * So we don't try at all. Instead we just remember that we're trying
       * to maximize the window, catch WM_WINDOWPOSCHANGING and
       * adjust the size then.
       */
      HMONITOR nearest_monitor;
      MONITORINFO nearest_info;

      nearest_monitor = MonitorFromWindow (GDK_SURFACE_HWND (window), MONITOR_DEFAULTTONEAREST);
      nearest_info.cbSize = sizeof (nearest_info);

      if (GetMonitorInfoA (nearest_monitor, &nearest_info))
        {
          /* MSDN says that we must specify maximized window
           * size as if it was located on the primary monitor.
           * However, we still need to account for a taskbar
           * that might or might not be on the nearest monitor where
           * window will actually end up.
           * "0" here is the top-left corner of the primary monitor.
           */
          /* An investigation into bug 765161 turned up a weird Windows WM behaviour
           * where it would interpret "0:0" as "top-left of the workea" (accounting for a taskbar
           * possibly being along the left/top edge of the screen) when window has styles
           * (i.e. not CSD), and interpret the same "0:0" as "top-left of the screen" (not
           * accounting for a taskbar) when window has no styles (i.e. a CSD window).
           * This doesn't seem to be documented anywhere.
           * The following code uses a simple CSD/non-CSD test, but it could be that
           * this behaviour hinges on just one particular window style.
           * Finding exactly which style that could be is not very useful for GTK, however.
           */
          mmi->ptMaxPosition.x = 0;
          mmi->ptMaxPosition.y = 0;

          if (_gdk_win32_surface_lacks_wm_decorations (window))
            {
              mmi->ptMaxPosition.x += (nearest_info.rcWork.left - nearest_info.rcMonitor.left);
              mmi->ptMaxPosition.y += (nearest_info.rcWork.top - nearest_info.rcMonitor.top);
            }

          mmi->ptMaxSize.x = nearest_info.rcWork.right - nearest_info.rcWork.left;
          mmi->ptMaxSize.y = nearest_info.rcWork.bottom - nearest_info.rcWork.top;
        }

      mmi->ptMaxTrackSize.x = GetSystemMetrics (SM_CXVIRTUALSCREEN) + impl->margins_x * impl->surface_scale;
      mmi->ptMaxTrackSize.y = GetSystemMetrics (SM_CYVIRTUALSCREEN) + impl->margins_y * impl->surface_scale;
    }

  return TRUE;
}

#define GDK_ANY_BUTTON_MASK (GDK_BUTTON1_MASK | \
			     GDK_BUTTON2_MASK | \
			     GDK_BUTTON3_MASK | \
			     GDK_BUTTON4_MASK | \
			     GDK_BUTTON5_MASK)

static gboolean
gdk_event_translate (MSG *msg,
		     int *ret_valp)
{
  RECT rect;
  POINT point;
  MINMAXINFO *mmi;
  HWND hwnd;
  BYTE key_state[256];
  HIMC himc;
  WINDOWPOS *windowpos;
  gboolean ignore_leave;

  GdkEvent *event;

  wchar_t wbuf[100];
  int ccount;

  GdkDisplay *display;
  GdkSurface *window = NULL;
  GdkWin32Surface *impl;
  GdkWin32Display *win32_display;

  GdkSurface *new_window;

  GdkDeviceManagerWin32 *device_manager_win32;

  GdkDeviceGrabInfo *keyboard_grab = NULL;
  GdkDeviceGrabInfo *pointer_grab = NULL;
  GdkSurface *grab_window = NULL;

  int button;

  char buf[256];
  gboolean return_val = FALSE;

  int i;

  GdkModifierType state;
  guint keyval;
  guint16 keycode;
  guint8 group;
  gboolean is_modifier;

  double delta_x, delta_y;
  GdkScrollDirection direction;
  GdkTranslatedKey translated;

  display = gdk_display_get_default ();
  win32_display = GDK_WIN32_DISPLAY (display);

  if (win32_display->filters)
    {
      /* Apply display filters */
      GdkWin32MessageFilterReturn result = apply_message_filters (display, msg, ret_valp, &win32_display->filters);

      if (result == GDK_WIN32_MESSAGE_FILTER_REMOVE)
	return TRUE;
    }

  window = gdk_win32_handle_table_lookup (msg->hwnd);

  if (window == NULL)
    {
      /* XXX Handle WM_QUIT here ? */
      if (msg->message == WM_QUIT)
	{
	  GDK_NOTE (EVENTS, g_print (" %d", (int) msg->wParam));
	  exit (msg->wParam);
	}
      else if (msg->message == WM_CREATE)
	{
	  window = (UNALIGNED GdkSurface*) (((LPCREATESTRUCTW) msg->lParam)->lpCreateParams);
	  GDK_SURFACE_HWND (window) = msg->hwnd;
	}
      else
	{
	  GDK_NOTE (EVENTS, g_print (" (no GdkSurface)"));
	}
      return FALSE;
    }

  device_manager_win32 = GDK_DEVICE_MANAGER_WIN32 (_gdk_device_manager);

  keyboard_grab = _gdk_display_get_last_device_grab (display,
                                                     device_manager_win32->core_keyboard);
  pointer_grab = _gdk_display_get_last_device_grab (display,
                                                    device_manager_win32->core_pointer);

  g_object_ref (window);

  /* window's refcount has now been increased, so code below should
   * not just return from this function, but instead goto done (or
   * break out of the big switch). To protect against forgetting this,
   * #define return to a syntax error...
   */
#define return GOTO_DONE_INSTEAD

  if (msg->message == aerosnap_message)
    _gdk_win32_surface_handle_aerosnap (window,
                                       (GdkWin32AeroSnapCombo) msg->wParam);

  switch (msg->message)
    {
    case WM_INPUTLANGCHANGE:
      _gdk_input_locale = (HKL) msg->lParam;
      _gdk_win32_keymap_set_active_layout (GDK_WIN32_KEYMAP (_gdk_win32_display_get_keymap (_gdk_display)), _gdk_input_locale);
      GetLocaleInfo (MAKELCID (LOWORD (_gdk_input_locale), SORT_DEFAULT),
		     LOCALE_IDEFAULTANSICODEPAGE,
		     buf, sizeof (buf));
      _gdk_input_codepage = atoi (buf);
      _gdk_keymap_serial++;
      GDK_NOTE (EVENTS,
		g_print (" cs:%lu hkl:%p%s cp:%d",
			 (gulong) msg->wParam,
			 (gpointer) msg->lParam, _gdk_input_locale_is_ime ? " (IME)" : "",
			 _gdk_input_codepage));
      gdk_display_setting_changed (display, "gtk-im-module");

      /* Generate a dummy key event to "nudge" IMContext */
      translated.keyval = GDK_KEY_VoidSymbol;
      translated.consumed = 0;
      translated.layout = 0;
      translated.level = 0;
      event = gdk_key_event_new (GDK_KEY_PRESS,
                                 window,
                                 device_manager_win32->core_keyboard,
                                 _gdk_win32_get_next_tick (msg->time),
                                 0,
                                 0,
                                 FALSE,
                                 &translated,
                                 &translated);
      _gdk_win32_append_event (event);
      break;

    case WM_SYSKEYUP:
    case WM_SYSKEYDOWN:
      GDK_NOTE (EVENTS,
		g_print (" %s ch:%.02x %s",
			 _gdk_win32_key_to_string (msg->lParam),
			 (int) msg->wParam,
			 decode_key_lparam (msg->lParam)));

      /* If posted without us having keyboard focus, ignore */
      if ((msg->wParam != VK_F10 && msg->wParam != VK_MENU) &&
	  !(HIWORD (msg->lParam) & KF_ALTDOWN))
	break;

      /* Let the system handle Alt-Tab, Alt-Space and Alt-F4 unless
       * the keyboard is grabbed.
       */
      if (!keyboard_grab &&
	  (msg->wParam == VK_TAB ||
	   msg->wParam == VK_SPACE ||
	   msg->wParam == VK_F4))
	break;

      /* Jump to code in common with WM_KEYUP and WM_KEYDOWN */
      goto keyup_or_down;

    case WM_KEYUP:
    case WM_KEYDOWN:
      GDK_NOTE (EVENTS,
		g_print (" %s ch:%.02x %s",
			 _gdk_win32_key_to_string (msg->lParam),
			 (int) msg->wParam,
			 decode_key_lparam (msg->lParam)));

    keyup_or_down:

      /* Ignore key messages intended for the IME */
      if (msg->wParam == VK_PROCESSKEY ||
	  in_ime_composition)
	break;

      /* Ignore autorepeats on modifiers */
      if (msg->message == WM_KEYDOWN &&
          (msg->wParam == VK_MENU ||
           msg->wParam == VK_CONTROL ||
           msg->wParam == VK_SHIFT) &&
           ((HIWORD(msg->lParam) & KF_REPEAT) >= 1))
        break;

      if (GDK_SURFACE_DESTROYED (window))
	break;

      impl = GDK_WIN32_SURFACE (window);

      API_CALL (GetKeyboardState, (key_state));

      ccount = 0;

      if (msg->wParam == VK_PACKET)
	{
	  ccount = ToUnicode (VK_PACKET, HIWORD (msg->lParam), key_state, wbuf, 1, 0);
	  if (ccount == 1)
	    {
	      if (wbuf[0] >= 0xD800 && wbuf[0] < 0xDC00)
	        {
		  if (msg->message == WM_KEYDOWN)
		    impl->leading_surrogate_keydown = wbuf[0];
		  else
		    impl->leading_surrogate_keyup = wbuf[0];

		  /* don't emit an event */
		  return_val = TRUE;
		  break;
	        }
	      else
		{
		  /* wait until an event is created */;
		}
	    }
	}

      keyval = GDK_KEY_VoidSymbol;
      keycode = msg->wParam;

      if (HIWORD (msg->lParam) & KF_EXTENDED)
	{
	  switch (msg->wParam)
	    {
	    case VK_CONTROL:
	      keycode = VK_RCONTROL;
	      break;
	    case VK_SHIFT:	/* Actually, KF_EXTENDED is not set
				 * for the right shift key.
				 */
	      keycode = VK_RSHIFT;
	      break;
	    case VK_MENU:
	      keycode = VK_RMENU;
	      break;
	    }
	}
      else if (msg->wParam == VK_SHIFT &&
	       LOBYTE (HIWORD (msg->lParam)) == _gdk_win32_keymap_get_rshift_scancode (GDK_WIN32_KEYMAP (_gdk_win32_display_get_keymap (_gdk_display))))
	keycode = VK_RSHIFT;

      is_modifier = (msg->wParam == VK_CONTROL ||
                     msg->wParam == VK_SHIFT ||
                     msg->wParam == VK_MENU);
      /* g_print ("ctrl:%02x lctrl:%02x rctrl:%02x alt:%02x lalt:%02x ralt:%02x\n", key_state[VK_CONTROL], key_state[VK_LCONTROL], key_state[VK_RCONTROL], key_state[VK_MENU], key_state[VK_LMENU], key_state[VK_RMENU]); */

      state = build_key_event_state (key_state);
      group = get_active_group ();

      if (msg->wParam == VK_PACKET && ccount == 1)
	{
	  if (wbuf[0] >= 0xD800 && wbuf[0] < 0xDC00)
	    {
	      g_assert_not_reached ();
	    }
	  else if (wbuf[0] >= 0xDC00 && wbuf[0] < 0xE000)
	    {
	      wchar_t leading;

              if (msg->message == WM_KEYDOWN)
		leading = impl->leading_surrogate_keydown;
	      else
		leading = impl->leading_surrogate_keyup;

	      keyval = gdk_unicode_to_keyval ((leading - 0xD800) * 0x400 + wbuf[0] - 0xDC00 + 0x10000);
	    }
	  else
	    {
	      keyval = gdk_unicode_to_keyval (wbuf[0]);
	    }
	}
      else
	{
	  gdk_keymap_translate_keyboard_state (_gdk_win32_display_get_keymap (display),
					       keycode,
					       state,
					       group,
					       &keyval,
					       NULL, NULL, NULL);
	}

      if (msg->message == WM_KEYDOWN)
	impl->leading_surrogate_keydown = 0;
      else
	impl->leading_surrogate_keyup = 0;

  /* Only one release key event is fired when both shift keys are pressed together
     and then released. In order to send the missing event, press events for shift
     keys are recorded and sent together when the release event occurs.
     Other modifiers (e.g. ctrl, alt) don't have this problem. */
  if (msg->message == WM_KEYDOWN && msg->wParam == VK_SHIFT)
    {
      int pressed_shift = msg->lParam & 0xffffff; /* mask shift modifier */
      if (both_shift_pressed[0] == 0)
        both_shift_pressed[0] = pressed_shift;
      else if (both_shift_pressed[0] != pressed_shift)
        both_shift_pressed[1] = pressed_shift;
    }

  if (msg->message == WM_KEYUP && msg->wParam == VK_SHIFT)
    {
      if (both_shift_pressed[0] != 0 && both_shift_pressed[1] != 0)
        {
          int tmp_retval;
          MSG fake_release = *msg;
          int pressed_shift = msg->lParam & 0xffffff;

          if (both_shift_pressed[0] == pressed_shift)
            fake_release.lParam = both_shift_pressed[1];
          else
            fake_release.lParam = both_shift_pressed[0];

          both_shift_pressed[0] = both_shift_pressed[1] = 0;
          gdk_event_translate (&fake_release, &tmp_retval);
        }
      both_shift_pressed[0] = both_shift_pressed[1] = 0;
    }

      /* Reset ALT_MASK if it is the Alt key itself */
      if (msg->wParam == VK_MENU)
	state &= ~GDK_ALT_MASK;

      /* FIXME do proper translation */
      translated.keyval = keyval;
      translated.consumed = 0;
      translated.layout = group;
      translated.level = 0;
      event = gdk_key_event_new ((msg->message == WM_KEYDOWN || msg->message == WM_SYSKEYDOWN)
                                   ? GDK_KEY_PRESS
                                   : GDK_KEY_RELEASE,
                                 window,
                                 device_manager_win32->core_keyboard,
                                 _gdk_win32_get_next_tick (msg->time),
                                 state,
                                 keycode,
                                 is_modifier,
                                 &translated,
                                 &translated);

      _gdk_win32_append_event (event);

      return_val = TRUE;
      break;

    case WM_SYSCHAR:
      if (msg->wParam != VK_SPACE)
	{
	  /* To prevent beeps, don't let DefWindowProcW() be called */
	  return_val = TRUE;
	  goto done;
	}
      break;

    case WM_IME_STARTCOMPOSITION:
      in_ime_composition = TRUE;
      break;

    case WM_IME_ENDCOMPOSITION:
      in_ime_composition = FALSE;
      break;

    case WM_IME_COMPOSITION:
      /* On Win2k WM_IME_CHAR doesn't work correctly for non-Unicode
       * applications. Thus, handle WM_IME_COMPOSITION with
       * GCS_RESULTSTR instead, fetch the Unicode chars from the IME
       * with ImmGetCompositionStringW().
       *
       * See for instance
       * http://groups.google.com/groups?selm=natX5.57%24g77.19788%40nntp2.onemain.com
       * and
       * http://groups.google.com/groups?selm=u2XfrXw5BHA.1628%40tkmsftngp02
       * for comments by other people that seems to have the same
       * experience. WM_IME_CHAR just gives question marks, apparently
       * because of going through some conversion to the current code
       * page.
       *
       * WM_IME_CHAR might work on NT4 or Win9x with ActiveIMM, but
       * use WM_IME_COMPOSITION there, too, to simplify the code.
       */
      GDK_NOTE (EVENTS, g_print (" %#lx", (long) msg->lParam));

      if (!(msg->lParam & GCS_RESULTSTR))
	break;

      if (GDK_SURFACE_DESTROYED (window))
	break;

      himc = ImmGetContext (msg->hwnd);
      ccount = ImmGetCompositionStringW (himc, GCS_RESULTSTR,
					 wbuf, sizeof (wbuf));
      ImmReleaseContext (msg->hwnd, himc);

      ccount /= 2;

      API_CALL (GetKeyboardState, (key_state));

      for (i = 0; i < ccount; i++)
	{
          /* Build a key press event */
          translated.keyval = gdk_unicode_to_keyval (wbuf[i]);
          translated.consumed = 0;
          translated.layout = get_active_group ();
          translated.level = 0;
          event = gdk_key_event_new (GDK_KEY_PRESS,
                                     window,
                                     device_manager_win32->core_keyboard,
                                     _gdk_win32_get_next_tick (msg->time),
                                     build_key_event_state (key_state),
                                     0,
                                     FALSE,
                                     &translated,
                                     &translated);

          _gdk_win32_append_event (event);

          /* Build a key release event.  */
          event = gdk_key_event_new (GDK_KEY_RELEASE,
                                     window,
                                     device_manager_win32->core_keyboard,
                                     _gdk_win32_get_next_tick (msg->time),
                                     build_key_event_state (key_state),
                                     0,
                                     FALSE,
                                     &translated,
                                     &translated);

          _gdk_win32_append_event (event);
	}
      return_val = TRUE;
      break;

    case WM_LBUTTONDOWN:
      button = 1;
      goto buttondown0;

    case WM_MBUTTONDOWN:
      button = 2;
      goto buttondown0;

    case WM_RBUTTONDOWN:
      button = 3;
      goto buttondown0;

    case WM_XBUTTONDOWN:
      if (HIWORD (msg->wParam) == XBUTTON1)
	button = 4;
      else
	button = 5;

    buttondown0:
      GDK_NOTE (EVENTS,
		g_print (" (%d,%d)",
			 GET_X_LPARAM (msg->lParam), GET_Y_LPARAM (msg->lParam)));

      g_set_object (&window, find_window_for_mouse_event (window, msg));
      /* TODO_CSW?: there used to some synthesize and propagate */
      if (GDK_SURFACE_DESTROYED (window))
	break;

      if (pointer_grab == NULL)
	{
	  SetCapture (GDK_SURFACE_HWND (window));
	  g_set_object (&implicit_grab_surface, g_object_ref (window));
	}
      else
	g_set_object (&implicit_grab_surface, NULL);

      generate_button_event (GDK_BUTTON_PRESS, button,
			     window, msg);

      return_val = TRUE;
      break;

    case WM_LBUTTONUP:
      button = 1;
      goto buttonup0;

    case WM_MBUTTONUP:
      button = 2;
      goto buttonup0;

    case WM_RBUTTONUP:
      button = 3;
      goto buttonup0;

    case WM_XBUTTONUP:
      if (HIWORD (msg->wParam) == XBUTTON1)
	button = 4;
      else
	button = 5;

    buttonup0:
      GDK_NOTE (EVENTS,
		g_print (" (%d,%d)",
			 GET_X_LPARAM (msg->lParam), GET_Y_LPARAM (msg->lParam)));

      g_set_object (&window, find_window_for_mouse_event (window, msg));

      if (pointer_grab == NULL && implicit_grab_surface != NULL)
	{
	  int state = build_pointer_event_state (msg);

	  /* We keep the implicit grab until no buttons at all are held down */
	  if ((state & GDK_ANY_BUTTON_MASK & ~(GDK_BUTTON1_MASK << (button - 1))) == 0)
	    {
	      ReleaseCapture ();

	      new_window = NULL;
	      hwnd = WindowFromPoint (msg->pt);
	      if (hwnd != NULL)
		{
		  POINT client_pt = msg->pt;

		  ScreenToClient (hwnd, &client_pt);
		  GetClientRect (hwnd, &rect);
		  if (PtInRect (&rect, client_pt))
		    new_window = gdk_win32_handle_table_lookup (hwnd);
		}

	      synthesize_crossing_events (display,
					  implicit_grab_surface, new_window,
					  GDK_CROSSING_UNGRAB,
					  &msg->pt,
					  0, /* TODO: Set right mask */
					  msg->time,
					  FALSE);
	      g_set_object (&implicit_grab_surface, NULL);
	      g_set_object (&mouse_window, new_window);
	      mouse_window_ignored_leave = NULL;
	    }
	}
      else
	g_set_object (&implicit_grab_surface, NULL);

      generate_button_event (GDK_BUTTON_RELEASE, button,
			     window, msg);

      impl = GDK_WIN32_SURFACE (window);

      /* End a drag op when the same button that started it is released */
      if (impl->drag_move_resize_context.op != GDK_WIN32_DRAGOP_NONE &&
          impl->drag_move_resize_context.button == button)
        gdk_win32_surface_end_move_resize_drag (window);

      return_val = TRUE;
      break;

    case WM_MOUSEMOVE:
      GDK_NOTE (EVENTS,
		g_print (" %p (%d,%d)",
			 (gpointer) msg->wParam,
			 GET_X_LPARAM (msg->lParam), GET_Y_LPARAM (msg->lParam)));

      new_window = window;

      if (pointer_grab != NULL)
	{
	  POINT pt;
	  pt = msg->pt;

	  new_window = NULL;
	  hwnd = WindowFromPoint (pt);
	  if (hwnd != NULL)
	    {
	      POINT client_pt = pt;

	      ScreenToClient (hwnd, &client_pt);
	      GetClientRect (hwnd, &rect);
	      if (PtInRect (&rect, client_pt))
		new_window = gdk_win32_handle_table_lookup (hwnd);
	    }

	  if (!pointer_grab->owner_events &&
	      new_window != NULL &&
	      new_window != pointer_grab->surface)
	    new_window = NULL;
	}

      if (mouse_window != new_window)
	{
	  GDK_NOTE (EVENTS, g_print (" mouse_sinwod %p -> %p",
				     mouse_window ? GDK_SURFACE_HWND (mouse_window) : NULL,
				     new_window ? GDK_SURFACE_HWND (new_window) : NULL));
	  synthesize_crossing_events (display,
				      mouse_window, new_window,
				      GDK_CROSSING_NORMAL,
				      &msg->pt,
				      0, /* TODO: Set right mask */
				      msg->time,
				      FALSE);
	  g_set_object (&mouse_window, new_window);
	  mouse_window_ignored_leave = NULL;
	  if (new_window != NULL)
	    track_mouse_event (TME_LEAVE, GDK_SURFACE_HWND (new_window));
	}
      else if (new_window != NULL &&
	       new_window == mouse_window_ignored_leave)
	{
	  /* If we ignored a leave event for this window and we're now getting
	     input again we need to re-arm the mouse tracking, as that was
	     cancelled by the mouseleave. */
	  mouse_window_ignored_leave = NULL;
	  track_mouse_event (TME_LEAVE, GDK_SURFACE_HWND (new_window));
	}

      g_set_object (&window, find_window_for_mouse_event (window, msg));
      impl = GDK_WIN32_SURFACE (window);

      /* If we haven't moved, don't create any GDK event. Windows
       * sends WM_MOUSEMOVE messages after a new window is shows under
       * the mouse, even if the mouse hasn't moved. This disturbs gtk.
       */
      if ((msg->pt.x + _gdk_offset_x) / impl->surface_scale == current_root_x &&
	  (msg->pt.y + _gdk_offset_y) / impl->surface_scale == current_root_y)
	break;

      current_root_x = (msg->pt.x + _gdk_offset_x) / impl->surface_scale;
      current_root_y = (msg->pt.y + _gdk_offset_y) / impl->surface_scale;


      if (impl->drag_move_resize_context.op != GDK_WIN32_DRAGOP_NONE)
        {
          gdk_win32_surface_do_move_resize_drag (window, current_root_x, current_root_y);
        }
      else if (_gdk_input_ignore_core == 0)
	{
	  current_x = (gint16) GET_X_LPARAM (msg->lParam) / impl->surface_scale;
	  current_y = (gint16) GET_Y_LPARAM (msg->lParam) / impl->surface_scale;

	  event = gdk_motion_event_new (window,
	                                device_manager_win32->core_pointer,
                                        NULL,
                                        _gdk_win32_get_next_tick (msg->time),
	                                build_pointer_event_state (msg),
                                        current_x,
                                        current_y,
                                        NULL);

	  _gdk_win32_append_event (event);
	}

      return_val = TRUE;
      break;

    case WM_NCMOUSEMOVE:
      GDK_NOTE (EVENTS,
		g_print (" (%d,%d)",
			 GET_X_LPARAM (msg->lParam), GET_Y_LPARAM (msg->lParam)));
      break;

    case WM_MOUSELEAVE:
      GDK_NOTE (EVENTS, g_print (" %d (%ld,%ld)",
				 HIWORD (msg->wParam), msg->pt.x, msg->pt.y));

      new_window = NULL;
      hwnd = WindowFromPoint (msg->pt);
      ignore_leave = FALSE;
      if (hwnd != NULL)
	{
	  char classname[64];

	  POINT client_pt = msg->pt;

	  /* The synapitics trackpad drivers have this irritating
	     feature where it pops up a window right under the pointer
	     when you scroll. We ignore the leave and enter events for
	     this window */
	  if (GetClassNameA (hwnd, classname, sizeof(classname)) &&
	      strcmp (classname, SYNAPSIS_ICON_WINDOW_CLASS) == 0)
	    ignore_leave = TRUE;

	  ScreenToClient (hwnd, &client_pt);
	  GetClientRect (hwnd, &rect);
	  if (PtInRect (&rect, client_pt))
	    new_window = gdk_win32_handle_table_lookup (hwnd);
	}

      if (!ignore_leave)
	synthesize_crossing_events (display,
				    mouse_window, new_window,
				    GDK_CROSSING_NORMAL,
				    &msg->pt,
				    0, /* TODO: Set right mask */
				    msg->time,
				    FALSE);
      g_set_object (&mouse_window, new_window);
      mouse_window_ignored_leave = ignore_leave ? new_window : NULL;


      return_val = TRUE;
      break;

    case WM_MOUSEWHEEL:
    case WM_MOUSEHWHEEL:
      GDK_NOTE (EVENTS, g_print (" %d", (short) HIWORD (msg->wParam)));

      /* WM_MOUSEWHEEL is delivered to the focus window. Work around
       * that. Also, the position is in screen coordinates, not client
       * coordinates as with the button messages. I love the
       * consistency of Windows.
       */
      point.x = GET_X_LPARAM (msg->lParam);
      point.y = GET_Y_LPARAM (msg->lParam);

      if ((hwnd = WindowFromPoint (point)) == NULL)
	break;

      {
	char classname[64];

	/* The synapitics trackpad drivers have this irritating
	   feature where it pops up a window right under the pointer
	   when you scroll. We backtrack and to the toplevel and
	   find the innermost child instead. */
	if (GetClassNameA (hwnd, classname, sizeof(classname)) &&
	    strcmp (classname, SYNAPSIS_ICON_WINDOW_CLASS) == 0)
	  {
	    HWND hwndc;

	    /* Find our toplevel window */
	    hwnd = GetAncestor (msg->hwnd, GA_ROOT);

	    /* Walk back up to the outermost child at the desired point */
	    do {
	      ScreenToClient (hwnd, &point);
	      hwndc = ChildWindowFromPoint (hwnd, point);
	      ClientToScreen (hwnd, &point);
	    } while (hwndc != hwnd && (hwnd = hwndc, 1));
	  }
      }

      msg->hwnd = hwnd;
      if ((new_window = gdk_win32_handle_table_lookup (msg->hwnd)) == NULL)
	break;

      if (new_window != window)
	{
	  g_set_object (&window, new_window);
	}

      impl = GDK_WIN32_SURFACE (window);
      ScreenToClient (msg->hwnd, &point);

      delta_x = delta_y = 0.0;

      if (msg->message == WM_MOUSEWHEEL)
        delta_y = (double) GET_WHEEL_DELTA_WPARAM (msg->wParam) / (double) WHEEL_DELTA;
      else if (msg->message == WM_MOUSEHWHEEL)
        delta_x = (double) GET_WHEEL_DELTA_WPARAM (msg->wParam) / (double) WHEEL_DELTA;
      /* Positive delta scrolls up, not down,
         see API documentation for WM_MOUSEWHEEL message.
       */
      delta_y *= -1.0;

      event = gdk_scroll_event_new (window,
                                    device_manager_win32->core_pointer,
                                    NULL,
                                    _gdk_win32_get_next_tick (msg->time),
                                    build_pointer_event_state (msg),
                                    delta_x,
                                    delta_y,
                                    FALSE);

      _gdk_win32_append_event (event);

      /* Append the discrete version too */
      direction = 0;
      if (msg->message == WM_MOUSEWHEEL)
	direction = (((short) HIWORD (msg->wParam)) > 0)
	              ? GDK_SCROLL_UP
                      : GDK_SCROLL_DOWN;
      else if (msg->message == WM_MOUSEHWHEEL)
	direction = (((short) HIWORD (msg->wParam)) > 0)
                      ? GDK_SCROLL_RIGHT
                      : GDK_SCROLL_LEFT;

      event = gdk_scroll_event_new_discrete (window,
                                             device_manager_win32->core_pointer,
                                             NULL,
                                             _gdk_win32_get_next_tick (msg->time),
                                             build_pointer_event_state (msg),
                                             direction,
                                             TRUE);

      _gdk_win32_append_event (event);

      return_val = TRUE;
      break;

    case WM_HSCROLL:
      /* Just print more debugging information, don't actually handle it. */
      GDK_NOTE (EVENTS,
		(g_print (" %s",
			  (LOWORD (msg->wParam) == SB_ENDSCROLL ? "ENDSCROLL" :
			   (LOWORD (msg->wParam) == SB_LEFT ? "LEFT" :
			    (LOWORD (msg->wParam) == SB_RIGHT ? "RIGHT" :
			     (LOWORD (msg->wParam) == SB_LINELEFT ? "LINELEFT" :
			      (LOWORD (msg->wParam) == SB_LINERIGHT ? "LINERIGHT" :
			       (LOWORD (msg->wParam) == SB_PAGELEFT ? "PAGELEFT" :
				(LOWORD (msg->wParam) == SB_PAGERIGHT ? "PAGERIGHT" :
				 (LOWORD (msg->wParam) == SB_THUMBPOSITION ? "THUMBPOSITION" :
				  (LOWORD (msg->wParam) == SB_THUMBTRACK ? "THUMBTRACK" :
				   "???")))))))))),
		 (LOWORD (msg->wParam) == SB_THUMBPOSITION ||
		  LOWORD (msg->wParam) == SB_THUMBTRACK) ?
		 (g_print (" %d", HIWORD (msg->wParam)), 0) : 0));
      break;

    case WM_VSCROLL:
      /* Just print more debugging information, don't actually handle it. */
      GDK_NOTE (EVENTS,
		(g_print (" %s",
			  (LOWORD (msg->wParam) == SB_ENDSCROLL ? "ENDSCROLL" :
			   (LOWORD (msg->wParam) == SB_BOTTOM ? "BOTTOM" :
			    (LOWORD (msg->wParam) == SB_TOP ? "TOP" :
			     (LOWORD (msg->wParam) == SB_LINEDOWN ? "LINDOWN" :
			      (LOWORD (msg->wParam) == SB_LINEUP ? "LINEUP" :
			       (LOWORD (msg->wParam) == SB_PAGEDOWN ? "PAGEDOWN" :
				(LOWORD (msg->wParam) == SB_PAGEUP ? "PAGEUP" :
				 (LOWORD (msg->wParam) == SB_THUMBPOSITION ? "THUMBPOSITION" :
				  (LOWORD (msg->wParam) == SB_THUMBTRACK ? "THUMBTRACK" :
				   "???")))))))))),
		 (LOWORD (msg->wParam) == SB_THUMBPOSITION ||
		  LOWORD (msg->wParam) == SB_THUMBTRACK) ?
		 (g_print (" %d", HIWORD (msg->wParam)), 0) : 0));
      break;

     case WM_MOUSEACTIVATE:
       {
	 if (GDK_IS_DRAG_SURFACE (window))
	   {
	     *ret_valp = MA_NOACTIVATE;
	     return_val = TRUE;
	   }

	 if (_gdk_modal_blocked (window))
	   {
	     *ret_valp = MA_NOACTIVATEANDEAT;
	     return_val = TRUE;
	   }
       }

       break;

    case WM_KILLFOCUS:
      if (keyboard_grab != NULL &&
	  !GDK_SURFACE_DESTROYED (keyboard_grab->surface) &&
	  (_modal_operation_in_progress & GDK_WIN32_MODAL_OP_DND) == 0)
	{
	  generate_grab_broken_event (_gdk_device_manager, keyboard_grab->surface, TRUE, NULL);
	}
      G_GNUC_FALLTHROUGH;

    case WM_SETFOCUS:
      if (keyboard_grab != NULL &&
	  !keyboard_grab->owner_events)
	break;

      if (GDK_SURFACE_DESTROYED (window))
	break;

      generate_focus_event (_gdk_device_manager, window, (msg->message == WM_SETFOCUS));
      return_val = TRUE;
      break;

    case WM_ERASEBKGND:
      GDK_NOTE (EVENTS, g_print (" %p", (HANDLE) msg->wParam));

      if (GDK_SURFACE_DESTROYED (window))
	break;

      return_val = TRUE;
      *ret_valp = 1;
      break;

    case WM_SYNCPAINT:
      sync_timer = SetTimer (GDK_SURFACE_HWND (window),
			     1,
			     200, sync_timer_proc);
      break;

    case WM_PAINT:
      handle_wm_paint (msg, window);
      break;

    case WM_SETCURSOR:
      GDK_NOTE (EVENTS, g_print (" %#x %#x",
				 LOWORD (msg->lParam), HIWORD (msg->lParam)));

      if (pointer_grab != NULL)
        grab_window = pointer_grab->surface;

      if (grab_window == NULL && LOWORD (msg->lParam) != HTCLIENT)
	break;

      return_val = FALSE;

      if (grab_window != NULL &&
          !GDK_SURFACE_DESTROYED (grab_window))
        {
          win32_display = GDK_WIN32_DISPLAY (gdk_surface_get_display (grab_window));

          if (win32_display->grab_cursor != NULL)
            {
              GDK_NOTE (EVENTS, g_print (" (grab SetCursor(%p)", gdk_win32_hcursor_get_handle (win32_display->grab_cursor)));
              SetCursor (gdk_win32_hcursor_get_handle (win32_display->grab_cursor));
              return_val = TRUE;
              *ret_valp = TRUE;
            }
        }

      if (!return_val &&
          !GDK_SURFACE_DESTROYED (window) &&
          GDK_WIN32_SURFACE (window)->cursor != NULL)
        {
          win32_display = GDK_WIN32_DISPLAY (gdk_surface_get_display (window));
          GDK_NOTE (EVENTS, g_print (" (window SetCursor(%p)", gdk_win32_hcursor_get_handle (GDK_WIN32_SURFACE (window)->cursor)));
          SetCursor (gdk_win32_hcursor_get_handle (GDK_WIN32_SURFACE (window)->cursor));
          return_val = TRUE;
          *ret_valp = TRUE;
        }

      break;

    case WM_SYSMENU:
      return_val = handle_wm_sysmenu (window, msg, ret_valp);
      break;

    case WM_INITMENU:
      impl = GDK_WIN32_SURFACE (window);

      if (impl->have_temp_styles)
        {
          LONG_PTR window_style;

          window_style = GetWindowLongPtr (GDK_SURFACE_HWND (window),
                                           GWL_STYLE);
          /* Handling WM_SYSMENU added extra styles to this window,
           * remove them now.
           */
          window_style &= ~impl->temp_styles;
          SetWindowLongPtr (GDK_SURFACE_HWND (window),
                            GWL_STYLE,
                            window_style);
        }

      break;

    case WM_SYSCOMMAND:
      switch (msg->wParam)
	{
	case SC_MINIMIZE:
	case SC_RESTORE:
          do_show_window (window, msg->wParam == SC_MINIMIZE ? TRUE : FALSE);

          if (msg->wParam == SC_RESTORE)
            _gdk_win32_surface_invalidate_egl_framebuffer (window);

	  break;
        case SC_MAXIMIZE:
          impl = GDK_WIN32_SURFACE (window);
          impl->maximizing = TRUE;
	  break;
	}

      break;

    case WM_ENTERSIZEMOVE:
      _modal_move_resize_window = msg->hwnd;
      _gdk_win32_begin_modal_call (GDK_WIN32_MODAL_OP_SIZEMOVE_MASK);
      break;

    case WM_EXITSIZEMOVE:
      if (_modal_operation_in_progress & GDK_WIN32_MODAL_OP_SIZEMOVE_MASK)
	{
	  _modal_move_resize_window = NULL;
	  _gdk_win32_end_modal_call (GDK_WIN32_MODAL_OP_SIZEMOVE_MASK);
	}
      break;

    case WM_ENTERMENULOOP:
      _gdk_win32_begin_modal_call (GDK_WIN32_MODAL_OP_MENU);
      break;

    case WM_EXITMENULOOP:
      if (_modal_operation_in_progress & GDK_WIN32_MODAL_OP_MENU)
	_gdk_win32_end_modal_call (GDK_WIN32_MODAL_OP_MENU);
      break;

      break;

    /*
     * Handle WM_CANCELMODE and do nothing in response to it when DnD is
     * active. Otherwise pass it to DefWindowProc, which will call ReleaseCapture()
     * on our behalf.
     * This prevents us from losing mouse capture when alt-tabbing during DnD
     * (this includes the feature of Windows Explorer where dragging stuff over
     * a window button in the taskbar causes that window to receive focus, i.e.
     * keyboardless alt-tabbing).
     */
    case WM_CANCELMODE:
      if (_modal_operation_in_progress & GDK_WIN32_MODAL_OP_DND)
        {
          return_val = TRUE;
          *ret_valp = 0;
        }
      break;

    case WM_CAPTURECHANGED:
      /* Sometimes we don't get WM_EXITSIZEMOVE, for instance when you
	 select move/size in the menu and then click somewhere without
	 moving/resizing. We work around this using WM_CAPTURECHANGED. */
      if (_modal_operation_in_progress & GDK_WIN32_MODAL_OP_SIZEMOVE_MASK)
	{
	  _modal_move_resize_window = NULL;
	  _gdk_win32_end_modal_call (GDK_WIN32_MODAL_OP_SIZEMOVE_MASK);
	}

      impl = GDK_WIN32_SURFACE (window);

      if (impl->drag_move_resize_context.op != GDK_WIN32_DRAGOP_NONE)
        gdk_win32_surface_end_move_resize_drag (window);
      break;

    case WM_WINDOWPOSCHANGING:
      GDK_NOTE (EVENTS, (windowpos = (WINDOWPOS *) msg->lParam,
			 g_print (" %s %s %dx%d@%+d%+d now below %p",
				  _gdk_win32_surface_pos_bits_to_string (windowpos->flags),
				  (windowpos->hwndInsertAfter == HWND_BOTTOM ? "BOTTOM" :
				   (windowpos->hwndInsertAfter == HWND_NOTOPMOST ? "NOTOPMOST" :
				    (windowpos->hwndInsertAfter == HWND_TOP ? "TOP" :
				     (windowpos->hwndInsertAfter == HWND_TOPMOST ? "TOPMOST" :
				      (sprintf (buf, "%p", windowpos->hwndInsertAfter),
				       buf))))),
				  windowpos->cx, windowpos->cy, windowpos->x, windowpos->y,
				  GetNextWindow (msg->hwnd, GW_HWNDPREV))));

      if (GDK_SURFACE_IS_MAPPED (window))
        {

          impl = GDK_WIN32_SURFACE (window);

          if (impl->maximizing)
            {
              MINMAXINFO our_mmi;

              if (_gdk_win32_surface_fill_min_max_info (window, &our_mmi))
                {
                  windowpos = (WINDOWPOS *) msg->lParam;
                  windowpos->cx = our_mmi.ptMaxSize.x;
                  windowpos->cy = our_mmi.ptMaxSize.y;
                }

              impl->maximizing = FALSE;
            }
        }

      break;

    case WM_WINDOWPOSCHANGED:
      windowpos = (WINDOWPOS *) msg->lParam;
      GDK_NOTE (EVENTS, g_print (" %s %s %dx%d@%+d%+d",
				 _gdk_win32_surface_pos_bits_to_string (windowpos->flags),
				 (windowpos->hwndInsertAfter == HWND_BOTTOM ? "BOTTOM" :
				  (windowpos->hwndInsertAfter == HWND_NOTOPMOST ? "NOTOPMOST" :
				   (windowpos->hwndInsertAfter == HWND_TOP ? "TOP" :
				    (windowpos->hwndInsertAfter == HWND_TOPMOST ? "TOPMOST" :
				     (sprintf (buf, "%p", windowpos->hwndInsertAfter),
				      buf))))),
				 windowpos->cx, windowpos->cy, windowpos->x, windowpos->y));

      /* Break grabs on unmap or minimize */
      if (windowpos->flags & SWP_HIDEWINDOW ||
	  ((windowpos->flags & SWP_STATECHANGED) && IsIconic (msg->hwnd)))
      {
        GdkDevice *device = gdk_seat_get_pointer (gdk_display_get_default_seat (display));

        if ((pointer_grab != NULL && pointer_grab->surface == window) ||
            (keyboard_grab != NULL && keyboard_grab->surface == window))
          gdk_device_ungrab (device, msg -> time);
    }

      /* Update window state */
      if (windowpos->flags & (SWP_STATECHANGED | SWP_SHOWWINDOW | SWP_HIDEWINDOW))
	{
	  GdkToplevelState set_bits, unset_bits, old_state, new_state;

	  old_state = window->state;

	  set_bits = 0;
	  unset_bits = 0;

	  if (IsWindowVisible (msg->hwnd))
	    unset_bits |= GDK_TOPLEVEL_STATE_WITHDRAWN;
	  else
	    set_bits |= GDK_TOPLEVEL_STATE_WITHDRAWN;

	  if (IsIconic (msg->hwnd))
	    set_bits |= GDK_TOPLEVEL_STATE_MINIMIZED;
	  else
	    unset_bits |= GDK_TOPLEVEL_STATE_MINIMIZED;

	  if (IsZoomed (msg->hwnd))
	    set_bits |= GDK_TOPLEVEL_STATE_MAXIMIZED;
	  else
	    unset_bits |= GDK_TOPLEVEL_STATE_MAXIMIZED;

	  gdk_synthesize_surface_state (window, unset_bits, set_bits);

	  new_state = window->state;

	  /* Whenever one window changes iconified state we need to also
	   * change the iconified state in all transient related windows,
	   * as windows doesn't give icons for transient childrens.
	   */
	  if ((old_state & GDK_TOPLEVEL_STATE_MINIMIZED) !=
	      (new_state & GDK_TOPLEVEL_STATE_MINIMIZED))
	    do_show_window (window, (new_state & GDK_TOPLEVEL_STATE_MINIMIZED));
	}

      /* Show, New size or position => configure event */
      if (!(windowpos->flags & SWP_NOCLIENTMOVE) ||
	  !(windowpos->flags & SWP_NOCLIENTSIZE) ||
	  (windowpos->flags & SWP_SHOWWINDOW))
	{
	  if (!IsIconic (msg->hwnd) &&
	      !GDK_SURFACE_DESTROYED (window))
	    _gdk_win32_emit_configure_event (window);
	}

      if ((windowpos->flags & SWP_HIDEWINDOW) &&
	  !GDK_SURFACE_DESTROYED (window))
	{
	  /* Make transient parent the foreground window when window unmaps */
	  impl = GDK_WIN32_SURFACE (window);

	  if (impl->transient_owner &&
	      GetForegroundWindow () == GDK_SURFACE_HWND (window))
	    SetForegroundWindow (GDK_SURFACE_HWND (impl->transient_owner));
	}

      if (!(windowpos->flags & SWP_NOCLIENTSIZE))
	{
	  if (window->resize_count > 1)
	    window->resize_count -= 1;
	}

      /* Call modal timer immediate so that we repaint faster after a resize. */
      if (_modal_operation_in_progress & GDK_WIN32_MODAL_OP_SIZEMOVE_MASK)
	modal_timer_proc (0,0,0,0);

      /* Claim as handled, so that WM_SIZE and WM_MOVE are avoided */
      return_val = TRUE;
      *ret_valp = 0;
      break;

    case WM_SIZING:
      GetWindowRect (GDK_SURFACE_HWND (window), &rect);
      GDK_NOTE (EVENTS, g_print (" %s curr:%s drag:%s",
				 (msg->wParam == WMSZ_BOTTOM ? "BOTTOM" :
				  (msg->wParam == WMSZ_BOTTOMLEFT ? "BOTTOMLEFT" :
				   (msg->wParam == WMSZ_LEFT ? "LEFT" :
				    (msg->wParam == WMSZ_TOPLEFT ? "TOPLEFT" :
				     (msg->wParam == WMSZ_TOP ? "TOP" :
				      (msg->wParam == WMSZ_TOPRIGHT ? "TOPRIGHT" :
				       (msg->wParam == WMSZ_RIGHT ? "RIGHT" :

					(msg->wParam == WMSZ_BOTTOMRIGHT ? "BOTTOMRIGHT" :
					 "???")))))))),
				 _gdk_win32_rect_to_string (&rect),
				 _gdk_win32_rect_to_string ((RECT *) msg->lParam)));

      impl = GDK_WIN32_SURFACE (window);

      break;

    case WM_GETMINMAXINFO:
      mmi = (MINMAXINFO*) msg->lParam;

      GDK_NOTE (EVENTS, g_print (" (mintrack:%ldx%ld maxtrack:%ldx%ld "
				 "maxpos:%+ld%+ld maxsize:%ldx%ld)",
				 mmi->ptMinTrackSize.x, mmi->ptMinTrackSize.y,
				 mmi->ptMaxTrackSize.x, mmi->ptMaxTrackSize.y,
				 mmi->ptMaxPosition.x, mmi->ptMaxPosition.y,
				 mmi->ptMaxSize.x, mmi->ptMaxSize.y));

      if (_gdk_win32_surface_fill_min_max_info (window, mmi))
        {
          /* Don't call DefWindowProcW() */
          GDK_NOTE (EVENTS,
                    g_print (" (handled, mintrack:%ldx%ld maxtrack:%ldx%ld "
                             "maxpos:%+ld%+ld maxsize:%ldx%ld)",
                             mmi->ptMinTrackSize.x, mmi->ptMinTrackSize.y,
                             mmi->ptMaxTrackSize.x, mmi->ptMaxTrackSize.y,
                             mmi->ptMaxPosition.x, mmi->ptMaxPosition.y,
                             mmi->ptMaxSize.x, mmi->ptMaxSize.y));

          return_val = TRUE;
        }

      break;

    case WM_CLOSE:
      if (GDK_SURFACE_DESTROYED (window))
	break;

      event = gdk_delete_event_new (window);

      _gdk_win32_append_event (event);

      impl = GDK_WIN32_SURFACE (window);

      if (impl->transient_owner && GetForegroundWindow() == GDK_SURFACE_HWND (window))
	{
	  SetForegroundWindow (GDK_SURFACE_HWND (impl->transient_owner));
	}

      return_val = TRUE;
      break;

    case WM_DPICHANGED:
      handle_dpi_changed (window, msg);
      return_val = FALSE;
      *ret_valp = 0;
      break;

    case WM_NCDESTROY:
      if ((pointer_grab != NULL && pointer_grab->surface == window) ||
          (keyboard_grab && keyboard_grab->surface == window))
      {
        GdkDevice *device = gdk_seat_get_pointer (gdk_display_get_default_seat (display));
        gdk_device_ungrab (device, msg -> time);
      }

      if ((window != NULL) && (msg->hwnd != GetDesktopWindow ()))
	gdk_surface_destroy_notify (window);

      if (window == NULL || GDK_SURFACE_DESTROYED (window))
	break;

      event = gdk_delete_event_new (window);

      _gdk_win32_append_event (event);

      return_val = TRUE;
      break;

    case WM_DWMCOMPOSITIONCHANGED:
      gdk_win32_display_check_composited (GDK_WIN32_DISPLAY (display));
      _gdk_win32_surface_enable_transparency (window);
      break;

    case WM_ACTIVATE:
      GDK_NOTE (EVENTS, g_print (" %s%s %p",
				 (LOWORD (msg->wParam) == WA_ACTIVE ? "ACTIVE" :
				  (LOWORD (msg->wParam) == WA_CLICKACTIVE ? "CLICKACTIVE" :
				   (LOWORD (msg->wParam) == WA_INACTIVE ? "INACTIVE" : "???"))),
				 HIWORD (msg->wParam) ? " minimized" : "",
				 (HWND) msg->lParam));
      if (GDK_IS_POPUP (window) || GDK_IS_DRAG_SURFACE (window))
        {
          /* Popups cannot be activated or de-activated - 
           * they only support keyboard focus, which GTK
           * will handle for us.
           */
          *ret_valp = 0;
          return_val = TRUE;
          break;
        }
      /* We handle mouse clicks for modally-blocked windows under WM_MOUSEACTIVATE,
       * but we still need to deal with alt-tab, or with SetActiveWindow() type
       * situations.
       */
      if (_gdk_modal_blocked (window) && LOWORD (msg->wParam) == WA_ACTIVE)
	{
	  GdkSurface *modal_current = _gdk_modal_current ();
	  SetActiveWindow (GDK_SURFACE_HWND (modal_current));
	  *ret_valp = 0;
	  return_val = TRUE;
	  break;
	}

      if (LOWORD (msg->wParam) == WA_INACTIVE)
        {
          if (msg->lParam != 0)
            {
               GdkSurface *other_surface = gdk_win32_handle_table_lookup ((HWND) msg->lParam);
               if (other_surface != NULL &&
                   (GDK_IS_POPUP (other_surface) || GDK_IS_DRAG_SURFACE (other_surface)))
                {
                  /* We're being deactivated in favour of some popup or temp window.
                   * Since only toplevels can have visual focus, pretend that
                   * nothing happened.
                   */
                  *ret_valp = 0;
                  return_val = TRUE;
                  break;
                }
            }

          gdk_synthesize_surface_state (window, GDK_TOPLEVEL_STATE_FOCUSED, 0);
        }
      else
        {
          gdk_synthesize_surface_state (window, 0, GDK_TOPLEVEL_STATE_FOCUSED);

          /* Bring any tablet contexts to the top of the overlap order when
           * one of our windows is activated.
           * NOTE: It doesn't seem to work well if it is done in WM_ACTIVATEAPP
           * instead
           */
          _gdk_input_set_tablet_active ();
        }

      break;

    case WM_ACTIVATEAPP:
      GDK_NOTE (EVENTS, g_print (" %s thread: %" G_GINT64_FORMAT,
				 msg->wParam ? "YES" : "NO",
				 (gint64) msg->lParam));
      break;
    case WM_NCHITTEST:
      /* TODO: pass all messages to DwmDefWindowProc() first! */
      return_val = handle_nchittest (msg->hwnd, window,
                                     GET_X_LPARAM (msg->lParam),
                                     GET_Y_LPARAM (msg->lParam), ret_valp);
      break;

      /* Handle WINTAB events here, as we know that the device manager will
       * use the fixed WT_DEFBASE as lcMsgBase, and we thus can use the
       * constants as case labels.
       */
    case WT_PACKET:
      GDK_NOTE (EVENTS, g_print (" %d %p",
				 (int) msg->wParam, (gpointer) msg->lParam));
      goto wintab;

    case WT_CSRCHANGE:
      GDK_NOTE (EVENTS, g_print (" %d %p",
				 (int) msg->wParam, (gpointer) msg->lParam));
      goto wintab;

    case WT_PROXIMITY:
      GDK_NOTE (EVENTS, g_print (" %p %d %d",
				 (gpointer) msg->wParam,
				 LOWORD (msg->lParam),
				 HIWORD (msg->lParam)));
      /* Fall through */
    wintab:

      event = gdk_input_other_event (display, msg, window);
      if (event)
        {
          _gdk_win32_append_event (event);
	  gdk_event_unref (event);
        }

      break;
    }

done:

  if (window)
    g_object_unref (window);

#undef return
  return return_val;
}

void
_gdk_win32_display_queue_events (GdkDisplay *display)
{
  MSG msg;

  if (modal_win32_dialog != NULL)
    return;

  while (PeekMessageW (&msg, NULL, 0, 0, PM_REMOVE))
    {
      TranslateMessage (&msg);
      DispatchMessageW (&msg);
    }
}

static gboolean
gdk_event_prepare (GSource *source,
		   int     *timeout)
{
  GdkWin32EventSource *event_source = (GdkWin32EventSource *)source;
  gboolean retval;

  *timeout = -1;

  if (event_source->display->event_pause_count > 0)
    retval =_gdk_event_queue_find_first (event_source->display) != NULL;
  else
    retval = (_gdk_event_queue_find_first (event_source->display) != NULL ||
              (modal_win32_dialog == NULL &&
               GetQueueStatus (QS_ALLINPUT) != 0));

  return retval;
}

static gboolean
gdk_event_check (GSource *source)
{
  GdkWin32EventSource *event_source = (GdkWin32EventSource *)source;
  gboolean retval;

  if (event_source->display->event_pause_count > 0)
    retval = _gdk_event_queue_find_first (event_source->display) != NULL;
  else if (event_source->event_poll_fd.revents & G_IO_IN)
    retval = (_gdk_event_queue_find_first (event_source->display) != NULL ||
              (modal_win32_dialog == NULL &&
               GetQueueStatus (QS_ALLINPUT) != 0));
  else
    retval = FALSE;

  return retval;
}

static gboolean
gdk_event_dispatch (GSource     *source,
                    GSourceFunc  callback,
                    gpointer     user_data)
{
  GdkWin32EventSource *event_source = (GdkWin32EventSource *)source;
  GdkEvent *event;

  _gdk_win32_display_queue_events (event_source->display);
  event = _gdk_event_unqueue (event_source->display);

  if (event)
    {
      _gdk_event_emit (event);

      gdk_event_unref (event);
    }

  return TRUE;
}

void
gdk_win32_set_modal_dialog_libgtk_only (HWND window)
{
  modal_win32_dialog = window;
}