summaryrefslogtreecommitdiff
path: root/gdk/win32/gdkclipdrop-win32.c
blob: 5c1d361a3609e1295e4e202333adfa132be3da65 (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
/* GDK - The GIMP Drawing Kit
 * Copyright (C) 1995-1997 Peter Mattis, Spencer Kimball and Josh MacDonald
 * Copyright (C) 1998-2002 Tor Lillqvist
 *
 * 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/.
 */

/*
GTK has two clipboards - normal clipboard and primary clipboard
Primary clipboard is only handled
internally by GTK (it's not portable to Windows).

("C:" means clipboard client (requestor), "S:" means clipboard server (provider))
("transmute" here means "change the format of some data"; this term is used here
 instead of "convert" to avoid clashing with the old g(t|d)k_selection_convert() APIs,
 which are completely unrelated)

For Clipboard:
GTK calls one of the gdk_clipboard_set* () functions (either supplying
its own content provider, or giving a GTyped data for which GDK will
create a content provider automatically).
That function associates the content provider with the clipboard and calls
S: gdk_clipboard_claim(),
to claim ownership. GDK first calls the backend implementation of
that function, then the
S: gdk_clipboard_real_claim()
implementation.
The "real" function does some mundane bookkeeping, whereas the backend
implementation advertises the formats supported by the clipboard,
if the call says that the claim is local. Non-local (remote) claims
are there just to tell GDK that some other process owns the clipboard
and claims to provide data in particular formats.
No data is sent anywhere.

The content provider has a callback, which will be invoked every time
the data from this provider is needed.

GTK might also call gdk_clipboard_store_async(), which instructs
the backend to put the data into the OS clipboard manager (if
supported and available) so that it remains available for other
processes after the clipboard owner terminates.

When something needs to be obtained from clipboard, GTK calls
C: gdk_clipboard_read_async () -> gdk_clipboard_read_internal (),
providing it with a string-array of mime/types, which is internally
converted into a GdkContentFormats object.
That function creates a task.

Then, if the clipboard is local, it calls
C: gdk_clipboard_read_local_async(),
which matches given formats to the content provider formats and, if there's a match,
creates a pipe, calls
C: gdk_clipboard_write_async()
on the write end, and sets the read end as a return value of the task, which will
later be given to the caller-specified callback.

If the clipboard isn't local, it calls
C: read_async()
of the backend clipboard stream class.
The backend starts creating a stream (somehow) and sets up the callback to return that
stream via the task, once the stream is created.
Either way, the caller-specified callback is invoked, and it gets the read end
of a stream by calling
C: gdk_clipboard_read_finish(),
then reads the data from the stream and unrefs the stream once it is done.
IRL applications use wrappers, which create an extra task that gets the
stream, reads from it asynchronously and turns the bytes that it reads into
some kind of application-specific object type. GDK comes pre-equipped with
functions that read arbitrary GTypes (as long as they are serializable),
texts (strings) or textures (GdkPixbufs) this way.

On Windows:
Clipboard is opened by OpenClipboard(), emptied by EmptyClipboard() (which also
makes the window the clipboard owner), data is put into it by SetClipboardData().
Clipboard is closed with CloseClipboard().
If SetClipboardData() is given a NULL data value, the owner will later
receive WM_RENDERFORMAT message, in response to which it must call
SetClipboardData() with the provided handle and the actual data this time.
This way applications can avoid storing everything in the clipboard
all the time, only putting the data there as it is requested by other applications.
At some undefined points of time an application might get WM_RENDERALLFORMATS
message, it should respond by opening the clipboard and rendering
into it all the data that it offers, as if responding to multiple WM_RENDERFORMAT
messages.

On GDK-Win32:

Any operations that require OpenClipboard()/CloseClipboard() combo (i.e.
almost everything, except for WM_RENDERFORMAT handling) is offloaded into
separate thread, which tries to complete any operations in the queue.
Each operation routine usually starts with a timeout check (all operations
time out after 30 seconds), then a check for clipboard status (to abort
any operations that became obsolete due to clipboard status being changed - 
i.e. retrieving clipboard contents is aborted if clipboard contents change
before the operation can be completed), then an attempt to OpenClipboard().
Failure to OpenClipboard() leads to the queue processing stopping, and
resuming from the beginning after another 1-second delay.
A success in OpenClipboard() allows the operation to continue.
The thread remembers the fact that it has clipboard open, and does
not try to close & reopen it, unless that is strictly necessary.
The clipboard is closed after each queue processing run.

GTK calls one of the gdk_clipboard_set* () functions (either supplying
its own content provider, or giving a GTyped data for which GDK will
create a content provider automatically).
That function associates the content provider with the clipboard and calls
S: gdk_clipboard_claim(),
to claim ownership. GDK first calls the backend implementation of
that function,
S: gdk_win32_clipboard_claim(),
which maps the supported GDK contentformats to W32 data formats and
caches this mapping, then the
S: gdk_clipboard_real_claim()
implementation.
The "real" function does some mundane bookkeeping, whereas the backend
implementation advertises the formats supported by the clipboard,
if the call says that the claim is local. Non-local (remote) claims
are there just to tell GDK that some other process owns the clipboard
and claims to provide data in particular formats.
For the local claims gdk_win32_clipboard_claim() queues a clipboard
advertise operation (see above).
That operation will call EmptyClipboard() to claim the ownership,
then call SetClipboardData() with NULL value for each W32 data format
supported, advertising the W32 data formats to other processes.
No data is sent anywhere.

The content provider has a callback, which will be invoked every time
the data from this provider is needed.

GTK might also call gdk_clipboard_store_async(), which instructs
the W32 backend to put the data into the OS clipboard manager by
sending WM_RENDERALLFORMATS to itself and then handling it normally.

Every time W32 backend gets WM_DRAWCLIPBOARD or WM_CLIPBOARDUPDATE,
it calls GetUpdatedClipboardFormats() and GetClipboardSequenceNumber()
and caches the results of both. These calls do not require the clipboard
to be opened.
After that it would call
C: gdk_win32_clipboard_claim_remote()
to indicate that some other process owns the clipboard and supports
the formats from the cached list. If the process is the owner,
the remote claim is not performed (it's assumed that a local claim
was already made when a clipboard content provider is set, so no need
to do that either).
Note: clipboard sequence number changes with each SetClipboardData() call.
Specifically, a process that uses delayed rendering (like GDK does)
must call SetClipboardData() with NULL value every time the data changes,
even if its format remains the same.
The cached remote formats are then mapped into GDK contentformats.
This map is separate from the one that maps supported GDK contentformats
to W32 formats for locally-claimed clipboards.

When something needs to be obtained from clipboard, GTK calls
C: gdk_clipboard_read_async () -> gdk_clipboard_read_internal (),
providing it with a string-array of mime/types, which is internally
converted into a GdkContentFormats object.
That function creates a task.

Then, if the clipboard is local, it calls
C: gdk_clipboard_read_local_async(),
which matches given formats to the content provider formats and, if there's a match,
creates a pipe, calls
C: gdk_clipboard_write_async()
on the write end, and sets the read end as a return value of the task, which will
later be given to the caller-specified callback.

If the clipboard isn't local, it calls
C: read_async()
of the W32 backend clipboard stream class.
It then queues a retrieve operation (see above).
The retrieve operation goes over formats available on the clipboard,
and picks the first one that matches the list supplied with the retrieve
operation (that is, it gives priority to formats at the top of the clipboard
format list, even if such formats are at the bottom of the list of formats
supported by the application; this is due to the fact that formats at the
top of the clipboard format list are usually "raw" or "native" and assumed
to not to be transmuted by the clipboard owner from some other format,
and thus it is better to use these, if the requesting application can handle
them). It then calls GetClipboardData(), which either causes
a WM_RENDERFORMAT to be sent to the server (for delayed rendering),
or it just grabs the data from the OS.

Server-side GDK catches WM_RENDERFORMAT, figures out a contentformat
to request (it has an earlier advertisement cached in the thread, so
there's no need to ask the main thread for anything), and
creates a render request, then sends it to the main thread.
After that it keeps polling the queue until the request comes back.
The main thread render handler creates an output stream that
writes the data into a global memory buffer, then calls
S: gdk_clipboard_write_async()
to write the data.
The callback finishes that up with
S: gdk_clipboard_write_finish(),
which sends the render request back to the clipborad thread,
along with the data. The clipboard thread then calls
S: SetClipboardData()
with the clipboard handle provided by the OS on behalf of the client.

Once the data handle is available, the clipboard thread creates a stream
that reads from a copy of that data (after transmutation, if necessary),
and sends that stream back to the main thread. The data is kept in a client-side
memory buffer (owned by the stream), the HGLOBAL given by the OS is not held
around for this to happen.
The stream is then returned through the task to the caller.

Either way, the caller-specified callback is invoked, and it gets the read end
of a stream by calling
C: gdk_clipboard_read_finish(),
then reads the data from the stream and unrefs the stream once it is done.
The local buffer that backed the stream is freed with the stream.
IRL applications use wrappers, which create an extra task that gets the
stream, reads from it asynchronously and turns the bytes that it reads into
some kind of application-specific object type. GDK comes pre-equipped with
functions that read arbitrary GTypes (as long as they are serializable),
texts (strings) or textures (GdkPixbufs) this way.

If data must be stored on the clipboard, because the application is quitting,
GTK will call
S: gdk_clipboard_store_async()
on all the clipboards it owns. This creates multiple write stream (one for each
format being stored), each backed by a HGLOBAL memory object. Once all memory
objects are written, the backend queues a store operation, passing along
all these HGLOBAL objects. The clipboard thread processes that by sending
WM_RENDERALLFORMATS to the window, then signals the task that it's done.

When clipboard owner changes, the old owner receives WM_DESTROYCLIPBOARD message,
the clipboard thread schedules a call to gdk_clipboard_claim_remote()
in the main thread, with an empty list of formats,
to indicate that the clipboard is now owned by a remote process.
Later the OS will send WM_DRAWCLIPBOARD or WM_CLIPBOARDUPDATE to indicate
the new clipboard contents (see above).

DND:
GDK-Win32:
DnD server runs in a separate thread, and schedules calls to be
made in the main thread in response to the DnD thread being invoked
by the OS (using OLE2 mechanism).
The DnD thread normally just idles, until the main thread tells it
to call DoDragDrop(), at which point it enters the DoDragDrop() call
(which means that its OLE2 DnD callbacks get invoked repeatedly by the OS
 in response to user actions), and doesn't leave it until the DnD
operation is finished.

Otherwise it's similar to how the clipboard works. Only the DnD server
(drag source) works in a thread. DnD client (drop target) works normally.
*/

#include "config.h"
#include <string.h>
#include <stdlib.h>

/* For C-style COM wrapper macros */
#define COBJMACROS

/* for CIDA */
#include <shlobj.h>

#include "gdkdisplay.h"
#include "gdkprivate-win32.h"
#include "gdkclipboardprivate.h"
#include "gdkclipboard-win32.h"
#include "gdkclipdrop-win32.h"
#include "gdkhdataoutputstream-win32.h"
#include "gdk/gdkdragprivate.h"
#include "gdkwin32dnd.h"
#include "gdkwin32dnd-private.h"
#include "gdkwin32.h"
#include "gdkintl.h"

#define HIDA_GetPIDLFolder(pida) (LPCITEMIDLIST)(((LPBYTE)pida)+(pida)->aoffset[0])
#define HIDA_GetPIDLItem(pida, i) (LPCITEMIDLIST)(((LPBYTE)pida)+(pida)->aoffset[i+1])

#define CLIPBOARD_OPERATION_TIMEOUT (G_USEC_PER_SEC * 30)

/* GetClipboardData() times out after 30 seconds.
 * Try to reply (even if it's a no-action reply due to a timeout)
 * before that happens.
 */
#define CLIPBOARD_RENDER_TIMEOUT (G_USEC_PER_SEC * 29)

gboolean _gdk_win32_transmute_windows_data (UINT          from_w32format,
                                            const char   *to_contentformat,
                                            HANDLE        hdata,
                                            guchar      **set_data,
                                            gsize        *set_data_length);

/* Just to avoid calling RegisterWindowMessage() every time */
static UINT thread_wakeup_message;

typedef enum _GdkWin32ClipboardThreadQueueItemType GdkWin32ClipboardThreadQueueItemType;

enum _GdkWin32ClipboardThreadQueueItemType
{
  GDK_WIN32_CLIPBOARD_THREAD_QUEUE_ITEM_ADVERTISE = 1,
  GDK_WIN32_CLIPBOARD_THREAD_QUEUE_ITEM_RETRIEVE = 2,
  GDK_WIN32_CLIPBOARD_THREAD_QUEUE_ITEM_STORE = 3,
};

typedef struct _GdkWin32ClipboardThreadQueueItem GdkWin32ClipboardThreadQueueItem;

struct _GdkWin32ClipboardThreadQueueItem
{
  GdkWin32ClipboardThreadQueueItemType  item_type;
  gint64                                start_time;
  gint64                                end_time;
  gpointer                              opaque_task;
};

typedef struct _GdkWin32ClipboardThreadAdvertise GdkWin32ClipboardThreadAdvertise;

struct _GdkWin32ClipboardThreadAdvertise
{
  GdkWin32ClipboardThreadQueueItem  parent;
  GArray                      *pairs; /* of GdkWin32ContentFormatPair */
  gboolean                     unset;
};

typedef struct _GdkWin32ClipboardThreadRetrieve GdkWin32ClipboardThreadRetrieve;

struct _GdkWin32ClipboardThreadRetrieve
{
  GdkWin32ClipboardThreadQueueItem  parent;
  GArray                      *pairs; /* of GdkWin32ContentFormatPair */
  gint64                       sequence_number;
};

typedef struct _GdkWin32ClipboardStorePrepElement GdkWin32ClipboardStorePrepElement;

struct _GdkWin32ClipboardStorePrepElement
{
  UINT           w32format;
  const char    *contentformat;
  HANDLE         handle;
  GOutputStream *stream;
};

typedef struct _GdkWin32ClipboardStorePrep GdkWin32ClipboardStorePrep;

struct _GdkWin32ClipboardStorePrep
{
  GTask             *store_task;
  GArray            *elements; /* of GdkWin32ClipboardStorePrepElement */
};

typedef struct _GdkWin32ClipboardThreadStore GdkWin32ClipboardThreadStore;

struct _GdkWin32ClipboardThreadStore
{
  GdkWin32ClipboardThreadQueueItem  parent;
  GArray                      *elements; /* of GdkWin32ClipboardStorePrepElement */
};

typedef struct _GdkWin32ClipboardThreadRender GdkWin32ClipboardThreadRender;

struct _GdkWin32ClipboardThreadRender
{
  /* The handle that the main thread prepares for us.
   * We just give it to SetClipboardData ().
   * NULL means that the rendering failed.
   */
  HANDLE                                main_thread_data_handle;

  /* The format that is being requested of us */
  GdkWin32ContentFormatPair             pair;
};

typedef struct _GdkWin32ClipboardThread GdkWin32ClipboardThread;

struct _GdkWin32ClipboardThread
{
  /* A hidden window that owns our clipboard
   * and receives clipboard-related messages.
   */
  HWND         clipboard_window;

  /* We receive instructions from the main thread in this queue */
  GAsyncQueue *input_queue;

  /* Last observer owner of the clipboard, as reported by the OS.
   * This is compared to GetClipboardOwner() return value to see
   * whether the owner changed.
   */
  HWND         stored_hwnd_owner;

  /* The last time we saw an owner change event.
   * Any requests made before this time are invalid and
   * fail automatically.
   */
  gint64       owner_change_time;

  /* The handle that was given to OpenClipboard().
   * NULL is a valid handle,
   * INVALID_HANDLE_VALUE means that the clipboard is closed.
   */
  HWND         clipboard_opened_for;

  HWND         hwnd_next_viewer;

  /* We can't peek the queue or "unpop" queue items,
   * so the items that we can't act upon (yet) got
   * to be stored *somewhere*.
   */
  GList       *dequeued_items;

  /* Wakeup timer id (1 if timer is set, 0 otherwise) */
  UINT         wakeup_timer;

  /* The formats that the main thread claims to provide */
  GArray      *cached_advertisement; /* of GdkWin32ContentFormatPair */

  /* We receive rendered clipboard data in this queue.
   * Contains GdkWin32ClipboardThreadRender structs.
   */
  GAsyncQueue *render_queue; 

  /* Set to TRUE when we're calling EmptyClipboard () */
  gboolean     ignore_destroy_clipboard;
};

/* The code is much more secure if we don't rely on the OS to keep
 * this around for us.
 */
static GdkWin32ClipboardThread *clipboard_thread_data = NULL;

typedef struct _GdkWin32ClipboardThreadResponse GdkWin32ClipboardThreadResponse;

struct _GdkWin32ClipboardThreadResponse
{
  GdkWin32ClipboardThreadQueueItemType  item_type;
  GError                               *error;
  gpointer                              opaque_task;
  GInputStream                         *input_stream;
};

gboolean
_gdk_win32_format_uses_hdata (UINT w32format)
{
  switch (w32format)
    {
    case CF_DIB:
    case CF_DIBV5:
    case CF_DIF:
    case CF_DSPBITMAP:
    case CF_DSPENHMETAFILE:
    case CF_DSPMETAFILEPICT:
    case CF_DSPTEXT:
    case CF_OEMTEXT:
    case CF_RIFF:
    case CF_SYLK:
    case CF_TEXT:
    case CF_TIFF:
    case CF_UNICODETEXT:
    case CF_WAVE:
      return TRUE;
    default:
      if (w32format >= 0xC000)
        return TRUE;
      else
        return FALSE;
    }
}


/* This function is called in the main thread */
static gboolean
clipboard_window_created (gpointer user_data)
{
  GdkWin32Clipdrop *clipdrop = _gdk_win32_clipdrop_get ();

  clipdrop->clipboard_window = (HWND) user_data;

  return G_SOURCE_REMOVE;
}

/* This function is called in the main thread */
static gboolean
clipboard_owner_changed (gpointer user_data)
{
  GdkDisplay *display = gdk_display_get_default ();
  GdkClipboard *clipboard = gdk_display_get_clipboard (display);
  gdk_win32_clipboard_claim_remote (GDK_WIN32_CLIPBOARD (clipboard));

  return G_SOURCE_REMOVE;
}

typedef struct _GdkWin32ClipboardRenderAndStream GdkWin32ClipboardRenderAndStream;

struct _GdkWin32ClipboardRenderAndStream
{
  GdkWin32ClipboardThreadRender *render;
  GdkWin32HDataOutputStream *stream;
};

static void
clipboard_render_hdata_ready (GObject      *clipboard,
                              GAsyncResult *result,
                              gpointer      user_data)
{
  GError *error = NULL;
  GdkWin32ClipboardRenderAndStream render_and_stream = *(GdkWin32ClipboardRenderAndStream *) user_data;
  GdkWin32Clipdrop *clipdrop = _gdk_win32_clipdrop_get ();

  g_free (user_data);

  if (!gdk_clipboard_write_finish (GDK_CLIPBOARD (clipboard), result, &error))
    {
      HANDLE handle;
      gboolean is_hdata;
      GDK_NOTE(CLIPBOARD, g_printerr ("%p: failed to write HData-backed stream: %s\n", clipboard, error->message));
      g_error_free (error);
      g_output_stream_close (G_OUTPUT_STREAM (render_and_stream.stream), NULL, NULL);
      handle = gdk_win32_hdata_output_stream_get_handle (render_and_stream.stream, &is_hdata);

      if (is_hdata)
        API_CALL (GlobalFree, (handle));
      else
        API_CALL (CloseHandle, (handle));

      render_and_stream.render->main_thread_data_handle = NULL;
    }
  else
    {
      g_output_stream_close (G_OUTPUT_STREAM (render_and_stream.stream), NULL, NULL);
      render_and_stream.render->main_thread_data_handle = gdk_win32_hdata_output_stream_get_handle (render_and_stream.stream, NULL);
    }

  g_async_queue_push (clipdrop->clipboard_render_queue, render_and_stream.render);
  g_object_unref (render_and_stream.stream);
}

/* This function is called in the main thread */
static gboolean
clipboard_render (gpointer user_data)
{
  GdkWin32ClipboardThreadRender *render = (GdkWin32ClipboardThreadRender *) user_data;
  GdkWin32Clipdrop *clipdrop = _gdk_win32_clipdrop_get ();
  GdkDisplay *display = gdk_display_get_default ();
  GdkClipboard *clipboard = gdk_display_get_clipboard (display);
  GError *error = NULL;
  GOutputStream *stream = gdk_win32_hdata_output_stream_new (&render->pair, &error);
  GdkWin32ClipboardRenderAndStream *render_and_stream;

  if (stream == NULL)
    {
      GDK_NOTE (SELECTION, g_printerr ("%p: failed create a HData-backed stream: %s\n", clipboard, error->message));
      g_error_free (error);
      render->main_thread_data_handle = NULL;
      g_async_queue_push (clipdrop->clipboard_render_queue, render);

      return G_SOURCE_REMOVE;
    }

  render_and_stream = g_new0 (GdkWin32ClipboardRenderAndStream, 1);
  render_and_stream->render = render;
  render_and_stream->stream = GDK_WIN32_HDATA_OUTPUT_STREAM (stream);

  gdk_clipboard_write_async (GDK_CLIPBOARD (clipboard),
                             render->pair.contentformat,
                             stream,
                             G_PRIORITY_DEFAULT,
                             NULL,
                             clipboard_render_hdata_ready,
                             render_and_stream);

  /* Keep our reference to the stream, don't unref it */

  return G_SOURCE_REMOVE;
}

/* This function is called in the main thread */
static gboolean
clipboard_thread_response (gpointer user_data)
{
  GdkWin32ClipboardThreadResponse *response = (GdkWin32ClipboardThreadResponse *) user_data;
  GTask *task = (GTask *) response->opaque_task;

  if (task != NULL)
    {
      if (response->error)
        g_task_return_error (task, response->error);
      else if (response->input_stream)
        g_task_return_pointer (task, response->input_stream, g_object_unref);
      else
        g_task_return_boolean (task, TRUE);

      g_object_unref (task);
    }

  g_free (response);

  return G_SOURCE_REMOVE;
}

static void
free_prep_element (GdkWin32ClipboardStorePrepElement *el)
{
  if (el->handle)
    {
      if (_gdk_win32_format_uses_hdata (el->w32format))
        GlobalFree (el->handle);
      else
        CloseHandle (el->handle);
    }

  if (el->stream)
    g_object_unref (el->stream);
}

static void
free_queue_item (GdkWin32ClipboardThreadQueueItem *item)
{
  GdkWin32ClipboardThreadAdvertise *adv;
  GdkWin32ClipboardThreadRetrieve *retr;
  GdkWin32ClipboardThreadStore    *store;
  int i;

  switch (item->item_type)
    {
    case GDK_WIN32_CLIPBOARD_THREAD_QUEUE_ITEM_ADVERTISE:
      adv = (GdkWin32ClipboardThreadAdvertise *) item;
      if (adv->pairs)
        g_array_free (adv->pairs, TRUE);
      break;
    case GDK_WIN32_CLIPBOARD_THREAD_QUEUE_ITEM_RETRIEVE:
      retr = (GdkWin32ClipboardThreadRetrieve *) item;
      if (retr->pairs)
        g_array_free (retr->pairs, TRUE);
      break;
    case GDK_WIN32_CLIPBOARD_THREAD_QUEUE_ITEM_STORE:
      store = (GdkWin32ClipboardThreadStore *) item;
      for (i = 0; i < store->elements->len; i++)
        {
          GdkWin32ClipboardStorePrepElement *el = &g_array_index (store->elements, GdkWin32ClipboardStorePrepElement, i);
          free_prep_element (el);
        }
      g_array_free (store->elements, TRUE);
      break;
    }

  g_free (item);
}

static void
send_response (GdkWin32ClipboardThreadQueueItemType  request_type,
               gpointer                              opaque_task,
               GError                               *error)
{
  GdkWin32ClipboardThreadResponse *response = g_new0 (GdkWin32ClipboardThreadResponse, 1);
  response->error = error;
  response->opaque_task = opaque_task;
  response->item_type = request_type;
  g_idle_add_full (G_PRIORITY_DEFAULT, clipboard_thread_response, response, NULL);
}

static void
send_input_stream (GdkWin32ClipboardThreadQueueItemType  request_type,
                   gpointer                              opaque_task,
                   GInputStream                         *stream)
{
  GdkWin32ClipboardThreadResponse *response = g_new0 (GdkWin32ClipboardThreadResponse, 1);
  response->input_stream = stream;
  response->opaque_task = opaque_task;
  response->item_type = request_type;
  g_idle_add_full (G_PRIORITY_DEFAULT, clipboard_thread_response, response, NULL);
}

static DWORD
try_open_clipboard (HWND hwnd)
{
  if (clipboard_thread_data->clipboard_opened_for == hwnd)
    return NO_ERROR;

  if (clipboard_thread_data->clipboard_opened_for != INVALID_HANDLE_VALUE)
    {
      API_CALL (CloseClipboard, ());
      clipboard_thread_data->clipboard_opened_for = INVALID_HANDLE_VALUE;
    }

  if (!OpenClipboard (hwnd))
    return GetLastError ();

  clipboard_thread_data->clipboard_opened_for = hwnd;

  return NO_ERROR;
}

static gboolean
process_advertise (GdkWin32ClipboardThreadAdvertise *adv)
{
  DWORD error_code;
  int i;

  if (g_get_monotonic_time () > adv->parent.end_time)
    {
      GDK_NOTE (CLIPBOARD, g_printerr ("An advertise task timed out\n"));
      send_response (adv->parent.item_type,
                     adv->parent.opaque_task,
                     g_error_new (G_IO_ERROR, G_IO_ERROR_FAILED,
                                  _("Cannot claim clipboard ownership. OpenClipboard() timed out.")));
      return FALSE;
    }

  if (clipboard_thread_data->owner_change_time > adv->parent.start_time)
    {
      GDK_NOTE (CLIPBOARD, g_printerr ("An advertise task timed out due to ownership change\n"));
      send_response (adv->parent.item_type,
                     adv->parent.opaque_task,
                     g_error_new (G_IO_ERROR, G_IO_ERROR_FAILED,
                                  _("Cannot claim clipboard ownership. Another process claimed it before us.")));
      return FALSE;
    }

  error_code = try_open_clipboard (adv->unset ? NULL : clipboard_thread_data->clipboard_window);

  if (error_code == ERROR_ACCESS_DENIED)
    return TRUE;

  if (G_UNLIKELY (error_code != NO_ERROR))
    {
      send_response (adv->parent.item_type,
                     adv->parent.opaque_task,
                     g_error_new (G_IO_ERROR, G_IO_ERROR_FAILED,
                                  _("Cannot claim clipboard ownership. OpenClipboard() failed: 0x%lx."), error_code));
      return FALSE;
    }

  clipboard_thread_data->ignore_destroy_clipboard = TRUE;
  if (!EmptyClipboard ())
    {
      clipboard_thread_data->ignore_destroy_clipboard = FALSE;
      error_code = GetLastError ();
      send_response (adv->parent.item_type,
                     adv->parent.opaque_task,
                     g_error_new (G_IO_ERROR, G_IO_ERROR_FAILED,
                                  _("Cannot claim clipboard ownership. EmptyClipboard() failed: 0x%lx."), error_code));
      return FALSE;
    }

  clipboard_thread_data->ignore_destroy_clipboard = FALSE;

  if (adv->unset)
    return FALSE;

  for (i = 0; i < adv->pairs->len; i++)
    {
      GdkWin32ContentFormatPair *pair = &g_array_index (adv->pairs, GdkWin32ContentFormatPair, i);

      SetClipboardData (pair->w32format, NULL);
    }

  if (clipboard_thread_data->cached_advertisement)
    g_array_free (clipboard_thread_data->cached_advertisement, TRUE);

  clipboard_thread_data->cached_advertisement = adv->pairs;

  /* To enure that we don't free it later on */
  adv->pairs = NULL;

  send_response (adv->parent.item_type,
                 adv->parent.opaque_task,
                 NULL);

  return FALSE;
}

static gboolean
process_store (GdkWin32ClipboardThreadStore *store)
{
  DWORD error_code;
  int i;

  if (g_get_monotonic_time () > store->parent.end_time)
    {
      GDK_NOTE (CLIPBOARD, g_printerr ("A store task timed out\n"));
      send_response (store->parent.item_type,
                     store->parent.opaque_task,
                     g_error_new (G_IO_ERROR, G_IO_ERROR_FAILED,
                                  _("Cannot set clipboard data. OpenClipboard() timed out.")));
      return FALSE;
    }

  if (clipboard_thread_data->owner_change_time > store->parent.start_time)
    {
      GDK_NOTE (CLIPBOARD, g_printerr ("A store task timed out due to ownership change\n"));
      send_response (store->parent.item_type,
                     store->parent.opaque_task,
                     g_error_new (G_IO_ERROR, G_IO_ERROR_FAILED,
                                  _("Cannot set clipboard data. Another process claimed clipboard ownership.")));
      return FALSE;
    }

  error_code = try_open_clipboard (clipboard_thread_data->clipboard_window);

  if (error_code == ERROR_ACCESS_DENIED)
    return TRUE;

  if (G_UNLIKELY (error_code != NO_ERROR))
    {
      send_response (store->parent.item_type,
                     store->parent.opaque_task,
                     g_error_new (G_IO_ERROR, G_IO_ERROR_FAILED,
                                  _("Cannot set clipboard data. OpenClipboard() failed: 0x%lx."), error_code));
      return FALSE;
    }

  /* It's possible for another process to claim ownership
   * between between us entering this function and us opening the clipboard.
   * So check the ownership one last time.
   * Unlike the advertisement routine above, here we don't want to
   * claim clipboard ownership - we want to store stuff in the clipboard
   * that we already own, otherwise we're just killing stuff that some other
   * process put in there, which is not nice.
   */
  if (GetClipboardOwner () != clipboard_thread_data->clipboard_window)
    {
      send_response (store->parent.item_type,
                     store->parent.opaque_task,
                     g_error_new (G_IO_ERROR, G_IO_ERROR_FAILED,
                                  _("Cannot set clipboard data. Another process claimed clipboard ownership.")));
      return FALSE;
    }

  for (i = 0; i < store->elements->len; i++)
    {
      GdkWin32ClipboardStorePrepElement *el = &g_array_index (store->elements, GdkWin32ClipboardStorePrepElement, i);
      if (el->handle != NULL && el->w32format != 0)
        if (SetClipboardData (el->w32format, el->handle))
          el->handle = NULL; /* the OS now owns the handle, don't free it later on */
    }

  send_response (store->parent.item_type,
                 store->parent.opaque_task,
                 NULL);

  return FALSE;
}

static gpointer
grab_data_from_hdata (GdkWin32ClipboardThreadRetrieve *retr,
                      HANDLE                           hdata,
                      gsize                           *data_len)
{
  gpointer ptr;
  SIZE_T length;
  guchar *data;

  ptr = GlobalLock (hdata);
  if (ptr == NULL)
    {
      DWORD error_code = GetLastError ();
      send_response (retr->parent.item_type,
                     retr->parent.opaque_task,
                     g_error_new (G_IO_ERROR, G_IO_ERROR_FAILED,
                                  _("Cannot get clipboard data. GlobalLock(0x%p) failed: 0x%lx."), hdata, error_code));
      return NULL;
    }

  length = GlobalSize (hdata);
  if (length == 0 && GetLastError () != NO_ERROR)
    {
      DWORD error_code = GetLastError ();
      send_response (retr->parent.item_type,
                     retr->parent.opaque_task,
                     g_error_new (G_IO_ERROR, G_IO_ERROR_FAILED,
                                  _("Cannot get clipboard data. GlobalSize(0x%p) failed: 0x%lx."), hdata, error_code));
      GlobalUnlock (hdata);
      return NULL;
    }

  data = g_try_malloc (length);

  if (data == NULL)
    {
      char *length_str = g_strdup_printf ("%" G_GSIZE_FORMAT, length);
      send_response (retr->parent.item_type,
                     retr->parent.opaque_task,
                     g_error_new (G_IO_ERROR, G_IO_ERROR_FAILED,
                                  _("Cannot get clipboard data. Failed to allocate %s bytes to store the data."), length_str));
      g_free (length_str);
      GlobalUnlock (hdata);
      return NULL;
    }

  memcpy (data, ptr, length);
  *data_len = length;

  GlobalUnlock (hdata);

  return data;
}

static gboolean
process_retrieve (GdkWin32ClipboardThreadRetrieve *retr)
{
  DWORD error_code;
  int i;
  UINT fmt, fmt_to_use;
  HANDLE hdata;
  GdkWin32ContentFormatPair *pair;
  guchar *data;
  gsize   data_len;
  GInputStream *stream;

  if (g_get_monotonic_time () > retr->parent.end_time)
    {
      GDK_NOTE (CLIPBOARD, g_printerr ("A retrieve task timed out\n"));
      send_response (retr->parent.item_type,
                     retr->parent.opaque_task,
                     g_error_new (G_IO_ERROR, G_IO_ERROR_FAILED,
                                  _("Cannot get clipboard data. OpenClipboard() timed out.")));
      return FALSE;
    }

  if (clipboard_thread_data->owner_change_time > retr->parent.start_time)
    {
      GDK_NOTE (CLIPBOARD, g_printerr ("A retrieve task timed out due to ownership change\n"));
      send_response (retr->parent.item_type,
                     retr->parent.opaque_task,
                     g_error_new (G_IO_ERROR, G_IO_ERROR_FAILED,
                                  _("Cannot get clipboard data. Clipboard ownership changed.")));
      return FALSE;
    }

  if (GetClipboardSequenceNumber () > retr->sequence_number)
    {
      GDK_NOTE (CLIPBOARD, g_printerr ("A retrieve task timed out due to data change\n"));
      send_response (retr->parent.item_type,
                     retr->parent.opaque_task,
                     g_error_new (G_IO_ERROR, G_IO_ERROR_FAILED,
                                  _("Cannot get clipboard data. Clipboard data changed before we could get it.")));
      return FALSE;
    }

  if (clipboard_thread_data->clipboard_opened_for == INVALID_HANDLE_VALUE)
    error_code = try_open_clipboard (clipboard_thread_data->clipboard_window);
  else
    error_code = try_open_clipboard (clipboard_thread_data->clipboard_opened_for);

  if (error_code == ERROR_ACCESS_DENIED)
    return TRUE;

  if (G_UNLIKELY (error_code != NO_ERROR))
    {
      send_response (retr->parent.item_type,
                     retr->parent.opaque_task,
                     g_error_new (G_IO_ERROR, G_IO_ERROR_FAILED,
                                  _("Cannot get clipboard data. OpenClipboard() failed: 0x%lx."), error_code));
      return FALSE;
    }

  for (fmt_to_use = 0, pair = NULL, fmt = 0;
       fmt_to_use == 0 && 0 != (fmt = EnumClipboardFormats (fmt));
      )
    {
      for (i = 0; i < retr->pairs->len; i++)
        {
          pair = &g_array_index (retr->pairs, GdkWin32ContentFormatPair, i);

          if (pair->w32format != fmt)
            continue;

          fmt_to_use = fmt;
          break;
        }
    }

  if (!fmt_to_use)
    {
      send_response (retr->parent.item_type,
                     retr->parent.opaque_task,
                     g_error_new (G_IO_ERROR, G_IO_ERROR_FAILED,
                                  _("Cannot get clipboard data. No compatible transfer format found.")));
      return FALSE;
    }

  if ((hdata = GetClipboardData (fmt_to_use)) == NULL)
    {
      error_code = GetLastError ();
      send_response (retr->parent.item_type,
                     retr->parent.opaque_task,
                     g_error_new (G_IO_ERROR, G_IO_ERROR_FAILED,
                                  _("Cannot get clipboard data. GetClipboardData() failed: 0x%lx."), error_code));
      return FALSE;
    }

  if (!pair->transmute)
    {
      if (_gdk_win32_format_uses_hdata (pair->w32format))
        {
          data = grab_data_from_hdata (retr, hdata, &data_len);

          if (data == NULL)
            return FALSE;
        }
      else
        {
          data_len = sizeof (HANDLE);
          data = g_malloc (data_len);
          memcpy (data, &hdata, data_len);
        }
    }
  else
    {
      _gdk_win32_transmute_windows_data (pair->w32format, pair->contentformat, hdata, &data, &data_len);

      if (data == NULL)
        return FALSE;
    }

  stream = g_memory_input_stream_new_from_data (data, data_len, g_free);
  g_object_set_data (G_OBJECT (stream), "gdk-clipboard-stream-contenttype", (gpointer) pair->contentformat);

  GDK_NOTE (CLIPBOARD, g_printerr ("reading clipboard data from a %" G_GSIZE_FORMAT "-byte buffer\n",
                                   data_len));
  send_input_stream (retr->parent.item_type,
                     retr->parent.opaque_task,
                     stream);

  return FALSE;
}

static gboolean
process_clipboard_queue ()
{
  GdkWin32ClipboardThreadQueueItem *placeholder;
  GList *p;
  gboolean try_again;
  GList *p_next;

  for (p = clipboard_thread_data->dequeued_items, p_next = NULL; p; p = p_next)
    {
      placeholder = (GdkWin32ClipboardThreadQueueItem *) p->data;
      p_next = p->next;

      switch (placeholder->item_type)
        {
        case GDK_WIN32_CLIPBOARD_THREAD_QUEUE_ITEM_ADVERTISE:
          try_again = process_advertise ((GdkWin32ClipboardThreadAdvertise *) placeholder);
          break;
        case GDK_WIN32_CLIPBOARD_THREAD_QUEUE_ITEM_RETRIEVE:
          try_again = process_retrieve ((GdkWin32ClipboardThreadRetrieve *) placeholder);
          break;
        case GDK_WIN32_CLIPBOARD_THREAD_QUEUE_ITEM_STORE:
          try_again = process_store ((GdkWin32ClipboardThreadStore *) placeholder);
          break;
        }

      if (try_again)
        return FALSE;

      clipboard_thread_data->dequeued_items = g_list_delete_link (clipboard_thread_data->dequeued_items, p);
      free_queue_item (placeholder);
    }

  while ((placeholder = g_async_queue_try_pop (clipboard_thread_data->input_queue)) != NULL)
    {
      switch (placeholder->item_type)
        {
        case GDK_WIN32_CLIPBOARD_THREAD_QUEUE_ITEM_ADVERTISE:
          try_again = process_advertise ((GdkWin32ClipboardThreadAdvertise *) placeholder);
          break;
        case GDK_WIN32_CLIPBOARD_THREAD_QUEUE_ITEM_RETRIEVE:
          try_again = process_retrieve ((GdkWin32ClipboardThreadRetrieve *) placeholder);
          break;
        case GDK_WIN32_CLIPBOARD_THREAD_QUEUE_ITEM_STORE:
          try_again = process_store ((GdkWin32ClipboardThreadStore *) placeholder);
          break;
        }

      if (!try_again)
        {
          free_queue_item (placeholder);
          continue;
        }

      clipboard_thread_data->dequeued_items = g_list_append (clipboard_thread_data->dequeued_items, placeholder);

      return FALSE;
    }

  return TRUE;
}

static void
discard_render (GdkWin32ClipboardThreadRender *render,
                gboolean                       dont_touch_the_handle)
{
  GdkWin32ClipboardThreadRender render_copy = *render;

  g_free (render);

  if (dont_touch_the_handle || render_copy.main_thread_data_handle == NULL)
    return;

  if (_gdk_win32_format_uses_hdata (render_copy.pair.w32format))
    API_CALL (GlobalFree, (render_copy.main_thread_data_handle));
  else
    API_CALL (CloseHandle, (render_copy.main_thread_data_handle));
}

static LRESULT
inner_clipboard_window_procedure (HWND   hwnd,
                                  UINT   message,
                                  WPARAM wparam,
                                  LPARAM lparam)
{
  if (message == thread_wakeup_message ||
      message == WM_TIMER)
    {
      gboolean queue_is_empty = FALSE;

      if (clipboard_thread_data == NULL)
        {
          g_warning ("Clipboard thread got an actionable message with no thread data");
          return DefWindowProcW (hwnd, message, wparam, lparam);
        }

      queue_is_empty = process_clipboard_queue ();

      if (queue_is_empty && clipboard_thread_data->wakeup_timer)
        {
          API_CALL (KillTimer, (clipboard_thread_data->clipboard_window, clipboard_thread_data->wakeup_timer));
          clipboard_thread_data->wakeup_timer = 0;
        }

      /* Close the clipboard after each queue run, if it's open.
       * It would be wrong to keep it open, even if we would
       * need it again a second later.
       * queue_is_empty == FALSE implies that the clipboard
       * is closed already, but it's better to be sure.
       */
      if (clipboard_thread_data->clipboard_opened_for != INVALID_HANDLE_VALUE)
        {
          API_CALL (CloseClipboard, ());
          clipboard_thread_data->clipboard_opened_for = INVALID_HANDLE_VALUE;
        }

      if (queue_is_empty ||
          clipboard_thread_data->wakeup_timer != 0)
        return 0;

      if (SetTimer (clipboard_thread_data->clipboard_window, 1, 1000, NULL))
        clipboard_thread_data->wakeup_timer = 1;
      else
        g_critical ("Failed to set a timer for the clipboard window 0x%p: %lu",
                    clipboard_thread_data->clipboard_window,
                    GetLastError ());
    }

  switch (message)
    {
    case WM_DESTROY: /* remove us from chain */
      {
        if (clipboard_thread_data == NULL)
          {
            g_warning ("Clipboard thread got an actionable message with no thread data");
            return DefWindowProcW (hwnd, message, wparam, lparam);
          }

        ChangeClipboardChain (hwnd, clipboard_thread_data->hwnd_next_viewer);
        PostQuitMessage (0);
        return 0;
      }
    case WM_CHANGECBCHAIN:
      {
        HWND hwndRemove = (HWND) wparam; /* handle of window being removed */
        HWND hwndNext   = (HWND) lparam; /* handle of next window in chain */

        if (clipboard_thread_data == NULL)
          {
            g_warning ("Clipboard thread got an actionable message with no thread data");
            return DefWindowProcW (hwnd, message, wparam, lparam);
          }

        if (hwndRemove == clipboard_thread_data->hwnd_next_viewer)
          clipboard_thread_data->hwnd_next_viewer = hwndNext == hwnd ? NULL : hwndNext;
        else if (clipboard_thread_data->hwnd_next_viewer != NULL)
          return SendMessage (clipboard_thread_data->hwnd_next_viewer, message, wparam, lparam);

        return 0;
      }
    case WM_DESTROYCLIPBOARD:
      {
        return 0;
      }
    case WM_CLIPBOARDUPDATE:
    case WM_DRAWCLIPBOARD:
      {
        HWND hwnd_owner;
        HWND hwnd_opener;
/*
        GdkEvent *event;
*/
        if (clipboard_thread_data == NULL)
          {
            g_warning ("Clipboard thread got an actionable message with no thread data");
            return DefWindowProcW (hwnd, message, wparam, lparam);
          }

        hwnd_owner = GetClipboardOwner ();

        if ((hwnd_owner == NULL) &&
            (GetLastError () != ERROR_SUCCESS))
            WIN32_API_FAILED ("GetClipboardOwner");

        hwnd_opener = GetOpenClipboardWindow ();

        GDK_NOTE (DND, g_print (" drawclipboard owner: %p; opener %p ", hwnd_owner, hwnd_opener));

#ifdef G_ENABLE_DEBUG
        if (_gdk_debug_flags & GDK_DEBUG_DND)
          {
            /* FIXME: grab and print clipboard formats without opening the clipboard
            if (clipboard_thread_data->clipboard_opened_for != INVALID_HANDLE_VALUE ||
                OpenClipboard (hwnd))
              {
                UINT nFormat = 0;

                while ((nFormat = EnumClipboardFormats (nFormat)) != 0)
                  g_print ("%s ", _gdk_win32_cf_to_string (nFormat));

                if (clipboard_thread_data->clipboard_opened_for == INVALID_HANDLE_VALUE)
                  CloseClipboard ();
              }
            else
              {
                WIN32_API_FAILED ("OpenClipboard");
              }
             */
          }
#endif

        GDK_NOTE (DND, g_print (" \n"));

        if (clipboard_thread_data->stored_hwnd_owner != hwnd_owner)
          {
            clipboard_thread_data->stored_hwnd_owner = hwnd_owner;
            clipboard_thread_data->owner_change_time = g_get_monotonic_time ();

            if (hwnd_owner != clipboard_thread_data->clipboard_window)
              {
                if (clipboard_thread_data->cached_advertisement)
                  g_array_free (clipboard_thread_data->cached_advertisement, TRUE);

                clipboard_thread_data->cached_advertisement = NULL;
              }

            API_CALL (PostMessage, (clipboard_thread_data->clipboard_window, thread_wakeup_message, 0, 0));

            if (hwnd_owner != clipboard_thread_data->clipboard_window)
              g_idle_add_full (G_PRIORITY_DEFAULT, clipboard_owner_changed, NULL, NULL);
          }

        if (clipboard_thread_data->hwnd_next_viewer != NULL)
          return SendMessage (clipboard_thread_data->hwnd_next_viewer, message, wparam, lparam);

        /* clear error to avoid confusing SetClipboardViewer() return */
        SetLastError (0);

        return 0;
      }
    case WM_RENDERALLFORMATS:
      {
        if (clipboard_thread_data == NULL)
          {
            g_warning ("Clipboard thread got an actionable message with no thread data");
            return DefWindowProcW (hwnd, message, wparam, lparam);
          }

        if (clipboard_thread_data->cached_advertisement == NULL)
          return DefWindowProcW (hwnd, message, wparam, lparam);

        if (API_CALL (OpenClipboard, (hwnd)))
          {
            int i;
            GdkWin32ContentFormatPair *pair;

            for (pair = NULL, i = 0;
                 i < clipboard_thread_data->cached_advertisement->len;
                 i++)
              {
                pair = &g_array_index (clipboard_thread_data->cached_advertisement, GdkWin32ContentFormatPair, i);

                if (pair->w32format != 0)
                  SendMessage (hwnd, WM_RENDERFORMAT, pair->w32format, 0);
              }

            API_CALL (CloseClipboard, ());
          }

        return 0;
      }
    case WM_RENDERFORMAT:
      {
        int i;
        GdkWin32ClipboardThreadRender *render;
        GdkWin32ClipboardThreadRender *returned_render;
        GdkWin32ContentFormatPair *pair;


        GDK_NOTE (EVENTS, g_print (" %s", _gdk_win32_cf_to_string (wparam)));

        if (clipboard_thread_data == NULL)
          {
            g_warning ("Clipboard thread got an actionable message with no thread data");
            return DefWindowProcW (hwnd, message, wparam, lparam);
          }

        if (clipboard_thread_data->cached_advertisement == NULL)
          return DefWindowProcW (hwnd, message, wparam, lparam);

        for (pair = NULL, i = 0;
             i < clipboard_thread_data->cached_advertisement->len;
             i++)
          {
            pair = &g_array_index (clipboard_thread_data->cached_advertisement, GdkWin32ContentFormatPair, i);

            if (pair->w32format == wparam)
              break;

            pair = NULL;
          }

        if (pair == NULL)
          {
            GDK_NOTE (EVENTS, g_print (" (contentformat not found)"));
            return DefWindowProcW (hwnd, message, wparam, lparam);
          }

        /* Clear the queue */
        while ((render = g_async_queue_try_pop (clipboard_thread_data->render_queue)) != NULL)
          discard_render (render, FALSE);

        render = g_new0 (GdkWin32ClipboardThreadRender, 1);
        render->pair = *pair;
        g_idle_add_full (G_PRIORITY_DEFAULT, clipboard_render, render, NULL);
        returned_render = g_async_queue_timeout_pop (clipboard_thread_data->render_queue, CLIPBOARD_RENDER_TIMEOUT);

        /* We should get back the same pointer, ignore everything else. */
        while (returned_render != NULL && returned_render != render)
        {
          discard_render (returned_render, FALSE);
          /* Technically, we should use timed pop here as well,
           * as it's *possible* for a late render struct
           * to come down the queue just after we cleared
           * the queue, but before our idle function
           * triggered the actual render to be pushed.
           * If you get many "Clipboard rendering timed out" warnings,
           * this is probably why.
           */
          returned_render = g_async_queue_try_pop (clipboard_thread_data->render_queue);
        }

        /* Just in case */
        render = NULL;

        if (returned_render == NULL)
          {
            g_warning ("Clipboard rendering timed out");
          }
        else if (returned_render->main_thread_data_handle)
          {
            BOOL set_data_succeeded;
            /* The requestor is holding the clipboard, no
             * OpenClipboard() is required/possible
             */
            GDK_NOTE (DND,
                      g_print (" SetClipboardData (%s, %p)",
                               _gdk_win32_cf_to_string (wparam),
                               returned_render->main_thread_data_handle));

            SetLastError (0);
            set_data_succeeded = (SetClipboardData (wparam, returned_render->main_thread_data_handle) != NULL);

            if (!set_data_succeeded)
              WIN32_API_FAILED ("SetClipboardData");

            discard_render (returned_render, set_data_succeeded);
          }

        return 0;
      }
    default:
      /* Otherwise call DefWindowProcW(). */
      GDK_NOTE (EVENTS, g_print (" DefWindowProcW"));
      return DefWindowProcW (hwnd, message, wparam, lparam);
    }
}

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

  GDK_NOTE (EVENTS, g_print ("clipboard thread %s %p",
			     _gdk_win32_message_to_string (message), hwnd));
  retval = inner_clipboard_window_procedure (hwnd, message, wparam, lparam);

  GDK_NOTE (EVENTS, g_print (" => %" G_GINT64_FORMAT "\n", (gint64) retval));

  return retval;
}

/*
 * Creates a hidden window and adds it to the clipboard chain
 */
static gboolean
register_clipboard_notification ()
{
  WNDCLASS wclass = { 0, };
  ATOM klass;

  wclass.lpszClassName = "GdkClipboardNotification";
  wclass.lpfnWndProc = _clipboard_window_procedure;
  wclass.hInstance = _gdk_dll_hinstance;
  wclass.cbWndExtra = sizeof (GdkWin32ClipboardThread *);

  klass = RegisterClass (&wclass);
  if (!klass)
    return FALSE;

  clipboard_thread_data->clipboard_window = CreateWindow (MAKEINTRESOURCE (klass),
                                                NULL, WS_POPUP,
                                                0, 0, 0, 0, NULL, NULL,
                                                _gdk_dll_hinstance, NULL);

  if (clipboard_thread_data->clipboard_window == NULL)
    goto failed;

  SetLastError (0);
  clipboard_thread_data->hwnd_next_viewer = SetClipboardViewer (clipboard_thread_data->clipboard_window);

  if (clipboard_thread_data->hwnd_next_viewer == NULL && GetLastError() != NO_ERROR)
    {
      DestroyWindow (clipboard_thread_data->clipboard_window);
      goto failed;
    }

  g_idle_add_full (G_PRIORITY_DEFAULT, clipboard_window_created, (gpointer) clipboard_thread_data->clipboard_window, NULL);

  /* FIXME: http://msdn.microsoft.com/en-us/library/ms649033(v=VS.85).aspx */
  /* This is only supported by Vista, and not yet by mingw64 */
  /* if (AddClipboardFormatListener (hwnd) == FALSE) */
  /*   goto failed; */

  return TRUE;

failed:
  g_critical ("Failed to install clipboard viewer");
  UnregisterClass (MAKEINTRESOURCE (klass), _gdk_dll_hinstance);
  return FALSE;
}

static gpointer
_gdk_win32_clipboard_thread_main (gpointer data)
{
  MSG msg;
  GAsyncQueue *queue = (GAsyncQueue *) data;
  GAsyncQueue *render_queue = (GAsyncQueue *) g_async_queue_pop (queue);

  g_assert (clipboard_thread_data == NULL);

  clipboard_thread_data = g_new0 (GdkWin32ClipboardThread, 1);
  clipboard_thread_data->input_queue = queue;
  clipboard_thread_data->render_queue = render_queue;
  clipboard_thread_data->clipboard_opened_for = INVALID_HANDLE_VALUE;

  if (!register_clipboard_notification ())
    {
      g_async_queue_unref (queue);
      g_clear_pointer (&clipboard_thread_data, g_free);

      return NULL;
    }

  while (GetMessage (&msg, NULL, 0, 0))
    {
      TranslateMessage (&msg); 
      DispatchMessage (&msg); 
    }

  /* Just in case, as this should only happen when we shut down */
  DestroyWindow (clipboard_thread_data->clipboard_window);
  CloseHandle (clipboard_thread_data->clipboard_window);
  g_async_queue_unref (queue);
  g_clear_pointer (&clipboard_thread_data, g_free);

  return NULL;
}

G_DEFINE_TYPE (GdkWin32Clipdrop, gdk_win32_clipdrop, G_TYPE_OBJECT)

static void
gdk_win32_clipdrop_class_init (GdkWin32ClipdropClass *klass)
{
}

void
_gdk_win32_clipdrop_init (void)
{
  _win32_main_thread = g_thread_self ();
  _win32_clipdrop = GDK_WIN32_CLIPDROP (g_object_new (GDK_TYPE_WIN32_CLIPDROP, NULL));
}

static void
gdk_win32_clipdrop_init (GdkWin32Clipdrop *win32_clipdrop)
{
  GArray             *atoms;
  GArray             *cfs;
  GSList             *pixbuf_formats;
  GSList             *rover;
  int                 i;
  GArray             *comp;
  GdkWin32ContentFormatPair fmt;
  HMODULE                   user32;

  thread_wakeup_message = RegisterWindowMessage ("GDK_WORKER_THREAD_WEAKEUP");

  user32 = LoadLibrary ("user32.dll");
  win32_clipdrop->GetUpdatedClipboardFormats = (GetUpdatedClipboardFormatsFunc) GetProcAddress (user32, "GetUpdatedClipboardFormats");
  FreeLibrary (user32);

  atoms = g_array_sized_new (FALSE, TRUE, sizeof (const char *), GDK_WIN32_ATOM_INDEX_LAST);
  g_array_set_size (atoms, GDK_WIN32_ATOM_INDEX_LAST);
  cfs = g_array_sized_new (FALSE, TRUE, sizeof (UINT), GDK_WIN32_CF_INDEX_LAST);
  g_array_set_size (cfs, GDK_WIN32_CF_INDEX_LAST);

  win32_clipdrop->known_atoms = atoms;
  win32_clipdrop->known_clipboard_formats = cfs;

  _gdk_atom_array_index (atoms, GDK_WIN32_ATOM_INDEX_GDK_SELECTION) = g_intern_static_string ("GDK_SELECTION");
  _gdk_atom_array_index (atoms, GDK_WIN32_ATOM_INDEX_CLIPBOARD_MANAGER) = g_intern_static_string ("CLIPBOARD_MANAGER");
  _gdk_atom_array_index (atoms, GDK_WIN32_ATOM_INDEX_WM_TRANSIENT_FOR) = g_intern_static_string ("WM_TRANSIENT_FOR");
  _gdk_atom_array_index (atoms, GDK_WIN32_ATOM_INDEX_TARGETS) = g_intern_static_string ("TARGETS");
  _gdk_atom_array_index (atoms, GDK_WIN32_ATOM_INDEX_DELETE) = g_intern_static_string ("DELETE");
  _gdk_atom_array_index (atoms, GDK_WIN32_ATOM_INDEX_SAVE_TARGETS) = g_intern_static_string ("SAVE_TARGETS");
  _gdk_atom_array_index (atoms, GDK_WIN32_ATOM_INDEX_TEXT_PLAIN_UTF8) = g_intern_static_string ("text/plain;charset=utf-8");
  _gdk_atom_array_index (atoms, GDK_WIN32_ATOM_INDEX_TEXT_PLAIN) = g_intern_static_string ("text/plain");
  _gdk_atom_array_index (atoms, GDK_WIN32_ATOM_INDEX_TEXT_URI_LIST) = g_intern_static_string ("text/uri-list");
  _gdk_atom_array_index (atoms, GDK_WIN32_ATOM_INDEX_TEXT_HTML) = g_intern_static_string ("text/html");
  _gdk_atom_array_index (atoms, GDK_WIN32_ATOM_INDEX_IMAGE_PNG) = g_intern_static_string ("image/png");
  _gdk_atom_array_index (atoms, GDK_WIN32_ATOM_INDEX_IMAGE_JPEG) = g_intern_static_string ("image/jpeg");
  _gdk_atom_array_index (atoms, GDK_WIN32_ATOM_INDEX_IMAGE_BMP) = g_intern_static_string ("image/bmp");
  _gdk_atom_array_index (atoms, GDK_WIN32_ATOM_INDEX_IMAGE_GIF) = g_intern_static_string ("image/gif");

  _gdk_atom_array_index (atoms, GDK_WIN32_ATOM_INDEX_LOCAL_DND_SELECTION) = g_intern_static_string ("LocalDndSelection");
  _gdk_atom_array_index (atoms, GDK_WIN32_ATOM_INDEX_DROPFILES_DND) = g_intern_static_string ("DROPFILES_DND");
  _gdk_atom_array_index (atoms, GDK_WIN32_ATOM_INDEX_OLE2_DND) = g_intern_static_string ("OLE2_DND");

  _gdk_atom_array_index (atoms, GDK_WIN32_ATOM_INDEX_PNG)= g_intern_static_string ("PNG");
  _gdk_atom_array_index (atoms, GDK_WIN32_ATOM_INDEX_JFIF) = g_intern_static_string ("JFIF");
  _gdk_atom_array_index (atoms, GDK_WIN32_ATOM_INDEX_GIF) = g_intern_static_string ("GIF");

  /* These are a bit unusual. It's here to allow GTK applications
   * to actually support CF_DIB and Shell ID List clipboard formats on their own,
   * instead of allowing GDK to use them internally for interoperability.
   */
  _gdk_atom_array_index (atoms, GDK_WIN32_ATOM_INDEX_CF_DIB) = g_intern_static_string ("application/x.windows.CF_DIB");
  _gdk_atom_array_index (atoms, GDK_WIN32_ATOM_INDEX_CFSTR_SHELLIDLIST) = g_intern_static_string ("application/x.windows.Shell IDList Array");
  _gdk_atom_array_index (atoms, GDK_WIN32_ATOM_INDEX_CF_UNICODETEXT) = g_intern_static_string ("application/x.windows.CF_UNICODETEXT");
  _gdk_atom_array_index (atoms, GDK_WIN32_ATOM_INDEX_CF_TEXT) = g_intern_static_string ("application/x.windows.CF_TEXT");

  /* MS Office 2007, at least, offers images in common file formats
   * using clipboard format names like "PNG" and "JFIF". So we follow
   * the lead and map the GDK contentformat "image/png" to the clipboard
   * format name "PNG" etc.
   */
  _gdk_cf_array_index (cfs, GDK_WIN32_CF_INDEX_PNG) = RegisterClipboardFormatA ("PNG");
  _gdk_cf_array_index (cfs, GDK_WIN32_CF_INDEX_JFIF) = RegisterClipboardFormatA ("JFIF");
  _gdk_cf_array_index (cfs, GDK_WIN32_CF_INDEX_GIF) = RegisterClipboardFormatA ("GIF");

  _gdk_cf_array_index (cfs, GDK_WIN32_CF_INDEX_UNIFORMRESOURCELOCATORW) = RegisterClipboardFormatA ("UniformResourceLocatorW");
  _gdk_cf_array_index (cfs, GDK_WIN32_CF_INDEX_CFSTR_SHELLIDLIST) = RegisterClipboardFormatA (CFSTR_SHELLIDLIST);
  _gdk_cf_array_index (cfs, GDK_WIN32_CF_INDEX_HTML_FORMAT) = RegisterClipboardFormatA ("HTML Format");
  _gdk_cf_array_index (cfs, GDK_WIN32_CF_INDEX_TEXT_HTML) = RegisterClipboardFormatA ("text/html");

  _gdk_cf_array_index (cfs, GDK_WIN32_CF_INDEX_IMAGE_PNG) = RegisterClipboardFormatA ("image/png");
  _gdk_cf_array_index (cfs, GDK_WIN32_CF_INDEX_IMAGE_JPEG) = RegisterClipboardFormatA ("image/jpeg");
  _gdk_cf_array_index (cfs, GDK_WIN32_CF_INDEX_IMAGE_BMP) = RegisterClipboardFormatA ("image/bmp");
  _gdk_cf_array_index (cfs, GDK_WIN32_CF_INDEX_IMAGE_GIF) = RegisterClipboardFormatA ("image/gif");
  _gdk_cf_array_index (cfs, GDK_WIN32_CF_INDEX_TEXT_URI_LIST) = RegisterClipboardFormatA ("text/uri-list");
  _gdk_cf_array_index (cfs, GDK_WIN32_CF_INDEX_TEXT_PLAIN_UTF8) = RegisterClipboardFormatA ("text/plain;charset=utf-8");

  win32_clipdrop->active_source_drags = g_hash_table_new_full (NULL, NULL, (GDestroyNotify) g_object_unref, NULL);

  pixbuf_formats = gdk_pixbuf_get_formats ();

  win32_clipdrop->n_known_pixbuf_formats = 0;
  for (rover = pixbuf_formats; rover != NULL; rover = rover->next)
    {
      char **mime_types =
	gdk_pixbuf_format_get_mime_types ((GdkPixbufFormat *) rover->data);
      char **mime_type;

      for (mime_type = mime_types; *mime_type != NULL; mime_type++)
	win32_clipdrop->n_known_pixbuf_formats++;
    }

  win32_clipdrop->known_pixbuf_formats = g_new (const char *, win32_clipdrop->n_known_pixbuf_formats);

  i = 0;
  for (rover = pixbuf_formats; rover != NULL; rover = rover->next)
    {
      char **mime_types =
	gdk_pixbuf_format_get_mime_types ((GdkPixbufFormat *) rover->data);
      char **mime_type;

      for (mime_type = mime_types; *mime_type != NULL; mime_type++)
	win32_clipdrop->known_pixbuf_formats[i++] = g_intern_string (*mime_type);
    }

  g_slist_free (pixbuf_formats);

  win32_clipdrop->compatibility_w32formats = g_hash_table_new_full (NULL, NULL, NULL, (GDestroyNotify) g_array_unref);

  /* GTK actually has more text formats, but it's unlikely that we'd
   * get anything other than UTF8_STRING these days.
   * GTKTEXTBUFFERCONTENTS format can potentially be converted to
   * W32-compatible rich text format, but that's too complex to address right now.
   */
  comp = g_array_sized_new (FALSE, FALSE, sizeof (GdkWin32ContentFormatPair), 3);
  fmt.contentformat = _gdk_atom_array_index (atoms, GDK_WIN32_ATOM_INDEX_TEXT_PLAIN_UTF8);

  fmt.w32format = _gdk_cf_array_index (cfs, GDK_WIN32_CF_INDEX_TEXT_PLAIN_UTF8);
  fmt.transmute = FALSE;
  g_array_append_val (comp, fmt);

  fmt.w32format = CF_UNICODETEXT;
  fmt.transmute = TRUE;
  g_array_append_val (comp, fmt);

  fmt.w32format = CF_TEXT;
  g_array_append_val (comp, fmt);

  g_hash_table_replace (win32_clipdrop->compatibility_w32formats, (gpointer) fmt.contentformat, comp);


  comp = g_array_sized_new (FALSE, FALSE, sizeof (GdkWin32ContentFormatPair), 2);
  fmt.contentformat = _gdk_atom_array_index (atoms, GDK_WIN32_ATOM_INDEX_IMAGE_PNG);

  fmt.w32format = _gdk_cf_array_index (cfs, GDK_WIN32_CF_INDEX_IMAGE_PNG);
  fmt.transmute = FALSE;
  g_array_append_val (comp, fmt);

  fmt.w32format = _gdk_cf_array_index (cfs, GDK_WIN32_CF_INDEX_PNG);
  g_array_append_val (comp, fmt);

  g_hash_table_replace (win32_clipdrop->compatibility_w32formats, (gpointer) fmt.contentformat, comp);


  comp = g_array_sized_new (FALSE, FALSE, sizeof (GdkWin32ContentFormatPair), 2);
  fmt.contentformat = _gdk_atom_array_index (atoms, GDK_WIN32_ATOM_INDEX_IMAGE_JPEG);

  fmt.w32format = _gdk_cf_array_index (cfs, GDK_WIN32_CF_INDEX_IMAGE_JPEG);
  fmt.transmute = FALSE;
  g_array_append_val (comp, fmt);

  fmt.w32format = _gdk_cf_array_index (cfs, GDK_WIN32_CF_INDEX_JFIF);
  g_array_append_val (comp, fmt);

  g_hash_table_replace (win32_clipdrop->compatibility_w32formats, (gpointer) fmt.contentformat, comp);


  comp = g_array_sized_new (FALSE, FALSE, sizeof (GdkWin32ContentFormatPair), 2);
  fmt.contentformat = _gdk_atom_array_index (atoms, GDK_WIN32_ATOM_INDEX_IMAGE_GIF);

  fmt.w32format = _gdk_cf_array_index (cfs, GDK_WIN32_CF_INDEX_IMAGE_GIF);
  fmt.transmute = FALSE;
  g_array_append_val (comp, fmt);

  fmt.w32format = _gdk_cf_array_index (cfs, GDK_WIN32_CF_INDEX_GIF);
  g_array_append_val (comp, fmt);

  g_hash_table_replace (win32_clipdrop->compatibility_w32formats, (gpointer) fmt.contentformat, comp);


  comp = g_array_sized_new (FALSE, FALSE, sizeof (GdkWin32ContentFormatPair), 2);
  fmt.contentformat = _gdk_atom_array_index (atoms, GDK_WIN32_ATOM_INDEX_IMAGE_BMP);

  fmt.w32format = _gdk_cf_array_index (cfs, GDK_WIN32_CF_INDEX_IMAGE_BMP);
  fmt.transmute = FALSE;
  g_array_append_val (comp, fmt);

  fmt.w32format = CF_DIB;
  fmt.transmute = TRUE;
  g_array_append_val (comp, fmt);

  g_hash_table_replace (win32_clipdrop->compatibility_w32formats, (gpointer) fmt.contentformat, comp);


/* Not implemented, but definitely possible
  comp = g_array_sized_new (FALSE, FALSE, sizeof (GdkWin32ContentFormatPair), 2);
  fmt.contentformat = _gdk_atom_array_index (atoms, GDK_WIN32_ATOM_INDEX_TEXT_URI_LIST);

  fmt.w32format = _gdk_cf_array_index (cfs, GDK_WIN32_CF_INDEX_TEXT_URI_LIST);
  fmt.transmute = FALSE;
  g_array_append_val (comp, fmt);

  fmt.w32format = _gdk_cf_array_index (cfs, GDK_WIN32_CF_INDEX_CFSTR_SHELLIDLIST);
  fmt.transmute = TRUE;
  g_array_append_val (comp, fmt);

  g_hash_table_replace (win32_clipdrop->compatibility_w32formats, fmt.contentformat, comp);
*/

  win32_clipdrop->compatibility_contentformats = g_hash_table_new_full (NULL, NULL, NULL, (GDestroyNotify) g_array_unref);

  comp = g_array_sized_new (FALSE, FALSE, sizeof (GdkWin32ContentFormatPair), 2);
  fmt.w32format = CF_TEXT;
  fmt.transmute = FALSE;

  fmt.contentformat = _gdk_atom_array_index (atoms, GDK_WIN32_ATOM_INDEX_CF_TEXT);
  g_array_append_val (comp, fmt);

  fmt.contentformat = _gdk_atom_array_index (atoms, GDK_WIN32_ATOM_INDEX_TEXT_PLAIN_UTF8);
  fmt.transmute = TRUE;
  g_array_append_val (comp, fmt);

  g_hash_table_replace (win32_clipdrop->compatibility_contentformats, GINT_TO_POINTER (CF_TEXT), comp);


  comp = g_array_sized_new (FALSE, FALSE, sizeof (GdkWin32ContentFormatPair), 2);
  fmt.w32format = CF_UNICODETEXT;
  fmt.transmute = FALSE;

  fmt.contentformat = _gdk_atom_array_index (atoms, GDK_WIN32_ATOM_INDEX_CF_UNICODETEXT);
  g_array_append_val (comp, fmt);

  fmt.contentformat = _gdk_atom_array_index (atoms, GDK_WIN32_ATOM_INDEX_TEXT_PLAIN_UTF8);
  fmt.transmute = TRUE;
  g_array_append_val (comp, fmt);

  g_hash_table_replace (win32_clipdrop->compatibility_contentformats, GINT_TO_POINTER (CF_UNICODETEXT), comp);


  comp = g_array_sized_new (FALSE, FALSE, sizeof (GdkWin32ContentFormatPair), 2);
  fmt.w32format = _gdk_cf_array_index (cfs, GDK_WIN32_CF_INDEX_PNG);
  fmt.transmute = FALSE;

  fmt.contentformat = _gdk_atom_array_index (atoms, GDK_WIN32_ATOM_INDEX_PNG);
  g_array_append_val (comp, fmt);

  fmt.contentformat = _gdk_atom_array_index (atoms, GDK_WIN32_ATOM_INDEX_IMAGE_PNG);
  g_array_append_val (comp, fmt);

  g_hash_table_replace (win32_clipdrop->compatibility_contentformats, GINT_TO_POINTER (_gdk_cf_array_index (cfs, GDK_WIN32_CF_INDEX_PNG)), comp);


  comp = g_array_sized_new (FALSE, FALSE, sizeof (GdkWin32ContentFormatPair), 2);
  fmt.w32format = _gdk_cf_array_index (cfs, GDK_WIN32_CF_INDEX_JFIF);
  fmt.transmute = FALSE;

  fmt.contentformat = _gdk_atom_array_index (atoms, GDK_WIN32_ATOM_INDEX_JFIF);
  g_array_append_val (comp, fmt);

  fmt.contentformat = _gdk_atom_array_index (atoms, GDK_WIN32_ATOM_INDEX_IMAGE_JPEG);
  g_array_append_val (comp, fmt);

  g_hash_table_replace (win32_clipdrop->compatibility_contentformats, GINT_TO_POINTER (_gdk_cf_array_index (cfs, GDK_WIN32_CF_INDEX_JFIF)), comp);


  comp = g_array_sized_new (FALSE, FALSE, sizeof (GdkWin32ContentFormatPair), 2);
  fmt.w32format = _gdk_cf_array_index (cfs, GDK_WIN32_CF_INDEX_GIF);
  fmt.transmute = FALSE;

  fmt.contentformat = _gdk_atom_array_index (atoms, GDK_WIN32_ATOM_INDEX_GIF);
  g_array_append_val (comp, fmt);

  fmt.contentformat = _gdk_atom_array_index (atoms, GDK_WIN32_ATOM_INDEX_IMAGE_GIF);
  g_array_append_val (comp, fmt);

  g_hash_table_replace (win32_clipdrop->compatibility_contentformats, GINT_TO_POINTER (_gdk_cf_array_index (cfs, GDK_WIN32_CF_INDEX_GIF)), comp);


  comp = g_array_sized_new (FALSE, FALSE, sizeof (GdkWin32ContentFormatPair), 2);
  fmt.w32format = CF_DIB;
  fmt.transmute = FALSE;

  fmt.contentformat = _gdk_atom_array_index (atoms, GDK_WIN32_ATOM_INDEX_CF_DIB);
  g_array_append_val (comp, fmt);

  fmt.contentformat = _gdk_atom_array_index (atoms, GDK_WIN32_ATOM_INDEX_IMAGE_BMP);
  fmt.transmute = TRUE;
  g_array_append_val (comp, fmt);

  g_hash_table_replace (win32_clipdrop->compatibility_contentformats, GINT_TO_POINTER (CF_DIB), comp);


  comp = g_array_sized_new (FALSE, FALSE, sizeof (GdkWin32ContentFormatPair), 2);
  fmt.w32format = _gdk_cf_array_index (cfs, GDK_WIN32_CF_INDEX_CFSTR_SHELLIDLIST);
  fmt.transmute = FALSE;

  fmt.contentformat = _gdk_atom_array_index (atoms, GDK_WIN32_ATOM_INDEX_CFSTR_SHELLIDLIST);
  g_array_append_val (comp, fmt);

  fmt.contentformat = _gdk_atom_array_index (atoms, GDK_WIN32_ATOM_INDEX_TEXT_URI_LIST);
  fmt.transmute = TRUE;
  g_array_append_val (comp, fmt);

  g_hash_table_replace (win32_clipdrop->compatibility_contentformats, GINT_TO_POINTER (_gdk_cf_array_index (cfs, GDK_WIN32_CF_INDEX_CFSTR_SHELLIDLIST)), comp);

  win32_clipdrop->clipboard_open_thread_queue = g_async_queue_new ();
  win32_clipdrop->clipboard_render_queue = g_async_queue_new ();
  /* Out of sheer laziness, we just push the extra queue through the
   * main queue, instead of allocating a struct with two queue
   * pointers and then passing *that* to the thread.
   */
  g_async_queue_push (win32_clipdrop->clipboard_open_thread_queue, g_async_queue_ref (win32_clipdrop->clipboard_render_queue));
  win32_clipdrop->clipboard_open_thread = g_thread_new ("GDK Win32 Clipboard Thread",
                                                        _gdk_win32_clipboard_thread_main,
                                                        g_async_queue_ref (win32_clipdrop->clipboard_open_thread_queue));

  win32_clipdrop->dnd_queue = g_async_queue_new ();
  win32_clipdrop->dnd_thread = g_thread_new ("GDK Win32 DnD Thread",
                                             _gdk_win32_dnd_thread_main,
                                             g_async_queue_ref (win32_clipdrop->dnd_queue));
  win32_clipdrop->dnd_thread_id = GPOINTER_TO_UINT (g_async_queue_pop (win32_clipdrop->dnd_queue));
}

#define CLIPBOARD_IDLE_ABORT_TIME 30

static const char *
predefined_name (UINT fmt)
{
#define CASE(fmt) case fmt: return #fmt
  switch (fmt)
    {
    CASE (CF_TEXT);
    CASE (CF_BITMAP);
    CASE (CF_METAFILEPICT);
    CASE (CF_SYLK);
    CASE (CF_DIF);
    CASE (CF_TIFF);
    CASE (CF_OEMTEXT);
    CASE (CF_DIB);
    CASE (CF_PALETTE);
    CASE (CF_PENDATA);
    CASE (CF_RIFF);
    CASE (CF_WAVE);
    CASE (CF_UNICODETEXT);
    CASE (CF_ENHMETAFILE);
    CASE (CF_HDROP);
    CASE (CF_LOCALE);
    CASE (CF_DIBV5);
    CASE (CF_MAX);

    CASE (CF_OWNERDISPLAY);
    CASE (CF_DSPTEXT);
    CASE (CF_DSPBITMAP);
    CASE (CF_DSPMETAFILEPICT);
    CASE (CF_DSPENHMETAFILE);
#undef CASE
    default:
      return NULL;
    }
}

char *
_gdk_win32_get_clipboard_format_name (UINT      fmt,
                                      gboolean *is_predefined)
{
  int registered_name_w_len = 1024;
  wchar_t *registered_name_w = g_malloc (registered_name_w_len);
  char *registered_name = NULL;
  int gcfn_result;
  const char *predef = predefined_name (fmt);

  /* TODO: cache the result in a hash table */

  do
    {
      gcfn_result = GetClipboardFormatNameW (fmt, registered_name_w, registered_name_w_len);

      if (gcfn_result > 0 && gcfn_result < registered_name_w_len)
        {
          registered_name = g_utf16_to_utf8 (registered_name_w, -1, NULL, NULL, NULL);
          g_clear_pointer (&registered_name_w, g_free);
          if (!registered_name)
            gcfn_result = 0;
          else
            *is_predefined = FALSE;
          break;
        }

      /* If GetClipboardFormatNameW() used up all the space, it means that
       * we probably need a bigger buffer, but cap this at 1 megabyte.
       */
      if (gcfn_result == 0 || registered_name_w_len > 1024 * 1024)
        {
          gcfn_result = 0;
          g_clear_pointer (&registered_name_w, g_free);
          break;
        }

      registered_name_w_len *= 2;
      registered_name_w = g_realloc (registered_name_w, registered_name_w_len);
      gcfn_result = registered_name_w_len;
    } while (gcfn_result == registered_name_w_len);

  if (registered_name == NULL &&
      predef != NULL)
    {
      registered_name = g_strdup (predef);
      *is_predefined = TRUE;
    }

  return registered_name;
}

/* This turns an arbitrary string into a string that
 * *looks* like a mime/type, such as:
 * "application/x.windows.FOO_BAR" from "FOO_BAR".
 * Does nothing for strings that already look like a mime/type
 * (no spaces, one slash, with at least one char on each side of the slash).
 */
const char *
_gdk_win32_get_clipboard_format_name_as_interned_mimetype (char *w32format_name)
{
  char *mime_type;
  const char *result;
  char *space = strchr (w32format_name, ' ');
  char *slash = strchr (w32format_name, '/');

  if (space == NULL &&
      slash > w32format_name &&
      slash[1] != '\0' &&
      strchr (&slash[1], '/') == NULL)
    return g_intern_string (w32format_name);

  mime_type = g_strdup_printf ("application/x.windows.%s", w32format_name);
  result = g_intern_string (mime_type);
  g_free (mime_type);

  return result;
}

static GArray *
get_compatibility_w32formats_for_contentformat (const char *contentformat)
{
  GArray *result = NULL;
  int i;
  GdkWin32Clipdrop *clipdrop = _gdk_win32_clipdrop_get ();

  result = g_hash_table_lookup (clipdrop->compatibility_w32formats, contentformat);

  if (result != NULL)
    return result;

  for (i = 0; i < clipdrop->n_known_pixbuf_formats; i++)
    {
      if (contentformat != clipdrop->known_pixbuf_formats[i])
        continue;

      /* Any format known to gdk-pixbuf can be presented as PNG or BMP */
      result = g_hash_table_lookup (clipdrop->compatibility_w32formats,
                                    _gdk_win32_clipdrop_atom (GDK_WIN32_ATOM_INDEX_IMAGE_PNG));
      break;
    }

  return result;
}

static GArray *
_gdk_win32_get_compatibility_contentformats_for_w32format (UINT w32format)
{
  GArray *result = NULL;
  GdkWin32Clipdrop *clipdrop = _gdk_win32_clipdrop_get ();

  result = g_hash_table_lookup (clipdrop->compatibility_contentformats, GINT_TO_POINTER (w32format));

  if (result != NULL)
    return result;

  /* TODO: reverse gdk-pixbuf conversion? We have to somehow
   * match gdk-pixbuf format names to the corresponding clipboard
   * format names. The former are known only at runtime,
   * the latter are presently unknown...
   * Maybe try to get the data and then just feed it to gdk-pixbuf,
   * see if it knows what it is?
   */

  return result;
}

/* Turn W32 format into a GDK content format and add it
 * to the array of W32 format <-> GDK content format pairs
 * and/or to a GDK contentformat builder.
 * Also add compatibility GDK content formats for that W32 format.
 * The added content format string is always interned.
 * Ensures that duplicates are not added to the pairs array
 * (builder already takes care of that for itself).
 */
void
_gdk_win32_add_w32format_to_pairs (UINT                      w32format,
                                   GArray                   *pairs,
                                   GdkContentFormatsBuilder *builder)
{
  gboolean predef;
  char *w32format_name = _gdk_win32_get_clipboard_format_name (w32format, &predef);
  const char *interned_w32format_name;
  GdkWin32ContentFormatPair pair;
  GArray *comp_pairs;
  int i, j;

  if (w32format_name != NULL)
    {
      interned_w32format_name = _gdk_win32_get_clipboard_format_name_as_interned_mimetype (w32format_name);
      GDK_NOTE (DND, g_print ("Maybe add as-is format %s (%s) (0x%p)\n", w32format_name, interned_w32format_name, interned_w32format_name));
      g_free (w32format_name);

      if (pairs && interned_w32format_name != 0)
        {
          for (j = 0; j < pairs->len; j++)
            if (g_array_index (pairs, GdkWin32ContentFormatPair, j).contentformat == interned_w32format_name)
              break;
          if (j == pairs->len)
            {
              pair.w32format = w32format;
              pair.contentformat = interned_w32format_name;
              pair.transmute = FALSE;
              g_array_append_val (pairs, pair);
            }
        }
      if (builder != NULL && interned_w32format_name != 0)
        gdk_content_formats_builder_add_mime_type (builder, interned_w32format_name);
    }

  comp_pairs = _gdk_win32_get_compatibility_contentformats_for_w32format (w32format);

 if (pairs != NULL && comp_pairs != NULL)
   for (i = 0; i < comp_pairs->len; i++)
     {
       pair = g_array_index (comp_pairs, GdkWin32ContentFormatPair, i);

       for (j = 0; j < pairs->len; j++)
         if (g_array_index (pairs, GdkWin32ContentFormatPair, j).contentformat == pair.contentformat &&
             g_array_index (pairs, GdkWin32ContentFormatPair, j).w32format == pair.w32format)
           break;

       if (j == pairs->len)
         g_array_append_val (pairs, pair);
     }

 if (builder != NULL && comp_pairs != NULL)
   for (i = 0; i < comp_pairs->len; i++)
     {
       pair = g_array_index (comp_pairs, GdkWin32ContentFormatPair, i);

       gdk_content_formats_builder_add_mime_type (builder, pair.contentformat);
     }
}

static void
transmute_cf_unicodetext_to_utf8_string (const guchar    *data,
                                         int              length,
                                         guchar         **set_data,
                                         gsize           *set_data_length,
                                         GDestroyNotify  *set_data_destroy)
{
  wchar_t *ptr, *p, *q;
  char *result;
  glong wclen, u8_len;

  /* Strip out \r */
  ptr = (wchar_t *) data;
  p = ptr;
  q = ptr;
  wclen = 0;

  while (p < ptr + length / 2)
    {
      if (*p != L'\r')
        {
          *q++ = *p;
          wclen++;
        }
      p++;
    }

  result = g_utf16_to_utf8 (ptr, wclen, NULL, &u8_len, NULL);

  if (result)
    {
      *set_data = (guchar *) result;

      if (set_data_length)
        *set_data_length = u8_len + 1;
      if (set_data_destroy)
        *set_data_destroy = (GDestroyNotify) g_free;
    }
}

static void
transmute_utf8_string_to_cf_unicodetext (const guchar    *data,
                                         int              length,
                                         guchar         **set_data,
                                         gsize           *set_data_length,
                                         GDestroyNotify  *set_data_destroy)
{
  glong wclen;
  GError *err = NULL;
  glong size;
  int i;
  wchar_t *wcptr, *p;

  wcptr = g_utf8_to_utf16 ((char *) data, length, NULL, &wclen, &err);
  if (err != NULL)
    {
      g_warning ("Failed to convert utf8: %s", err->message);
      g_clear_error (&err);
      return;
    }

  wclen++; /* Terminating 0 */
  size = wclen * 2;
  for (i = 0; i < wclen; i++)
    if (wcptr[i] == L'\n' && (i == 0 || wcptr[i - 1] != L'\r'))
      size += 2;

  *set_data = g_malloc0 (size);
  if (set_data_length)
    *set_data_length = size;
  if (set_data_destroy)
    *set_data_destroy = (GDestroyNotify) g_free;

  p = (wchar_t *) *set_data;

  for (i = 0; i < wclen; i++)
    {
      if (wcptr[i] == L'\n' && (i == 0 || wcptr[i - 1] != L'\r'))
	*p++ = L'\r';
      *p++ = wcptr[i];
    }

  g_free (wcptr);
}

static int
wchar_to_str (const wchar_t  *wstr,
              char         **retstr,
              UINT            cp)
{
  char *str;
  int   len;
  int   lenc;

  len = WideCharToMultiByte (cp, 0, wstr, -1, NULL, 0, NULL, NULL);

  if (len <= 0)
    return -1;

  str = g_malloc (sizeof (char) * len);

  lenc = WideCharToMultiByte (cp, 0, wstr, -1, str, len, NULL, NULL);

  if (lenc != len)
    {
      g_free (str);

      return -3;
    }

  *retstr = str;

  return 0;
}

static void
transmute_utf8_string_to_cf_text (const guchar    *data,
                                  int              length,
                                  guchar         **set_data,
                                  gsize           *set_data_length,
                                  GDestroyNotify  *set_data_destroy)
{
  glong rlen;
  GError *err = NULL;
  gsize size;
  int i;
  char *strptr, *p;
  wchar_t *wcptr;

  wcptr = g_utf8_to_utf16 ((char *) data, length, NULL, NULL, &err);
  if (err != NULL)
    {
      g_warning ("Failed to convert utf8: %s", err->message);
      g_clear_error (&err);
      return;
    }

  if (wchar_to_str (wcptr, &strptr, CP_ACP) != 0)
    {
      g_warning ("Failed to convert utf-16 %S to ACP", wcptr);
      g_free (wcptr);
      return;
    }

  rlen = strlen (strptr);
  g_free (wcptr);

  rlen++; /* Terminating 0 */
  size = rlen * sizeof (char);
  for (i = 0; i < rlen; i++)
    if (strptr[i] == '\n' && (i == 0 || strptr[i - 1] != '\r'))
      size += sizeof (char);

  *set_data = g_malloc0 (size);
  if (set_data_length)
    *set_data_length = size;
  if (set_data_destroy)
    *set_data_destroy = (GDestroyNotify) g_free;

  p = (char *) *set_data;

  for (i = 0; i < rlen; i++)
    {
      if (strptr[i] == '\n' && (i == 0 || strptr[i - 1] != '\r'))
	*p++ = '\r';
      *p++ = strptr[i];
    }

  g_free (strptr);
}

static int
str_to_wchar (const char  *str,
              wchar_t    **wretstr,
              UINT         cp)
{
  wchar_t *wstr;
  int      len;
  int      lenc;

  len = MultiByteToWideChar (cp, 0, str, -1, NULL, 0);

  if (len <= 0)
    return -1;

  wstr = g_malloc (sizeof (wchar_t) * len);

  lenc = MultiByteToWideChar (cp, 0, str, -1, wstr, len);

  if (lenc != len)
    {
      g_free (wstr);

      return -3;
    }

  *wretstr = wstr;

  return 0;
}

static void
transmute_cf_text_to_utf8_string (const guchar    *data,
                                  int              length,
                                  guchar         **set_data,
                                  gsize           *set_data_length,
                                  GDestroyNotify  *set_data_destroy)
{
  char *ptr, *p, *q;
  char *result;
  glong wclen, u8_len;
  wchar_t *wstr;

  /* Strip out \r */
  ptr = (char *) data;
  p = ptr;
  q = ptr;
  wclen = 0;

  while (p < ptr + length / 2)
    {
      if (*p != '\r')
        {
          *q++ = *p;
          wclen++;
        }
      p++;
    }

  if (str_to_wchar (ptr, &wstr, CP_ACP) < 0)
    return;

  result = g_utf16_to_utf8 (wstr, -1, NULL, &u8_len, NULL);

  if (result)
    {
      *set_data = (guchar *) result;

      if (set_data_length)
        *set_data_length = u8_len + 1;
      if (set_data_destroy)
        *set_data_destroy = (GDestroyNotify) g_free;
    }

  g_free (wstr);
}

static void
transmute_cf_dib_to_image_bmp (const guchar    *data,
                               int              length,
                               guchar         **set_data,
                               gsize           *set_data_length,
                               GDestroyNotify  *set_data_destroy)
{
  /* Need to add a BMP file header so gdk-pixbuf can load
   * it.
   *
   * If the data is from Mozilla Firefox or IE7, and
   * starts with an "old fashioned" BITMAPINFOHEADER,
   * i.e. with biSize==40, and biCompression == BI_RGB and
   * biBitCount==32, we assume that the "extra" byte in
   * each pixel in fact is alpha.
   *
   * The gdk-pixbuf bmp loader doesn't trust 32-bit BI_RGB
   * bitmaps to in fact have alpha, so we have to convince
   * it by changing the bitmap header to a version 5
   * BI_BITFIELDS one with explicit alpha mask indicated.
   *
   * The RGB bytes that are in bitmaps on the clipboard
   * originating from Firefox or IE7 seem to be
   * premultiplied with alpha. The gdk-pixbuf bmp loader
   * of course doesn't expect that, so we have to undo the
   * premultiplication before feeding the bitmap to the
   * bmp loader.
   *
   * Note that for some reason the bmp loader used to want
   * the alpha bytes in its input to actually be
   * 255-alpha, but here we assume that this has been
   * fixed before this is committed.
   */
  BITMAPINFOHEADER *bi = (BITMAPINFOHEADER *) data;
  BITMAPFILEHEADER *bf;
  gpointer result;
  int data_length = length;
  int new_length;
  gboolean make_dibv5 = FALSE;
  BITMAPV5HEADER *bV5;
  guchar *p;
  guint i;

  if (bi->biSize == sizeof (BITMAPINFOHEADER) &&
      bi->biPlanes == 1 &&
      bi->biBitCount == 32 &&
      bi->biCompression == BI_RGB &&
#if 0
      /* Maybe check explicitly for Mozilla or IE7?
       *
       * If the clipboard format
       * application/x-moz-nativeimage is present, that is
       * a reliable indicator that the data is offered by
       * Mozilla one would think. For IE7,
       * UniformResourceLocatorW is presumably not that
       * uniqie, so probably need to do some
       * GetClipboardOwner(), GetWindowThreadProcessId(),
       * OpenProcess(), GetModuleFileNameEx() dance to
       * check?
       */
      (IsClipboardFormatAvailable
       (RegisterClipboardFormatA ("application/x-moz-nativeimage")) ||
       IsClipboardFormatAvailable
       (RegisterClipboardFormatA ("UniformResourceLocatorW"))) &&
#endif
      TRUE)
    {
      /* We turn the BITMAPINFOHEADER into a
       * BITMAPV5HEADER before feeding it to gdk-pixbuf.
       */
      new_length = (data_length +
		    sizeof (BITMAPFILEHEADER) +
		    (sizeof (BITMAPV5HEADER) - sizeof (BITMAPINFOHEADER)));
      make_dibv5 = TRUE;
    }
  else
    {
      new_length = data_length + sizeof (BITMAPFILEHEADER);
    }

  result = g_try_malloc (new_length);

  if (result == NULL)
    return;

  bf = (BITMAPFILEHEADER *) result;
  bf->bfType = 0x4d42; /* "BM" */
  bf->bfSize = new_length;
  bf->bfReserved1 = 0;
  bf->bfReserved2 = 0;

  *set_data = result;

  if (set_data_length)
    *set_data_length = new_length;
  if (set_data_destroy)
    *set_data_destroy = g_free;

  if (!make_dibv5)
    {
      bf->bfOffBits = (sizeof (BITMAPFILEHEADER) +
		       bi->biSize +
		       bi->biClrUsed * sizeof (RGBQUAD));

      if (bi->biCompression == BI_BITFIELDS && bi->biBitCount >= 16)
        {
          /* Screenshots taken with PrintScreen or
           * Alt + PrintScreen are found on the clipboard in
           * this format. In this case the BITMAPINFOHEADER is
           * followed by three DWORD specifying the masks of the
           * red green and blue components, so adjust the offset
           * accordingly. */
          bf->bfOffBits += (3 * sizeof (DWORD));
        }

      memcpy ((char *) result + sizeof (BITMAPFILEHEADER),
	      bi,
	      data_length);

      return;
    }

  bV5 = (BITMAPV5HEADER *) ((char *) result + sizeof (BITMAPFILEHEADER));

  bV5->bV5Size = sizeof (BITMAPV5HEADER);
  bV5->bV5Width = bi->biWidth;
  bV5->bV5Height = bi->biHeight;
  bV5->bV5Planes = 1;
  bV5->bV5BitCount = 32;
  bV5->bV5Compression = BI_BITFIELDS;
  bV5->bV5SizeImage = 4 * bV5->bV5Width * ABS (bV5->bV5Height);
  bV5->bV5XPelsPerMeter = bi->biXPelsPerMeter;
  bV5->bV5YPelsPerMeter = bi->biYPelsPerMeter;
  bV5->bV5ClrUsed = 0;
  bV5->bV5ClrImportant = 0;
  /* Now the added mask fields */
  bV5->bV5RedMask   = 0x00ff0000;
  bV5->bV5GreenMask = 0x0000ff00;
  bV5->bV5BlueMask  = 0x000000ff;
  bV5->bV5AlphaMask = 0xff000000;
  ((char *) &bV5->bV5CSType)[3] = 's';
  ((char *) &bV5->bV5CSType)[2] = 'R';
  ((char *) &bV5->bV5CSType)[1] = 'G';
  ((char *) &bV5->bV5CSType)[0] = 'B';
  /* Ignore colorspace and profile fields */
  bV5->bV5Intent = LCS_GM_GRAPHICS;
  bV5->bV5Reserved = 0;

  bf->bfOffBits = (sizeof (BITMAPFILEHEADER) +
		   bV5->bV5Size);

  p = ((guchar *) result) + sizeof (BITMAPFILEHEADER) + sizeof (BITMAPV5HEADER);
  memcpy (p, ((char *) bi) + bi->biSize,
          data_length - sizeof (BITMAPINFOHEADER));

  for (i = 0; i < bV5->bV5SizeImage/4; i++)
    {
      if (p[3] != 0)
        {
          double inverse_alpha = 255./p[3];

          p[0] = p[0] * inverse_alpha + 0.5;
          p[1] = p[1] * inverse_alpha + 0.5;
          p[2] = p[2] * inverse_alpha + 0.5;
        }

      p += 4;
    }
}

static void
transmute_cf_shell_id_list_to_text_uri_list (const guchar    *data,
                                             int              length,
                                             guchar         **set_data,
                                             gsize           *set_data_length,
                                             GDestroyNotify  *set_data_destroy)
{
  guint i;
  CIDA *cida = (CIDA *) data;
  guint number_of_ids = cida->cidl;
  GString *result = g_string_new (NULL);
  PCIDLIST_ABSOLUTE folder_id = HIDA_GetPIDLFolder (cida);
  wchar_t path_w[MAX_PATH + 1];

  for (i = 0; i < number_of_ids; i++)
    {
      PCUIDLIST_RELATIVE file_id = HIDA_GetPIDLItem (cida, i);
      PIDLIST_ABSOLUTE file_id_full = ILCombine (folder_id, file_id);

      if (SHGetPathFromIDListW (file_id_full, path_w))
        {
          char *filename = g_utf16_to_utf8 (path_w, -1, NULL, NULL, NULL);

          if (filename)
            {
              char *uri = g_filename_to_uri (filename, NULL, NULL);

              if (uri)
                {
                  g_string_append (result, uri);
                  g_string_append (result, "\r\n");
                  g_free (uri);
                }

              g_free (filename);
            }
        }

      ILFree (file_id_full);
    }

  *set_data = (guchar *) result->str;
  if (set_data_length)
    *set_data_length = result->len;
  if (set_data_destroy)
    *set_data_destroy = g_free;

  g_string_free (result, FALSE);
}

void
transmute_image_bmp_to_cf_dib (const guchar    *data,
                               int              length,
                               guchar         **set_data,
                               gsize           *set_data_length,
                               GDestroyNotify  *set_data_destroy)
{
  int size;
  guchar *ptr;

  g_return_if_fail (length >= sizeof (BITMAPFILEHEADER));

  /* No conversion is needed, just strip the BITMAPFILEHEADER */
  size = length - sizeof (BITMAPFILEHEADER);
  ptr = g_malloc (size);

  memcpy (ptr, data + sizeof (BITMAPFILEHEADER), size);

  *set_data = ptr;

  if (set_data_length)
    *set_data_length = size;
  if (set_data_destroy)
    *set_data_destroy = g_free;
}

gboolean
_gdk_win32_transmute_windows_data (UINT          from_w32format,
                                   const char   *to_contentformat,
                                   HANDLE        hdata,
                                   guchar      **set_data,
                                   gsize        *set_data_length)
{
  const guchar *data;
  SIZE_T        length;

  /* FIXME: error reporting */

  if ((data = GlobalLock (hdata)) == NULL)
    {
      return FALSE;
    }

  length = GlobalSize (hdata);

  if ((to_contentformat == _gdk_win32_clipdrop_atom (GDK_WIN32_ATOM_INDEX_IMAGE_PNG) &&
       from_w32format == _gdk_win32_clipdrop_cf (GDK_WIN32_CF_INDEX_PNG)) ||
      (to_contentformat == _gdk_win32_clipdrop_atom (GDK_WIN32_ATOM_INDEX_IMAGE_JPEG) &&
       from_w32format == _gdk_win32_clipdrop_cf (GDK_WIN32_CF_INDEX_JFIF)) ||
      (to_contentformat == _gdk_win32_clipdrop_atom (GDK_WIN32_ATOM_INDEX_GIF) &&
       from_w32format == _gdk_win32_clipdrop_cf (GDK_WIN32_CF_INDEX_GIF)))
    {
      /* No transmutation needed */
      *set_data = g_memdup (data, length);
      *set_data_length = length;
    }
  else if (to_contentformat == _gdk_win32_clipdrop_atom (GDK_WIN32_ATOM_INDEX_TEXT_PLAIN_UTF8) &&
           from_w32format == CF_UNICODETEXT)
    {
      transmute_cf_unicodetext_to_utf8_string (data, length, set_data, set_data_length, NULL);
    }
  else if (to_contentformat == _gdk_win32_clipdrop_atom (GDK_WIN32_ATOM_INDEX_TEXT_PLAIN_UTF8) &&
           from_w32format == CF_TEXT)
    {
      transmute_cf_text_to_utf8_string (data, length, set_data, set_data_length, NULL);
    }
  else if (to_contentformat == _gdk_win32_clipdrop_atom (GDK_WIN32_ATOM_INDEX_IMAGE_BMP) &&
           (from_w32format == CF_DIB || from_w32format == CF_DIBV5))
    {
      transmute_cf_dib_to_image_bmp (data, length, set_data, set_data_length, NULL);
    }
  else if (to_contentformat == _gdk_win32_clipdrop_atom (GDK_WIN32_ATOM_INDEX_TEXT_URI_LIST) &&
           from_w32format == _gdk_win32_clipdrop_cf (GDK_WIN32_CF_INDEX_CFSTR_SHELLIDLIST))
    {
      transmute_cf_shell_id_list_to_text_uri_list (data, length, set_data, set_data_length, NULL);
    }
  else
    {
      g_warning ("Don't know how to transmute W32 format 0x%x to content format 0x%p (%s)",
                 from_w32format, to_contentformat, to_contentformat);
      return FALSE;
    }

  GlobalUnlock (hdata);

  return TRUE;
}

gboolean
_gdk_win32_transmute_contentformat (const char    *from_contentformat,
                                    UINT           to_w32format,
                                    const guchar  *data,
                                    int            length,
                                    guchar       **set_data,
                                    gsize         *set_data_length)
{
  if ((from_contentformat == _gdk_win32_clipdrop_atom (GDK_WIN32_ATOM_INDEX_IMAGE_PNG) &&
       to_w32format == _gdk_win32_clipdrop_cf (GDK_WIN32_CF_INDEX_PNG)) ||
      (from_contentformat == _gdk_win32_clipdrop_atom (GDK_WIN32_ATOM_INDEX_IMAGE_JPEG) &&
       to_w32format == _gdk_win32_clipdrop_cf (GDK_WIN32_CF_INDEX_JFIF)) ||
      (from_contentformat == _gdk_win32_clipdrop_atom (GDK_WIN32_ATOM_INDEX_GIF) &&
       to_w32format == _gdk_win32_clipdrop_cf (GDK_WIN32_CF_INDEX_GIF)))
    {
      /* No conversion needed */
      *set_data = g_memdup (data, length);
      *set_data_length = length;
    }
  else if (from_contentformat == _gdk_win32_clipdrop_atom (GDK_WIN32_ATOM_INDEX_TEXT_PLAIN_UTF8) &&
           to_w32format == CF_UNICODETEXT)
    {
      transmute_utf8_string_to_cf_unicodetext (data, length, set_data, set_data_length, NULL);
    }
  else if (from_contentformat == _gdk_win32_clipdrop_atom (GDK_WIN32_ATOM_INDEX_TEXT_PLAIN_UTF8) &&
           to_w32format == CF_TEXT)
    {
      transmute_utf8_string_to_cf_text (data, length, set_data, set_data_length, NULL);
    }
  else if (from_contentformat == _gdk_win32_clipdrop_atom (GDK_WIN32_ATOM_INDEX_IMAGE_BMP) &&
           to_w32format == CF_DIB)
    {
      transmute_image_bmp_to_cf_dib (data, length, set_data, set_data_length, NULL);
    }
  else if (from_contentformat == _gdk_win32_clipdrop_atom (GDK_WIN32_ATOM_INDEX_IMAGE_BMP) &&
           to_w32format == CF_DIBV5)
    {
      transmute_image_bmp_to_cf_dib (data, length, set_data, set_data_length, NULL);
    }
/*
  else if (from_contentformat == _gdk_win32_clipdrop_atom (GDK_WIN32_ATOM_INDEX_TEXT_URI_LIST) &&
           to_w32format == _gdk_win32_clipdrop_cf (GDK_WIN32_CF_INDEX_CFSTR_SHELLIDLIST))
    {
      transmute_text_uri_list_to_shell_id_list (data, length, set_data, set_data_length, NULL);
    }
*/
  else
    {
      g_warning ("Don't know how to transmute from target 0x%p to format 0x%x", from_contentformat, to_w32format);

      return FALSE;
    }

  return TRUE;
}

int
_gdk_win32_add_contentformat_to_pairs (const char *contentformat,
                                       GArray     *array)
{
  int added_count = 0;
  wchar_t *contentformat_w;
  GdkWin32ContentFormatPair fmt;
  int i;
  GArray *comp_pairs;
  int starting_point;
  const wchar_t *prefix = L"application/x.windows.";
  size_t prefix_len = wcslen (prefix);
  size_t offset = 0;

  for (i = 0; i < array->len; i++)
    if (g_array_index (array, GdkWin32ContentFormatPair, i).contentformat == contentformat)
      break;

  /* Don't put duplicates into the array */
  if (i < array->len)
    return added_count;

  /* Only check the newly-added pairs for duplicates,
   * all the ones that exist right now have different targets.
   */
  starting_point = array->len;

  contentformat_w = g_utf8_to_utf16 (contentformat, -1, NULL, NULL, NULL);

  if (contentformat_w == NULL)
    return added_count;

  if (wcsnicmp (contentformat_w, prefix, prefix_len) == 0)
    offset = prefix_len;
  else
    offset = 0;

  fmt.w32format = RegisterClipboardFormatW (&contentformat_w[offset]);
  GDK_NOTE (DND, g_print ("Registered clipboard format %S as 0x%x\n", &contentformat_w[offset], fmt.w32format));
  g_free (contentformat_w);
  fmt.contentformat = contentformat;
  fmt.transmute = FALSE;

  /* Add the "as-is" pair */
  g_array_append_val (array, fmt);
  added_count += 1;

  comp_pairs = get_compatibility_w32formats_for_contentformat (contentformat);
  for (i = 0; comp_pairs != NULL && i < comp_pairs->len; i++)
    {
      int j;

      fmt = g_array_index (comp_pairs, GdkWin32ContentFormatPair, i);

      /* Don't put duplicates into the array */
      for (j = starting_point; j < array->len; j++)
        if (g_array_index (array, GdkWin32ContentFormatPair, j).w32format == fmt.w32format)
          break;

      if (j < array->len)
        continue;

      /* Add a compatibility pair */
      g_array_append_val (array, fmt);
      added_count += 1;
    }

  return added_count;
}

void
_gdk_win32_advertise_clipboard_contentformats (GTask             *task,
                                               GdkContentFormats *contentformats)
{
  GdkWin32Clipdrop *clipdrop = _gdk_win32_clipdrop_get ();
  GdkWin32ClipboardThreadAdvertise *adv = g_new0 (GdkWin32ClipboardThreadAdvertise, 1);
  const char * const *mime_types;
  gsize mime_types_len;
  gsize i;

  g_assert (clipdrop->clipboard_window != NULL);

  adv->parent.item_type = GDK_WIN32_CLIPBOARD_THREAD_QUEUE_ITEM_ADVERTISE;
  adv->parent.start_time = g_get_monotonic_time ();
  adv->parent.end_time = adv->parent.start_time + CLIPBOARD_OPERATION_TIMEOUT;
  adv->parent.opaque_task = task;

  if (contentformats == NULL)
    {
      adv->unset = TRUE;
    }
  else
    {
      adv->unset = FALSE;

      adv->pairs = g_array_new (FALSE, FALSE, sizeof (GdkWin32ContentFormatPair));
      mime_types = gdk_content_formats_get_mime_types (contentformats, &mime_types_len);

      for (i = 0; i < mime_types_len; i++)
        _gdk_win32_add_contentformat_to_pairs (mime_types[i], adv->pairs);
    }

  g_async_queue_push (clipdrop->clipboard_open_thread_queue, adv);
  API_CALL (PostMessage, (clipdrop->clipboard_window, thread_wakeup_message, 0, 0));

  return;
}

void
_gdk_win32_retrieve_clipboard_contentformats (GTask             *task,
                                              GdkContentFormats *contentformats)
{
  GdkWin32Clipdrop *clipdrop = _gdk_win32_clipdrop_get ();
  GdkWin32ClipboardThreadRetrieve *retr = g_new0 (GdkWin32ClipboardThreadRetrieve, 1);
  const char * const *mime_types;
  gsize mime_types_len;
  gsize i;

  g_assert (clipdrop->clipboard_window != NULL);

  retr->parent.item_type = GDK_WIN32_CLIPBOARD_THREAD_QUEUE_ITEM_RETRIEVE;
  retr->parent.start_time = g_get_monotonic_time ();
  retr->parent.end_time = retr->parent.start_time + CLIPBOARD_OPERATION_TIMEOUT;
  retr->parent.opaque_task = task;
  retr->pairs = g_array_new (FALSE, FALSE, sizeof (GdkWin32ContentFormatPair));
  retr->sequence_number = GetClipboardSequenceNumber ();

  mime_types = gdk_content_formats_get_mime_types (contentformats, &mime_types_len);

  for (i = 0; i < mime_types_len; i++)
    _gdk_win32_add_contentformat_to_pairs (mime_types[i], retr->pairs);

  g_async_queue_push (clipdrop->clipboard_open_thread_queue, retr);
  API_CALL (PostMessage, (clipdrop->clipboard_window, thread_wakeup_message, 0, 0));

  return;
}

typedef struct _GdkWin32ClipboardHDataPrepAndStream GdkWin32ClipboardHDataPrepAndStream;

struct _GdkWin32ClipboardHDataPrepAndStream
{
  GdkWin32ClipboardStorePrep *prep;
  GdkWin32HDataOutputStream  *stream;
};

static void
clipboard_store_hdata_ready (GObject      *clipboard,
                             GAsyncResult *result,
                             gpointer      user_data)
{
  GError *error = NULL;
  int i;
  gboolean no_other_streams;
  GdkWin32ClipboardHDataPrepAndStream *prep_and_stream = (GdkWin32ClipboardHDataPrepAndStream *) user_data;
  GdkWin32ClipboardStorePrep *prep = prep_and_stream->prep;
  GdkWin32HDataOutputStream  *stream = prep_and_stream->stream;
  GdkWin32ClipboardThreadStore *store;
  GdkWin32Clipdrop *clipdrop;

  g_clear_pointer (&prep_and_stream, g_free);

  if (!gdk_clipboard_write_finish (GDK_CLIPBOARD (clipboard), result, &error))
    {
      HANDLE handle;
      gboolean is_hdata;

      GDK_NOTE(CLIPBOARD, g_printerr ("Failed to write stream: %s\n", error->message));
      g_error_free (error);
      for (i = 0; i < prep->elements->len; i++)
        free_prep_element (&g_array_index (prep->elements, GdkWin32ClipboardStorePrepElement, i));
      g_free (prep);
      g_output_stream_close (G_OUTPUT_STREAM (stream), NULL, NULL);
      handle = gdk_win32_hdata_output_stream_get_handle (stream, &is_hdata);

      if (is_hdata)
        API_CALL (GlobalFree, (handle));
      else
        API_CALL (CloseHandle, (handle));

      g_object_unref (stream);

      return;
    }

  for (i = 0, no_other_streams = TRUE; i < prep->elements->len; i++)
    {
      GdkWin32ClipboardStorePrepElement *el = &g_array_index (prep->elements, GdkWin32ClipboardStorePrepElement, i);

      if (el->stream == G_OUTPUT_STREAM (stream))
        {
          g_output_stream_close (el->stream, NULL, NULL);
          el->handle = gdk_win32_hdata_output_stream_get_handle (GDK_WIN32_HDATA_OUTPUT_STREAM (el->stream), NULL);
          g_object_unref (el->stream);
          el->stream = NULL;
        }
      else if (el->stream != NULL)
        no_other_streams = FALSE;
    }

  if (!no_other_streams)
    return;

  clipdrop = _gdk_win32_clipdrop_get ();

  store = g_new0 (GdkWin32ClipboardThreadStore, 1);

  store->parent.start_time = g_get_monotonic_time ();
  store->parent.end_time = store->parent.start_time + CLIPBOARD_OPERATION_TIMEOUT;
  store->parent.item_type = GDK_WIN32_CLIPBOARD_THREAD_QUEUE_ITEM_STORE;
  store->parent.opaque_task = prep->store_task;
  store->elements = prep->elements;

  g_async_queue_push (clipdrop->clipboard_open_thread_queue, store);
  API_CALL (PostMessage, (clipdrop->clipboard_window, thread_wakeup_message, 0, 0));

  g_free (prep);
}

gboolean
_gdk_win32_store_clipboard_contentformats (GdkClipboard      *cb,
                                           GTask             *task,
                                           GdkContentFormats *contentformats)
{
  GArray *pairs; /* of GdkWin32ContentFormatPair */
  const char * const *mime_types;
  gsize n_mime_types;
  gsize i;
  GdkWin32Clipdrop *clipdrop = _gdk_win32_clipdrop_get ();
  GdkWin32ClipboardStorePrep *prep;

  g_assert (clipdrop->clipboard_window != NULL);

  mime_types = gdk_content_formats_get_mime_types (contentformats, &n_mime_types);

  pairs = g_array_sized_new (FALSE,
                             FALSE,
                             sizeof (GdkWin32ContentFormatPair),
                             n_mime_types);

  for (i = 0; i < n_mime_types; i++)
    _gdk_win32_add_contentformat_to_pairs (mime_types[i], pairs);

  if (pairs->len <= 0)
    {
      g_array_free (pairs, TRUE);

      return FALSE;
    }

  prep = g_new0 (GdkWin32ClipboardStorePrep, 1);
  prep->elements = g_array_sized_new (FALSE, TRUE, sizeof (GdkWin32ClipboardStorePrepElement), pairs->len);
  prep->store_task = task;

  for (i = 0; i < pairs->len; i++)
    {
      GdkWin32ClipboardStorePrepElement el;
      GdkWin32ContentFormatPair *pair = &g_array_index (pairs, GdkWin32ContentFormatPair, i);

      el.stream = gdk_win32_hdata_output_stream_new (pair, NULL);

      if (!el.stream)
        continue;

      el.w32format = pair->w32format;
      el.contentformat = pair->contentformat;
      el.handle = NULL;
      g_array_append_val (prep->elements, el);
    }

  for (i = 0; i < prep->elements->len; i++)
    {
      GdkWin32ClipboardStorePrepElement *el = &g_array_index (prep->elements, GdkWin32ClipboardStorePrepElement, i);
      GdkWin32ClipboardHDataPrepAndStream *prep_and_stream = g_new0 (GdkWin32ClipboardHDataPrepAndStream, 1);
      prep_and_stream->prep = prep;
      prep_and_stream->stream = GDK_WIN32_HDATA_OUTPUT_STREAM (el->stream);

      gdk_clipboard_write_async (GDK_CLIPBOARD (cb),
                                 el->contentformat,
                                 el->stream,
                                 G_PRIORITY_DEFAULT,
                                 NULL,
                                 clipboard_store_hdata_ready,
                                 prep_and_stream);
    }

  g_array_free (pairs, TRUE);

  return TRUE;
}