summaryrefslogtreecommitdiffstats
path: root/gfx/cairo/cairo/src/cairo-win32-surface.c
blob: 2d739559064d7d026668bc48136e1323089e505b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

#ifndef WIN32_LEAN_AND_MEAN
# define WIN32_LEAN_AND_MEAN
#endif
/* We require at least Windows 7 features */
#if !defined(WINVER) || (WINVER < 0x0601)
# define WINVER 0x0601
#endif
#if !defined(_WIN32_WINNT) || (_WIN32_WINNT < 0x0601)
# define _WIN32_WINNT 0x0601
#endif

#include "cairoint.h"

#include "cairo-clip-private.h"
#include "cairo-composite-rectangles-private.h"
#include "cairo-error-private.h"
#include "cairo-paginated-private.h"
#include "cairo-win32-private.h"
#include "cairo-scaled-font-subsets-private.h"
#include "cairo-surface-fallback-private.h"
#include "cairo-surface-clipper-private.h"
#include "cairo-gstate-private.h"
#include "cairo-private.h"
#include <wchar.h>
#include <windows.h>
#include <d3d9.h>

#if defined(__MINGW32__) && !defined(ETO_PDY)
# define ETO_PDY 0x2000
#endif

#undef DEBUG_COMPOSITE

/* for older SDKs */
#ifndef SHADEBLENDCAPS
#define SHADEBLENDCAPS  120
#endif
#ifndef SB_NONE
#define SB_NONE         0x00000000
#endif

#define PELS_72DPI  ((LONG)(72. / 0.0254))

/**
 * SECTION:cairo-win32
 * @Title: Win32 Surfaces
 * @Short_Description: Microsoft Windows surface support
 * @See_Also: #cairo_surface_t
 *
 * The Microsoft Windows surface is used to render cairo graphics to
 * Microsoft Windows windows, bitmaps, and printing device contexts.
 *
 * The surface returned by cairo_win32_printing_surface_create() is of surface
 * type %CAIRO_SURFACE_TYPE_WIN32_PRINTING and is a multi-page vector surface
 * type.
 *
 * The surface returned by the other win32 constructors is of surface type
 * %CAIRO_SURFACE_TYPE_WIN32 and is a raster surface type.
 */

/**
 * CAIRO_HAS_WIN32_SURFACE:
 *
 * Defined if the Microsoft Windows surface backend is available.
 * This macro can be used to conditionally compile backend-specific code.
 */

static const cairo_surface_backend_t cairo_win32_surface_backend;

/**
 * _cairo_win32_print_gdi_error:
 * @context: context string to display along with the error
 *
 * Helper function to dump out a human readable form of the
 * current error code.
 *
 * Return value: A cairo status code for the error code
 **/
cairo_status_t
_cairo_win32_print_gdi_error (const char *context)
{
    void *lpMsgBuf;
    DWORD last_error = GetLastError ();

    if (!FormatMessageW (FORMAT_MESSAGE_ALLOCATE_BUFFER |
			 FORMAT_MESSAGE_FROM_SYSTEM,
			 NULL,
			 last_error,
			 MAKELANGID (LANG_NEUTRAL, SUBLANG_DEFAULT),
			 (LPWSTR) &lpMsgBuf,
			 0, NULL)) {
	fprintf (stderr, "%s: Unknown GDI error", context);
    } else {
	fwprintf (stderr, L"%s: %S", context, (wchar_t *)lpMsgBuf);

	LocalFree (lpMsgBuf);
    }
    fflush(stderr);

    /* We should switch off of last_status, but we'd either return
     * CAIRO_STATUS_NO_MEMORY or CAIRO_STATUS_UNKNOWN_ERROR and there
     * is no CAIRO_STATUS_UNKNOWN_ERROR.
     */

    return _cairo_error (CAIRO_STATUS_NO_MEMORY);
}

uint32_t
_cairo_win32_flags_for_dc (HDC dc)
{
    uint32_t flags = 0;

    if (GetDeviceCaps(dc, TECHNOLOGY) == DT_RASDISPLAY) {
	flags |= CAIRO_WIN32_SURFACE_IS_DISPLAY;

	/* These will always be possible, but the actual GetDeviceCaps
	 * calls will return whether they're accelerated or not.
	 * We may want to use our own (pixman) routines sometimes
	 * if they're eventually faster, but for now have GDI do
	 * everything.
	 */
	flags |= CAIRO_WIN32_SURFACE_CAN_BITBLT;
	flags |= CAIRO_WIN32_SURFACE_CAN_ALPHABLEND;
	flags |= CAIRO_WIN32_SURFACE_CAN_STRETCHBLT;
	flags |= CAIRO_WIN32_SURFACE_CAN_STRETCHDIB;
    } else {
	int cap;

	cap = GetDeviceCaps(dc, SHADEBLENDCAPS);
	if (cap != SB_NONE)
	    flags |= CAIRO_WIN32_SURFACE_CAN_ALPHABLEND;

	cap = GetDeviceCaps(dc, RASTERCAPS);
	if (cap & RC_BITBLT)
	    flags |= CAIRO_WIN32_SURFACE_CAN_BITBLT;
	if (cap & RC_STRETCHBLT)
	    flags |= CAIRO_WIN32_SURFACE_CAN_STRETCHBLT;
	if (cap & RC_STRETCHDIB)
	    flags |= CAIRO_WIN32_SURFACE_CAN_STRETCHDIB;
    }

    return flags;
}

static cairo_status_t
_create_dc_and_bitmap (cairo_win32_surface_t *surface,
		       HDC                    original_dc,
		       cairo_format_t         format,
		       int                    width,
		       int                    height,
		       unsigned char        **bits_out,
		       int                   *rowstride_out)
{
    cairo_status_t status;

    BITMAPINFO *bitmap_info = NULL;
    struct {
	BITMAPINFOHEADER bmiHeader;
	RGBQUAD bmiColors[2];
    } bmi_stack;
    void *bits;

    int num_palette = 0;	/* Quiet GCC */
    int i;

    surface->dc = NULL;
    surface->bitmap = NULL;
    surface->is_dib = FALSE;

    switch (format) {
    default:
    case CAIRO_FORMAT_INVALID:
	return _cairo_error (CAIRO_STATUS_INVALID_FORMAT);
    case CAIRO_FORMAT_ARGB32:
    case CAIRO_FORMAT_RGB24:
	num_palette = 0;
	break;

    case CAIRO_FORMAT_A8:
	num_palette = 256;
	break;

    case CAIRO_FORMAT_A1:
	num_palette = 2;
	break;
    }

    if (num_palette > 2) {
	bitmap_info = _cairo_malloc_ab_plus_c (num_palette, sizeof(RGBQUAD), sizeof(BITMAPINFOHEADER));
	if (!bitmap_info)
	    return _cairo_error (CAIRO_STATUS_NO_MEMORY);
    } else {
	bitmap_info = (BITMAPINFO *)&bmi_stack;
    }

    bitmap_info->bmiHeader.biSize = sizeof (BITMAPINFOHEADER);
    bitmap_info->bmiHeader.biWidth = width == 0 ? 1 : width;
    bitmap_info->bmiHeader.biHeight = height == 0 ? -1 : - height; /* top-down */
    bitmap_info->bmiHeader.biSizeImage = 0;
    bitmap_info->bmiHeader.biXPelsPerMeter = PELS_72DPI; /* unused here */
    bitmap_info->bmiHeader.biYPelsPerMeter = PELS_72DPI; /* unused here */
    bitmap_info->bmiHeader.biPlanes = 1;

    switch (format) {
    /* We can't create real RGB24 bitmaps because something seems to
     * break if we do, especially if we don't set up an image
     * fallback.  It could be a bug with using a 24bpp pixman image
     * (and creating one with masks).  So treat them like 32bpp.
     * Note: This causes problems when using BitBlt/AlphaBlend/etc!
     * see end of file.
     */
    case CAIRO_FORMAT_RGB24:
    case CAIRO_FORMAT_ARGB32:
	bitmap_info->bmiHeader.biBitCount = 32;
	bitmap_info->bmiHeader.biCompression = BI_RGB;
	bitmap_info->bmiHeader.biClrUsed = 0;	/* unused */
	bitmap_info->bmiHeader.biClrImportant = 0;
	break;

    case CAIRO_FORMAT_A8:
	bitmap_info->bmiHeader.biBitCount = 8;
	bitmap_info->bmiHeader.biCompression = BI_RGB;
	bitmap_info->bmiHeader.biClrUsed = 256;
	bitmap_info->bmiHeader.biClrImportant = 0;

	for (i = 0; i < 256; i++) {
	    bitmap_info->bmiColors[i].rgbBlue = i;
	    bitmap_info->bmiColors[i].rgbGreen = i;
	    bitmap_info->bmiColors[i].rgbRed = i;
	    bitmap_info->bmiColors[i].rgbReserved = 0;
	}

	break;

    case CAIRO_FORMAT_A1:
	bitmap_info->bmiHeader.biBitCount = 1;
	bitmap_info->bmiHeader.biCompression = BI_RGB;
	bitmap_info->bmiHeader.biClrUsed = 2;
	bitmap_info->bmiHeader.biClrImportant = 0;

	for (i = 0; i < 2; i++) {
	    bitmap_info->bmiColors[i].rgbBlue = i * 255;
	    bitmap_info->bmiColors[i].rgbGreen = i * 255;
	    bitmap_info->bmiColors[i].rgbRed = i * 255;
	    bitmap_info->bmiColors[i].rgbReserved = 0;
	}

	break;
    }

    surface->dc = CreateCompatibleDC (original_dc);
    if (!surface->dc)
	goto FAIL;

    surface->bitmap = CreateDIBSection (surface->dc,
			                bitmap_info,
			                DIB_RGB_COLORS,
			                &bits,
			                NULL, 0);
    if (!surface->bitmap)
	goto FAIL;

    surface->is_dib = TRUE;

    GdiFlush();

    surface->saved_dc_bitmap = SelectObject (surface->dc,
					     surface->bitmap);
    if (!surface->saved_dc_bitmap)
	goto FAIL;

    if (bitmap_info && num_palette > 2)
	free (bitmap_info);

    if (bits_out)
	*bits_out = bits;

    if (rowstride_out) {
	/* Windows bitmaps are padded to 32-bit (dword) boundaries */
	switch (format) {
	case CAIRO_FORMAT_ARGB32:
	case CAIRO_FORMAT_RGB24:
	    *rowstride_out = 4 * width;
	    break;

	case CAIRO_FORMAT_A8:
	    *rowstride_out = (width + 3) & ~3;
	    break;

	case CAIRO_FORMAT_A1:
	    *rowstride_out = ((width + 31) & ~31) / 8;
	    break;
	}
    }

    surface->flags = _cairo_win32_flags_for_dc (surface->dc);

    return CAIRO_STATUS_SUCCESS;

 FAIL:
    status = _cairo_win32_print_gdi_error ("_create_dc_and_bitmap");

    if (bitmap_info && num_palette > 2)
	free (bitmap_info);

    if (surface->saved_dc_bitmap) {
	SelectObject (surface->dc, surface->saved_dc_bitmap);
	surface->saved_dc_bitmap = NULL;
    }

    if (surface->bitmap) {
	DeleteObject (surface->bitmap);
	surface->bitmap = NULL;
    }

    if (surface->dc) {
 	DeleteDC (surface->dc);
	surface->dc = NULL;
    }

    return status;
}

static cairo_surface_t *
_cairo_win32_surface_create_for_dc (HDC             original_dc,
				    cairo_format_t  format,
				    int	            width,
				    int	            height)
{
    cairo_status_t status;
    cairo_win32_surface_t *surface;
    unsigned char *bits;
    int rowstride;

    if (! CAIRO_FORMAT_VALID (format))
	return _cairo_surface_create_in_error (_cairo_error (CAIRO_STATUS_INVALID_FORMAT));

    surface = malloc (sizeof (cairo_win32_surface_t));
    if (surface == NULL)
	return _cairo_surface_create_in_error (_cairo_error (CAIRO_STATUS_NO_MEMORY));

    surface->clip_region = NULL;

    status = _create_dc_and_bitmap (surface, original_dc, format,
				    width, height,
				    &bits, &rowstride);
    if (status)
	goto FAIL;

    surface->image = cairo_image_surface_create_for_data (bits, format,
							  width, height, rowstride);
    status = surface->image->status;
    if (status)
	goto FAIL;

    surface->format = format;
    surface->d3d9surface = NULL;

    surface->clip_rect.x = 0;
    surface->clip_rect.y = 0;
    surface->clip_rect.width = width;
    surface->clip_rect.height = height;

    surface->initial_clip_rgn = NULL;
    surface->had_simple_clip = FALSE;

    surface->extents = surface->clip_rect;
    surface->font_subsets = NULL;

    _cairo_surface_init (&surface->base,
			 &cairo_win32_surface_backend,
			 NULL, /* device */
			 _cairo_content_from_format (format));

    return &surface->base;

 FAIL:
    if (surface->bitmap) {
	SelectObject (surface->dc, surface->saved_dc_bitmap);
	DeleteObject (surface->bitmap);
	DeleteDC (surface->dc);
    }
    free (surface);

    return _cairo_surface_create_in_error (status);
}

static cairo_surface_t *
_cairo_win32_surface_create_similar_internal (void	    *abstract_src,
					      cairo_content_t content,
					      int	     width,
					      int	     height,
					      cairo_bool_t   force_dib)
{
    cairo_win32_surface_t *src = abstract_src;
    cairo_format_t format = _cairo_format_from_content (content);
    cairo_surface_t *new_surf = NULL;

    /* We force a DIB always if:
     * - we need alpha; or
     * - the parent is a DIB; or
     * - the parent is for printing (because we don't care about the bit depth at that point)
     *
     * We also might end up with a DIB even if a DDB is requested if DDB creation failed
     * due to out of memory.
     */
    if (src->is_dib ||
	(content & CAIRO_CONTENT_ALPHA) ||
	src->base.backend->type == CAIRO_SURFACE_TYPE_WIN32_PRINTING)
    {
	force_dib = TRUE;
    }

    if (!force_dib) {
	/* try to create a ddb */
	new_surf = cairo_win32_surface_create_with_ddb (src->dc, CAIRO_FORMAT_RGB24, width, height);

	if (new_surf->status != CAIRO_STATUS_SUCCESS)
	    new_surf = NULL;
    }

    if (new_surf == NULL) {
	new_surf = _cairo_win32_surface_create_for_dc (src->dc, format, width, height);
    }

    return new_surf;
}

cairo_surface_t *
_cairo_win32_surface_create_similar (void	    *abstract_src,
				     cairo_content_t content,
				     int	     width,
				     int	     height)
{
    return _cairo_win32_surface_create_similar_internal (abstract_src, content, width, height, FALSE);
}

cairo_status_t
_cairo_win32_surface_finish (void *abstract_surface)
{
    cairo_win32_surface_t *surface = abstract_surface;

    if (surface->image)
	cairo_surface_destroy (surface->image);

    /* If we created the Bitmap and DC, destroy them */
    if (surface->bitmap) {
	SelectObject (surface->dc, surface->saved_dc_bitmap);
	DeleteObject (surface->bitmap);
	DeleteDC (surface->dc);
    } else {
	_cairo_win32_restore_initial_clip (surface);
    }

    if (surface->d3d9surface) {
        IDirect3DSurface9_ReleaseDC (surface->d3d9surface, surface->dc);
        IDirect3DSurface9_Release (surface->d3d9surface);
    }

    if (surface->initial_clip_rgn)
	DeleteObject (surface->initial_clip_rgn);

    if (surface->font_subsets != NULL)
	_cairo_scaled_font_subsets_destroy (surface->font_subsets);

    return CAIRO_STATUS_SUCCESS;
}

static void
get_d3d9_dc_and_clear_clip (cairo_win32_surface_t *surface)
{
    IDirect3DSurface9_GetDC (surface->d3d9surface, &surface->dc);
    // The DC that we get back from the surface will not have
    // a clip so clear surface->clip_region so that we don't think we have
    // one when we don't.
    _cairo_win32_surface_set_clip_region (surface, NULL);
}

static cairo_status_t
_cairo_win32_surface_d3d9_lock_rect (cairo_win32_surface_t  *surface,
				   int                     x,
				   int                     y,
				   int                     width,
				   int                     height,
				   cairo_image_surface_t **local_out)
{
    cairo_image_surface_t *local;
    cairo_int_status_t status;

    RECT rectin = { x, y, x+width, y+height };
    D3DLOCKED_RECT rectout;
    HRESULT hr;
    hr = IDirect3DSurface9_ReleaseDC (surface->d3d9surface, surface->dc);
    hr = IDirect3DSurface9_LockRect (surface->d3d9surface,
	                             &rectout, &rectin, 0);
    surface->dc = 0; // Don't use the DC when this is locked!
    if (hr) {
	get_d3d9_dc_and_clear_clip (surface);
        return CAIRO_INT_STATUS_UNSUPPORTED;
    }
    local = cairo_image_surface_create_for_data (rectout.pBits,
	                                         surface->format,
						 width, height,
						 rectout.Pitch);
    if (local == NULL) {
	IDirect3DSurface9_UnlockRect (surface->d3d9surface);
	get_d3d9_dc_and_clear_clip (surface);
        return CAIRO_INT_STATUS_UNSUPPORTED;
    }
    if (local->base.status) {
	IDirect3DSurface9_UnlockRect (surface->d3d9surface);
	get_d3d9_dc_and_clear_clip (surface);
        return local->base.status;
    }

    *local_out = local;

    return CAIRO_STATUS_SUCCESS;
}

static cairo_status_t
_cairo_win32_surface_get_subimage (cairo_win32_surface_t  *surface,
				   int                     x,
				   int                     y,
				   int                     width,
				   int                     height,
				   cairo_win32_surface_t **local_out)
{
    cairo_win32_surface_t *local;
    cairo_int_status_t status;
    cairo_content_t content = _cairo_content_from_format (surface->format);

    local =
	(cairo_win32_surface_t *) _cairo_win32_surface_create_similar_internal
	(surface, content, width, height, TRUE);
    if (local == NULL)
	return CAIRO_INT_STATUS_UNSUPPORTED;
    if (local->base.status)
	return local->base.status;

    status = CAIRO_INT_STATUS_UNSUPPORTED;

    /* Only BitBlt if the source surface supports it. */
    if ((surface->flags & CAIRO_WIN32_SURFACE_CAN_BITBLT) &&
	BitBlt (local->dc,
		0, 0,
		width, height,
		surface->dc,
		x, y,
		SRCCOPY))
    {
	status = CAIRO_STATUS_SUCCESS;
    }

    if (status) {
	/* If we failed here, most likely the source or dest doesn't
	 * support BitBlt/AlphaBlend (e.g. a printer).
	 * You can't reliably get bits from a printer DC, so just fill in
	 * the surface as white (common case for printing).
	 */

	RECT r;
	r.left = r.top = 0;
	r.right = width;
	r.bottom = height;
	FillRect(local->dc, &r, (HBRUSH)GetStockObject(WHITE_BRUSH));
    }

    *local_out = local;

    return CAIRO_STATUS_SUCCESS;
}

static void
_cairo_win32_convert_ddb_to_dib (cairo_win32_surface_t *surface)
{
    cairo_win32_surface_t *new_surface;
    int width  = surface->extents.width  + surface->extents.x;
    int height = surface->extents.height + surface->extents.y;

    BOOL ok;
    HBITMAP oldbitmap;

    new_surface = (cairo_win32_surface_t*)
	_cairo_win32_surface_create_for_dc (surface->dc,
					    surface->format,
					    width,
					    height);

    if (new_surface->base.status)
	return;

    /* DDB can't be 32bpp, so BitBlt is safe */
    ok = BitBlt (new_surface->dc,
		 0, 0, width, height,
		 surface->dc,
		 0, 0, SRCCOPY);

    if (!ok)
	goto out;

    /* Now swap around new_surface and surface's internal bitmap
     * pointers. */
    DeleteDC (new_surface->dc);
    new_surface->dc = NULL;

    oldbitmap = SelectObject (surface->dc, new_surface->bitmap);
    DeleteObject (oldbitmap);

    surface->image = new_surface->image;
    surface->is_dib = new_surface->is_dib;
    surface->bitmap = new_surface->bitmap;

    new_surface->bitmap = NULL;
    new_surface->image = NULL;

    /* Finally update flags */
    surface->flags = _cairo_win32_flags_for_dc (surface->dc);

  out:
    cairo_surface_destroy ((cairo_surface_t*)new_surface);
}

static cairo_status_t
_cairo_win32_surface_acquire_source_image (void                    *abstract_surface,
					   cairo_image_surface_t  **image_out,
					   void                   **image_extra)
{
    cairo_win32_surface_t *surface = abstract_surface;
    cairo_status_t status;

    if (!surface->image && !surface->is_dib && surface->bitmap &&
	(surface->flags & CAIRO_WIN32_SURFACE_CAN_CONVERT_TO_DIB) != 0)
    {
	/* This is a DDB, and we're being asked to use it as a source for
	 * something that we couldn't support natively.  So turn it into
	 * a DIB, so that we have an equivalent image surface, as long
	 * as we're allowed to via flags.
	 */
	_cairo_win32_convert_ddb_to_dib (surface);
    }

    if (surface->image) {
	*image_out = (cairo_image_surface_t *)surface->image;
	*image_extra = NULL;
	return CAIRO_STATUS_SUCCESS;
    }

    if (surface->d3d9surface) {
	cairo_image_surface_t *local;
	status = _cairo_win32_surface_d3d9_lock_rect (abstract_surface, 0, 0,
						      surface->extents.width,
						      surface->extents.height, &local);
	if (status)
	    return status;

	*image_out = local;
	*image_extra = surface;
    } else {
	cairo_win32_surface_t *local;
	status = _cairo_win32_surface_get_subimage (abstract_surface, 0, 0,
						    surface->extents.width,
						    surface->extents.height, &local);
	if (status)
	    return status;

	*image_out = (cairo_image_surface_t *)local->image;
	*image_extra = local;
    }
    // image_extra is always of type cairo_win32_surface_t. For d3d9surface it points
    // to the original surface to get back the d3d9surface and properly unlock.

    return CAIRO_STATUS_SUCCESS;
}

static void
_cairo_win32_surface_release_source_image (void                   *abstract_surface,
					   cairo_image_surface_t  *image,
					   void                   *image_extra)
{
    cairo_win32_surface_t *surface = abstract_surface;
    cairo_win32_surface_t *local = image_extra;

    if (local && local->d3d9surface) {
	IDirect3DSurface9_UnlockRect (local->d3d9surface);
	get_d3d9_dc_and_clear_clip (surface);
	cairo_surface_destroy ((cairo_surface_t *)image);
    } else {
	cairo_surface_destroy ((cairo_surface_t *)local);
    }
}

static cairo_status_t
_cairo_win32_surface_acquire_dest_image (void                    *abstract_surface,
					 cairo_rectangle_int_t   *interest_rect,
					 cairo_image_surface_t  **image_out,
					 cairo_rectangle_int_t   *image_rect,
					 void                   **image_extra)
{
    cairo_win32_surface_t *surface = abstract_surface;
    cairo_status_t status;

    if (surface->image) {
	GdiFlush();

	*image_out = (cairo_image_surface_t *) surface->image;
	*image_extra = NULL;
	*image_rect = surface->extents;
	return CAIRO_STATUS_SUCCESS;
    }

    if (surface->d3d9surface) {
	cairo_image_surface_t *local = NULL;
	status = _cairo_win32_surface_d3d9_lock_rect (abstract_surface,
						interest_rect->x,
						interest_rect->y,
						interest_rect->width,
						interest_rect->height, &local);

	if (status)
	    return status;

	*image_out = local;
	*image_extra = surface;
    } else {
	cairo_win32_surface_t *local = NULL;
	status = _cairo_win32_surface_get_subimage (abstract_surface,
						interest_rect->x,
						interest_rect->y,
						interest_rect->width,
						interest_rect->height, &local);

	if (status)
	    return status;

	*image_out = (cairo_image_surface_t *) local->image;
	*image_extra = local;
    }
    // image_extra is always of type cairo_win32_surface_t. For d3d9surface it points
    // to the original surface to get back the d3d9surface and properly unlock.

    *image_rect = *interest_rect;
    return CAIRO_STATUS_SUCCESS;
}

static void
_cairo_win32_surface_release_dest_image (void                    *abstract_surface,
					 cairo_rectangle_int_t   *interest_rect,
					 cairo_image_surface_t   *image,
					 cairo_rectangle_int_t   *image_rect,
					 void                    *image_extra)
{
    cairo_win32_surface_t *surface = abstract_surface;
    cairo_win32_surface_t *local = image_extra;

    if (!local)
	return;

    if (local->d3d9surface) {
	IDirect3DSurface9_UnlockRect (local->d3d9surface);
	get_d3d9_dc_and_clear_clip (surface);
	cairo_surface_destroy ((cairo_surface_t *)image);
    } else {

	/* clear any clip that's currently set on the surface
	   so that we can blit uninhibited. */
	_cairo_win32_surface_set_clip_region (surface, NULL);

	if (!BitBlt (surface->dc,
		     image_rect->x, image_rect->y,
		     image_rect->width, image_rect->height,
		     local->dc,
		     0, 0,
		     SRCCOPY))
	    _cairo_win32_print_gdi_error ("_cairo_win32_surface_release_dest_image");

	cairo_surface_destroy ((cairo_surface_t *)local);
    }

}

cairo_status_t
_cairo_win32_surface_set_clip_region (void           *abstract_surface,
				      cairo_region_t *region)
{
    cairo_win32_surface_t *surface = abstract_surface;
    cairo_status_t status = CAIRO_STATUS_SUCCESS;

    if (surface->clip_region == region)
	return CAIRO_STATUS_SUCCESS;

    cairo_region_destroy (surface->clip_region);
    surface->clip_region = cairo_region_reference (region);

    /* The semantics we want is that any clip set by cairo combines
     * is intersected with the clip on device context that the
     * surface was created for. To implement this, we need to
     * save the original clip when first setting a clip on surface.
     */

    /* Clear any clip set by cairo, return to the original first */
    status = _cairo_win32_restore_initial_clip (surface);

    /* Then combine any new region with it */
    if (region) {
	cairo_rectangle_int_t extents;
	int num_rects;
	RGNDATA *data;
	size_t data_size;
	RECT *rects;
	int i;
	HRGN gdi_region;

	/* Create a GDI region for the cairo region */

	cairo_region_get_extents (region, &extents);
	num_rects = cairo_region_num_rectangles (region);
	/* XXX see notes in _cairo_win32_save_initial_clip --
	 * this code will interact badly with a HDC which had an initial
	 * world transform -- we should probably manually transform the
	 * region rects, because SelectClipRgn takes device units, not
	 * logical units (unlike IntersectClipRect).
	 */

	data_size = sizeof (RGNDATAHEADER) + num_rects * sizeof (RECT);
	data = malloc (data_size);
	if (!data)
	    return _cairo_error(CAIRO_STATUS_NO_MEMORY);
	rects = (RECT *)data->Buffer;

	data->rdh.dwSize = sizeof (RGNDATAHEADER);
	data->rdh.iType = RDH_RECTANGLES;
	data->rdh.nCount = num_rects;
	data->rdh.nRgnSize = num_rects * sizeof (RECT);
	data->rdh.rcBound.left = extents.x;
	data->rdh.rcBound.top = extents.y;
	data->rdh.rcBound.right = extents.x + extents.width;
	data->rdh.rcBound.bottom = extents.y + extents.height;

	for (i = 0; i < num_rects; i++) {
	    cairo_rectangle_int_t rect;

	    cairo_region_get_rectangle (region, i, &rect);

	    rects[i].left   = rect.x;
	    rects[i].top    = rect.y;
	    rects[i].right  = rect.x + rect.width;
	    rects[i].bottom = rect.y + rect.height;
	}

	gdi_region = ExtCreateRegion (NULL, data_size, data);
	free (data);

	if (!gdi_region)
	    return _cairo_error (CAIRO_STATUS_NO_MEMORY);

	/* AND the new region into our DC */
	if (ExtSelectClipRgn (surface->dc, gdi_region, RGN_AND) == ERROR)
	    status = _cairo_win32_print_gdi_error ("_cairo_win32_surface_set_clip_region");

	DeleteObject (gdi_region);
    }

    return status;
}

#if !defined(AC_SRC_OVER)
#define AC_SRC_OVER                 0x00
#pragma pack(1)
typedef struct {
    BYTE   BlendOp;
    BYTE   BlendFlags;
    BYTE   SourceConstantAlpha;
    BYTE   AlphaFormat;
}BLENDFUNCTION;
#pragma pack()
#endif

/* for compatibility with VC++ 6 */
#ifndef AC_SRC_ALPHA
#define AC_SRC_ALPHA                0x01
#endif

typedef BOOL (WINAPI *cairo_alpha_blend_func_t) (HDC hdcDest,
						 int nXOriginDest,
						 int nYOriginDest,
						 int nWidthDest,
						 int hHeightDest,
						 HDC hdcSrc,
						 int nXOriginSrc,
						 int nYOriginSrc,
						 int nWidthSrc,
						 int nHeightSrc,
						 BLENDFUNCTION blendFunction);

static cairo_int_status_t
_composite_alpha_blend (cairo_win32_surface_t *dst,
			cairo_win32_surface_t *src,
			int                    alpha,
			int                    src_x,
			int                    src_y,
			int                    src_w,
			int                    src_h,
			int                    dst_x,
			int                    dst_y,
			int                    dst_w,
			int                    dst_h)
{
    static unsigned alpha_blend_checked = FALSE;
    static cairo_alpha_blend_func_t alpha_blend = NULL;

    BLENDFUNCTION blend_function;

    /* Check for AlphaBlend dynamically */
    if (!alpha_blend_checked) {
	    HMODULE msimg32_dll = LoadLibraryW (L"msimg32");

	    if (msimg32_dll != NULL)
		alpha_blend = (cairo_alpha_blend_func_t)GetProcAddress (msimg32_dll,
									"AlphaBlend");
		alpha_blend_checked = TRUE;
    }

    if (alpha_blend == NULL)
	return CAIRO_INT_STATUS_UNSUPPORTED;
    if (!(dst->flags & CAIRO_WIN32_SURFACE_CAN_ALPHABLEND))
	return CAIRO_INT_STATUS_UNSUPPORTED;
    if (src->format == CAIRO_FORMAT_RGB24 && dst->format == CAIRO_FORMAT_ARGB32)
	return CAIRO_INT_STATUS_UNSUPPORTED;

    blend_function.BlendOp = AC_SRC_OVER;
    blend_function.BlendFlags = 0;
    blend_function.SourceConstantAlpha = alpha;
    blend_function.AlphaFormat = (src->format == CAIRO_FORMAT_ARGB32) ? AC_SRC_ALPHA : 0;

    if (!alpha_blend (dst->dc,
		      dst_x, dst_y,
		      dst_w, dst_h,
		      src->dc,
		      src_x, src_y,
		      src_w, src_h,
		      blend_function))
	return _cairo_win32_print_gdi_error ("_cairo_win32_surface_composite(AlphaBlend)");

    return CAIRO_STATUS_SUCCESS;
}

/* makes the alpha channel in a RGB24 surface 0xff */
static void
make_opaque (cairo_image_surface_t *image, cairo_rectangle_int_t src_r)
{
    int x; int y;
    for (y = 0; y < src_r.height; y++) {
        for (x = 0; x < src_r.width; x++) {
            image->data[(src_r.y + y) * image->stride + (src_r.x + x)*4 + 3] = 0xff;
        }
    }
}

static cairo_int_status_t
_cairo_win32_surface_composite_inner (cairo_win32_surface_t *src,
				      cairo_image_surface_t *src_image,
				      cairo_win32_surface_t *dst,
				      cairo_rectangle_int_t src_extents,
				      cairo_rectangle_int_t src_r,
				      cairo_rectangle_int_t dst_r,
				      int alpha,
				      cairo_bool_t needs_alpha,
				      cairo_bool_t needs_scale)
{
    /* Then do BitBlt, StretchDIBits, StretchBlt, AlphaBlend, or MaskBlt */
    if (src_image) {
	if (needs_alpha || needs_scale)
	    return CAIRO_INT_STATUS_UNSUPPORTED;

	if (dst->flags & CAIRO_WIN32_SURFACE_CAN_STRETCHBLT) {
	    BITMAPINFO bi;
	    bi.bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
	    bi.bmiHeader.biWidth = src_image->width;
	    bi.bmiHeader.biHeight = - src_image->height;
	    bi.bmiHeader.biSizeImage = 0;
	    bi.bmiHeader.biXPelsPerMeter = PELS_72DPI;
	    bi.bmiHeader.biYPelsPerMeter = PELS_72DPI;
	    bi.bmiHeader.biPlanes = 1;
	    bi.bmiHeader.biBitCount = 32;
	    bi.bmiHeader.biCompression = BI_RGB;
	    bi.bmiHeader.biClrUsed = 0;
	    bi.bmiHeader.biClrImportant = 0;

	    /* StretchDIBits is broken with top-down dibs; you need to do some
	     * special munging to make the coordinate space work (basically,
	     * need to address everything based on the bottom left, instead of top left,
	     * and need to tell it to flip the resulting image.
	     *
	     * See http://blog.vlad1.com/archives/2006/10/26/134/ and comments.
	     */
	    if (!StretchDIBits (dst->dc,
				/* dst x,y,w,h */
				dst_r.x, dst_r.y + dst_r.height - 1,
				dst_r.width, - (int) dst_r.height,
				/* src x,y,w,h */
				src_r.x, src_extents.height - src_r.y + 1,
				src_r.width, - (int) src_r.height,
				src_image->data,
				&bi,
				DIB_RGB_COLORS,
				SRCCOPY))
		return _cairo_win32_print_gdi_error ("_cairo_win32_surface_composite(StretchDIBits)");
	}
    } else if (!needs_alpha) {
	if (src->format == CAIRO_FORMAT_RGB24 && dst->format == CAIRO_FORMAT_ARGB32) {
	    /* Because we store RGB24 & ARGB32 in the same way GDI has no way
	     * to ignore the alpha channel from a RGB24 source. Therefore, we set
	     * the alpha channel in our RGB24 source to opaque so that we can treat
	     * it like ARGB32. */
	    GdiFlush();
	    make_opaque(src->image, src_r);
	}
	/* BitBlt or StretchBlt? */
	if (!needs_scale && (dst->flags & CAIRO_WIN32_SURFACE_CAN_BITBLT)) {
            if (!BitBlt (dst->dc,
			 dst_r.x, dst_r.y,
			 dst_r.width, dst_r.height,
			 src->dc,
			 src_r.x, src_r.y,
			 SRCCOPY))
		return _cairo_win32_print_gdi_error ("_cairo_win32_surface_composite(BitBlt)");
	} else if (dst->flags & CAIRO_WIN32_SURFACE_CAN_STRETCHBLT) {
	    /* StretchBlt? */
	    /* XXX check if we want HALFTONE, based on the src filter */
	    BOOL success;
	    int oldmode = SetStretchBltMode(dst->dc, HALFTONE);
	    success = StretchBlt(dst->dc,
				 dst_r.x, dst_r.y,
				 dst_r.width, dst_r.height,
				 src->dc,
				 src_r.x, src_r.y,
				 src_r.width, src_r.height,
				 SRCCOPY);
	    SetStretchBltMode(dst->dc, oldmode);

	    if (!success)
		return _cairo_win32_print_gdi_error ("StretchBlt");
	}
    } else if (needs_alpha && !needs_scale) {
	RECT r = {0, 0, 5000, 5000};
        //FillRect(dst->dc, &r, GetStockObject(DKGRAY_BRUSH));
  	return _composite_alpha_blend (dst, src, alpha,
				       src_r.x, src_r.y, src_r.width, src_r.height,
				       dst_r.x, dst_r.y, dst_r.width, dst_r.height);
    }

    return CAIRO_STATUS_SUCCESS;
}

/* from pixman-private.h */
#define MOD(a,b) ((a) < 0 ? ((b) - ((-(a) - 1) % (b))) - 1 : (a) % (b))

static cairo_int_status_t
_cairo_win32_surface_composite (cairo_operator_t	op,
				const cairo_pattern_t	*pattern,
				const cairo_pattern_t	*mask_pattern,
				void			*abstract_dst,
				int			src_x,
				int			src_y,
				int			mask_x,
				int			mask_y,
				int			dst_x,
				int			dst_y,
				unsigned int		width,
				unsigned int		height,
				cairo_region_t	       *clip_region)
{
    cairo_win32_surface_t *dst = abstract_dst;
    cairo_win32_surface_t *src;
    cairo_surface_pattern_t *src_surface_pattern;
    int alpha;
    double scalex, scaley;
    cairo_fixed_t x0_fixed, y0_fixed;
    cairo_int_status_t status;

    cairo_bool_t needs_alpha, needs_scale, needs_repeat, needs_pad;
    cairo_image_surface_t *src_image = NULL;

    cairo_format_t src_format;
    cairo_rectangle_int_t src_extents;

    cairo_rectangle_int_t src_r = { src_x, src_y, width, height };
    cairo_rectangle_int_t dst_r = { dst_x, dst_y, width, height };

#ifdef DEBUG_COMPOSITE
    fprintf (stderr, "+++ composite: %d %p %p %p [%d %d] [%d %d] [%d %d] %dx%d\n",
	     op, pattern, mask_pattern, abstract_dst, src_x, src_y, mask_x, mask_y, dst_x, dst_y, width, height);
#endif

    /* If the destination can't do any of these, then
     * we may as well give up, since this is what we'll
     * look to for optimization.
     */
    if ((dst->flags & (CAIRO_WIN32_SURFACE_CAN_BITBLT |
		       CAIRO_WIN32_SURFACE_CAN_ALPHABLEND |
		       CAIRO_WIN32_SURFACE_CAN_STRETCHBLT |
		       CAIRO_WIN32_SURFACE_CAN_STRETCHDIB))
	== 0)
    {
	goto UNSUPPORTED;
    }

    if (pattern->type != CAIRO_PATTERN_TYPE_SURFACE)
	goto UNSUPPORTED;

    if (pattern->extend != CAIRO_EXTEND_NONE &&
	pattern->extend != CAIRO_EXTEND_REPEAT &&
	pattern->extend != CAIRO_EXTEND_PAD)
	goto UNSUPPORTED;

    if (mask_pattern) {
	/* FIXME: When we fully support RENDER style 4-channel
	 * masks we need to check r/g/b != 1.0.
	 */
	if (mask_pattern->type != CAIRO_PATTERN_TYPE_SOLID)
	    return CAIRO_INT_STATUS_UNSUPPORTED;

	alpha = ((cairo_solid_pattern_t *)mask_pattern)->color.alpha_short >> 8;
    } else {
	alpha = 255;
    }

    src_surface_pattern = (cairo_surface_pattern_t *)pattern;
    src = (cairo_win32_surface_t *)src_surface_pattern->surface;

    if (src->base.type == CAIRO_SURFACE_TYPE_IMAGE &&
	dst->flags & (CAIRO_WIN32_SURFACE_CAN_STRETCHDIB))
    {
	/* In some very limited cases, we can use StretchDIBits to draw
	 * an image surface directly:
	 *  - source is CAIRO_FORMAT_ARGB32
	 *  - dest is CAIRO_FORMAT_ARGB32
	 *  - alpha is 255
	 *  - operator is SOURCE or OVER
	 *  - image stride is 4*width
	 */
	src_image = (cairo_image_surface_t*) src;

	if (src_image->format != CAIRO_FORMAT_RGB24 ||
	    dst->format != CAIRO_FORMAT_RGB24 ||
	    alpha != 255 ||
	    (op != CAIRO_OPERATOR_SOURCE && op != CAIRO_OPERATOR_OVER) ||
	    src_image->stride != (src_image->width * 4))
	{
	    goto UNSUPPORTED;
	}

	src_format = src_image->format;
	src_extents.x = 0;
	src_extents.y = 0;
	src_extents.width = src_image->width;
	src_extents.height = src_image->height;
    } else if (src->base.backend != dst->base.backend) {
	goto UNSUPPORTED;
    } else {
	src_format = src->format;
	src_extents = src->extents;
    }


#ifdef DEBUG_COMPOSITE
    fprintf (stderr, "Before check: src size: (%d %d) xy [%d %d] -> dst [%d %d %d %d] {srcmat %f %f %f %f}\n",
	     src_extents.width, src_extents.height,
	     src_x, src_y,
	     dst_x, dst_y, width, height,
	     pattern->matrix.x0, pattern->matrix.y0, pattern->matrix.xx, pattern->matrix.yy);
#endif

    /* We can only use GDI functions if the source and destination rectangles
     * are on integer pixel boundaries.  Figure that out here.
     */
    x0_fixed = _cairo_fixed_from_double(pattern->matrix.x0 / pattern->matrix.xx);
    y0_fixed = _cairo_fixed_from_double(pattern->matrix.y0 / pattern->matrix.yy);

    if (pattern->matrix.yx != 0.0 ||
	pattern->matrix.xy != 0.0 ||
	!_cairo_fixed_is_integer(x0_fixed) ||
	!_cairo_fixed_is_integer(y0_fixed))
    {
	goto UNSUPPORTED;
    }

    scalex = pattern->matrix.xx;
    scaley = pattern->matrix.yy;

    src_r.x += _cairo_fixed_integer_part(x0_fixed);
    src_r.y += _cairo_fixed_integer_part(y0_fixed);

    /* Success, right? */
    if (scalex == 0.0 || scaley == 0.0)
	return CAIRO_STATUS_SUCCESS;

    if (scalex != 1.0 || scaley != 1.0)
	goto UNSUPPORTED;

    /* If the src coordinates are outside of the source surface bounds,
     * we have to fix them up, because this is an error for the GDI
     * functions.
     */

#ifdef DEBUG_COMPOSITE
    fprintf (stderr, "before: [%d %d %d %d] -> [%d %d %d %d]\n",
	     src_r.x, src_r.y, src_r.width, src_r.height,
	     dst_r.x, dst_r.y, dst_r.width, dst_r.height);
    fflush (stderr);
#endif

    /* If the src rectangle doesn't wholly lie within the src extents,
     * fudge things.  We really need to do fixup on the unpainted
     * region -- e.g. the SOURCE operator is broken for areas outside
     * of the extents, because it won't clear that area to transparent
     * black.
     */

    needs_pad = FALSE;
    if (pattern->extend != CAIRO_EXTEND_REPEAT) {
	needs_repeat = FALSE;

	/* If the src rect and the extents of the source image don't overlap at all,
	 * we can't do anything useful here.
	 */
	if (src_r.x > src_extents.width || src_r.y > src_extents.height ||
	    (src_r.x + src_r.width) < 0 || (src_r.y + src_r.height) < 0)
	{
	    if (op == CAIRO_OPERATOR_OVER)
		return CAIRO_STATUS_SUCCESS;
	    goto UNSUPPORTED;
	}

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

	    dst_r.width += src_r.x;
	    dst_r.x -= src_r.x;

            src_r.x = 0;
            needs_pad = TRUE;
	}

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

	    dst_r.height += src_r.y;
	    dst_r.y -= src_r.y;
	    
            src_r.y = 0;
            needs_pad = TRUE;
	}

	if (src_r.x + src_r.width > src_extents.width) {
	    src_r.width = src_extents.width - src_r.x;
	    dst_r.width = src_r.width;
            needs_pad = TRUE;
	}

	if (src_r.y + src_r.height > src_extents.height) {
	    src_r.height = src_extents.height - src_r.y;
	    dst_r.height = src_r.height;
            needs_pad = TRUE;
	}
    } else {
	needs_repeat = TRUE;
    }

    if (pattern->extend == CAIRO_EXTEND_PAD && needs_pad) {
        goto UNSUPPORTED;
    }

    /*
     * Operations that we can do:
     *
     * AlphaBlend uses the following formula for alpha when not use the per-pixel alpha (AlphaFormat = 0)
     *   Dst.Alpha = Src.Alpha * (SCA/255.0) + Dst.Alpha * (1.0 - (SCA/255.0))
     * This turns into Dst.Alpha = Src.Alpha when SCA = 255.
     * (http://msdn.microsoft.com/en-us/library/aa921335.aspx)
     *
     *  RGB OVER  RGB -> BitBlt (same as SOURCE)
     *  RGB OVER ARGB -> Partially supported, We convert this operation into a ARGB SOURCE ARGB
     *                   by setting the alpha values of the source to 255.
     * ARGB OVER ARGB -> AlphaBlend, with AC_SRC_ALPHA
     * ARGB OVER  RGB -> AlphaBlend, with AC_SRC_ALPHA; we'll have junk in the dst A byte
     * 
     *  RGB OVER  RGB + mask -> AlphaBlend, no AC_SRC_ALPHA
     *  RGB OVER ARGB + mask -> Partially supported, We convert this operation into a ARGB OVER ARGB + mask
     *                          by setting the alpha values of the source to 255.
     * ARGB OVER ARGB + mask -> AlphaBlend, with AC_SRC_ALPHA
     * ARGB OVER  RGB + mask -> AlphaBlend, with AC_SRC_ALPHA; junk in the dst A byte
     * 
     *  RGB SOURCE  RGB -> BitBlt
     *  RGB SOURCE ARGB -> Partially supported, We convert this operation into a ARGB SOURCE ARGB
     *                     by setting the alpha values of the source to 255.
     * ARGB SOURCE ARGB -> BitBlt
     * ARGB SOURCE  RGB -> BitBlt
     * 
     *  RGB SOURCE  RGB + mask -> unsupported
     *  RGB SOURCE ARGB + mask -> unsupported
     * ARGB SOURCE ARGB + mask -> unsupported
     * ARGB SOURCE  RGB + mask -> unsupported
     */

    /*
     * Figure out what action to take.
     */
    if (op == CAIRO_OPERATOR_OVER) {
	if (alpha == 0)
	    return CAIRO_STATUS_SUCCESS;

	if (src_format == dst->format) {
	    if (alpha == 255 && src_format == CAIRO_FORMAT_RGB24) {
		needs_alpha = FALSE;
	    } else {
		needs_alpha = TRUE;
	    }
	} else if (src_format == CAIRO_FORMAT_ARGB32 &&
		   dst->format == CAIRO_FORMAT_RGB24)
	{
	    needs_alpha = TRUE;
	} else if (src_format == CAIRO_FORMAT_RGB24 &&
		   dst->format == CAIRO_FORMAT_ARGB32 &&
		   src->image)
	{
	    if (alpha == 255) {
		needs_alpha = FALSE;
	    } else {
		needs_alpha = TRUE;
	    }
	} else {
	    goto UNSUPPORTED;
	}
    } else if (alpha == 255 && op == CAIRO_OPERATOR_SOURCE) {
	if ((src_format == dst->format) ||
	    (src_format == CAIRO_FORMAT_ARGB32 && dst->format == CAIRO_FORMAT_RGB24) ||
	    (src_format == CAIRO_FORMAT_RGB24  && dst->format == CAIRO_FORMAT_ARGB32 && src->image))
	{
	    needs_alpha = FALSE;
	} else {
	    goto UNSUPPORTED;
	}
    } else {
	goto UNSUPPORTED;
    }

    if (scalex == 1.0 && scaley == 1.0) {
	needs_scale = FALSE;
    } else {
	/* Should never be reached until we turn StretchBlt back on */
	needs_scale = TRUE;
    }

#ifdef DEBUG_COMPOSITE
    fprintf (stderr, "action: [%d %d %d %d] -> [%d %d %d %d]\n",
	     src_r.x, src_r.y, src_r.width, src_r.height,
	     dst_r.x, dst_r.y, dst_r.width, dst_r.height);
    fflush (stderr);
#endif

    status = _cairo_win32_surface_set_clip_region (dst, clip_region);
    if (status)
	return status;

    /* If we need to repeat, we turn the repeated blit into
     * a bunch of piece-by-piece blits.
     */
    if (needs_repeat) {
	cairo_rectangle_int_t piece_src_r, piece_dst_r;
	uint32_t rendered_width = 0, rendered_height = 0;
	uint32_t to_render_height, to_render_width;
	int32_t piece_x, piece_y;
	int32_t src_start_x = MOD(src_r.x, src_extents.width);
	int32_t src_start_y = MOD(src_r.y, src_extents.height);

	if (needs_scale)
	    goto UNSUPPORTED;

	/* If both the src and dest have an image, we may as well fall
	 * back, because it will be faster than our separate blits.
	 * Our blit code will be fastest when the src is a DDB and the
	 * destination is a DDB.
	 */
	if ((src_image || src->image) && dst->image)
	    goto UNSUPPORTED;

	/* If the src is not a bitmap but an on-screen (or unknown)
	 * DC, chances are that fallback will be faster.
	 */
	if (src->bitmap == NULL)
	    goto UNSUPPORTED;

	/* If we can use PatBlt, just do so */
	if (!src_image && !needs_alpha)
	{
	    HBRUSH brush;
	    HGDIOBJ old_brush;
	    POINT old_brush_origin;

	    /* Set up the brush with our bitmap */
	    brush = CreatePatternBrush (src->bitmap);

	    /* SetBrushOrgEx sets the coordinates in the destination DC of where the
	     * pattern should start.
	     */
	    SetBrushOrgEx (dst->dc, dst_r.x - src_start_x,
			   dst_r.y - src_start_y, &old_brush_origin);

	    old_brush = SelectObject (dst->dc, brush);

	    PatBlt (dst->dc, dst_r.x, dst_r.y, dst_r.width, dst_r.height, PATCOPY);

	    /* Restore the old brush and pen */
	    SetBrushOrgEx (dst->dc, old_brush_origin.x, old_brush_origin.y, NULL);
	    SelectObject (dst->dc, old_brush);
	    DeleteObject (brush);

	    return CAIRO_STATUS_SUCCESS;
	}

	/* If we were not able to use PatBlt, then manually expand out the blit */

	/* Arbitrary factor; we think that going through
	 * fallback will be faster if we have to do more
	 * than this amount of blits in either direction.
	 */
	if (dst_r.width / src_extents.width > 5 ||
	    dst_r.height / src_extents.height > 5)
	    goto UNSUPPORTED;

	for (rendered_height = 0;
	     rendered_height < dst_r.height;
	     rendered_height += to_render_height)
	{
	    piece_y = (src_start_y + rendered_height) % src_extents.height;
	    to_render_height = src_extents.height - piece_y;

	    if (rendered_height + to_render_height > dst_r.height)
		to_render_height = dst_r.height - rendered_height;

	    for (rendered_width = 0;
		 rendered_width < dst_r.width;
		 rendered_width += to_render_width)
	    {
		piece_x = (src_start_x + rendered_width) % src_extents.width;
		to_render_width = src_extents.width - piece_x;

		if (rendered_width + to_render_width > dst_r.width)
		    to_render_width = dst_r.width - rendered_width;

		piece_src_r.x = piece_x;
		piece_src_r.y = piece_y;
		piece_src_r.width = to_render_width;
		piece_src_r.height = to_render_height;

		piece_dst_r.x = dst_r.x + rendered_width;
		piece_dst_r.y = dst_r.y + rendered_height;
		piece_dst_r.width = to_render_width;
		piece_dst_r.height = to_render_height;

		status = _cairo_win32_surface_composite_inner (src, src_image, dst,
							       src_extents, piece_src_r, piece_dst_r,
							       alpha, needs_alpha, needs_scale);
		if (status != CAIRO_STATUS_SUCCESS) {
		    /* Uh oh.  If something failed, and it's the first
		     * piece, then we can jump to UNSUPPORTED. 
		     * Otherwise, this is bad times, because part of the
		     * rendering was already done. */
		    if (rendered_width == 0 &&
			rendered_height == 0)
		    {
			goto UNSUPPORTED;
		    }

		    return status;
		}
	    }
	}
    } else {
	status = _cairo_win32_surface_composite_inner (src, src_image, dst,
						       src_extents, src_r, dst_r,
						       alpha, needs_alpha, needs_scale);
    }

    if (status == CAIRO_STATUS_SUCCESS)
	return status;

UNSUPPORTED:
    /* Fall back to image surface directly, if this is a DIB surface */
    if (dst->image) {
	GdiFlush();

	return dst->image->backend->composite (op, pattern, mask_pattern,
					       dst->image,
					       src_x, src_y,
					       mask_x, mask_y,
					       dst_x, dst_y,
					       width, height,
					       clip_region);
    }

    return CAIRO_INT_STATUS_UNSUPPORTED;
}

/* This big function tells us how to optimize operators for the
 * case of solid destination and constant-alpha source
 *
 * Note: This function needs revisiting if we add support for
 *       super-luminescent colors (a == 0, r,g,b > 0)
 */
static enum { DO_CLEAR, DO_SOURCE, DO_NOTHING, DO_UNSUPPORTED }
categorize_solid_dest_operator (cairo_operator_t op,
				unsigned short   alpha)
{
    enum { SOURCE_TRANSPARENT, SOURCE_LIGHT, SOURCE_SOLID, SOURCE_OTHER } source;

    if (alpha >= 0xff00)
	source = SOURCE_SOLID;
    else if (alpha < 0x100)
	source = SOURCE_TRANSPARENT;
    else
	source = SOURCE_OTHER;

    switch (op) {
    case CAIRO_OPERATOR_CLEAR:    /* 0                 0 */
    case CAIRO_OPERATOR_OUT:      /* 1 - Ab            0 */
	return DO_CLEAR;
	break;

    case CAIRO_OPERATOR_SOURCE:   /* 1                 0 */
    case CAIRO_OPERATOR_IN:       /* Ab                0 */
	return DO_SOURCE;
	break;

    case CAIRO_OPERATOR_OVER:     /* 1            1 - Aa */
    case CAIRO_OPERATOR_ATOP:     /* Ab           1 - Aa */
	if (source == SOURCE_SOLID)
	    return DO_SOURCE;
	else if (source == SOURCE_TRANSPARENT)
	    return DO_NOTHING;
	else
	    return DO_UNSUPPORTED;
	break;

    case CAIRO_OPERATOR_DEST_OUT: /* 0            1 - Aa */
    case CAIRO_OPERATOR_XOR:      /* 1 - Ab       1 - Aa */
	if (source == SOURCE_SOLID)
	    return DO_CLEAR;
	else if (source == SOURCE_TRANSPARENT)
	    return DO_NOTHING;
	else
	    return DO_UNSUPPORTED;
    	break;

    case CAIRO_OPERATOR_DEST:     /* 0                 1 */
    case CAIRO_OPERATOR_DEST_OVER:/* 1 - Ab            1 */
    case CAIRO_OPERATOR_SATURATE: /* min(1,(1-Ab)/Aa)  1 */
	return DO_NOTHING;
	break;

    case CAIRO_OPERATOR_DEST_IN:  /* 0                Aa */
    case CAIRO_OPERATOR_DEST_ATOP:/* 1 - Ab           Aa */
	if (source == SOURCE_SOLID)
	    return DO_NOTHING;
	else if (source == SOURCE_TRANSPARENT)
	    return DO_CLEAR;
	else
	    return DO_UNSUPPORTED;
	break;

    case CAIRO_OPERATOR_ADD:	  /* 1                1 */
	if (source == SOURCE_TRANSPARENT)
	    return DO_NOTHING;
	else
	    return DO_UNSUPPORTED;
	break;
    }

    ASSERT_NOT_REACHED;
    return DO_UNSUPPORTED;
}

static cairo_status_t
_cairo_win32_surface_fill_rectangles_stretchdib (HDC                   dc,
                                                 const cairo_color_t   *color,
                                                 cairo_rectangle_int_t *rect,
                                                 int                   num_rects)
{
    BITMAPINFO bi;
    int pixel = ((color->alpha_short >> 8) << 24) |
                ((color->red_short >> 8) << 16) |
                ((color->green_short >> 8) << 8) |
                (color->blue_short >> 8);
    int i;

    /* Experiments suggest that it's impossible to use FillRect to set the alpha value
       of a Win32 HDC for a transparent window. So instead we use StretchDIBits of a single
       pixel, which does work. */
    bi.bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
    bi.bmiHeader.biWidth = 1;
    bi.bmiHeader.biHeight = 1;
    bi.bmiHeader.biSizeImage = 0;
    bi.bmiHeader.biXPelsPerMeter = PELS_72DPI;
    bi.bmiHeader.biYPelsPerMeter = PELS_72DPI;
    bi.bmiHeader.biPlanes = 1;
    bi.bmiHeader.biBitCount = 32;
    bi.bmiHeader.biCompression = BI_RGB;
    bi.bmiHeader.biClrUsed = 0;
    bi.bmiHeader.biClrImportant = 0;

    for (i = 0; i < num_rects; i++) {
        if (!StretchDIBits (dc,
                            /* dst x,y,w,h */
                            rect[i].x, rect[i].y, rect[i].width, rect[i].height,
                            /* src x,y,w,h */
                            0, 0, 1, 1,
                            &pixel,
                            &bi,
                            DIB_RGB_COLORS,
                            SRCCOPY))
            return _cairo_win32_print_gdi_error ("_cairo_win32_surface_fill_rectangles_stretchdib(StretchDIBits)");
    }
    return CAIRO_STATUS_SUCCESS;
}

static cairo_int_status_t
_cairo_win32_surface_fill_rectangles (void			*abstract_surface,
				      cairo_operator_t		op,
				      const cairo_color_t	*color,
				      cairo_rectangle_int_t	*rects,
				      int			num_rects)
{
    cairo_win32_surface_t *surface = abstract_surface;
    cairo_status_t status;
    COLORREF new_color;
    HBRUSH new_brush;
    int i;

    status = _cairo_win32_surface_set_clip_region (surface, NULL);
    if (status)
        return status;

    if (surface->format == CAIRO_FORMAT_ARGB32 &&
        (surface->flags & CAIRO_WIN32_SURFACE_CAN_STRETCHDIB) &&
        (op == CAIRO_OPERATOR_SOURCE ||
         (op == CAIRO_OPERATOR_OVER && color->alpha_short >= 0xff00))) {
        return _cairo_win32_surface_fill_rectangles_stretchdib (surface->dc,
                                                                color, rects, num_rects);
    }
    if (surface->format != CAIRO_FORMAT_RGB24)
        return CAIRO_INT_STATUS_UNSUPPORTED;

    /* Optimize for no destination alpha (surface->pixman_image is non-NULL for all
     * surfaces with alpha.)
     */
    switch (categorize_solid_dest_operator (op, color->alpha_short)) {
    case DO_CLEAR:
	new_color = RGB (0, 0, 0);
	break;
    case DO_SOURCE:
	new_color = RGB (color->red_short >> 8, color->green_short >> 8, color->blue_short >> 8);
	break;
    case DO_NOTHING:
	return CAIRO_STATUS_SUCCESS;
    case DO_UNSUPPORTED:
    default:
	return CAIRO_INT_STATUS_UNSUPPORTED;
    }

    new_brush = CreateSolidBrush (new_color);
    if (!new_brush)
	return _cairo_win32_print_gdi_error ("_cairo_win32_surface_fill_rectangles");

    for (i = 0; i < num_rects; i++) {
	RECT rect;

	rect.left = rects[i].x;
	rect.top = rects[i].y;
	rect.right = rects[i].x + rects[i].width;
	rect.bottom = rects[i].y + rects[i].height;

	if (!FillRect (surface->dc, &rect, new_brush))
	    goto FAIL;
    }

    DeleteObject (new_brush);

    return CAIRO_STATUS_SUCCESS;

 FAIL:
    status = _cairo_win32_print_gdi_error ("_cairo_win32_surface_fill_rectangles");

    DeleteObject (new_brush);

    return status;
}

cairo_bool_t
_cairo_win32_surface_get_extents (void		          *abstract_surface,
				  cairo_rectangle_int_t   *rectangle)
{
    cairo_win32_surface_t *surface = abstract_surface;

    *rectangle = surface->extents;
    return TRUE;
}

static cairo_status_t
_cairo_win32_surface_flush (void *abstract_surface)
{
    return _cairo_win32_surface_set_clip_region (abstract_surface, NULL);
}

#define STACK_GLYPH_SIZE 256

cairo_int_status_t
_cairo_win32_surface_show_glyphs_internal (void			*surface,
					   cairo_operator_t	 op,
					   const cairo_pattern_t	*source,
					   cairo_glyph_t		*glyphs,
					   int			 num_glyphs,
					   cairo_scaled_font_t	*scaled_font,
					   cairo_clip_t		*clip,
					   int			*remaining_glyphs,
					   cairo_bool_t           glyph_indexing)
{
#ifdef CAIRO_HAS_WIN32_FONT
    if (scaled_font->backend->type == CAIRO_FONT_TYPE_DWRITE) {
#ifdef CAIRO_HAS_DWRITE_FONT
        return _cairo_dwrite_show_glyphs_on_surface(surface, op, source, glyphs, num_glyphs, scaled_font, clip);
#endif
    } else {
	cairo_win32_surface_t *dst = surface;
        
	WORD glyph_buf_stack[STACK_GLYPH_SIZE];
	WORD *glyph_buf = glyph_buf_stack;
	int dxy_buf_stack[2 * STACK_GLYPH_SIZE];
	int *dxy_buf = dxy_buf_stack;

	BOOL win_result = 0;
	int i, j;

	cairo_solid_pattern_t *solid_pattern;
	COLORREF color;

	cairo_matrix_t device_to_logical;

	int start_x, start_y;
	double user_x, user_y;
	int logical_x, logical_y;
	unsigned int glyph_index_option;

	/* We can only handle win32 fonts */
	if (cairo_scaled_font_get_type (scaled_font) != CAIRO_FONT_TYPE_WIN32)
	    return CAIRO_INT_STATUS_UNSUPPORTED;

	/* We can only handle opaque solid color sources */
	if (!_cairo_pattern_is_opaque_solid(source))
	    return CAIRO_INT_STATUS_UNSUPPORTED;

	/* We can only handle operator SOURCE or OVER with the destination
	 * having no alpha */
	if ((op != CAIRO_OPERATOR_SOURCE && op != CAIRO_OPERATOR_OVER) ||
	    (dst->format != CAIRO_FORMAT_RGB24))
	    return CAIRO_INT_STATUS_UNSUPPORTED;

	/* If we have a fallback mask clip set on the dst, we have
	 * to go through the fallback path, but only if we're not
	 * doing this for printing */
	if (clip != NULL) {
	    if ((dst->flags & CAIRO_WIN32_SURFACE_FOR_PRINTING) == 0) {
		cairo_region_t *clip_region;
		cairo_status_t status;

		status = _cairo_clip_get_region (clip, &clip_region);
		assert (status != CAIRO_INT_STATUS_NOTHING_TO_DO);
		if (status)
		    return status;

		_cairo_win32_surface_set_clip_region (surface, clip_region);
	    }
	} else {
	    _cairo_win32_surface_set_clip_region (surface, NULL);
	}

	solid_pattern = (cairo_solid_pattern_t *)source;
	color = RGB(((int)solid_pattern->color.red_short) >> 8,
		    ((int)solid_pattern->color.green_short) >> 8,
		    ((int)solid_pattern->color.blue_short) >> 8);

	cairo_win32_scaled_font_get_device_to_logical(scaled_font, &device_to_logical);

	SaveDC(dst->dc);

	cairo_win32_scaled_font_select_font(scaled_font, dst->dc);
	SetTextColor(dst->dc, color);
	SetTextAlign(dst->dc, TA_BASELINE | TA_LEFT);
	SetBkMode(dst->dc, TRANSPARENT);

	if (num_glyphs > STACK_GLYPH_SIZE) {
	    glyph_buf = (WORD *) _cairo_malloc_ab (num_glyphs, sizeof(WORD));
	    dxy_buf = (int *) _cairo_malloc_abc (num_glyphs, sizeof(int), 2);
	}

	/* It is vital that dx values for dxy_buf are calculated from the delta of
	 * _logical_ x coordinates (not user x coordinates) or else the sum of all
	 * previous dx values may start to diverge from the current glyph's x
	 * coordinate due to accumulated rounding error. As a result strings could
	 * be painted shorter or longer than expected. */

	user_x = glyphs[0].x;
	user_y = glyphs[0].y;

	cairo_matrix_transform_point(&device_to_logical,
				     &user_x, &user_y);

	logical_x = _cairo_lround (user_x);
	logical_y = _cairo_lround (user_y);

	start_x = logical_x;
	start_y = logical_y;

	for (i = 0, j = 0; i < num_glyphs; ++i, j = 2 * i) {
	    glyph_buf[i] = (WORD) glyphs[i].index;
	    if (i == num_glyphs - 1) {
		dxy_buf[j] = 0;
		dxy_buf[j+1] = 0;
	    } else {
		double next_user_x = glyphs[i+1].x;
		double next_user_y = glyphs[i+1].y;
		int next_logical_x, next_logical_y;

		cairo_matrix_transform_point(&device_to_logical,
					     &next_user_x, &next_user_y);

		next_logical_x = _cairo_lround (next_user_x);
		next_logical_y = _cairo_lround (next_user_y);

		dxy_buf[j] = _cairo_lround (next_logical_x - logical_x);
		dxy_buf[j+1] = _cairo_lround (logical_y - next_logical_y);
		    /* note that GDI coordinate system is inverted */

		logical_x = next_logical_x;
		logical_y = next_logical_y;
	    }
	}

	if (glyph_indexing)
	    glyph_index_option = ETO_GLYPH_INDEX;
	else
	    glyph_index_option = 0;

	win_result = ExtTextOutW(dst->dc,
				 start_x,
				 start_y,
				 glyph_index_option | ETO_PDY,
				 NULL,
				 glyph_buf,
				 num_glyphs,
				 dxy_buf);
	if (!win_result) {
	    _cairo_win32_print_gdi_error("_cairo_win32_surface_show_glyphs(ExtTextOutW failed)");
	}

	RestoreDC(dst->dc, -1);

	if (glyph_buf != glyph_buf_stack) {
	    free(glyph_buf);
	    free(dxy_buf);
	}
	return (win_result) ? CAIRO_STATUS_SUCCESS : CAIRO_INT_STATUS_UNSUPPORTED;
    }
#else
    return CAIRO_INT_STATUS_UNSUPPORTED;
#endif
}

#undef STACK_GLYPH_SIZE

cairo_int_status_t
_cairo_win32_surface_show_glyphs (void			*surface,
 				  cairo_operator_t	 op,
 				  const cairo_pattern_t *source,
 				  cairo_glyph_t	 	*glyphs,
 				  int			 num_glyphs,
 				  cairo_scaled_font_t	*scaled_font,
 				  cairo_clip_t          *clip,
 				  int		      	*remaining_glyphs)
{
    return _cairo_win32_surface_show_glyphs_internal (surface,
 						      op,
 						      source,
 						      glyphs,
 						      num_glyphs,
 						      scaled_font,
 						      clip,
 						      remaining_glyphs,
 						      TRUE);
}

static cairo_surface_t *
cairo_win32_surface_create_internal (HDC hdc, cairo_format_t format)
{
    cairo_win32_surface_t *surface;

    RECT rect;

    surface = malloc (sizeof (cairo_win32_surface_t));
    if (surface == NULL)
	return _cairo_surface_create_in_error (_cairo_error (CAIRO_STATUS_NO_MEMORY));

    if (_cairo_win32_save_initial_clip (hdc, surface) != CAIRO_STATUS_SUCCESS) {
	free (surface);
	return _cairo_surface_create_in_error (_cairo_error (CAIRO_STATUS_NO_MEMORY));
    }

    surface->clip_region = NULL;
    surface->image = NULL;
    surface->format = format;

    surface->d3d9surface = NULL;
    surface->dc = hdc;
    surface->bitmap = NULL;
    surface->is_dib = FALSE;
    surface->saved_dc_bitmap = NULL;
    surface->brush = NULL;
    surface->old_brush = NULL;
    surface->font_subsets = NULL;

    GetClipBox(hdc, &rect);
    surface->extents.x = rect.left;
    surface->extents.y = rect.top;
    surface->extents.width = rect.right - rect.left;
    surface->extents.height = rect.bottom - rect.top;

    surface->flags = _cairo_win32_flags_for_dc (surface->dc);

    _cairo_surface_init (&surface->base,
			 &cairo_win32_surface_backend,
			 NULL, /* device */
			 _cairo_content_from_format (format));

    return &surface->base;
}

/**
 * cairo_win32_surface_create:
 * @hdc: the DC to create a surface for
 *
 * Creates a cairo surface that targets the given DC.  The DC will be
 * queried for its initial clip extents, and this will be used as the
 * size of the cairo surface.  The resulting surface will always be of
 * format %CAIRO_FORMAT_RGB24; should you need another surface format,
 * you will need to create one through
 * cairo_win32_surface_create_with_dib() or call
 * cairo_win32_surface_create_with_alpha.
 *
 * Return value: the newly created surface
 **/
cairo_surface_t *
cairo_win32_surface_create (HDC hdc)
{
    /* Assume everything comes in as RGB24 */
    return cairo_win32_surface_create_internal(hdc, CAIRO_FORMAT_RGB24);
}

/**
 * cairo_win32_surface_create_with_alpha:
 * @hdc: the DC to create a surface for
 *
 * Creates a cairo surface that targets the given DC.  The DC will be
 * queried for its initial clip extents, and this will be used as the
 * size of the cairo surface.  The resulting surface will always be of
 * format %CAIRO_FORMAT_ARGB32; this format is used when drawing into
 * transparent windows.
 *
 * Return value: the newly created surface
 *
 * Since: 1.10
 **/
cairo_surface_t *
cairo_win32_surface_create_with_alpha (HDC hdc)
{
    return cairo_win32_surface_create_internal(hdc, CAIRO_FORMAT_ARGB32);
}

/**
 * cairo_win32_surface_create_with_dib:
 * @format: format of pixels in the surface to create
 * @width: width of the surface, in pixels
 * @height: height of the surface, in pixels
 *
 * Creates a device-independent-bitmap surface not associated with
 * any particular existing surface or device context. The created
 * bitmap will be uninitialized.
 *
 * Return value: the newly created surface
 *
 * Since: 1.2
 **/
cairo_surface_t *
cairo_win32_surface_create_with_dib (cairo_format_t format,
				     int	    width,
				     int	    height)
{
    return _cairo_win32_surface_create_for_dc (NULL, format, width, height);
}

/**
 * cairo_win32_surface_create_with_ddb:
 * @hdc: the DC to create a surface for
 * @format: format of pixels in the surface to create
 * @width: width of the surface, in pixels
 * @height: height of the surface, in pixels
 *
 * Creates a device-independent-bitmap surface not associated with
 * any particular existing surface or device context. The created
 * bitmap will be uninitialized.
 *
 * Return value: the newly created surface
 *
 * Since: 1.4
 **/
cairo_surface_t *
cairo_win32_surface_create_with_ddb (HDC hdc,
				     cairo_format_t format,
				     int width,
				     int height)
{
    cairo_win32_surface_t *new_surf;
    HBITMAP ddb;
    HDC screen_dc, ddb_dc;
    HBITMAP saved_dc_bitmap;

    if (format != CAIRO_FORMAT_RGB24)
	return _cairo_surface_create_in_error (_cairo_error (CAIRO_STATUS_INVALID_FORMAT));
/* XXX handle these eventually
	format != CAIRO_FORMAT_A8 ||
	format != CAIRO_FORMAT_A1)
*/

    if (!hdc) {
	screen_dc = GetDC (NULL);
	hdc = screen_dc;
    } else {
	screen_dc = NULL;
    }

    ddb_dc = CreateCompatibleDC (hdc);
    if (ddb_dc == NULL) {
	new_surf = (cairo_win32_surface_t*) _cairo_surface_create_in_error (_cairo_error (CAIRO_STATUS_NO_MEMORY));
	goto FINISH;
    }

    ddb = CreateCompatibleBitmap (hdc, width, height);
    if (ddb == NULL) {
	DeleteDC (ddb_dc);

	/* Note that if an app actually does hit this out of memory
	 * condition, it's going to have lots of other issues, as
	 * video memory is probably exhausted.  However, it can often
	 * continue using DIBs instead of DDBs.
	 */
	new_surf = (cairo_win32_surface_t*) _cairo_surface_create_in_error (_cairo_error (CAIRO_STATUS_NO_MEMORY));
	goto FINISH;
    }

    saved_dc_bitmap = SelectObject (ddb_dc, ddb);

    new_surf = (cairo_win32_surface_t*) cairo_win32_surface_create (ddb_dc);
    new_surf->bitmap = ddb;
    new_surf->saved_dc_bitmap = saved_dc_bitmap;
    new_surf->is_dib = FALSE;

FINISH:
    if (screen_dc)
	ReleaseDC (NULL, screen_dc);

    return (cairo_surface_t*) new_surf;
}

cairo_public cairo_surface_t *
cairo_win32_surface_create_with_d3dsurface9 (IDirect3DSurface9 *surface)
{
    HDC dc;
    cairo_surface_t *win_surface;

    IDirect3DSurface9_AddRef (surface);
    IDirect3DSurface9_GetDC (surface, &dc);
    win_surface = cairo_win32_surface_create_internal(dc, CAIRO_FORMAT_RGB24);
    if (likely(win_surface->status == CAIRO_STATUS_SUCCESS)) {
	((cairo_win32_surface_t*)win_surface)->d3d9surface = surface;
    }
    return win_surface;

}
/**
 * _cairo_surface_is_win32:
 * @surface: a #cairo_surface_t
 *
 * Checks if a surface is a win32 surface.  This will
 * return False if this is a win32 printing surface; use
 * _cairo_surface_is_win32_printing() to check for that.
 *
 * Return value: True if the surface is an win32 surface
 **/
int
_cairo_surface_is_win32 (cairo_surface_t *surface)
{
    return surface->backend == &cairo_win32_surface_backend;
}

/**
 * cairo_win32_surface_get_dc
 * @surface: a #cairo_surface_t
 *
 * Returns the HDC associated with this surface, or %NULL if none.
 * Also returns %NULL if the surface is not a win32 surface.
 *
 * Return value: HDC or %NULL if no HDC available.
 *
 * Since: 1.2
 **/
HDC
cairo_win32_surface_get_dc (cairo_surface_t *surface)
{
    cairo_win32_surface_t *winsurf;

    if (_cairo_surface_is_win32 (surface)){
	winsurf = (cairo_win32_surface_t *) surface;

	return winsurf->dc;
    }

    if (_cairo_surface_is_paginated (surface)) {
	cairo_surface_t *target;

	target = _cairo_paginated_surface_get_target (surface);

#ifndef CAIRO_OMIT_WIN32_PRINTING
	if (_cairo_surface_is_win32_printing (target)) {
	    winsurf = (cairo_win32_surface_t *) target;
	    return winsurf->dc;
	}
#endif
    }

    return NULL;
}


HDC
cairo_win32_get_dc_with_clip (cairo_t *cr)
{
    cairo_surface_t *surface = cr->gstate->target;
    cairo_clip_t clip;
    _cairo_clip_init_copy(&clip, &cr->gstate->clip);

    if (_cairo_surface_is_win32 (surface)){
	cairo_win32_surface_t *winsurf = (cairo_win32_surface_t *) surface;
	cairo_region_t *clip_region = NULL;
	cairo_status_t status;

	if (clip.path) {
	    status = _cairo_clip_get_region (&clip, &clip_region);
	    assert (status != CAIRO_INT_STATUS_NOTHING_TO_DO);
	    if (status) {
		_cairo_clip_fini(&clip);
		return NULL;
	    }
	}
	_cairo_win32_surface_set_clip_region (winsurf, clip_region);

	_cairo_clip_fini(&clip);
	return winsurf->dc;
    }

    if (_cairo_surface_is_paginated (surface)) {
	cairo_surface_t *target;

	target = _cairo_paginated_surface_get_target (surface);

#ifndef CAIRO_OMIT_WIN32_PRINTING
	if (_cairo_surface_is_win32_printing (target)) {
	    cairo_status_t status;
	    cairo_win32_surface_t *winsurf = (cairo_win32_surface_t *) target;

	    status = _cairo_surface_clipper_set_clip (&winsurf->clipper, &clip);

	    _cairo_clip_fini(&clip);

	    if (status)
		return NULL;

	    return winsurf->dc;
	}
#endif
    }

    _cairo_clip_fini(&clip);
    return NULL;
}



/**
 * cairo_win32_surface_get_image
 * @surface: a #cairo_surface_t
 *
 * Returns a #cairo_surface_t image surface that refers to the same bits
 * as the DIB of the Win32 surface.  If the passed-in win32 surface
 * is not a DIB surface, %NULL is returned.
 *
 * Return value: a #cairo_surface_t (owned by the win32 #cairo_surface_t),
 * or %NULL if the win32 surface is not a DIB.
 *
 * Since: 1.4
 */
cairo_surface_t *
cairo_win32_surface_get_image (cairo_surface_t *surface)
{
    if (!_cairo_surface_is_win32(surface))
	return NULL;

    return ((cairo_win32_surface_t*)surface)->image;
}

static cairo_bool_t
_cairo_win32_surface_is_similar (void *surface_a,
	                         void *surface_b)
{
    cairo_win32_surface_t *a = surface_a;
    cairo_win32_surface_t *b = surface_b;

    return a->dc == b->dc;
}

typedef struct _cairo_win32_surface_span_renderer {
    cairo_span_renderer_t base;

    cairo_operator_t op;
    const cairo_pattern_t *pattern;
    cairo_antialias_t antialias;

    uint8_t *mask_data;
    uint32_t mask_stride;

    cairo_image_surface_t *mask;
    cairo_win32_surface_t *dst;
    cairo_region_t *clip_region;

    cairo_composite_rectangles_t composite_rectangles;
} cairo_win32_surface_span_renderer_t;

static cairo_status_t
_cairo_win32_surface_span_renderer_render_rows (
    void				*abstract_renderer,
    int					 y,
    int					 height,
    const cairo_half_open_span_t	*spans,
    unsigned				 num_spans)
{
    cairo_win32_surface_span_renderer_t *renderer = abstract_renderer;
    while (height--)
	_cairo_image_surface_span_render_row (y++, spans, num_spans, renderer->mask_data, renderer->mask_stride);
    return CAIRO_STATUS_SUCCESS;
}

static void
_cairo_win32_surface_span_renderer_destroy (void *abstract_renderer)
{
    cairo_win32_surface_span_renderer_t *renderer = abstract_renderer;
    if (!renderer) return;

    if (renderer->mask != NULL)
	cairo_surface_destroy (&renderer->mask->base);

    free (renderer);
}

static cairo_status_t
_cairo_win32_surface_span_renderer_finish (void *abstract_renderer)
{
    cairo_win32_surface_span_renderer_t *renderer = abstract_renderer;
    cairo_status_t status = CAIRO_STATUS_SUCCESS;

    if (renderer->pattern == NULL || renderer->mask == NULL)
	return CAIRO_STATUS_SUCCESS;

    status = cairo_surface_status (&renderer->mask->base);
    if (status == CAIRO_STATUS_SUCCESS) {
	cairo_composite_rectangles_t *rects = &renderer->composite_rectangles;
	cairo_win32_surface_t *dst = renderer->dst;
	cairo_pattern_t *mask_pattern = cairo_pattern_create_for_surface (&renderer->mask->base);
	/* composite onto the image surface directly if we can */
	if (dst->image) {
	    GdiFlush(); /* XXX: I'm not sure if this needed or not */

	    status = dst->image->backend->composite (renderer->op,
		    renderer->pattern, mask_pattern, dst->image,
		    rects->bounded.x, rects->bounded.y,
		    0, 0,		/* mask.x, mask.y */
		    rects->bounded.x, rects->bounded.y,
		    rects->bounded.width, rects->bounded.height,
		    renderer->clip_region);
	} else {
	    /* otherwise go through the fallback_composite path which
	     * will do the appropriate surface acquisition */
	    status = _cairo_surface_fallback_composite (
		    renderer->op,
		    renderer->pattern, mask_pattern, &dst->base,
		    rects->bounded.x, rects->bounded.y,
		    0, 0,		/* mask.x, mask.y */
		    rects->bounded.x, rects->bounded.y,
		    rects->bounded.width, rects->bounded.height,
		    renderer->clip_region);
	}
	cairo_pattern_destroy (mask_pattern);

    }
    if (status != CAIRO_STATUS_SUCCESS)
	return _cairo_span_renderer_set_error (abstract_renderer,
					       status);
    return CAIRO_STATUS_SUCCESS;
}

static cairo_int_status_t
_cairo_win32_surface_paint (void			*abstract_surface,
			    cairo_operator_t		 op,
			    const cairo_pattern_t	*source,
			    cairo_clip_t		*clip)
{
    cairo_win32_surface_t *surface = abstract_surface;

    if (surface->image) {
	return _cairo_surface_paint (surface->image, op, source, clip);
    }
    return CAIRO_INT_STATUS_UNSUPPORTED;
}

static cairo_int_status_t
_cairo_win32_surface_mask (void				*abstract_surface,
			   cairo_operator_t		 op,
			   const cairo_pattern_t	*source,
			   const cairo_pattern_t	*mask,
			   cairo_clip_t			*clip)
{
    cairo_win32_surface_t *surface = abstract_surface;

    if (surface->image) {
	return _cairo_surface_mask (surface->image, op, source, mask, clip);
    }
    return CAIRO_INT_STATUS_UNSUPPORTED;
}

static cairo_int_status_t
_cairo_win32_surface_stroke (void			*abstract_surface,
			     cairo_operator_t		 op,
			     const cairo_pattern_t	*source,
			     cairo_path_fixed_t		*path,
			     const cairo_stroke_style_t	*style,
			     const cairo_matrix_t	*ctm,
			     const cairo_matrix_t	*ctm_inverse,
			     double			 tolerance,
			     cairo_antialias_t		 antialias,
			     cairo_clip_t		*clip)
{
    cairo_win32_surface_t *surface = abstract_surface;

    if (surface->image) {
	return _cairo_surface_stroke (surface->image, op, source,
					        path, style,
					        ctm, ctm_inverse,
					        tolerance, antialias,
					        clip);

    }
    return CAIRO_INT_STATUS_UNSUPPORTED;
}

static cairo_int_status_t
_cairo_win32_surface_fill (void				*abstract_surface,
			   cairo_operator_t		 op,
			   const cairo_pattern_t	*source,
			   cairo_path_fixed_t		*path,
			   cairo_fill_rule_t		 fill_rule,
			   double			 tolerance,
			   cairo_antialias_t		 antialias,
			   cairo_clip_t			*clip)
{
    cairo_win32_surface_t *surface = abstract_surface;

    if (surface->image) {
	return _cairo_surface_fill (surface->image, op, source,
					 path, fill_rule,
					 tolerance, antialias,
					 clip);
    }
    return CAIRO_INT_STATUS_UNSUPPORTED;
}


#include "cairoint.h"

#include "cairo-boxes-private.h"
#include "cairo-clip-private.h"
#include "cairo-composite-rectangles-private.h"
#include "cairo-error-private.h"
#include "cairo-region-private.h"
#include "cairo-spans-private.h"
#include "cairo-surface-fallback-private.h"

typedef struct {
    cairo_surface_t *dst;
    cairo_rectangle_int_t extents;
    cairo_image_surface_t *image;
    cairo_rectangle_int_t image_rect;
    void *image_extra;
} fallback_state_t;

/**
 * _fallback_init:
 *
 * Acquire destination image surface needed for an image-based
 * fallback.
 *
 * Return value: %CAIRO_INT_STATUS_NOTHING_TO_DO if the extents are not
 * visible, %CAIRO_STATUS_SUCCESS if some portion is visible and all
 * went well, or some error status otherwise.
 **/
static cairo_int_status_t
_fallback_init (fallback_state_t *state,
		cairo_surface_t  *dst,
		int               x,
		int               y,
		int               width,
		int               height)
{
    cairo_status_t status;

    state->extents.x = x;
    state->extents.y = y;
    state->extents.width = width;
    state->extents.height = height;

    state->dst = dst;

    status = _cairo_surface_acquire_dest_image (dst, &state->extents,
						&state->image, &state->image_rect,
						&state->image_extra);
    if (unlikely (status))
	return status;


    /* XXX: This NULL value tucked away in state->image is a rather
     * ugly interface. Cleaner would be to push the
     * CAIRO_INT_STATUS_NOTHING_TO_DO value down into
     * _cairo_surface_acquire_dest_image and its backend
     * counterparts. */
    assert (state->image != NULL);

    return CAIRO_STATUS_SUCCESS;
}

static void
_fallback_fini (fallback_state_t *state)
{
    _cairo_surface_release_dest_image (state->dst, &state->extents,
				       state->image, &state->image_rect,
				       state->image_extra);
}

typedef cairo_status_t
(*cairo_draw_func_t) (void                          *closure,
		      cairo_operator_t               op,
		      const cairo_pattern_t         *src,
		      cairo_surface_t               *dst,
		      int                            dst_x,
		      int                            dst_y,
		      const cairo_rectangle_int_t   *extents,
		      cairo_region_t		    *clip_region);

static cairo_status_t
_create_composite_mask_pattern (cairo_surface_pattern_t       *mask_pattern,
				cairo_clip_t                  *clip,
				cairo_draw_func_t              draw_func,
				void                          *draw_closure,
				cairo_surface_t               *dst,
				const cairo_rectangle_int_t   *extents)
{
    cairo_surface_t *mask;
    cairo_region_t *clip_region = NULL, *fallback_region = NULL;
    cairo_status_t status;
    cairo_bool_t clip_surface = FALSE;

    if (clip != NULL) {
	status = _cairo_clip_get_region (clip, &clip_region);
	if (unlikely (_cairo_status_is_error (status) ||
		      status == CAIRO_INT_STATUS_NOTHING_TO_DO))
	{
	    return status;
	}

	clip_surface = status == CAIRO_INT_STATUS_UNSUPPORTED;
    }

    /* We need to use solid here, because to use CAIRO_OPERATOR_SOURCE with
     * a mask (as called via _cairo_surface_mask) triggers assertion failures.
     */
    mask = _cairo_surface_create_similar_solid (dst,
						CAIRO_CONTENT_ALPHA,
						extents->width,
						extents->height,
						CAIRO_COLOR_TRANSPARENT,
						TRUE);
    if (unlikely (mask->status))
	return mask->status;

    if (clip_region && (extents->x || extents->y)) {
	fallback_region = cairo_region_copy (clip_region);
	status = fallback_region->status;
	if (unlikely (status))
	    goto CLEANUP_SURFACE;

	cairo_region_translate (fallback_region,
				-extents->x,
				-extents->y);
	clip_region = fallback_region;
    }

    status = draw_func (draw_closure, CAIRO_OPERATOR_ADD,
			&_cairo_pattern_white.base, mask,
			extents->x, extents->y,
			extents,
			clip_region);
    if (unlikely (status))
	goto CLEANUP_SURFACE;

    if (clip_surface)
	status = _cairo_clip_combine_with_surface (clip, mask, extents->x, extents->y);

    _cairo_pattern_init_for_surface (mask_pattern, mask);

 CLEANUP_SURFACE:
    if (fallback_region)
        cairo_region_destroy (fallback_region);
    cairo_surface_destroy (mask);

    return status;
}

/* Handles compositing with a clip surface when the operator allows
 * us to combine the clip with the mask
 */
static cairo_status_t
_clip_and_composite_with_mask (cairo_clip_t                  *clip,
			       cairo_operator_t               op,
			       const cairo_pattern_t         *src,
			       cairo_draw_func_t              draw_func,
			       void                          *draw_closure,
			       cairo_surface_t               *dst,
			       const cairo_rectangle_int_t   *extents)
{
    cairo_surface_pattern_t mask_pattern;
    cairo_status_t status;

    status = _create_composite_mask_pattern (&mask_pattern,
					     clip,
					     draw_func, draw_closure,
					     dst, extents);
    if (likely (status == CAIRO_STATUS_SUCCESS)) {
	status = _cairo_surface_composite (op,
					   src, &mask_pattern.base, dst,
					   extents->x,     extents->y,
					   0,              0,
					   extents->x,     extents->y,
					   extents->width, extents->height,
					   NULL);

	_cairo_pattern_fini (&mask_pattern.base);
    }

    return status;
}

/* Handles compositing with a clip surface when we have to do the operation
 * in two pieces and combine them together.
 */
static cairo_status_t
_clip_and_composite_combine (cairo_clip_t                  *clip,
			     cairo_operator_t               op,
			     const cairo_pattern_t         *src,
			     cairo_draw_func_t              draw_func,
			     void                          *draw_closure,
			     cairo_surface_t               *dst,
			     const cairo_rectangle_int_t   *extents)
{
    cairo_surface_t *intermediate;
    cairo_surface_pattern_t pattern;
    cairo_surface_pattern_t clip_pattern;
    cairo_surface_t *clip_surface;
    int clip_x, clip_y;
    cairo_status_t status;

    /* We'd be better off here creating a surface identical in format
     * to dst, but we have no way of getting that information. Instead
     * we ask the backend to create a similar surface of identical content,
     * in the belief that the backend will do something useful - like use
     * an identical format. For example, the xlib backend will endeavor to
     * use a compatible depth to enable core protocol routines.
     */
    intermediate =
	_cairo_surface_create_similar_scratch (dst, dst->content,
					       extents->width,
					       extents->height);
    if (intermediate == NULL) {
	intermediate =
	    _cairo_image_surface_create_with_content (dst->content,
						      extents->width,
						      extents->width);
    }
    if (unlikely (intermediate->status))
	return intermediate->status;

    /* Initialize the intermediate surface from the destination surface */
    _cairo_pattern_init_for_surface (&pattern, dst);
    status = _cairo_surface_composite (CAIRO_OPERATOR_SOURCE,
				       &pattern.base, NULL, intermediate,
				       extents->x,     extents->y,
				       0,              0,
				       0,              0,
				       extents->width, extents->height,
				       NULL);
    _cairo_pattern_fini (&pattern.base);
    if (unlikely (status))
	goto CLEANUP_SURFACE;

    status = (*draw_func) (draw_closure, op,
			   src, intermediate,
			   extents->x, extents->y,
			   extents,
			   NULL);
    if (unlikely (status))
	goto CLEANUP_SURFACE;

    assert (clip->path != NULL);
    clip_surface = _cairo_clip_get_surface (clip, dst, &clip_x, &clip_y);
    if (unlikely (clip_surface->status))
	goto CLEANUP_SURFACE;

    _cairo_pattern_init_for_surface (&clip_pattern, clip_surface);

    /* Combine that with the clip */
    status = _cairo_surface_composite (CAIRO_OPERATOR_DEST_IN,
				       &clip_pattern.base, NULL, intermediate,
				       extents->x - clip_x,
				       extents->y - clip_y,
				       0, 0,
				       0, 0,
				       extents->width, extents->height,
				       NULL);
    if (unlikely (status))
	goto CLEANUP_CLIP;

    /* Punch the clip out of the destination */
    status = _cairo_surface_composite (CAIRO_OPERATOR_DEST_OUT,
				       &clip_pattern.base, NULL, dst,
				       extents->x - clip_x,
				       extents->y - clip_y,
				       0, 0,
				       extents->x, extents->y,
				       extents->width, extents->height,
				       NULL);
    if (unlikely (status))
	goto CLEANUP_CLIP;

    /* Now add the two results together */
    _cairo_pattern_init_for_surface (&pattern, intermediate);
    status = _cairo_surface_composite (CAIRO_OPERATOR_ADD,
				       &pattern.base, NULL, dst,
				       0,              0,
				       0,              0,
				       extents->x,     extents->y,
				       extents->width, extents->height,
				       NULL);
    _cairo_pattern_fini (&pattern.base);

 CLEANUP_CLIP:
    _cairo_pattern_fini (&clip_pattern.base);
 CLEANUP_SURFACE:
    cairo_surface_destroy (intermediate);

    return status;
}

/* Handles compositing for %CAIRO_OPERATOR_SOURCE, which is special; it's
 * defined as (src IN mask IN clip) ADD (dst OUT (mask IN clip))
 */
static cairo_status_t
_clip_and_composite_source (cairo_clip_t                  *clip,
			    const cairo_pattern_t         *src,
			    cairo_draw_func_t              draw_func,
			    void                          *draw_closure,
			    cairo_surface_t               *dst,
			    const cairo_rectangle_int_t   *extents)
{
    cairo_surface_pattern_t mask_pattern;
    cairo_region_t *clip_region = NULL;
    cairo_status_t status;

    if (clip != NULL) {
	status = _cairo_clip_get_region (clip, &clip_region);
	if (unlikely (_cairo_status_is_error (status) ||
		      status == CAIRO_INT_STATUS_NOTHING_TO_DO))
	{
	    return status;
	}
    }

    /* Create a surface that is mask IN clip */
    status = _create_composite_mask_pattern (&mask_pattern,
					     clip,
					     draw_func, draw_closure,
					     dst, extents);
    if (unlikely (status))
	return status;

    /* Compute dest' = dest OUT (mask IN clip) */
    status = _cairo_surface_composite (CAIRO_OPERATOR_DEST_OUT,
				       &mask_pattern.base, NULL, dst,
				       0,              0,
				       0,              0,
				       extents->x,     extents->y,
				       extents->width, extents->height,
				       clip_region);

    if (unlikely (status))
	goto CLEANUP_MASK_PATTERN;

    /* Now compute (src IN (mask IN clip)) ADD dest' */
    status = _cairo_surface_composite (CAIRO_OPERATOR_ADD,
				       src, &mask_pattern.base, dst,
				       extents->x,     extents->y,
				       0,              0,
				       extents->x,     extents->y,
				       extents->width, extents->height,
				       clip_region);

 CLEANUP_MASK_PATTERN:
    _cairo_pattern_fini (&mask_pattern.base);
    return status;
}

static int
_cairo_rectangle_empty (const cairo_rectangle_int_t *rect)
{
    return rect->width == 0 || rect->height == 0;
}

/**
 * _clip_and_composite:
 * @clip: a #cairo_clip_t
 * @op: the operator to draw with
 * @src: source pattern
 * @draw_func: function that can be called to draw with the mask onto a surface.
 * @draw_closure: data to pass to @draw_func.
 * @dst: destination surface
 * @extents: rectangle holding a bounding box for the operation; this
 *           rectangle will be used as the size for the temporary
 *           surface.
 *
 * When there is a surface clip, we typically need to create an intermediate
 * surface. This function handles the logic of creating a temporary surface
 * drawing to it, then compositing the result onto the target surface.
 *
 * @draw_func is to called to draw the mask; it will be called no more
 * than once.
 *
 * Return value: %CAIRO_STATUS_SUCCESS if the drawing succeeded.
 **/
static cairo_status_t
_clip_and_composite (cairo_clip_t                  *clip,
		     cairo_operator_t               op,
		     const cairo_pattern_t         *src,
		     cairo_draw_func_t              draw_func,
		     void                          *draw_closure,
		     cairo_surface_t               *dst,
		     const cairo_rectangle_int_t   *extents)
{
    cairo_status_t status;

    if (_cairo_rectangle_empty (extents))
	/* Nothing to do */
	return CAIRO_STATUS_SUCCESS;

    if (op == CAIRO_OPERATOR_CLEAR) {
	src = &_cairo_pattern_white.base;
	op = CAIRO_OPERATOR_DEST_OUT;
    }

    if (op == CAIRO_OPERATOR_SOURCE) {
	status = _clip_and_composite_source (clip,
					     src,
					     draw_func, draw_closure,
					     dst, extents);
    } else {
	cairo_bool_t clip_surface = FALSE;
	cairo_region_t *clip_region = NULL;

	if (clip != NULL) {
	    status = _cairo_clip_get_region (clip, &clip_region);
	    if (unlikely (_cairo_status_is_error (status) ||
			  status == CAIRO_INT_STATUS_NOTHING_TO_DO))
	    {
		return status;
	    }

	    clip_surface = status == CAIRO_INT_STATUS_UNSUPPORTED;
	}

	if (clip_surface) {
	    if (_cairo_operator_bounded_by_mask (op)) {
		status = _clip_and_composite_with_mask (clip, op,
							src,
							draw_func, draw_closure,
							dst, extents);
	    } else {
		status = _clip_and_composite_combine (clip, op,
						      src,
						      draw_func, draw_closure,
						      dst, extents);
	    }
	} else {
	    status = draw_func (draw_closure, op,
				src, dst,
				0, 0,
				extents,
				clip_region);
	}
    }

    return status;
}

/* Composites a region representing a set of trapezoids.
 */
static cairo_status_t
_composite_trap_region (cairo_clip_t            *clip,
			const cairo_pattern_t	*src,
			cairo_operator_t         op,
			cairo_surface_t         *dst,
			cairo_region_t          *trap_region,
			const cairo_rectangle_int_t   *extents)
{
    cairo_status_t status;
    cairo_surface_pattern_t mask_pattern;
    cairo_pattern_t *mask = NULL;
    int mask_x = 0, mask_y =0;

    if (clip != NULL) {
	cairo_surface_t *clip_surface = NULL;
	int clip_x, clip_y;

	clip_surface = _cairo_clip_get_surface (clip, dst, &clip_x, &clip_y);
	if (unlikely (clip_surface->status))
	    return clip_surface->status;

	if (op == CAIRO_OPERATOR_CLEAR) {
	    src = &_cairo_pattern_white.base;
	    op = CAIRO_OPERATOR_DEST_OUT;
	}

	_cairo_pattern_init_for_surface (&mask_pattern, clip_surface);
	mask_x = extents->x - clip_x;
	mask_y = extents->y - clip_y;
	mask = &mask_pattern.base;
    }

    status = _cairo_surface_composite (op, src, mask, dst,
				       extents->x, extents->y,
				       mask_x, mask_y,
				       extents->x, extents->y,
				       extents->width, extents->height,
				       trap_region);

    if (mask != NULL)
      _cairo_pattern_fini (mask);

    return status;
}

typedef struct {
    cairo_traps_t *traps;
    cairo_antialias_t antialias;
} cairo_composite_traps_info_t;

static cairo_status_t
_composite_traps_draw_func (void                          *closure,
			    cairo_operator_t               op,
			    const cairo_pattern_t         *src,
			    cairo_surface_t               *dst,
			    int                            dst_x,
			    int                            dst_y,
			    const cairo_rectangle_int_t   *extents,
			    cairo_region_t		  *clip_region)
{
    cairo_composite_traps_info_t *info = closure;
    cairo_status_t status;
    cairo_region_t *extents_region = NULL;

    if (dst_x != 0 || dst_y != 0)
	_cairo_traps_translate (info->traps, - dst_x, - dst_y);

    if (clip_region == NULL &&
        !_cairo_operator_bounded_by_source (op)) {
        extents_region = cairo_region_create_rectangle (extents);
        if (unlikely (extents_region->status))
            return extents_region->status;
        cairo_region_translate (extents_region, -dst_x, -dst_y);
        clip_region = extents_region;
    }

    status = _cairo_surface_composite_trapezoids (op,
                                                  src, dst, info->antialias,
                                                  extents->x,         extents->y,
                                                  extents->x - dst_x, extents->y - dst_y,
                                                  extents->width,     extents->height,
                                                  info->traps->traps,
                                                  info->traps->num_traps,
                                                  clip_region);

    if (extents_region)
        cairo_region_destroy (extents_region);

    return status;
}

enum {
    HAS_CLEAR_REGION = 0x1,
};

static cairo_status_t
_clip_and_composite_region (const cairo_pattern_t *src,
			    cairo_operator_t op,
			    cairo_surface_t *dst,
			    cairo_region_t *trap_region,
			    cairo_clip_t *clip,
			    cairo_rectangle_int_t *extents)
{
    cairo_region_t clear_region;
    unsigned int has_region = 0;
    cairo_status_t status;

    if (! _cairo_operator_bounded_by_mask (op) && clip == NULL) {
	/* If we optimize drawing with an unbounded operator to
	 * _cairo_surface_fill_rectangles() or to drawing with a
	 * clip region, then we have an additional region to clear.
	 */
	_cairo_region_init_rectangle (&clear_region, extents);
	status = cairo_region_subtract (&clear_region, trap_region);
	if (unlikely (status))
	    return status;

	if (! cairo_region_is_empty (&clear_region))
	    has_region |= HAS_CLEAR_REGION;
    }

    if ((src->type == CAIRO_PATTERN_TYPE_SOLID || op == CAIRO_OPERATOR_CLEAR) &&
	clip == NULL)
    {
	const cairo_color_t *color;

	if (op == CAIRO_OPERATOR_CLEAR)
	    color = CAIRO_COLOR_TRANSPARENT;
	else
	    color = &((cairo_solid_pattern_t *)src)->color;

	/* Solid rectangles special case */
	status = _cairo_surface_fill_region (dst, op, color, trap_region);
    } else {
	/* For a simple rectangle, we can just use composite(), for more
	 * rectangles, we have to set a clip region. The cost of rasterizing
	 * trapezoids is pretty high for most backends currently, so it's
	 * worthwhile even if a region is needed.
	 *
	 * If we have a clip surface, we set it as the mask; this only works
	 * for bounded operators other than SOURCE; for unbounded operators,
	 * clip and mask cannot be interchanged. For SOURCE, the operator
	 * as implemented by the backends is different in its handling
	 * of the mask then what we want.
	 *
	 * CAIRO_INT_STATUS_UNSUPPORTED will be returned if the region has
	 * more than rectangle and the destination doesn't support clip
	 * regions. In that case, we fall through.
	 */
	status = _composite_trap_region (clip, src, op, dst,
					 trap_region, extents);
    }

    if (has_region & HAS_CLEAR_REGION) {
	if (status == CAIRO_STATUS_SUCCESS) {
	    status = _cairo_surface_fill_region (dst,
						 CAIRO_OPERATOR_CLEAR,
						 CAIRO_COLOR_TRANSPARENT,
						 &clear_region);
	}
	_cairo_region_fini (&clear_region);
    }

    return status;
}

/* avoid using region code to re-validate boxes */
static cairo_status_t
_fill_rectangles (cairo_surface_t *dst,
		  cairo_operator_t op,
		  const cairo_pattern_t *src,
		  cairo_traps_t *traps,
		  cairo_clip_t *clip)
{
    const cairo_color_t *color;
    cairo_rectangle_int_t stack_rects[CAIRO_STACK_ARRAY_LENGTH (cairo_rectangle_int_t)];
    cairo_rectangle_int_t *rects = stack_rects;
    cairo_status_t status;
    int i;

    if (! traps->is_rectilinear || ! traps->maybe_region)
	return CAIRO_INT_STATUS_UNSUPPORTED;

    /* XXX: convert clip region to geometric boxes? */
    if (clip != NULL)
	return CAIRO_INT_STATUS_UNSUPPORTED;

    /* XXX: fallback for the region_subtract() operation */
    if (! _cairo_operator_bounded_by_mask (op))
	return CAIRO_INT_STATUS_UNSUPPORTED;

    if (! (src->type == CAIRO_PATTERN_TYPE_SOLID || op == CAIRO_OPERATOR_CLEAR))
	return CAIRO_INT_STATUS_UNSUPPORTED;

    if (traps->has_intersections) {
	if (traps->is_rectangular) {
	    status = _cairo_bentley_ottmann_tessellate_rectangular_traps (traps, CAIRO_FILL_RULE_WINDING);
	} else {
	    status = _cairo_bentley_ottmann_tessellate_rectilinear_traps (traps, CAIRO_FILL_RULE_WINDING);
	}
	if (unlikely (status))
	    return status;
    }

    for (i = 0; i < traps->num_traps; i++) {
	if (! _cairo_fixed_is_integer (traps->traps[i].top)          ||
	    ! _cairo_fixed_is_integer (traps->traps[i].bottom)       ||
	    ! _cairo_fixed_is_integer (traps->traps[i].left.p1.x)    ||
	    ! _cairo_fixed_is_integer (traps->traps[i].right.p1.x))
	{
	    traps->maybe_region = FALSE;
	    return CAIRO_INT_STATUS_UNSUPPORTED;
	}
    }

    if (traps->num_traps > ARRAY_LENGTH (stack_rects)) {
	rects = _cairo_malloc_ab (traps->num_traps,
				  sizeof (cairo_rectangle_int_t));
	if (unlikely (rects == NULL))
	    return _cairo_error (CAIRO_STATUS_NO_MEMORY);
    }

    for (i = 0; i < traps->num_traps; i++) {
	int x1 = _cairo_fixed_integer_part (traps->traps[i].left.p1.x);
	int y1 = _cairo_fixed_integer_part (traps->traps[i].top);
	int x2 = _cairo_fixed_integer_part (traps->traps[i].right.p1.x);
	int y2 = _cairo_fixed_integer_part (traps->traps[i].bottom);

	rects[i].x = x1;
	rects[i].y = y1;
	rects[i].width = x2 - x1;
	rects[i].height = y2 - y1;
    }

    if (op == CAIRO_OPERATOR_CLEAR)
	color = CAIRO_COLOR_TRANSPARENT;
    else
	color = &((cairo_solid_pattern_t *)src)->color;

    status =  _cairo_surface_fill_rectangles (dst, op, color, rects, i);

    if (rects != stack_rects)
	free (rects);

    return status;
}

/* fast-path for very common composite of a single rectangle */
static cairo_status_t
_composite_rectangle (cairo_surface_t *dst,
		      cairo_operator_t op,
		      const cairo_pattern_t *src,
		      cairo_traps_t *traps,
		      cairo_clip_t *clip)
{
    cairo_rectangle_int_t rect;

    if (clip != NULL)
	return CAIRO_INT_STATUS_UNSUPPORTED;

    if (traps->num_traps > 1 || ! traps->is_rectilinear || ! traps->maybe_region)
	return CAIRO_INT_STATUS_UNSUPPORTED;

    if (! _cairo_fixed_is_integer (traps->traps[0].top)          ||
	! _cairo_fixed_is_integer (traps->traps[0].bottom)       ||
	! _cairo_fixed_is_integer (traps->traps[0].left.p1.x)    ||
	! _cairo_fixed_is_integer (traps->traps[0].right.p1.x))
    {
	traps->maybe_region = FALSE;
	return CAIRO_INT_STATUS_UNSUPPORTED;
    }

    rect.x = _cairo_fixed_integer_part (traps->traps[0].left.p1.x);
    rect.y = _cairo_fixed_integer_part (traps->traps[0].top);
    rect.width  = _cairo_fixed_integer_part (traps->traps[0].right.p1.x) - rect.x;
    rect.height = _cairo_fixed_integer_part (traps->traps[0].bottom) - rect.y;

    return _cairo_surface_composite (op, src, NULL, dst,
				     rect.x, rect.y,
				     0, 0,
				     rect.x, rect.y,
				     rect.width, rect.height,
				     NULL);
}

/* Warning: This call modifies the coordinates of traps */
static cairo_status_t
_clip_and_composite_trapezoids (const cairo_pattern_t *src,
				cairo_operator_t op,
				cairo_surface_t *dst,
				cairo_traps_t *traps,
				cairo_antialias_t antialias,
				cairo_clip_t *clip,
				cairo_rectangle_int_t *extents)
{
    cairo_composite_traps_info_t traps_info;
    cairo_region_t *clip_region = NULL;
    cairo_bool_t clip_surface = FALSE;
    cairo_status_t status;

    if (traps->num_traps == 0 && _cairo_operator_bounded_by_mask (op))
	return CAIRO_STATUS_SUCCESS;

    if (clip != NULL) {
	status = _cairo_clip_get_region (clip, &clip_region);
	if (unlikely (_cairo_status_is_error (status)))
	    return status;
	if (unlikely (status == CAIRO_INT_STATUS_NOTHING_TO_DO))
	    return CAIRO_STATUS_SUCCESS;

	clip_surface = status == CAIRO_INT_STATUS_UNSUPPORTED;
    }

    /* Use a fast path if the trapezoids consist of a simple region,
     * but we can only do this if we do not have a clip surface, or can
     * substitute the mask with the clip.
     */
    if (! clip_surface ||
	(_cairo_operator_bounded_by_mask (op) && op != CAIRO_OPERATOR_SOURCE))
    {
	cairo_region_t *trap_region = NULL;

        if (_cairo_operator_bounded_by_source (op)) {
            status = _fill_rectangles (dst, op, src, traps, clip);
            if (status != CAIRO_INT_STATUS_UNSUPPORTED)
                return status;

            status = _composite_rectangle (dst, op, src, traps, clip);
            if (status != CAIRO_INT_STATUS_UNSUPPORTED)
                return status;
        }

	status = _cairo_traps_extract_region (traps, &trap_region);
	if (unlikely (_cairo_status_is_error (status)))
	    return status;

	if (trap_region != NULL) {
	    status = cairo_region_intersect_rectangle (trap_region, extents);
	    if (unlikely (status)) {
		cairo_region_destroy (trap_region);
		return status;
	    }

	    if (clip_region != NULL) {
		status = cairo_region_intersect (trap_region, clip_region);
		if (unlikely (status)) {
		    cairo_region_destroy (trap_region);
		    return status;
		}
	    }

	    if (_cairo_operator_bounded_by_mask (op)) {
		cairo_rectangle_int_t trap_extents;

		cairo_region_get_extents (trap_region, &trap_extents);
		if (! _cairo_rectangle_intersect (extents, &trap_extents)) {
		    cairo_region_destroy (trap_region);
		    return CAIRO_STATUS_SUCCESS;
		}
	    }

	    status = _clip_and_composite_region (src, op, dst,
						 trap_region,
						 clip_surface ? clip : NULL,
						 extents);
	    cairo_region_destroy (trap_region);

	    if (likely (status != CAIRO_INT_STATUS_UNSUPPORTED))
		return status;
	}
    }

    /* No fast path, exclude self-intersections and clip trapezoids. */
    if (traps->has_intersections) {
	if (traps->is_rectangular)
	    status = _cairo_bentley_ottmann_tessellate_rectangular_traps (traps, CAIRO_FILL_RULE_WINDING);
	else if (traps->is_rectilinear)
	    status = _cairo_bentley_ottmann_tessellate_rectilinear_traps (traps, CAIRO_FILL_RULE_WINDING);
	else
	    status = _cairo_bentley_ottmann_tessellate_traps (traps, CAIRO_FILL_RULE_WINDING);
	if (unlikely (status))
	    return status;
    }

    /* Otherwise render the trapezoids to a mask and composite in the usual
     * fashion.
     */
    traps_info.traps = traps;
    traps_info.antialias = antialias;

    return _clip_and_composite (clip, op, src,
				_composite_traps_draw_func,
				&traps_info, dst, extents);
}

typedef struct {
    cairo_polygon_t		*polygon;
    cairo_fill_rule_t		 fill_rule;
    cairo_antialias_t		 antialias;
} cairo_composite_spans_info_t;

static cairo_status_t
_composite_spans_draw_func (void                          *closure,
			    cairo_operator_t               op,
			    const cairo_pattern_t         *src,
			    cairo_surface_t               *dst,
			    int                            dst_x,
			    int                            dst_y,
			    const cairo_rectangle_int_t   *extents,
			    cairo_region_t		  *clip_region)
{
    cairo_composite_rectangles_t rects;
    cairo_composite_spans_info_t *info = closure;

    rects.source = *extents;
    rects.mask = *extents;
    rects.bounded = *extents;
    /* The incoming dst_x/y are where we're pretending the origin of
     * the dst surface is -- *not* the offset of a rectangle where
     * we'd like to place the result. */
    rects.bounded.x -= dst_x;
    rects.bounded.y -= dst_y;
    rects.unbounded = rects.bounded;
    rects.is_bounded = _cairo_operator_bounded_by_either (op);

    return _cairo_surface_composite_polygon (dst, op, src,
					     info->fill_rule,
					     info->antialias,
					     &rects,
					     info->polygon,
					     clip_region);
}

static cairo_status_t
_cairo_win32_surface_span_renderer_composite
                 (void                          *closure,
		  cairo_operator_t               op,
		  const cairo_pattern_t         *src,
                  cairo_image_surface_t         *mask,
		  cairo_win32_surface_t         *dst,
		  int                            dst_x,
		  int                            dst_y,
		  const cairo_rectangle_int_t   *extents,
		  cairo_region_t		*clip_region)
{
    cairo_status_t status = CAIRO_STATUS_SUCCESS;

    if (src == NULL || mask == NULL)
	return CAIRO_STATUS_SUCCESS;

    status = cairo_surface_status (&mask->base);
    if (status == CAIRO_STATUS_SUCCESS) {
	cairo_pattern_t *mask_pattern = cairo_pattern_create_for_surface (&mask->base);
	/* composite onto the image surface directly if we can */
	if (dst->image) {
	    GdiFlush(); /* XXX: I'm not sure if this needed or not */

	    status = dst->image->backend->composite (op,
		    src, mask_pattern, dst->image,
                    extents->x, extents->y,
		    0, 0,		/* mask.x, mask.y */
                    extents->x - dst_x, extents->y - dst_y,
                    extents->width, extents->height,
		    clip_region);
	} else {
	    /* otherwise go through the fallback_composite path which
	     * will do the appropriate surface acquisition */
	    status = _cairo_surface_fallback_composite (
		    op,
		    src, mask_pattern, &dst->base,
                    extents->x, extents->y,
		    0, 0,		/* mask.x, mask.y */
                    extents->x - dst_x, extents->y - dst_y,
                    extents->width, extents->height,
		    clip_region);
	}
	cairo_pattern_destroy (mask_pattern);

    }
    return status;
}

typedef struct _cairo_image_surface_span_renderer {
    cairo_span_renderer_t base;

    uint8_t *mask_data;
    uint32_t mask_stride;
} cairo_image_surface_span_renderer_t;

cairo_status_t
_cairo_image_surface_span (void *abstract_renderer,
			   int y, int height,
			   const cairo_half_open_span_t *spans,
			   unsigned num_spans);

static cairo_status_t
_composite_spans (void                          *closure,
		  cairo_operator_t               op,
		  const cairo_pattern_t         *src,
		  cairo_surface_t               *dst,
		  int                            dst_x,
		  int                            dst_y,
		  const cairo_rectangle_int_t   *extents,
		  cairo_region_t		*clip_region)
{
    cairo_composite_spans_info_t *info = closure;
    cairo_image_surface_span_renderer_t renderer;
    cairo_scan_converter_t *converter;
    cairo_image_surface_t *mask;
    cairo_status_t status;

    converter = _cairo_tor_scan_converter_create (extents->x, extents->y,
						  extents->x + extents->width,
						  extents->y + extents->height,
						  info->fill_rule);
    status = converter->add_polygon (converter, info->polygon);
    if (unlikely (status))
	goto CLEANUP_CONVERTER;

    /* TODO: support rendering to A1 surfaces (or: go add span
     * compositing to pixman.) */

    {
	mask = cairo_image_surface_create (CAIRO_FORMAT_A8,
				           extents->width,
                                           extents->height);

	if (cairo_surface_status(&mask->base)) {
	    status = _cairo_error (CAIRO_STATUS_NO_MEMORY);
	    goto CLEANUP_CONVERTER;
	}
    }

    renderer.base.render_rows = _cairo_image_surface_span;
    renderer.mask_stride = cairo_image_surface_get_stride (mask);
    renderer.mask_data = cairo_image_surface_get_data (mask);
    renderer.mask_data -= extents->y * renderer.mask_stride + extents->x;

    status = converter->generate (converter, &renderer.base);
    if (unlikely (status))
	goto CLEANUP_RENDERER;

    _cairo_win32_surface_span_renderer_composite
                 (closure,
		  op,
		  src,
                  mask,
		  (cairo_win32_surface_t*)dst, // ewwww
		  dst_x,
		  dst_y,
		  extents,
		  clip_region);
#if 0
    {
	pixman_image_t *src;
	int src_x, src_y;

	src = _pixman_image_for_pattern (pattern, FALSE, extents, &src_x, &src_y);
	if (unlikely (src == NULL)) {
	    status = _cairo_error (CAIRO_STATUS_NO_MEMORY);
	    goto CLEANUP_RENDERER;
	}

	pixman_image_composite32 (_pixman_operator (op), src, mask, dst,
                                  extents->x + src_x, extents->y + src_y,
                                  0, 0, /* mask.x, mask.y */
                                  extents->x - dst_x, extents->y - dst_y,
                                  extents->width, extents->height);
	pixman_image_unref (src);
    }
#endif
 CLEANUP_RENDERER:
    cairo_surface_destroy (mask);
 CLEANUP_CONVERTER:
    converter->destroy (converter);
    return status;
}



cairo_status_t
_cairo_win32_surface_fallback_paint (cairo_surface_t		*surface,
			       cairo_operator_t		 op,
			       const cairo_pattern_t	*source,
			       cairo_clip_t		*clip)
{
    cairo_composite_rectangles_t extents;
    cairo_rectangle_int_t rect;
    cairo_clip_path_t *clip_path = clip ? clip->path : NULL;
    cairo_box_t boxes_stack[32], *clip_boxes = boxes_stack;
    cairo_boxes_t  boxes;
    int num_boxes = ARRAY_LENGTH (boxes_stack);
    cairo_status_t status;
    cairo_traps_t traps;

    if (!_cairo_surface_get_extents (surface, &rect))
        ASSERT_NOT_REACHED;

    status = _cairo_composite_rectangles_init_for_paint (&extents,
							 &rect,
							 op, source,
							 clip);
    if (unlikely (status))
	return status;

    if (_cairo_clip_contains_extents (clip, &extents))
	clip = NULL;

    status = _cairo_clip_to_boxes (&clip, &extents, &clip_boxes, &num_boxes);
    if (unlikely (status))
	return status;

    /* If the clip cannot be reduced to a set of boxes, we will need to
     * use a clipmask. Paint is special as it is the only operation that
     * does not implicitly use a mask, so we may be able to reduce this
     * operation to a fill...
     */
    if (clip != NULL && clip_path->prev == NULL &&
	_cairo_operator_bounded_by_mask (op))
    {
	return _cairo_surface_fill (surface, op, source,
				    &clip_path->path,
				    clip_path->fill_rule,
				    clip_path->tolerance,
				    clip_path->antialias,
				    NULL);
    }

    /* meh, surface-fallback is dying anyway... */
    _cairo_boxes_init_for_array (&boxes, clip_boxes, num_boxes);
    status = _cairo_traps_init_boxes (&traps, &boxes);
    if (unlikely (status))
	goto CLEANUP_BOXES;

    status = _clip_and_composite_trapezoids (source, op, surface,
					     &traps, CAIRO_ANTIALIAS_DEFAULT,
					     clip,
                                             extents.is_bounded ? &extents.bounded : &extents.unbounded);
    _cairo_traps_fini (&traps);

CLEANUP_BOXES:
    if (clip_boxes != boxes_stack)
	free (clip_boxes);

    return status;
}

static cairo_status_t
_cairo_surface_mask_draw_func (void                        *closure,
			       cairo_operator_t             op,
			       const cairo_pattern_t       *src,
			       cairo_surface_t             *dst,
			       int                          dst_x,
			       int                          dst_y,
			       const cairo_rectangle_int_t *extents,
			       cairo_region_t		   *clip_region)
{
    cairo_pattern_t *mask = closure;
    cairo_status_t status;
    cairo_region_t *extents_region = NULL;

    if (clip_region == NULL &&
        !_cairo_operator_bounded_by_source (op)) {
        extents_region = cairo_region_create_rectangle (extents);
        if (unlikely (extents_region->status))
            return extents_region->status;
        cairo_region_translate (extents_region, -dst_x, -dst_y);
        clip_region = extents_region;
    }

    if (src) {
	status = _cairo_surface_composite (op,
                                           src, mask, dst,
                                           extents->x,         extents->y,
                                           extents->x,         extents->y,
                                           extents->x - dst_x, extents->y - dst_y,
                                           extents->width,     extents->height,
                                           clip_region);
    } else {
	status = _cairo_surface_composite (op,
                                           mask, NULL, dst,
                                           extents->x,         extents->y,
                                           0,                  0, /* unused */
                                           extents->x - dst_x, extents->y - dst_y,
                                           extents->width,     extents->height,
                                           clip_region);
    }

    if (extents_region)
        cairo_region_destroy (extents_region);

    return status;
}

cairo_status_t
_cairo_win32_surface_fallback_mask (cairo_surface_t		*surface,
			      cairo_operator_t		 op,
			      const cairo_pattern_t	*source,
			      const cairo_pattern_t	*mask,
			      cairo_clip_t		*clip)
{
    cairo_composite_rectangles_t extents;
    cairo_rectangle_int_t rect;
    cairo_status_t status;

    if (!_cairo_surface_get_extents (surface, &rect))
        ASSERT_NOT_REACHED;

    status = _cairo_composite_rectangles_init_for_mask (&extents,
							&rect,
							op, source, mask, clip);
    if (unlikely (status))
	return status;

    if (_cairo_clip_contains_extents (clip, &extents))
	clip = NULL;

    if (clip != NULL && extents.is_bounded) {
	status = _cairo_clip_rectangle (clip, &extents.bounded);
	if (unlikely (status))
	    return status;
    }

    return _clip_and_composite (clip, op, source,
				_cairo_surface_mask_draw_func,
				(void *) mask,
				surface,
                                extents.is_bounded ? &extents.bounded : &extents.unbounded);
}

cairo_status_t
_cairo_win32_surface_fallback_stroke (cairo_surface_t		*surface,
				cairo_operator_t	 op,
				const cairo_pattern_t	*source,
				cairo_path_fixed_t	*path,
				const cairo_stroke_style_t	*stroke_style,
				const cairo_matrix_t		*ctm,
				const cairo_matrix_t		*ctm_inverse,
				double			 tolerance,
				cairo_antialias_t	 antialias,
				cairo_clip_t		*clip)
{
    cairo_polygon_t polygon;
    cairo_traps_t traps;
    cairo_box_t boxes_stack[32], *clip_boxes = boxes_stack;
    int num_boxes = ARRAY_LENGTH (boxes_stack);
    cairo_composite_rectangles_t extents;
    cairo_rectangle_int_t rect;
    cairo_status_t status;

    if (!_cairo_surface_get_extents (surface, &rect))
        ASSERT_NOT_REACHED;

    status = _cairo_composite_rectangles_init_for_stroke (&extents,
							  &rect,
							  op, source,
							  path, stroke_style, ctm,
							  clip);
    if (unlikely (status))
	return status;

    if (_cairo_clip_contains_extents (clip, &extents))
	clip = NULL;

    status = _cairo_clip_to_boxes (&clip, &extents, &clip_boxes, &num_boxes);
    if (unlikely (status))
	return status;

    _cairo_polygon_init (&polygon);
    _cairo_polygon_limit (&polygon, clip_boxes, num_boxes);

    _cairo_traps_init (&traps);
    _cairo_traps_limit (&traps, clip_boxes, num_boxes);

    if (path->is_rectilinear) {
	status = _cairo_path_fixed_stroke_rectilinear_to_traps (path,
								stroke_style,
								ctm,
								&traps);
	if (likely (status == CAIRO_STATUS_SUCCESS))
	    goto DO_TRAPS;

	if (_cairo_status_is_error (status))
	    goto CLEANUP;
    }

    status = _cairo_path_fixed_stroke_to_polygon (path,
						  stroke_style,
						  ctm, ctm_inverse,
						  tolerance,
						  &polygon);
    if (unlikely (status))
	goto CLEANUP;

    if (polygon.num_edges == 0)
	goto DO_TRAPS;

    if (_cairo_operator_bounded_by_mask (op)) {
	_cairo_box_round_to_rectangle (&polygon.extents, &extents.mask);
	if (! _cairo_rectangle_intersect (&extents.bounded, &extents.mask))
	    goto CLEANUP;
    }

    if (antialias != CAIRO_ANTIALIAS_NONE) {
	cairo_composite_spans_info_t info;

	info.polygon = &polygon;
	info.fill_rule = CAIRO_FILL_RULE_WINDING;
	info.antialias = antialias;

	status = _clip_and_composite (clip, op, source,
				      _composite_spans,
				      &info, surface,
                                      extents.is_bounded ? &extents.bounded : &extents.unbounded);
	goto CLEANUP;
    }

    /* Fall back to trapezoid fills. */
    status = _cairo_bentley_ottmann_tessellate_polygon (&traps,
							&polygon,
							CAIRO_FILL_RULE_WINDING);
    if (unlikely (status))
	goto CLEANUP;

  DO_TRAPS:
    status = _clip_and_composite_trapezoids (source, op, surface,
					     &traps, antialias,
					     clip,
                                             extents.is_bounded ? &extents.bounded : &extents.unbounded);
  CLEANUP:
    _cairo_traps_fini (&traps);
    _cairo_polygon_fini (&polygon);
    if (clip_boxes != boxes_stack)
	free (clip_boxes);

    return status;
}

cairo_status_t
_cairo_win32_surface_fallback_fill (cairo_surface_t		*surface,
			      cairo_operator_t		 op,
			      const cairo_pattern_t	*source,
			      cairo_path_fixed_t	*path,
			      cairo_fill_rule_t		 fill_rule,
			      double			 tolerance,
			      cairo_antialias_t		 antialias,
			      cairo_clip_t		*clip)
{
    cairo_polygon_t polygon;
    cairo_traps_t traps;
    cairo_box_t boxes_stack[32], *clip_boxes = boxes_stack;
    int num_boxes = ARRAY_LENGTH (boxes_stack);
    cairo_bool_t is_rectilinear;
    cairo_composite_rectangles_t extents;
    cairo_rectangle_int_t rect;
    cairo_status_t status;

    if (!_cairo_surface_get_extents (surface, &rect))
        ASSERT_NOT_REACHED;

    status = _cairo_composite_rectangles_init_for_fill (&extents,
							&rect,
							op, source, path,
							clip);
    if (unlikely (status))
	return status;

    if (_cairo_clip_contains_extents (clip, &extents))
	clip = NULL;

    status = _cairo_clip_to_boxes (&clip, &extents, &clip_boxes, &num_boxes);
    if (unlikely (status))
	return status;

    _cairo_traps_init (&traps);
    _cairo_traps_limit (&traps, clip_boxes, num_boxes);

    _cairo_polygon_init (&polygon);
    _cairo_polygon_limit (&polygon, clip_boxes, num_boxes);

    if (_cairo_path_fixed_fill_is_empty (path))
	goto DO_TRAPS;

    is_rectilinear = _cairo_path_fixed_is_rectilinear_fill (path);
    if (is_rectilinear) {
	status = _cairo_path_fixed_fill_rectilinear_to_traps (path,
							      fill_rule,
							      &traps);
	if (likely (status == CAIRO_STATUS_SUCCESS))
	    goto DO_TRAPS;

	if (_cairo_status_is_error (status))
	    goto CLEANUP;
    }

    status = _cairo_path_fixed_fill_to_polygon (path, tolerance, &polygon);
    if (unlikely (status))
	goto CLEANUP;

    if (polygon.num_edges == 0)
	goto DO_TRAPS;

    if (_cairo_operator_bounded_by_mask (op)) {
	_cairo_box_round_to_rectangle (&polygon.extents, &extents.mask);
	if (! _cairo_rectangle_intersect (&extents.bounded, &extents.mask))
	    goto CLEANUP;
    }

    if (is_rectilinear) {
	status = _cairo_bentley_ottmann_tessellate_rectilinear_polygon (&traps,
									&polygon,
									fill_rule);
	if (likely (status == CAIRO_STATUS_SUCCESS))
	    goto DO_TRAPS;

	if (unlikely (_cairo_status_is_error (status)))
	    goto CLEANUP;
    }


    if (antialias != CAIRO_ANTIALIAS_NONE) {
	cairo_composite_spans_info_t info;

	info.polygon = &polygon;
	info.fill_rule = fill_rule;
	info.antialias = antialias;

	status = _clip_and_composite (clip, op, source,
				      _composite_spans,
				      &info, surface,
                                      extents.is_bounded ? &extents.bounded : &extents.unbounded);
	goto CLEANUP;
    }

    /* Fall back to trapezoid fills. */
    status = _cairo_bentley_ottmann_tessellate_polygon (&traps,
							&polygon,
							fill_rule);
    if (unlikely (status))
	goto CLEANUP;

  DO_TRAPS:
    status = _clip_and_composite_trapezoids (source, op, surface,
					     &traps, antialias,
					     clip,
                                             extents.is_bounded ? &extents.bounded : &extents.unbounded);
  CLEANUP:
    _cairo_traps_fini (&traps);
    _cairo_polygon_fini (&polygon);
    if (clip_boxes != boxes_stack)
	free (clip_boxes);

    return status;
}

static const cairo_surface_backend_t cairo_win32_surface_backend = {
    CAIRO_SURFACE_TYPE_WIN32,
    _cairo_win32_surface_create_similar,
    _cairo_win32_surface_finish,
    _cairo_win32_surface_acquire_source_image,
    _cairo_win32_surface_release_source_image,
    _cairo_win32_surface_acquire_dest_image,
    _cairo_win32_surface_release_dest_image,
    NULL, /* clone similar */
    _cairo_win32_surface_composite,
    _cairo_win32_surface_fill_rectangles,
    NULL, /* composite_trapezoids */
    NULL, /* create_span_renderer */
    NULL, /* check_span_renderer */
    NULL, /* copy_page */
    NULL, /* show_page */
    _cairo_win32_surface_get_extents,
    NULL, /* old_show_glyphs */
    NULL, /* get_font_options */
    _cairo_win32_surface_flush,
    NULL, /* mark_dirty_rectangle */
    NULL, /* scaled_font_fini */
    NULL, /* scaled_glyph_fini */

    _cairo_win32_surface_fallback_paint,
    _cairo_win32_surface_fallback_mask,
    _cairo_win32_surface_fallback_stroke,
    _cairo_win32_surface_fallback_fill,
    _cairo_win32_surface_show_glyphs,

    NULL,  /* snapshot */
    _cairo_win32_surface_is_similar,
};

/* Notes:
 *
 * Win32 alpha-understanding functions
 *
 * BitBlt - will copy full 32 bits from a 32bpp DIB to result
 *          (so it's safe to use for ARGB32->ARGB32 SOURCE blits)
 *          (but not safe going RGB24->ARGB32, if RGB24 is also represented
 *           as a 32bpp DIB, since the alpha isn't discarded!)
 *
 * AlphaBlend - if both the source and dest have alpha, even if AC_SRC_ALPHA isn't set,
 *              it will still copy over the src alpha, because the SCA value (255) will be
 *              multiplied by all the src components.
 */


cairo_int_status_t
_cairo_win32_save_initial_clip (HDC hdc, cairo_win32_surface_t *surface)
{
    RECT rect;
    int clipBoxType;
    int gm;
    XFORM saved_xform;

    /* GetClipBox/GetClipRgn and friends interact badly with a world transform
     * set.  GetClipBox returns values in logical (transformed) coordinates;
     * it's unclear what GetClipRgn returns, because the region is empty in the
     * case of a SIMPLEREGION clip, but I assume device (untransformed) coordinates.
     * Similarily, IntersectClipRect works in logical units, whereas SelectClipRgn
     * works in device units.
     *
     * So, avoid the whole mess and get rid of the world transform
     * while we store our initial data and when we restore initial coordinates.
     *
     * XXX we may need to modify x/y by the ViewportOrg or WindowOrg
     * here in GM_COMPATIBLE; unclear.
     */
    gm = GetGraphicsMode (hdc);
    if (gm == GM_ADVANCED) {
	GetWorldTransform (hdc, &saved_xform);
	ModifyWorldTransform (hdc, NULL, MWT_IDENTITY);
    }

    clipBoxType = GetClipBox (hdc, &rect);
    if (clipBoxType == ERROR) {
	_cairo_win32_print_gdi_error ("cairo_win32_surface_create");
	SetGraphicsMode (hdc, gm);
	/* XXX: Can we make a more reasonable guess at the error cause here? */
	return _cairo_error (CAIRO_STATUS_NO_MEMORY);
    }

    surface->clip_rect.x = rect.left;
    surface->clip_rect.y = rect.top;
    surface->clip_rect.width = rect.right - rect.left;
    surface->clip_rect.height = rect.bottom - rect.top;

    surface->initial_clip_rgn = NULL;
    surface->had_simple_clip = FALSE;

    if (clipBoxType == COMPLEXREGION) {
	surface->initial_clip_rgn = CreateRectRgn (0, 0, 0, 0);
	if (GetClipRgn (hdc, surface->initial_clip_rgn) <= 0) {
	    DeleteObject(surface->initial_clip_rgn);
	    surface->initial_clip_rgn = NULL;
	}
    } else if (clipBoxType == SIMPLEREGION) {
	surface->had_simple_clip = TRUE;
    }

    if (gm == GM_ADVANCED)
	SetWorldTransform (hdc, &saved_xform);

    return CAIRO_STATUS_SUCCESS;
}

cairo_int_status_t
_cairo_win32_restore_initial_clip (cairo_win32_surface_t *surface)
{
    cairo_int_status_t status = CAIRO_STATUS_SUCCESS;

    XFORM saved_xform;
    int gm = GetGraphicsMode (surface->dc);
    if (gm == GM_ADVANCED) {
	GetWorldTransform (surface->dc, &saved_xform);
	ModifyWorldTransform (surface->dc, NULL, MWT_IDENTITY);
    }

    /* initial_clip_rgn will either be a real region or NULL (which means reset to no clip region) */
    SelectClipRgn (surface->dc, surface->initial_clip_rgn);

    if (surface->had_simple_clip) {
	/* then if we had a simple clip, intersect */
	IntersectClipRect (surface->dc,
			   surface->clip_rect.x,
			   surface->clip_rect.y,
			   surface->clip_rect.x + surface->clip_rect.width,
			   surface->clip_rect.y + surface->clip_rect.height);
    }

    if (gm == GM_ADVANCED)
	SetWorldTransform (surface->dc, &saved_xform);

    return status;
}

void
_cairo_win32_debug_dump_hrgn (HRGN rgn, char *header)
{
    RGNDATA *rd;
    unsigned int z;

    if (header)
	fprintf (stderr, "%s\n", header);

    if (rgn == NULL) {
	fprintf (stderr, " NULL\n");
    }

    z = GetRegionData(rgn, 0, NULL);
    rd = (RGNDATA*) malloc(z);
    z = GetRegionData(rgn, z, rd);

    fprintf (stderr, " %ld rects, bounds: %ld %ld %ld %ld\n",
	     rd->rdh.nCount,
	     rd->rdh.rcBound.left,
	     rd->rdh.rcBound.top,
	     rd->rdh.rcBound.right - rd->rdh.rcBound.left,
	     rd->rdh.rcBound.bottom - rd->rdh.rcBound.top);

    for (z = 0; z < rd->rdh.nCount; z++) {
	RECT r = ((RECT*)rd->Buffer)[z];
	fprintf (stderr, " [%d]: [%ld %ld %ld %ld]\n",
		 z, r.left, r.top, r.right - r.left, r.bottom - r.top);
    }

    free(rd);
    fflush (stderr);
}

/**
 * cairo_win32_surface_set_can_convert_to_dib
 * @surface: a #cairo_surface_t
 * @can_convert: a #cairo_bool_t indicating whether this surface can
 *               be coverted to a DIB if necessary
 *
 * A DDB surface with this flag set can be converted to a DIB if it's
 * used as a source in a way that GDI can't natively handle; for
 * example, drawing a RGB24 DDB onto an ARGB32 DIB.  Doing this
 * conversion results in a significant speed optimization, because we
 * can call on pixman to perform the operation natively, instead of
 * reading the data from the DC each time.
 *
 * Return value: %CAIRO_STATUS_SUCCESS if the flag was successfully
 * changed, or an error otherwise.
 * 
 */
cairo_status_t
cairo_win32_surface_set_can_convert_to_dib (cairo_surface_t *asurface, cairo_bool_t can_convert)
{
    cairo_win32_surface_t *surface = (cairo_win32_surface_t*) asurface;
    if (surface->base.type != CAIRO_SURFACE_TYPE_WIN32)
	return CAIRO_STATUS_SURFACE_TYPE_MISMATCH;

    if (surface->bitmap) {
	if (can_convert)
	    surface->flags |= CAIRO_WIN32_SURFACE_CAN_CONVERT_TO_DIB;
	else
	    surface->flags &= ~CAIRO_WIN32_SURFACE_CAN_CONVERT_TO_DIB;
    }

    return CAIRO_STATUS_SUCCESS;
}

/**
 * cairo_win32_surface_get_can_convert_to_dib
 * @surface: a #cairo_surface_t
 * @can_convert: a #cairo_bool_t* that receives the return value
 *
 * Returns the value of the flag indicating whether the surface can be
 * converted to a DIB if necessary, as set by
 * cairo_win32_surface_set_can_convert_to_dib.
 *
 * Return value: %CAIRO_STATUS_SUCCESS if the flag was successfully
 * retreived, or an error otherwise.
 * 
 */
cairo_status_t
cairo_win32_surface_get_can_convert_to_dib (cairo_surface_t *asurface, cairo_bool_t *can_convert)
{
    cairo_win32_surface_t *surface = (cairo_win32_surface_t*) asurface;
    if (surface->base.type != CAIRO_SURFACE_TYPE_WIN32)
	return CAIRO_STATUS_SURFACE_TYPE_MISMATCH;

    *can_convert = ((surface->flags & CAIRO_WIN32_SURFACE_CAN_CONVERT_TO_DIB) != 0);
    return CAIRO_STATUS_SUCCESS;
}

int
cairo_win32_surface_get_width (cairo_surface_t *asurface)
{
    cairo_win32_surface_t *surface = (cairo_win32_surface_t*) asurface;
    if (surface->base.type != CAIRO_SURFACE_TYPE_WIN32)
	return CAIRO_STATUS_SURFACE_TYPE_MISMATCH;

    return surface->extents.width;
}

int
cairo_win32_surface_get_height (cairo_surface_t *asurface)
{
    cairo_win32_surface_t *surface = (cairo_win32_surface_t*) asurface;
    if (surface->base.type != CAIRO_SURFACE_TYPE_WIN32)
	return CAIRO_STATUS_SURFACE_TYPE_MISMATCH;

    return surface->extents.height;
}