summaryrefslogtreecommitdiff
path: root/source/fitz/draw-device.c
blob: 7d81e4d3f7cb3370544131187030204a08d0ea37 (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
#include "fitz-imp.h"
#include "glyph-cache-imp.h"
#include "draw-imp.h"

#include <string.h>
#include <assert.h>
#include <math.h>

#define STACK_SIZE 96

/* Enable the following to attempt to support knockout and/or isolated
 * blending groups. */
#define ATTEMPT_KNOCKOUT_AND_ISOLATED

/* Enable the following to help debug group blending. */
#undef DUMP_GROUP_BLENDS

/* Enable the following to help debug graphics stack pushes/pops */
#undef DUMP_STACK_CHANGES

typedef struct fz_draw_device_s fz_draw_device;

enum {
	FZ_DRAWDEV_FLAGS_TYPE3 = 1,
};

typedef struct fz_draw_state_s fz_draw_state;

struct fz_draw_state_s {
	fz_irect scissor;
	fz_pixmap *dest;
	fz_pixmap *mask;
	fz_pixmap *shape;
	fz_pixmap *group_alpha;
	int blendmode;
	int id, encache;
	float alpha;
	fz_matrix ctm;
	float xstep, ystep;
	fz_irect area;
};

struct fz_draw_device_s
{
	fz_device super;
	fz_matrix transform;
	fz_rasterizer *rast;
	fz_default_colorspaces *default_cs;
	fz_colorspace *proof_cs;
	int flags;
	int resolve_spots;
	int top;
	fz_scale_cache *cache_x;
	fz_scale_cache *cache_y;
	fz_draw_state *stack;
	int stack_cap;
	fz_draw_state init_stack[STACK_SIZE];
};

#ifdef DUMP_GROUP_BLENDS

#include <stdio.h>

static int group_dump_count = 0;

static void fz_dump_blend(fz_context *ctx, const char *s, fz_pixmap *pix)
{
	char name[80];
	int psd = 0;

	if (!pix)
		return;

	if (pix->s || fz_colorspace_is_subtractive(ctx, pix->colorspace))
		psd = 1;

	fz_snprintf(name, sizeof(name), "dump%02d.%s", group_dump_count, psd ? "psd" : "png");
	printf("%s%02d%s(%p)", s ? s : "", group_dump_count++, psd ? "(PSD)" : "", pix);
	if (psd)
		fz_save_pixmap_as_psd(ctx, pix, name);
	else
		fz_save_pixmap_as_png(ctx, pix, name);
}

static void dump_spaces(int x, const char *s)
{
	int i;
	for (i = 0; i < x; i++)
		printf(" ");
	printf("%s", s);
}

#endif

#ifdef DUMP_STACK_CHANGES
#define STACK_PUSHED(A) stack_change(ctx, dev, ">" ## A)
#define STACK_POPPED(A) stack_change(ctx, dev, "<" ## A)
#define STACK_CONVERT(A) stack_change(ctx, dev, A)

static void stack_change(fz_context *ctx, fz_draw_device *dev, char *s)
{
	int depth = dev->top;
	int n;

	if (*s != '<')
		depth--;
	n = depth;
	while (n--)
		fputc(' ', stderr);
	fprintf(stderr, "%s (%d)\n", s, depth);
}
#else
#define STACK_PUSHED(A) do {} while (0)
#define STACK_POPPED(A) do {} while (0)
#define STACK_CONVERT(A) do {} while (0)
#endif

/* Logic below assumes that default cs is set to color context cs if there
 * was not a default in the document for that particular cs
 */
static fz_colorspace *fz_default_colorspace(fz_context *ctx, fz_default_colorspaces *default_cs, fz_colorspace *cs)
{
	if (cs == NULL)
		return NULL;
	if (default_cs == NULL)
		return cs;

	switch (fz_colorspace_type(ctx, cs))
	{
	case FZ_COLORSPACE_GRAY:
		if (cs == fz_device_gray(ctx))
			return fz_default_gray(ctx, default_cs);
		break;
	case FZ_COLORSPACE_RGB:
		if (cs == fz_device_rgb(ctx))
			return fz_default_rgb(ctx, default_cs);
		break;
	case FZ_COLORSPACE_CMYK:
		if (cs == fz_device_cmyk(ctx))
			return fz_default_cmyk(ctx, default_cs);
		break;
	default:
		break;
	}
	return cs;
}

static void fz_grow_stack(fz_context *ctx, fz_draw_device *dev)
{
	int max = dev->stack_cap * 2;
	fz_draw_state *stack;

	if (dev->stack == &dev->init_stack[0])
	{
		stack = Memento_label(fz_malloc_array(ctx, max, sizeof *stack), "draw device stack");
		memcpy(stack, dev->stack, sizeof(*stack) * dev->stack_cap);
	}
	else
	{
		stack = fz_resize_array(ctx, dev->stack, max, sizeof(*stack));
	}
	dev->stack = stack;
	dev->stack_cap = max;
}

/* 'Push' the stack. Returns a pointer to the current state, with state[1]
 * already having been initialised to contain the same thing. Simply
 * change any contents of state[1] that you want to and continue. */
static fz_draw_state *
push_stack(fz_context *ctx, fz_draw_device *dev)
{
	fz_draw_state *state;

	if (dev->top == dev->stack_cap-1)
		fz_grow_stack(ctx, dev);
	state = &dev->stack[dev->top];
	dev->top++;
	memcpy(&state[1], state, sizeof(*state));
	return state;
}

static void emergency_pop_stack(fz_context *ctx, fz_draw_device *dev, fz_draw_state *state)
{
	if (state[1].mask != state[0].mask)
		fz_drop_pixmap(ctx, state[1].mask);
	if (state[1].dest != state[0].dest)
		fz_drop_pixmap(ctx, state[1].dest);
	if (state[1].shape != state[0].shape)
		fz_drop_pixmap(ctx, state[1].shape);
	if (state[1].group_alpha != state[0].group_alpha)
		fz_drop_pixmap(ctx, state[1].group_alpha);
	dev->top--;
	STACK_POPPED("emergency");
	fz_rethrow(ctx);
}

static fz_draw_state *
fz_knockout_begin(fz_context *ctx, fz_draw_device *dev)
{
	fz_irect bbox, ga_bbox;
	fz_pixmap *dest, *shape;
	fz_pixmap *ga = NULL;
	fz_draw_state *state = &dev->stack[dev->top];
	int isolated = state->blendmode & FZ_BLEND_ISOLATED;

	if ((state->blendmode & FZ_BLEND_KNOCKOUT) == 0)
		return state;

	state = push_stack(ctx, dev);
	STACK_PUSHED("knockout");

	fz_pixmap_bbox(ctx, state->dest, &bbox);
	fz_intersect_irect(&bbox, &state->scissor);
	dest = fz_new_pixmap_with_bbox(ctx, state->dest->colorspace, &bbox, state->dest->seps, state->dest->alpha);
	if (state[0].group_alpha)
	{
		fz_pixmap_bbox(ctx, state->group_alpha, &ga_bbox);
		fz_intersect_irect(&ga_bbox, &state->scissor);
		ga = fz_new_pixmap_with_bbox(ctx, state->group_alpha->colorspace, &ga_bbox, state->group_alpha->seps, state->group_alpha->alpha);
	}

	if (isolated)
	{
		fz_clear_pixmap(ctx, dest);
		if (ga)
			fz_clear_pixmap(ctx, ga);
	}
	else
	{
		/* Find the last but one destination to copy */
		int i = dev->top-1; /* i = the one on entry (i.e. the last one) */
		fz_draw_state *prev = state;
		while (i > 0)
		{
			prev = &dev->stack[--i];
			if (prev->dest != state->dest)
				break;
		}
		if (prev->dest)
		{
			fz_copy_pixmap_rect(ctx, dest, prev->dest, &bbox, dev->default_cs);
			if (ga)
			{
				if (prev->group_alpha)
					fz_copy_pixmap_rect(ctx, ga, prev->group_alpha, &ga_bbox, dev->default_cs);
				else
					fz_clear_pixmap(ctx, ga);
			}
		}
		else
		{
			fz_clear_pixmap(ctx, dest);
			if (ga)
				fz_clear_pixmap(ctx, ga);
		}
	}

	/* Knockout groups (and only knockout groups) rely on shape */
	shape = fz_new_pixmap_with_bbox(ctx, NULL, &bbox, NULL, 1);
	fz_clear_pixmap(ctx, shape);
#ifdef DUMP_GROUP_BLENDS
	dump_spaces(dev->top-1, "");
	fz_dump_blend(ctx, "Knockout begin: background is ", dest);
	if (shape)
		fz_dump_blend(ctx, "/S=", shape);
	if (ga)
		fz_dump_blend(ctx, "/GA=", ga);
	printf("\n");
#endif
	state[1].group_alpha = ga;
	state[1].scissor = bbox;
	state[1].dest = dest;
	state[1].shape = shape;
	state[1].blendmode &= ~(FZ_BLEND_MODEMASK | FZ_BLEND_ISOLATED);

	return &state[1];
}

static void fz_knockout_end(fz_context *ctx, fz_draw_device *dev)
{
	fz_draw_state *state;

	if (dev->top == 0)
	{
		fz_warn(ctx, "unexpected knockout end");
		return;
	}
	state = &dev->stack[--dev->top];
	STACK_POPPED("knockout");
	if ((state[0].blendmode & FZ_BLEND_KNOCKOUT) == 0)
		return;

	assert((state[1].blendmode & FZ_BLEND_ISOLATED) == 0);
	assert((state[1].blendmode & FZ_BLEND_MODEMASK) == 0);

#ifdef DUMP_GROUP_BLENDS
	dump_spaces(dev->top, "");
	fz_dump_blend(ctx, "Knockout end: blending ", state[1].dest);
	if (state[1].shape)
		fz_dump_blend(ctx, "/S=", state[1].shape);
	if (state[1].group_alpha)
		fz_dump_blend(ctx, "/GA=", state[1].group_alpha);
	fz_dump_blend(ctx, " onto ", state[0].dest);
	if (state[0].shape)
		fz_dump_blend(ctx, "/S=", state[0].shape);
	if (state[0].group_alpha)
		fz_dump_blend(ctx, "/GA=", state[0].group_alpha);
	if ((state->blendmode & FZ_BLEND_MODEMASK) != 0)
		printf(" (blend %d)", state->blendmode & FZ_BLEND_MODEMASK);
	if ((state->blendmode & FZ_BLEND_ISOLATED) != 0)
		printf(" (isolated)");
	printf(" (knockout)");
#endif
	assert(state[1].shape);
	fz_blend_pixmap_knockout(ctx, state[0].dest, state[1].dest, state[1].shape);

	/* The following test should not be required, but just occasionally
	 * errors can cause the stack to get out of sync, and this saves our
	 * bacon. */
	if (state[0].dest != state[1].dest)
		fz_drop_pixmap(ctx, state[1].dest);
	if (state[1].group_alpha && state[0].group_alpha != state[1].group_alpha)
	{
		if (state[0].group_alpha)
			fz_blend_pixmap_knockout(ctx, state[0].group_alpha, state[1].group_alpha, state[1].shape);
		fz_drop_pixmap(ctx, state[1].group_alpha);
	}
	if (state[0].shape != state[1].shape)
	{
		if (state[0].shape)
			fz_paint_pixmap(state[0].shape, state[1].shape, 255);
		fz_drop_pixmap(ctx, state[1].shape);
	}
#ifdef DUMP_GROUP_BLENDS
	fz_dump_blend(ctx, " to get ", state[0].dest);
	if (state[0].shape)
		fz_dump_blend(ctx, "/S=", state[0].shape);
	if (state[0].group_alpha)
		fz_dump_blend(ctx, "/GA=", state[0].group_alpha);
	printf("\n");
#endif
}

static inline fz_matrix concat(const fz_matrix *one, const fz_matrix *two)
{
	fz_matrix ctm;
	fz_concat(&ctm, one, two);
	return ctm;
}

static int
colors_supported(fz_context *ctx, fz_colorspace *cs, fz_pixmap *dest)
{
	/* Even if we support separations in the destination, if the color space has CMY or K as one of
	 * its colorants and we are in RGB or Gray we will want to do the tint transform */
	if (!fz_colorspace_is_subtractive(ctx, dest->colorspace) && fz_colorspace_device_n_has_cmyk(ctx, cs))
		return 0;

	/* If we have separations then we should support it */
	if (dest->seps)
		return 1;

	/* If our destination is CMYK and the source color space is only C, M, Y or K we support it
	 * even if we have no seps */
	if (fz_colorspace_is_subtractive(ctx, dest->colorspace))
	{
		int i, n;
		if (fz_colorspace_device_n_has_only_cmyk(ctx, cs))
			return 1;

		n = fz_colorspace_n(ctx, cs);
		for (i = 0; i < n; i++)
		{
			const char *name = fz_colorspace_colorant(ctx, cs, i);

			if (!name)
				return 0;
			if (!strcmp(name, "All"))
				continue;
			if (!strcmp(name, "Cyan"))
				continue;
			if (!strcmp(name, "Magenta"))
				continue;
			if (!strcmp(name, "Yellow"))
				continue;
			if (!strcmp(name, "Black"))
				continue;
			if (!strcmp(name, "None"))
				continue;
			return 0;
		}
		return 1;
	}

	return 0;
}

static fz_overprint *
set_op_from_spaces(fz_context *ctx, fz_overprint *op, const fz_pixmap *dest, const fz_colorspace *src, int opm)
{
	int dn, sn, i, j, dc;

	if (!op)
		return NULL;

	if (!fz_colorspace_is_subtractive(ctx, src) || !fz_colorspace_is_subtractive(ctx, dest->colorspace))
		return NULL;

	sn = fz_colorspace_n(ctx, src);
	dn = dest->n - dest->alpha;
	dc = dn - dest->s;

	/* If a source colorant is not mentioned in the destination
	 * colorants (either process or spots), then it will be mapped
	 * to process colorants. In this case, the process colorants
	 * can never be protected.
	 */
	for (j = 0; j < sn; j++)
	{
		/* Run through the colorants looking for one that isn't mentioned.
		 * i.e. continue if we we find one, break if not. */
		const char *sname = fz_colorspace_colorant(ctx, src, j);
		if (!sname)
			break;
		if (!strcmp(sname, "All") || !strcmp(sname, "None"))
			continue;
		for (i = 0; i < dc; i++)
		{
			const char *name = fz_colorspace_colorant(ctx, dest->colorspace, i);
			if (!name)
				continue;
			if (!strcmp(name, sname))
				break;
		}
		if (i != dc)
			continue;
		for (; i < dn; i++)
		{
			const char *name = fz_separation_name(ctx, dest->seps, i - dc);
			if (!name)
				continue;
			if (!strcmp(name, sname))
				break;
		}
		if (i == dn)
		{
			/* This source colorant wasn't mentioned */
			break;
		}
	}
	if (j == sn)
	{
		/* We did not find any source colorants that weren't mentioned, so
		 * process colorants might not be touched... */
		for (i = 0; i < dc; i++)
		{
			const char *name = fz_colorspace_colorant(ctx, dest->colorspace, i);

			for (j = 0; j < sn; j++)
			{
				const char *sname = fz_colorspace_colorant(ctx, src, j);
				if (!name || !sname)
					continue;
				if (!strcmp(name, sname))
					break;
				if (!strcmp(sname, "All"))
					break;
			}
			if (j == sn)
				fz_set_overprint(op, i);
		}
	}
	for (i = dc; i < dn; i++)
	{
		const char *name = fz_separation_name(ctx, dest->seps, i - dc);

		for (j = 0; j < sn; j++)
		{
			const char *sname = fz_colorspace_colorant(ctx, src, j);
			if (!name || !sname)
				continue;
			if (!strcmp(name, sname))
				break;
			if (!strcmp(sname, "All"))
				break;
		}
		if (j == sn)
			fz_set_overprint(op, i);
	}

	return op;
}

static fz_overprint *
resolve_color(fz_context *ctx, fz_overprint *op, const float *color, fz_colorspace *colorspace, float alpha, const fz_color_params *color_params, unsigned char *colorbv, fz_pixmap *dest)
{
	float colorfv[FZ_MAX_COLORS];
	int i;
	int n = dest->n - dest->alpha;
	fz_colorspace *model = dest->colorspace;
	int devn, devgray;
	int effective_opm;

	if (colorspace == NULL && model != NULL)
		fz_throw(ctx, FZ_ERROR_GENERIC, "color destination requires source color");

	if (color_params == NULL)
		color_params = fz_default_color_params(ctx);

	effective_opm = color_params->opm;
	devn = fz_colorspace_is_device_n(ctx, colorspace);
	devgray = fz_colorspace_is_device_gray(ctx, colorspace);
	/* We can only overprint when enabled, and when we are in a subtractive colorspace */
	if (!color_params || color_params->op == 0 || !fz_colorspace_is_subtractive(ctx, dest->colorspace))
		op = NULL;
	else if (devgray)
	{
		/* Device Gray is additive, but seems to still be counted for overprint
		 * (see Ghent_V3.0/030_Gray_K_black_OP_x1a.pdf 030.pdf). */
	}
	/* If we are in a CMYK space (i.e. not a devn one, given we know we are subtractive at this point),
	 * then we only adhere to overprint mode if it's the same space as the destination. */
	/* FIXME: Possibly we need a better equivalency test here. */
	else if (!devn && colorspace != dest->colorspace)
	{
		effective_opm = 0;
	}

	if (n == 0)
		i = 0;
	else if (devn && colors_supported(ctx, colorspace, dest))
	{
		fz_convert_separation_colors(ctx, color_params, dest->colorspace, dest->seps, colorfv, colorspace, color);
		for (i = 0; i < n; i++)
			colorbv[i] = colorfv[i] * 255;
		op = set_op_from_spaces(ctx, op, dest, colorspace, effective_opm);
	}
	else
	{
		int c = n - dest->s;
		fz_convert_color(ctx, color_params, NULL, dest->colorspace, colorfv, colorspace, color);
		for (i = 0; i < c; i++)
			colorbv[i] = colorfv[i] * 255;
		for (; i < n; i++)
			colorbv[i] = 0;

	}
	colorbv[i] = alpha * 255;

	/* op && !devn => overpinting in cmyk or devicegray. */
	if (op && !devn)
	{
		/* We are overprinting, so protect all spots. */
		for (i = 4; i < n; i++)
			fz_set_overprint(op, i);
		/* If OPM, then protect all components for which the color values are zero.
		 * (but only if we're in devicecmyk). */
		if (effective_opm == 1 && colorspace != fz_device_gray(ctx))
			for (i = 0; i < n; i++)
				if (colorfv[i] == 0)
					fz_set_overprint(op, i);
	}

	return op;
}

static fz_draw_state *
push_group_for_separations(fz_context *ctx, fz_draw_device *dev, const fz_color_params *color_params, fz_default_colorspaces *default_cs)
{
	fz_separations *clone = fz_clone_separations_for_overprint(ctx, dev->stack[0].dest->seps);
	fz_colorspace *oi = fz_default_output_intent(ctx, default_cs);
	fz_colorspace *dcs = fz_device_cmyk(ctx);

	/* Pick sep target CMYK based upon proof and output intent settings.  Priority
	* is oi, proof, devicecmyk. */
	if (dev->proof_cs)
	{
		dcs = dev->proof_cs;
	}

	if (oi)
	{
		dcs = oi;
	}

	/* Not needed if dest has the seps, and we are not using a proof or the target is the same as the prooof and we don't have an oi or the target is the same as the oi */
	if ((clone == dev->stack[0].dest->seps) && (dev->proof_cs == NULL || dev->proof_cs == dev->stack[0].dest->colorspace) && (oi == NULL || oi == dev->stack[0].dest->colorspace))
	{
		fz_drop_separations(ctx, clone);
		dev->resolve_spots = 0;
		return &dev->stack[0];
	}

	/* Make a new pixmap to render to. */
	fz_try(ctx)
	{
		dev->stack[1] = dev->stack[0];
		dev->stack[1].dest = NULL; /* So we are safe to destroy */
		dev->stack[1].dest = fz_clone_pixmap_area_with_different_seps(ctx, dev->stack[0].dest, &dev->stack[0].scissor, dcs, clone, color_params, default_cs);
		dev->top++;
	}
	fz_always(ctx)
		fz_drop_separations(ctx, clone);
	fz_catch(ctx)
		fz_rethrow(ctx);

	return &dev->stack[1];
}

static void
fz_draw_fill_path(fz_context *ctx, fz_device *devp, const fz_path *path, int even_odd, const fz_matrix *in_ctm,
	fz_colorspace *colorspace_in, const float *color, float alpha, const fz_color_params *color_params)
{
	fz_draw_device *dev = (fz_draw_device*)devp;
	fz_matrix ctm = concat(in_ctm, &dev->transform);
	fz_rasterizer *rast = dev->rast;
	fz_colorspace *colorspace = fz_default_colorspace(ctx, dev->default_cs, colorspace_in);
	float expansion = fz_matrix_expansion(&ctm);
	float flatness = 0.3f / expansion;
	unsigned char colorbv[FZ_MAX_COLORS + 1];
	fz_irect bbox;
	fz_draw_state *state = &dev->stack[dev->top];
	fz_overprint op = { { 0 } };
	fz_overprint *eop;

	if (dev->top == 0 && dev->resolve_spots)
		state = push_group_for_separations(ctx, dev, color_params, dev->default_cs);

	if (flatness < 0.001f)
		flatness = 0.001f;

	fz_intersect_irect(fz_pixmap_bbox_no_ctx(state->dest, &bbox), &state->scissor);
	if (fz_flatten_fill_path(ctx, rast, path, &ctm, flatness, &bbox, &bbox))
		return;

	if (state->blendmode & FZ_BLEND_KNOCKOUT)
		state = fz_knockout_begin(ctx, dev);

	eop = resolve_color(ctx, &op, color, colorspace, alpha, color_params, colorbv, state->dest);

	fz_convert_rasterizer(ctx, rast, even_odd, state->dest, colorbv, eop);
	if (state->shape)
	{
		if (!rast->fns.reusable)
			fz_flatten_fill_path(ctx, rast, path, &ctm, flatness, &bbox, NULL);

		colorbv[0] = 255;
		fz_convert_rasterizer(ctx, rast, even_odd, state->shape, colorbv, 0);
	}
	if (state->group_alpha)
	{
		if (!rast->fns.reusable)
			fz_flatten_fill_path(ctx, rast, path, &ctm, flatness, &bbox, NULL);

		colorbv[0] = alpha * 255;
		fz_convert_rasterizer(ctx, rast, even_odd, state->group_alpha, colorbv, 0);
	}

	if (state->blendmode & FZ_BLEND_KNOCKOUT)
		fz_knockout_end(ctx, dev);
}

static void
fz_draw_stroke_path(fz_context *ctx, fz_device *devp, const fz_path *path, const fz_stroke_state *stroke, const fz_matrix *in_ctm,
	fz_colorspace *colorspace_in, const float *color, float alpha, const fz_color_params *color_params)
{
	fz_draw_device *dev = (fz_draw_device*)devp;
	fz_matrix ctm = concat(in_ctm, &dev->transform);
	fz_rasterizer *rast = dev->rast;
	fz_colorspace *colorspace = fz_default_colorspace(ctx, dev->default_cs, colorspace_in);
	float expansion = fz_matrix_expansion(&ctm);
	float flatness = 0.3f / expansion;
	float linewidth = stroke->linewidth;
	unsigned char colorbv[FZ_MAX_COLORS + 1];
	fz_irect bbox;
	float aa_level = 2.0f/(fz_rasterizer_graphics_aa_level(rast)+2);
	fz_draw_state *state = &dev->stack[dev->top];
	float mlw = fz_rasterizer_graphics_min_line_width(rast);
	fz_overprint op = { { 0 } };
	fz_overprint *eop;

	if (dev->top == 0 && dev->resolve_spots)
		state = push_group_for_separations(ctx, dev, color_params, dev->default_cs);

	if (mlw > aa_level)
		aa_level = mlw;
	if (linewidth * expansion < aa_level)
		linewidth = aa_level / expansion;
	if (flatness < 0.001f)
		flatness = 0.001f;

	fz_intersect_irect(fz_pixmap_bbox_no_ctx(state->dest, &bbox), &state->scissor);
	if (fz_flatten_stroke_path(ctx, rast, path, stroke, &ctm, flatness, linewidth, &bbox, &bbox))
		return;

	if (state->blendmode & FZ_BLEND_KNOCKOUT)
		state = fz_knockout_begin(ctx, dev);

	eop = resolve_color(ctx, &op, color, colorspace, alpha, color_params, colorbv, state->dest);

#ifdef DUMP_GROUP_BLENDS
	dump_spaces(dev->top, "");
	fz_dump_blend(ctx, "Before stroke ", state->dest);
	if (state->shape)
		fz_dump_blend(ctx, "/S=", state->shape);
	if (state->group_alpha)
		fz_dump_blend(ctx, "/GA=", state->group_alpha);
	printf("\n");
#endif
	fz_convert_rasterizer(ctx, rast, 0, state->dest, colorbv, eop);
	if (state->shape)
	{
		if (!rast->fns.reusable)
			(void)fz_flatten_stroke_path(ctx, rast, path, stroke, &ctm, flatness, linewidth, &bbox, NULL);

		colorbv[0] = 255;
		fz_convert_rasterizer(ctx, rast, 0, state->shape, colorbv, 0);
	}
	if (state->group_alpha)
	{
		if (!rast->fns.reusable)
			(void)fz_flatten_stroke_path(ctx, rast, path, stroke, &ctm, flatness, linewidth, &bbox, NULL);

		colorbv[0] = 255 * alpha;
		fz_convert_rasterizer(ctx, rast, 0, state->group_alpha, colorbv, 0);
	}
#ifdef DUMP_GROUP_BLENDS
	dump_spaces(dev->top, "");
	fz_dump_blend(ctx, "After stroke ", state->dest);
	if (state->shape)
		fz_dump_blend(ctx, "/S=", state->shape);
	if (state->group_alpha)
		fz_dump_blend(ctx, "/GA=", state->group_alpha);
	printf("\n");
#endif

	if (state->blendmode & FZ_BLEND_KNOCKOUT)
		fz_knockout_end(ctx, dev);
}

static void
fz_draw_clip_path(fz_context *ctx, fz_device *devp, const fz_path *path, int even_odd, const fz_matrix *in_ctm, const fz_rect *scissor)
{
	fz_draw_device *dev = (fz_draw_device*)devp;
	fz_matrix ctm = concat(in_ctm, &dev->transform);
	fz_rasterizer *rast = dev->rast;

	float expansion = fz_matrix_expansion(&ctm);
	float flatness = 0.3f / expansion;
	fz_irect bbox;
	fz_draw_state *state = &dev->stack[dev->top];
	fz_colorspace *model;
	fz_irect local_scissor;
	fz_irect *scissor_ptr;

	if (dev->top == 0 && dev->resolve_spots)
		(void)push_group_for_separations(ctx, dev, fz_default_color_params(ctx)/* FIXME */, dev->default_cs);

	if (flatness < 0.001f)
		flatness = 0.001f;

	state = push_stack(ctx, dev);
	STACK_PUSHED("clip path");
	model = state->dest->colorspace;

	scissor_ptr = &state->scissor;
	if (scissor)
	{
		fz_rect tscissor = *scissor;
		fz_transform_rect(&tscissor, &dev->transform);
		scissor_ptr = fz_intersect_irect(fz_irect_from_rect(&local_scissor, &tscissor), scissor_ptr);
	}
	fz_intersect_irect(fz_pixmap_bbox_no_ctx(state->dest, &bbox), scissor_ptr);

	if (fz_flatten_fill_path(ctx, rast, path, &ctm, flatness, &bbox, &bbox) || fz_is_rect_rasterizer(ctx, rast))
	{
		state[1].scissor = bbox;
		state[1].mask = NULL;
#ifdef DUMP_GROUP_BLENDS
		dump_spaces(dev->top-1, "Clip (rectangular) begin\n");
#endif
		return;
	}

	fz_try(ctx)
	{
		state[1].mask = fz_new_pixmap_with_bbox(ctx, NULL, &bbox, NULL, 1);
		fz_clear_pixmap(ctx, state[1].mask);
		state[1].dest = fz_new_pixmap_with_bbox(ctx, model, &bbox, state[0].dest->seps, state[0].dest->alpha);
		fz_copy_pixmap_rect(ctx, state[1].dest, state[0].dest, &bbox, dev->default_cs);
		if (state[1].shape)
		{
			state[1].shape = fz_new_pixmap_with_bbox(ctx, NULL, &bbox, NULL, 1);
			fz_clear_pixmap(ctx, state[1].shape);
		}
		if (state[1].group_alpha)
		{
			state[1].group_alpha = fz_new_pixmap_with_bbox(ctx, NULL, &bbox, NULL, 1);
			fz_clear_pixmap(ctx, state[1].group_alpha);
		}

		fz_convert_rasterizer(ctx, rast, even_odd, state[1].mask, NULL, 0);

		state[1].scissor = bbox;
#ifdef DUMP_GROUP_BLENDS
		dump_spaces(dev->top-1, "Clip (non-rectangular) begin\n");
#endif
	}
	fz_catch(ctx)
	{
		emergency_pop_stack(ctx, dev, state);
	}
}

static void
fz_draw_clip_stroke_path(fz_context *ctx, fz_device *devp, const fz_path *path, const fz_stroke_state *stroke, const fz_matrix *in_ctm, const fz_rect *scissor)
{
	fz_draw_device *dev = (fz_draw_device*)devp;
	fz_matrix ctm = concat(in_ctm, &dev->transform);
	fz_rasterizer *rast = dev->rast;

	float expansion = fz_matrix_expansion(&ctm);
	float flatness = 0.3f / expansion;
	float linewidth = stroke->linewidth;
	fz_irect bbox;
	fz_draw_state *state = &dev->stack[dev->top];
	fz_colorspace *model;
	float aa_level = 2.0f/(fz_rasterizer_graphics_aa_level(rast)+2);
	float mlw = fz_rasterizer_graphics_min_line_width(rast);
	fz_irect local_scissor;
	fz_irect *scissor_ptr;

	if (dev->top == 0 && dev->resolve_spots)
		(void)push_group_for_separations(ctx, dev, fz_default_color_params(ctx) /* FIXME */, dev->default_cs);

	if (mlw > aa_level)
		aa_level = mlw;
	if (linewidth * expansion < aa_level)
		linewidth = aa_level / expansion;
	if (flatness < 0.001f)
		flatness = 0.001f;

	state = push_stack(ctx, dev);
	STACK_PUSHED("clip stroke");
	model = state->dest->colorspace;

	scissor_ptr = &state->scissor;
	if (scissor)
	{
		fz_rect tscissor = *scissor;
		fz_transform_rect(&tscissor, &dev->transform);
		scissor_ptr = fz_intersect_irect(fz_irect_from_rect(&local_scissor, &tscissor), scissor_ptr);
	}
	fz_intersect_irect(fz_pixmap_bbox_no_ctx(state->dest, &bbox), scissor_ptr);

	if (fz_flatten_stroke_path(ctx, rast, path, stroke, &ctm, flatness, linewidth, &bbox, &bbox))
	{
		state[1].scissor = bbox;
		state[1].mask = NULL;
#ifdef DUMP_GROUP_BLENDS
		dump_spaces(dev->top-1, "Clip (stroke, empty) begin\n");
#endif
		return;
	}

	fz_try(ctx)
	{
		state[1].mask = fz_new_pixmap_with_bbox(ctx, NULL, &bbox, NULL, 1);
		fz_clear_pixmap(ctx, state[1].mask);
		/* When there is no alpha in the current destination (state[0].dest->alpha == 0)
		 * we have a choice. We can either create the new destination WITH alpha, or
		 * we can copy the old pixmap contents in. We opt for the latter here, but
		 * may want to revisit this decision in the future. */
		state[1].dest = fz_new_pixmap_with_bbox(ctx, model, &bbox, state[0].dest->seps, state[0].dest->alpha);
		if (state[0].dest->alpha)
			fz_clear_pixmap(ctx, state[1].dest);
		else
			fz_copy_pixmap_rect(ctx, state[1].dest, state[0].dest, &bbox, dev->default_cs);
		if (state->shape)
		{
			state[1].shape = fz_new_pixmap_with_bbox(ctx, NULL, &bbox, NULL, 1);
			fz_clear_pixmap(ctx, state[1].shape);
		}
		if (state->group_alpha)
		{
			state[1].group_alpha = fz_new_pixmap_with_bbox(ctx, NULL, &bbox, NULL, 1);
			fz_clear_pixmap(ctx, state[1].group_alpha);
		}

		fz_convert_rasterizer(ctx, rast, 0, state[1].mask, NULL, 0);

		state[1].blendmode |= FZ_BLEND_ISOLATED;
		state[1].scissor = bbox;
#ifdef DUMP_GROUP_BLENDS
		dump_spaces(dev->top-1, "Clip (stroke) begin\n");
#endif
	}
	fz_catch(ctx)
	{
		emergency_pop_stack(ctx, dev, state);
	}
}

static void
draw_glyph(unsigned char *colorbv, fz_pixmap *dst, fz_glyph *glyph,
	int xorig, int yorig, const fz_irect *scissor, fz_overprint *eop)
{
	unsigned char *dp;
	fz_irect bbox, bbox2;
	int x, y, w, h;
	int skip_x, skip_y;
	fz_pixmap *msk;

	fz_glyph_bbox_no_ctx(glyph, &bbox);
	fz_translate_irect(&bbox, xorig, yorig);
	fz_intersect_irect(&bbox, scissor); /* scissor < dst */

	if (fz_is_empty_irect(fz_intersect_irect(&bbox, fz_pixmap_bbox_no_ctx(dst, &bbox2))))
		return;

	x = bbox.x0;
	y = bbox.y0;
	w = bbox.x1 - bbox.x0;
	h = bbox.y1 - bbox.y0;

	skip_x = x - glyph->x - xorig;
	skip_y = y - glyph->y - yorig;

	msk = glyph->pixmap;
	dp = dst->samples + (unsigned int)((y - dst->y) * dst->stride + (x - dst->x) * dst->n);
	if (msk == NULL)
	{
		fz_paint_glyph(colorbv, dst, dp, glyph, w, h, skip_x, skip_y, eop);
	}
	else
	{
		unsigned char *mp = msk->samples + skip_y * msk->stride + skip_x;
		int da = dst->alpha;

		if (dst->colorspace)
		{
			fz_span_color_painter_t *fn;

			fn = fz_get_span_color_painter(dst->n, da, colorbv, eop);
			assert(fn);
			if (fn == NULL)
				return;
			while (h--)
			{
				(*fn)(dp, mp, dst->n, w, colorbv, da, eop);
				dp += dst->stride;
				mp += msk->stride;
			}
		}
		else
		{
			fz_span_painter_t *fn;

			fn = fz_get_span_painter(da, 1, 0, 255, eop);
			assert(fn);
			if (fn == NULL)
				return;
			while (h--)
			{
				(*fn)(dp, da, mp, 1, 0, w, 255, eop);
				dp += dst->stride;
				mp += msk->stride;
			}
		}
	}
}

static void
fz_draw_fill_text(fz_context *ctx, fz_device *devp, const fz_text *text, const fz_matrix *in_ctm,
	fz_colorspace *colorspace_in, const float *color, float alpha, const fz_color_params *color_params)
{
	fz_draw_device *dev = (fz_draw_device*)devp;
	fz_matrix ctm = concat(in_ctm, &dev->transform);
	fz_draw_state *state = &dev->stack[dev->top];
	fz_colorspace *model = state->dest->colorspace;
	unsigned char colorbv[FZ_MAX_COLORS + 1];
	unsigned char shapebv, shapebva;
	fz_text_span *span;
	int i;
	fz_colorspace *colorspace = NULL;
	fz_rasterizer *rast = dev->rast;
	fz_overprint op = { { 0 } };
	fz_overprint *eop;

	if (dev->top == 0 && dev->resolve_spots)
		state = push_group_for_separations(ctx, dev, color_params, dev->default_cs);

	if (colorspace_in)
		colorspace = fz_default_colorspace(ctx, dev->default_cs, colorspace_in);

	if (colorspace == NULL && model != NULL)
		fz_throw(ctx, FZ_ERROR_GENERIC, "color destination requires source color");

	if (color_params == NULL)
		color_params = fz_default_color_params(ctx);

	if (state->blendmode & FZ_BLEND_KNOCKOUT)
		state = fz_knockout_begin(ctx, dev);

	eop = resolve_color(ctx, &op, color, colorspace, alpha, color_params, colorbv, state->dest);
	shapebv = 255;
	shapebva = 255 * alpha;

	for (span = text->head; span; span = span->next)
	{
		fz_matrix tm, trm;
		fz_glyph *glyph;
		int gid;

		tm = span->trm;

		for (i = 0; i < span->len; i++)
		{
			gid = span->items[i].gid;
			if (gid < 0)
				continue;

			tm.e = span->items[i].x;
			tm.f = span->items[i].y;
			fz_concat(&trm, &tm, &ctm);

			glyph = fz_render_glyph(ctx, span->font, gid, &trm, model, &state->scissor, state->dest->alpha, fz_rasterizer_text_aa_level(rast));
			if (glyph)
			{
				fz_pixmap *pixmap = glyph->pixmap;
				int x = floorf(trm.e);
				int y = floorf(trm.f);
				if (pixmap == NULL || pixmap->n == 1)
				{
					draw_glyph(colorbv, state->dest, glyph, x, y, &state->scissor, eop);
					if (state->shape)
						draw_glyph(&shapebv, state->shape, glyph, x, y, &state->scissor, 0);
					if (state->group_alpha)
						draw_glyph(&shapebva, state->group_alpha, glyph, x, y, &state->scissor, 0);
				}
				else
				{
					fz_matrix mat;
					mat.a = pixmap->w; mat.b = mat.c = 0; mat.d = pixmap->h;
					mat.e = x + pixmap->x; mat.f = y + pixmap->y;
					fz_paint_image(state->dest, &state->scissor, state->shape, state->group_alpha, pixmap, &mat, alpha * 255, !(devp->hints & FZ_DONT_INTERPOLATE_IMAGES), devp->flags & FZ_DEVFLAG_GRIDFIT_AS_TILED, eop);
				}
				fz_drop_glyph(ctx, glyph);
			}
			else
			{
				fz_path *path = fz_outline_glyph(ctx, span->font, gid, &tm);
				if (path)
				{
					fz_draw_fill_path(ctx, devp, path, 0, in_ctm, colorspace, color, alpha, color_params);
					fz_drop_path(ctx, path);
				}
				else
				{
					fz_warn(ctx, "cannot render glyph");
				}
			}
		}
	}

	if (state->blendmode & FZ_BLEND_KNOCKOUT)
		fz_knockout_end(ctx, dev);
}

static void
fz_draw_stroke_text(fz_context *ctx, fz_device *devp, const fz_text *text, const fz_stroke_state *stroke,
	const fz_matrix *in_ctm, fz_colorspace *colorspace_in, const float *color, float alpha, const fz_color_params *color_params)
{
	fz_draw_device *dev = (fz_draw_device*)devp;
	fz_matrix ctm = concat(in_ctm, &dev->transform);
	fz_draw_state *state = &dev->stack[dev->top];
	unsigned char colorbv[FZ_MAX_COLORS + 1];
	unsigned char solid = 255;
	unsigned char alpha_byte = alpha * 255;
	fz_text_span *span;
	int i;
	fz_colorspace *colorspace = NULL;
	int aa = fz_rasterizer_text_aa_level(dev->rast);
	fz_overprint op = { { 0 } };
	fz_overprint *eop;

	if (dev->top == 0 && dev->resolve_spots)
		state = push_group_for_separations(ctx, dev, color_params, dev->default_cs);

	if (colorspace_in)
		colorspace = fz_default_colorspace(ctx, dev->default_cs, colorspace_in);

	if (state->blendmode & FZ_BLEND_KNOCKOUT)
		state = fz_knockout_begin(ctx, dev);

	eop = resolve_color(ctx, &op, color, colorspace, alpha, color_params, colorbv, state->dest);

	for (span = text->head; span; span = span->next)
	{
		fz_matrix tm, trm;
		fz_glyph *glyph;
		int gid;

		tm = span->trm;

		for (i = 0; i < span->len; i++)
		{
			gid = span->items[i].gid;
			if (gid < 0)
				continue;

			tm.e = span->items[i].x;
			tm.f = span->items[i].y;
			fz_concat(&trm, &tm, &ctm);

			glyph = fz_render_stroked_glyph(ctx, span->font, gid, &trm, &ctm, stroke, &state->scissor, aa);
			if (glyph)
			{
				int x = (int)trm.e;
				int y = (int)trm.f;
				draw_glyph(colorbv, state->dest, glyph, x, y, &state->scissor, eop);
				if (state->shape)
					draw_glyph(&solid, state->shape, glyph, x, y, &state->scissor, 0);
				if (state->group_alpha)
					draw_glyph(&alpha_byte, state->group_alpha, glyph, x, y, &state->scissor, 0);
				fz_drop_glyph(ctx, glyph);
			}
			else
			{
				fz_path *path = fz_outline_glyph(ctx, span->font, gid, &tm);
				if (path)
				{
					fz_draw_stroke_path(ctx, devp, path, stroke, in_ctm, colorspace, color, alpha, color_params);
					fz_drop_path(ctx, path);
				}
				else
				{
					fz_warn(ctx, "cannot render glyph");
				}
			}
		}
	}

	if (state->blendmode & FZ_BLEND_KNOCKOUT)
		fz_knockout_end(ctx, dev);
}

static void
fz_draw_clip_text(fz_context *ctx, fz_device *devp, const fz_text *text, const fz_matrix *in_ctm, const fz_rect *scissor)
{
	fz_draw_device *dev = (fz_draw_device*)devp;
	fz_matrix ctm = concat(in_ctm, &dev->transform);
	fz_irect bbox;
	fz_pixmap *mask, *dest, *shape, *group_alpha;
	fz_matrix tm, trm;
	fz_glyph *glyph;
	int i, gid;
	fz_draw_state *state;
	fz_colorspace *model;
	fz_text_span *span;
	fz_rect rect;
	fz_rasterizer *rast = dev->rast;

	if (dev->top == 0 && dev->resolve_spots)
		(void)push_group_for_separations(ctx, dev, fz_default_color_params(ctx)/* FIXME */, dev->default_cs);

	state = push_stack(ctx, dev);
	STACK_PUSHED("clip text");
	model = state->dest->colorspace;

	/* make the mask the exact size needed */
	fz_irect_from_rect(&bbox, fz_bound_text(ctx, text, NULL, &ctm, &rect));
	fz_intersect_irect(&bbox, &state->scissor);
	if (scissor)
	{
		fz_irect bbox2;
		fz_rect tscissor = *scissor;
		fz_transform_rect(&tscissor, &dev->transform);
		fz_intersect_irect(&bbox, fz_irect_from_rect(&bbox2, &tscissor));
	}

	fz_try(ctx)
	{
		mask = fz_new_pixmap_with_bbox(ctx, NULL, &bbox, NULL, 1);
		fz_clear_pixmap(ctx, mask);
		/* When there is no alpha in the current destination (state[0].dest->alpha == 0)
		 * we have a choice. We can either create the new destination WITH alpha, or
		 * we can copy the old pixmap contents in. We opt for the latter here, but
		 * may want to revisit this decision in the future. */
		dest = fz_new_pixmap_with_bbox(ctx, model, &bbox, state[0].dest->seps, state[0].dest->alpha);
		if (state[0].dest->alpha)
			fz_clear_pixmap(ctx, dest);
		else
			fz_copy_pixmap_rect(ctx, dest, state[0].dest, &bbox, dev->default_cs);
		if (state->shape)
		{
			shape = fz_new_pixmap_with_bbox(ctx, NULL, &bbox, NULL, 1);
			fz_clear_pixmap(ctx, shape);
		}
		else
			shape = NULL;
		if (state->group_alpha)
		{
			group_alpha = fz_new_pixmap_with_bbox(ctx, NULL, &bbox, NULL, 1);
			fz_clear_pixmap(ctx, group_alpha);
		}
		else
			group_alpha = NULL;

		state[1].blendmode |= FZ_BLEND_ISOLATED;
		state[1].scissor = bbox;
		state[1].dest = dest;
		state[1].mask = mask;
		state[1].shape = shape;
		state[1].group_alpha = group_alpha;
#ifdef DUMP_GROUP_BLENDS
		dump_spaces(dev->top-1, "Clip (text) begin\n");
#endif

		if (!fz_is_empty_irect(&bbox) && mask)
		{
			for (span = text->head; span; span = span->next)
			{
				tm = span->trm;

				for (i = 0; i < span->len; i++)
				{
					gid = span->items[i].gid;
					if (gid < 0)
						continue;

					tm.e = span->items[i].x;
					tm.f = span->items[i].y;
					fz_concat(&trm, &tm, &ctm);

					glyph = fz_render_glyph(ctx, span->font, gid, &trm, model, &state->scissor, state[1].dest->alpha, fz_rasterizer_text_aa_level(rast));
					if (glyph)
					{
						int x = (int)trm.e;
						int y = (int)trm.f;
						draw_glyph(NULL, mask, glyph, x, y, &bbox, 0);
						if (state[1].shape)
							draw_glyph(NULL, state[1].shape, glyph, x, y, &bbox, 0);
						if (state[1].group_alpha)
							draw_glyph(NULL, state[1].group_alpha, glyph, x, y, &bbox, 0);
						fz_drop_glyph(ctx, glyph);
					}
					else
					{
						fz_path *path = fz_outline_glyph(ctx, span->font, gid, &tm);
						if (path)
						{
							fz_pixmap *old_dest;
							float white = 1;

							old_dest = state[1].dest;
							state[1].dest = state[1].mask;
							state[1].mask = NULL;
							fz_try(ctx)
							{
								fz_draw_fill_path(ctx, devp, path, 0, in_ctm, fz_device_gray(ctx), &white, 1, NULL);
							}
							fz_always(ctx)
							{
								state[1].mask = state[1].dest;
								state[1].dest = old_dest;
								fz_drop_path(ctx, path);
							}
							fz_catch(ctx)
							{
								fz_rethrow(ctx);
							}
						}
						else
						{
							fz_warn(ctx, "cannot render glyph for clipping");
						}
					}
				}
			}
		}
	}
	fz_catch(ctx)
	{
		emergency_pop_stack(ctx, dev, state);
	}
}

static void
fz_draw_clip_stroke_text(fz_context *ctx, fz_device *devp, const fz_text *text, const fz_stroke_state *stroke, const fz_matrix *in_ctm, const fz_rect *scissor)
{
	fz_draw_device *dev = (fz_draw_device*)devp;
	fz_matrix ctm = concat(in_ctm, &dev->transform);
	fz_irect bbox;
	fz_pixmap *mask, *dest, *shape, *group_alpha;
	fz_matrix tm, trm;
	fz_glyph *glyph;
	int i, gid;
	fz_draw_state *state = push_stack(ctx, dev);
	fz_colorspace *model = state->dest->colorspace;
	fz_text_span *span;
	fz_rect rect;
	int aa = fz_rasterizer_text_aa_level(dev->rast);

	if (dev->top == 0 && dev->resolve_spots)
		state = push_group_for_separations(ctx, dev, fz_default_color_params(ctx)/* FIXME */, dev->default_cs);

	STACK_PUSHED("clip stroke text");
	/* make the mask the exact size needed */
	fz_irect_from_rect(&bbox, fz_bound_text(ctx, text, stroke, &ctm, &rect));
	fz_intersect_irect(&bbox, &state->scissor);
	if (scissor)
	{
		fz_irect bbox2;
		fz_rect tscissor = *scissor;
		fz_transform_rect(&tscissor, &dev->transform);
		fz_intersect_irect(&bbox, fz_irect_from_rect(&bbox2, &tscissor));
	}

	fz_try(ctx)
	{
		state[1].mask = mask = fz_new_pixmap_with_bbox(ctx, NULL, &bbox, NULL, 1);
		fz_clear_pixmap(ctx, mask);
		/* When there is no alpha in the current destination (state[0].dest->alpha == 0)
		 * we have a choice. We can either create the new destination WITH alpha, or
		 * we can copy the old pixmap contents in. We opt for the latter here, but
		 * may want to revisit this decision in the future. */
		state[1].dest = dest = fz_new_pixmap_with_bbox(ctx, model, &bbox, state[0].dest->seps, state[0].dest->alpha);
		if (state[0].dest->alpha)
			fz_clear_pixmap(ctx, state[1].dest);
		else
			fz_copy_pixmap_rect(ctx, state[1].dest, state[0].dest, &bbox, dev->default_cs);
		if (state->shape)
		{
			state[1].shape = shape = fz_new_pixmap_with_bbox(ctx, NULL, &bbox, NULL, 1);
			fz_clear_pixmap(ctx, shape);
		}
		else
			shape = state->shape;
		if (state->group_alpha)
		{
			state[1].group_alpha = group_alpha = fz_new_pixmap_with_bbox(ctx, NULL, &bbox, NULL, 1);
			fz_clear_pixmap(ctx, group_alpha);
		}
		else
			group_alpha = NULL;

		state[1].blendmode |= FZ_BLEND_ISOLATED;
		state[1].scissor = bbox;
#ifdef DUMP_GROUP_BLENDS
		dump_spaces(dev->top-1, "Clip (stroke text) begin\n");
#endif

		if (!fz_is_empty_irect(&bbox))
		{
			for (span = text->head; span; span = span->next)
			{
				tm = span->trm;

				for (i = 0; i < span->len; i++)
				{
					gid = span->items[i].gid;
					if (gid < 0)
						continue;

					tm.e = span->items[i].x;
					tm.f = span->items[i].y;
					fz_concat(&trm, &tm, &ctm);

					glyph = fz_render_stroked_glyph(ctx, span->font, gid, &trm, &ctm, stroke, &state->scissor, aa);
					if (glyph)
					{
						int x = (int)trm.e;
						int y = (int)trm.f;
						draw_glyph(NULL, mask, glyph, x, y, &bbox, 0);
						if (shape)
							draw_glyph(NULL, shape, glyph, x, y, &bbox, 0);
						if (group_alpha)
							draw_glyph(NULL, group_alpha, glyph, x, y, &bbox, 0);
						fz_drop_glyph(ctx, glyph);
					}
					else
					{
						fz_path *path = fz_outline_glyph(ctx, span->font, gid, &tm);
						if (path)
						{
							fz_pixmap *old_dest;
							float white = 1;

							state = &dev->stack[dev->top];
							old_dest = state[0].dest;
							state[0].dest = state[0].mask;
							state[0].mask = NULL;
							fz_try(ctx)
							{
								fz_draw_stroke_path(ctx, devp, path, stroke, in_ctm, fz_device_gray(ctx), &white, 1, NULL);
							}
							fz_always(ctx)
							{
								state[0].mask = state[0].dest;
								state[0].dest = old_dest;
								fz_drop_path(ctx, path);
							}
							fz_catch(ctx)
							{
								fz_rethrow(ctx);
							}
						}
						else
						{
							fz_warn(ctx, "cannot render glyph for stroked clipping");
						}
					}
				}
			}
		}
	}
	fz_catch(ctx)
	{
		emergency_pop_stack(ctx, dev, state);
	}
}

static void
fz_draw_ignore_text(fz_context *ctx, fz_device *dev, const fz_text *text, const fz_matrix *ctm)
{
}

static void
fz_draw_fill_shade(fz_context *ctx, fz_device *devp, fz_shade *shade, const fz_matrix *in_ctm, float alpha, const fz_color_params *color_params)
{
	fz_draw_device *dev = (fz_draw_device*)devp;
	fz_matrix ctm = concat(in_ctm, &dev->transform);
	fz_rect bounds;
	fz_irect bbox, scissor;
	fz_pixmap *dest, *shape, *group_alpha;
	unsigned char colorbv[FZ_MAX_COLORS + 1];
	unsigned char alpha_byte = 255 * alpha;
	fz_draw_state *state = &dev->stack[dev->top];
	fz_overprint op = { { 0 } };
	fz_overprint *eop;
	fz_colorspace *colorspace = fz_default_colorspace(ctx, dev->default_cs, shade->colorspace);

	if (dev->top == 0 && dev->resolve_spots)
		state = push_group_for_separations(ctx, dev, color_params, dev->default_cs);

	fz_bound_shade(ctx, shade, &ctm, &bounds);
	scissor = state->scissor;
	fz_intersect_irect(fz_irect_from_rect(&bbox, &bounds), &scissor);

	if (fz_is_empty_irect(&bbox))
		return;

	if (color_params == NULL)
		color_params = fz_default_color_params(ctx);

	if (state->blendmode & FZ_BLEND_KNOCKOUT)
		state = fz_knockout_begin(ctx, dev);

	dest = state->dest;
	shape = state->shape;
	group_alpha = state->group_alpha;

	if (alpha < 1)
	{
		dest = fz_new_pixmap_with_bbox(ctx, state->dest->colorspace, &bbox, state->dest->seps, state->dest->alpha);
		if (state->dest->alpha)
			fz_clear_pixmap(ctx, dest);
		else
			fz_copy_pixmap_rect(ctx, dest, state[0].dest, &bbox, dev->default_cs);
		if (shape)
		{
			shape = fz_new_pixmap_with_bbox(ctx, NULL, &bbox, NULL, 1);
			fz_clear_pixmap(ctx, shape);
		}
		if (group_alpha)
		{
			group_alpha = fz_new_pixmap_with_bbox(ctx, NULL, &bbox, NULL, 1);
			fz_clear_pixmap(ctx, group_alpha);
		}
	}

	if (shade->use_background)
	{
		unsigned char *s;
		int x, y, n, i;
		fz_color_params  local_cp;
		fz_color_params *cp = NULL;

		/* Disable OPM */
		if (color_params)
		{
			local_cp = *color_params;
			local_cp.opm = 0;
			cp = &local_cp;
		}

		eop = resolve_color(ctx, &op, shade->background, colorspace, alpha, cp, colorbv, state->dest);

		n = dest->n;
		if (eop)
		{
			for (y = scissor.y0; y < scissor.y1; y++)
			{
				s = dest->samples + (unsigned int)((y - dest->y) * dest->stride + (scissor.x0 - dest->x) * n);
				for (x = scissor.x0; x < scissor.x1; x++)
				{
					for (i = 0; i < n; i++)
						if (fz_overprint_component(eop, i))
							*s++ = colorbv[i];
				}
			}
		}
		else
		{
			for (y = scissor.y0; y < scissor.y1; y++)
			{
				s = dest->samples + (unsigned int)((y - dest->y) * dest->stride + (scissor.x0 - dest->x) * n);
				for (x = scissor.x0; x < scissor.x1; x++)
				{
					for (i = 0; i < n; i++)
						*s++ = colorbv[i];
				}
			}
		}
		if (shape)
		{
			for (y = scissor.y0; y < scissor.y1; y++)
			{
				s = shape->samples + (unsigned int)((y - shape->y) * shape->stride + (scissor.x0 - shape->x));
				for (x = scissor.x0; x < scissor.x1; x++)
				{
					*s++ = 255;
				}
			}
		}
		if (group_alpha)
		{
			for (y = scissor.y0; y < scissor.y1; y++)
			{
				s = group_alpha->samples + (unsigned int)((y - group_alpha->y) * group_alpha->stride + (scissor.x0 - group_alpha->x));
				for (x = scissor.x0; x < scissor.x1; x++)
				{
					*s++ = alpha_byte;
				}
			}
		}
	}

	if (color_params->op)
	{
		eop = set_op_from_spaces(ctx, &op, dest, colorspace, 0);
	}
	else
		eop = NULL;

	fz_paint_shade(ctx, shade, colorspace, &ctm, dest, color_params, &bbox, eop);
	if (shape)
		fz_clear_pixmap_rect_with_value(ctx, shape, 255, &bbox);
	if (group_alpha)
		fz_clear_pixmap_rect_with_value(ctx, group_alpha, 255, &bbox);

#ifdef DUMP_GROUP_BLENDS
	dump_spaces(dev->top, "");
	fz_dump_blend(ctx, "Shade ", dest);
	if (shape)
		fz_dump_blend(ctx, "/S=", shape);
	if (group_alpha)
		fz_dump_blend(ctx, "/GA=", group_alpha);
	printf("\n");
#endif

	if (alpha < 1)
	{
		/* FIXME: eop */
		fz_paint_pixmap(state->dest, dest, alpha * 255);
		fz_drop_pixmap(ctx, dest);
		if (shape)
		{
			fz_paint_pixmap(state->shape, shape, 255);
			fz_drop_pixmap(ctx, shape);
		}
		if (group_alpha)
		{
			fz_paint_pixmap(state->group_alpha, group_alpha, alpha * 255);
			fz_drop_pixmap(ctx, group_alpha);
		}
	}

	if (state->blendmode & FZ_BLEND_KNOCKOUT)
		fz_knockout_end(ctx, dev);
}

static fz_pixmap *
fz_transform_pixmap(fz_context *ctx, fz_draw_device *dev, const fz_pixmap *image, fz_matrix *ctm, int x, int y, int dx, int dy, int gridfit, const fz_irect *clip)
{
	fz_pixmap *scaled;

	if (ctm->a != 0 && ctm->b == 0 && ctm->c == 0 && ctm->d != 0)
	{
		/* Unrotated or X-flip or Y-flip or XY-flip */
		fz_matrix m = *ctm;
		if (gridfit)
		{
			fz_gridfit_matrix(dev->flags & FZ_DEVFLAG_GRIDFIT_AS_TILED, &m);
		}
		scaled = fz_scale_pixmap_cached(ctx, image, m.e, m.f, m.a, m.d, clip, dev->cache_x, dev->cache_y);
		if (!scaled)
			return NULL;
		ctm->a = scaled->w;
		ctm->d = scaled->h;
		ctm->e = scaled->x;
		ctm->f = scaled->y;
		return scaled;
	}

	if (ctm->a == 0 && ctm->b != 0 && ctm->c != 0 && ctm->d == 0)
	{
		/* Other orthogonal flip/rotation cases */
		fz_matrix m = *ctm;
		fz_irect rclip;
		if (gridfit)
			fz_gridfit_matrix(dev->flags & FZ_DEVFLAG_GRIDFIT_AS_TILED, &m);
		if (clip)
		{
			rclip.x0 = clip->y0;
			rclip.y0 = clip->x0;
			rclip.x1 = clip->y1;
			rclip.y1 = clip->x1;
		}
		scaled = fz_scale_pixmap_cached(ctx, image, m.f, m.e, m.b, m.c, (clip ? &rclip : NULL), dev->cache_x, dev->cache_y);
		if (!scaled)
			return NULL;
		ctm->b = scaled->w;
		ctm->c = scaled->h;
		ctm->f = scaled->x;
		ctm->e = scaled->y;
		return scaled;
	}

	/* Downscale, non rectilinear case */
	if (dx > 0 && dy > 0)
	{
		scaled = fz_scale_pixmap_cached(ctx, image, 0, 0, dx, dy, NULL, dev->cache_x, dev->cache_y);
		return scaled;
	}

	return NULL;
}

int
fz_default_image_scale(void *arg, int dst_w, int dst_h, int src_w, int src_h)
{
	(void)arg;
	return dst_w < src_w && dst_h < src_h;
}

static fz_pixmap *
convert_pixmap_for_painting(fz_context *ctx, fz_pixmap *pixmap, fz_colorspace *model, fz_colorspace *src_cs, fz_pixmap *dest, const fz_color_params *color_params, fz_draw_device *dev, fz_overprint **eop)
{
	fz_pixmap *converted;

	if (fz_colorspace_is_device_n(ctx, src_cs) && dest->seps)
	{
		converted = fz_clone_pixmap_area_with_different_seps(ctx, pixmap, NULL, model, dest->seps, color_params, dev->default_cs);
		*eop = set_op_from_spaces(ctx, *eop, dest, src_cs, 0);
	}
	else
	{
		converted = fz_convert_pixmap(ctx, pixmap, model, NULL, dev->default_cs, color_params, 1);
		if (*eop)
		{
			if (fz_colorspace_type(ctx, model) != FZ_COLORSPACE_CMYK)
			{
				/* Can only overprint to CMYK based spaces */
				*eop = NULL;
			}
			else if (!fz_colorspace_is_device_n(ctx, pixmap->colorspace))
			{
				int i;
				int n = dest->n - dest->alpha;
				for (i = 4; i < n; i++)
					fz_set_overprint(*eop, i);
			}
			else
			{
				*eop = set_op_from_spaces(ctx, *eop, dest, src_cs, 0);
			}
		}
	}
	fz_drop_pixmap(ctx, pixmap);

	return converted;
}

static void
fz_draw_fill_image(fz_context *ctx, fz_device *devp, fz_image *image, const fz_matrix *in_ctm, float alpha, const fz_color_params *color_params)
{
	fz_draw_device *dev = (fz_draw_device*)devp;
	fz_matrix local_ctm = concat(in_ctm, &dev->transform);
	fz_pixmap *pixmap;
	int after;
	int dx, dy;
	fz_draw_state *state = &dev->stack[dev->top];
	fz_colorspace *model;
	fz_irect clip;
	fz_matrix inverse;
	fz_irect src_area;
	fz_colorspace *src_cs;
	fz_overprint op = { { 0 } };
	fz_overprint *eop = &op;

	if (alpha == 0)
		return;

	if (dev->top == 0 && dev->resolve_spots)
		state = push_group_for_separations(ctx, dev, color_params, dev->default_cs);
	model = state->dest->colorspace;

	fz_intersect_irect(fz_pixmap_bbox(ctx, state->dest, &clip), &state->scissor);

	if (image->w == 0 || image->h == 0)
		return;

	if (!color_params || color_params->op == 0)
		eop = NULL;

	/* ctm maps the image (expressed as the unit square) onto the
	 * destination device. Reverse that to get a mapping from
	 * the destination device to the source pixels. */
	if (fz_try_invert_matrix(&inverse, &local_ctm))
	{
		/* Not invertible. Could just bail? Use the whole image
		 * for now. */
		src_area.x0 = 0;
		src_area.x1 = image->w;
		src_area.y0 = 0;
		src_area.y1 = image->h;
	}
	else
	{
		float exp;
		fz_rect rect;
		fz_irect sane;
		/* We want to scale from image coords, not from unit square */
		fz_post_scale(&inverse, image->w, image->h);
		/* Are we scaling up or down? exp < 1 means scaling down. */
		exp = fz_matrix_max_expansion(&inverse);
		fz_rect_from_irect(&rect, &clip);
		fz_transform_rect(&rect, &inverse);
		/* Allow for support requirements for scalers. */
		fz_expand_rect(&rect, fz_max(exp, 1) * 4);
		fz_irect_from_rect(&src_area, &rect);
		sane.x0 = 0;
		sane.y0 = 0;
		sane.x1 = image->w;
		sane.y1 = image->h;
		fz_intersect_irect(&src_area, &sane);
		if (fz_is_empty_irect(&src_area))
			return;
	}

	pixmap = fz_get_pixmap_from_image(ctx, image, &src_area, &local_ctm, &dx, &dy);
	src_cs = fz_default_colorspace(ctx, dev->default_cs, pixmap->colorspace);

	/* convert images with more components (cmyk->rgb) before scaling */
	/* convert images with fewer components (gray->rgb) after scaling */
	/* convert images with expensive colorspace transforms after scaling */

	fz_var(pixmap);

	fz_try(ctx)
	{
		int conversion_required = (src_cs != model || state->dest->seps);

		if (state->blendmode & FZ_BLEND_KNOCKOUT)
			state = fz_knockout_begin(ctx, dev);

		switch (fz_colorspace_type(ctx, src_cs))
		{
		case FZ_COLORSPACE_GRAY:
			after = 1;
			break;
		case FZ_COLORSPACE_INDEXED:
			after = 0;
			break;
		default:
			if (fz_colorspace_n(ctx, src_cs) <= fz_colorspace_n(ctx, model))
				after = 1;
			else
				after = 0;
			break;
		}

		if (conversion_required && !after)
			pixmap = convert_pixmap_for_painting(ctx, pixmap, model, src_cs, state->dest, color_params, dev, &eop);

		if (!(devp->hints & FZ_DONT_INTERPOLATE_IMAGES) && ctx->tuning->image_scale(ctx->tuning->image_scale_arg, dx, dy, pixmap->w, pixmap->h))
		{
			int gridfit = alpha == 1.0f && !(dev->flags & FZ_DRAWDEV_FLAGS_TYPE3);
			fz_pixmap *scaled = fz_transform_pixmap(ctx, dev, pixmap, &local_ctm, state->dest->x, state->dest->y, dx, dy, gridfit, &clip);
			if (!scaled)
			{
				if (dx < 1)
					dx = 1;
				if (dy < 1)
					dy = 1;
				scaled = fz_scale_pixmap_cached(ctx, pixmap, pixmap->x, pixmap->y, dx, dy, NULL, dev->cache_x, dev->cache_y);
			}
			if (scaled)
			{
				fz_drop_pixmap(ctx, pixmap);
				pixmap = scaled;
			}
		}

		if (conversion_required && after)
		{
#if FZ_PLOTTERS_RGB
			if (state->dest->seps == NULL &&
				((src_cs == fz_device_gray(ctx) && model == fz_device_rgb(ctx)) ||
				(src_cs == fz_device_gray(ctx) && model == fz_device_bgr(ctx))))
			{
				/* We have special case rendering code for gray -> rgb/bgr */
			}
			else
#endif
				pixmap = convert_pixmap_for_painting(ctx, pixmap, model, src_cs, state->dest, color_params, dev, &eop);
		}

		fz_paint_image(state->dest, &state->scissor, state->shape, state->group_alpha, pixmap, &local_ctm, alpha * 255, !(devp->hints & FZ_DONT_INTERPOLATE_IMAGES), devp->flags & FZ_DEVFLAG_GRIDFIT_AS_TILED, eop);
	}
	fz_always(ctx)
	{
		fz_drop_pixmap(ctx, pixmap);
		if (state->blendmode & FZ_BLEND_KNOCKOUT)
			fz_knockout_end(ctx, dev);
	}
	fz_catch(ctx)
		fz_rethrow(ctx);
}

static void
fz_draw_fill_image_mask(fz_context *ctx, fz_device *devp, fz_image *image, const fz_matrix *in_ctm,
	fz_colorspace *colorspace_in, const float *color, float alpha, const fz_color_params *color_params)
{
	fz_draw_device *dev = (fz_draw_device*)devp;
	fz_matrix local_ctm = concat(in_ctm, &dev->transform);
	unsigned char colorbv[FZ_MAX_COLORS + 1];
	fz_pixmap *scaled = NULL;
	fz_pixmap *pixmap;
	int dx, dy;
	fz_draw_state *state = &dev->stack[dev->top];
	fz_irect clip;
	fz_matrix inverse;
	fz_irect src_area;
	fz_colorspace *colorspace = NULL;
	fz_overprint op = { { 0 } };
	fz_overprint *eop;

	if (alpha == 0)
		return;

	if (dev->top == 0 && dev->resolve_spots)
		state = push_group_for_separations(ctx, dev, color_params, dev->default_cs);

	if (colorspace_in)
		colorspace = fz_default_colorspace(ctx, dev->default_cs, colorspace_in);

	fz_pixmap_bbox(ctx, state->dest, &clip);
	fz_intersect_irect(&clip, &state->scissor);

	if (image->w == 0 || image->h == 0)
		return;

	/* ctm maps the image (expressed as the unit square) onto the
	 * destination device. Reverse that to get a mapping from
	 * the destination device to the source pixels. */
	if (fz_try_invert_matrix(&inverse, &local_ctm))
	{
		/* Not invertible. Could just bail? Use the whole image
		 * for now. */
		src_area.x0 = 0;
		src_area.x1 = image->w;
		src_area.y0 = 0;
		src_area.y1 = image->h;
	}
	else
	{
		float exp;
		fz_rect rect;
		fz_irect sane;
		/* We want to scale from image coords, not from unit square */
		fz_post_scale(&inverse, image->w, image->h);
		/* Are we scaling up or down? exp < 1 means scaling down. */
		exp = fz_matrix_max_expansion(&inverse);
		fz_rect_from_irect(&rect, &clip);
		fz_transform_rect(&rect, &inverse);
		/* Allow for support requirements for scalers. */
		fz_expand_rect(&rect, fz_max(exp, 1) * 4);
		fz_irect_from_rect(&src_area, &rect);
		sane.x0 = 0;
		sane.y0 = 0;
		sane.x1 = image->w;
		sane.y1 = image->h;
		fz_intersect_irect(&src_area, &sane);
		if (fz_is_empty_irect(&src_area))
			return;
	}

	pixmap = fz_get_pixmap_from_image(ctx, image, &src_area, &local_ctm, &dx, &dy);

	fz_var(pixmap);

	fz_try(ctx)
	{
		if (state->blendmode & FZ_BLEND_KNOCKOUT)
			state = fz_knockout_begin(ctx, dev);

		if (ctx->tuning->image_scale(ctx->tuning->image_scale_arg, dx, dy, pixmap->w, pixmap->h))
		{
			int gridfit = alpha == 1.0f && !(dev->flags & FZ_DRAWDEV_FLAGS_TYPE3);
			scaled = fz_transform_pixmap(ctx, dev, pixmap, &local_ctm, state->dest->x, state->dest->y, dx, dy, gridfit, &clip);
			if (!scaled)
			{
				if (dx < 1)
					dx = 1;
				if (dy < 1)
					dy = 1;
				scaled = fz_scale_pixmap_cached(ctx, pixmap, pixmap->x, pixmap->y, dx, dy, NULL, dev->cache_x, dev->cache_y);
			}
			if (scaled)
			{
				fz_drop_pixmap(ctx, pixmap);
				pixmap = scaled;
			}
		}

		eop = resolve_color(ctx, &op, color, colorspace, alpha, color_params, colorbv, state->dest);

		fz_paint_image_with_color(state->dest, &state->scissor, state->shape, state->group_alpha, pixmap, &local_ctm, colorbv, !(devp->hints & FZ_DONT_INTERPOLATE_IMAGES), devp->flags & FZ_DEVFLAG_GRIDFIT_AS_TILED, eop);

		if (state->blendmode & FZ_BLEND_KNOCKOUT)
			fz_knockout_end(ctx, dev);
	}
	fz_always(ctx)
		fz_drop_pixmap(ctx, pixmap);
	fz_catch(ctx)
		fz_rethrow(ctx);
}

static void
fz_draw_clip_image_mask(fz_context *ctx, fz_device *devp, fz_image *image, const fz_matrix *in_ctm, const fz_rect *scissor)
{
	fz_draw_device *dev = (fz_draw_device*)devp;
	fz_matrix local_ctm = concat(in_ctm, &dev->transform);
	fz_irect bbox;
	fz_pixmap *scaled = NULL;
	fz_pixmap *pixmap = NULL;
	int dx, dy;
	fz_draw_state *state = push_stack(ctx, dev);
	fz_colorspace *model = state->dest->colorspace;
	fz_irect clip;
	fz_rect urect;

	if (dev->top == 0 && dev->resolve_spots)
		state = push_group_for_separations(ctx, dev, fz_default_color_params(ctx)/* FIXME */, dev->default_cs);

	STACK_PUSHED("clip image mask");
	fz_pixmap_bbox(ctx, state->dest, &clip);
	fz_intersect_irect(&clip, &state->scissor);

	if (image->w == 0 || image->h == 0)
	{
#ifdef DUMP_GROUP_BLENDS
		dump_spaces(dev->top-1, "Clip (image mask) (empty) begin\n");
#endif
		state[1].scissor = fz_empty_irect;
		state[1].mask = NULL;
		return;
	}

#ifdef DUMP_GROUP_BLENDS
	dump_spaces(dev->top-1, "Clip (image mask) begin\n");
#endif

	urect = fz_unit_rect;
	fz_irect_from_rect(&bbox, fz_transform_rect(&urect, &local_ctm));
	fz_intersect_irect(&bbox, &state->scissor);
	if (scissor)
	{
		fz_irect bbox2;
		fz_rect tscissor = *scissor;
		fz_transform_rect(&tscissor, &dev->transform);
		fz_intersect_irect(&bbox, fz_irect_from_rect(&bbox2, &tscissor));
	}

	pixmap = fz_get_pixmap_from_image(ctx, image, NULL, &local_ctm, &dx, &dy);

	fz_try(ctx)
	{
		state[1].mask = fz_new_pixmap_with_bbox(ctx, NULL, &bbox, NULL, 1);
		fz_clear_pixmap(ctx, state[1].mask);

		state[1].dest = fz_new_pixmap_with_bbox(ctx, model, &bbox, state[0].dest->seps, state[0].dest->alpha);
		fz_copy_pixmap_rect(ctx, state[1].dest, state[0].dest, &bbox, dev->default_cs);
		if (state[0].shape)
		{
			state[1].shape = fz_new_pixmap_with_bbox(ctx, NULL, &bbox, NULL, 1);
			fz_clear_pixmap(ctx, state[1].shape);
		}
		if (state[0].group_alpha)
		{
			state[1].group_alpha = fz_new_pixmap_with_bbox(ctx, NULL, &bbox, NULL, 1);
			fz_clear_pixmap(ctx, state[1].group_alpha);
		}

		state[1].blendmode |= FZ_BLEND_ISOLATED;
		state[1].scissor = bbox;

		if (ctx->tuning->image_scale(ctx->tuning->image_scale_arg, dx, dy, pixmap->w, pixmap->h))
		{
			int gridfit = !(dev->flags & FZ_DRAWDEV_FLAGS_TYPE3);
			scaled = fz_transform_pixmap(ctx, dev, pixmap, &local_ctm, state->dest->x, state->dest->y, dx, dy, gridfit, &clip);
			if (!scaled)
			{
				if (dx < 1)
					dx = 1;
				if (dy < 1)
					dy = 1;
				scaled = fz_scale_pixmap_cached(ctx, pixmap, pixmap->x, pixmap->y, dx, dy, NULL, dev->cache_x, dev->cache_y);
			}
			if (scaled)
			{
				fz_drop_pixmap(ctx, pixmap);
				pixmap = scaled;
			}
		}
#ifdef DUMP_GROUP_BLENDS
		dump_spaces(dev->top, "");
		fz_dump_blend(ctx, "Creating imagemask: plotting ", pixmap);
		fz_dump_blend(ctx, " onto ", state[1].mask);
		if (state[1].shape)
			fz_dump_blend(ctx, "/S=", state[1].shape);
		if (state[1].group_alpha)
			fz_dump_blend(ctx, "/GA=", state[1].group_alpha);
#endif
		fz_paint_image(state[1].mask, &bbox, state[1].shape, state[1].group_alpha, pixmap, &local_ctm, 255, !(devp->hints & FZ_DONT_INTERPOLATE_IMAGES), devp->flags & FZ_DEVFLAG_GRIDFIT_AS_TILED, 0);
#ifdef DUMP_GROUP_BLENDS
		fz_dump_blend(ctx, " to get ", state[1].mask);
		if (state[1].shape)
			fz_dump_blend(ctx, "/S=", state[1].shape);
		if (state[1].group_alpha)
			fz_dump_blend(ctx, "/GA=", state[1].group_alpha);
		printf("\n");
#endif
	}
	fz_always(ctx)
		fz_drop_pixmap(ctx, pixmap);
	fz_catch(ctx)
		emergency_pop_stack(ctx, dev, state);
}

static void
fz_draw_pop_clip(fz_context *ctx, fz_device *devp)
{
	fz_draw_device *dev = (fz_draw_device*)devp;
	fz_draw_state *state;

	if (dev->top == 0)
	{
		fz_warn(ctx, "Unexpected pop clip");
		return;
	}
	state = &dev->stack[--dev->top];
	STACK_POPPED("clip");

	/* We can get here with state[1].mask == NULL if the clipping actually
	 * resolved to a rectangle earlier.
	 */
	if (state[1].mask)
	{
#ifdef DUMP_GROUP_BLENDS
		dump_spaces(dev->top, "");
		fz_dump_blend(ctx, "Clipping ", state[1].dest);
		if (state[1].shape)
			fz_dump_blend(ctx, "/S=", state[1].shape);
		if (state[1].group_alpha)
			fz_dump_blend(ctx, "/GA=", state[1].group_alpha);
		fz_dump_blend(ctx, " onto ", state[0].dest);
		if (state[0].shape)
			fz_dump_blend(ctx, "/S=", state[0].shape);
		if (state[0].group_alpha)
			fz_dump_blend(ctx, "/GA=", state[0].group_alpha);
		fz_dump_blend(ctx, " with ", state[1].mask);
#endif
		fz_paint_pixmap_with_mask(state[0].dest, state[1].dest, state[1].mask);
		if (state[0].shape != state[1].shape)
		{
			fz_paint_pixmap_with_mask(state[0].shape, state[1].shape, state[1].mask);
			fz_drop_pixmap(ctx, state[1].shape);
		}
		if (state[0].group_alpha != state[1].group_alpha)
		{
			fz_paint_pixmap_with_mask(state[0].group_alpha, state[1].group_alpha, state[1].mask);
			fz_drop_pixmap(ctx, state[1].group_alpha);
		}
		/* The following tests should not be required, but just occasionally
		 * errors can cause the stack to get out of sync, and this might save
		 * our bacon. */
		if (state[0].mask != state[1].mask)
			fz_drop_pixmap(ctx, state[1].mask);
		if (state[0].dest != state[1].dest)
			fz_drop_pixmap(ctx, state[1].dest);
#ifdef DUMP_GROUP_BLENDS
		fz_dump_blend(ctx, " to get ", state[0].dest);
		if (state[0].shape)
			fz_dump_blend(ctx, "/S=", state[0].shape);
		if (state[0].group_alpha)
			fz_dump_blend(ctx, "/GA=", state[0].group_alpha);
		printf("\n");
#endif
	}
	else
	{
#ifdef DUMP_GROUP_BLENDS
		dump_spaces(dev->top, "Clip end\n");
#endif
	}
}

static void
fz_draw_begin_mask(fz_context *ctx, fz_device *devp, const fz_rect *rect, int luminosity, fz_colorspace *colorspace_in, const float *colorfv, const fz_color_params *color_params)
{
	fz_draw_device *dev = (fz_draw_device*)devp;
	fz_pixmap *dest;
	fz_irect bbox;
	fz_draw_state *state = push_stack(ctx, dev);
	fz_pixmap *shape = state->shape;
	fz_pixmap *group_alpha = state->group_alpha;
	fz_rect trect = *rect;
	fz_colorspace *colorspace = NULL;

	if (dev->top == 0 && dev->resolve_spots)
		state = push_group_for_separations(ctx, dev, color_params, dev->default_cs);

	if (colorspace_in)
		colorspace = fz_default_colorspace(ctx, dev->default_cs, colorspace_in);

	if (color_params == NULL)
		color_params = fz_default_color_params(ctx);

	STACK_PUSHED("mask");
	fz_transform_rect(&trect, &dev->transform);
	fz_intersect_irect(fz_irect_from_rect(&bbox, &trect), &state->scissor);

	/* Reset the blendmode for the mask rendering. In particular,
	 * don't carry forward knockout or isolated. */
	state[1].blendmode = 0;

	fz_try(ctx)
	{
		/* If luminosity, then we generate a mask from the greyscale value of the shapes.
		 * If !luminosity, then we generate a mask from the alpha value of the shapes.
		 */
		if (luminosity)
			state[1].dest = dest = fz_new_pixmap_with_bbox(ctx, fz_device_gray(ctx), &bbox, NULL, 0);
		else
			state[1].dest = dest = fz_new_pixmap_with_bbox(ctx, NULL, &bbox, NULL, 1);
		if (state->shape)
		{
			/* FIXME: If we ever want to support AIS true, then
			 * we probably want to create a shape pixmap here,
			 * using: shape = fz_new_pixmap_with_bbox(NULL, bbox);
			 * then, in the end_mask code, we create the mask
			 * from this rather than dest.
			 */
			state[1].shape = shape = NULL;
		}
		if (state->group_alpha)
		{
			state[1].group_alpha = group_alpha = NULL;
		}

		if (luminosity)
		{
			float bc;
			if (!colorspace)
				colorspace = fz_device_gray(ctx);
			fz_convert_color(ctx, color_params, NULL, fz_device_gray(ctx), &bc, colorspace, colorfv);
			fz_clear_pixmap_with_value(ctx, dest, bc * 255);
			if (shape)
				fz_clear_pixmap_with_value(ctx, shape, 255);
			if (group_alpha)
				fz_clear_pixmap_with_value(ctx, group_alpha, 255);
		}
		else
		{
			fz_clear_pixmap(ctx, dest);
			if (shape)
				fz_clear_pixmap(ctx, shape);
			if (group_alpha)
				fz_clear_pixmap(ctx, group_alpha);
		}

#ifdef DUMP_GROUP_BLENDS
		dump_spaces(dev->top-1, "Mask begin\n");
#endif
		state[1].scissor = bbox;
	}
	fz_catch(ctx)
	{
		emergency_pop_stack(ctx, dev, state);
	}
}

static void
fz_draw_end_mask(fz_context *ctx, fz_device *devp)
{
	fz_draw_device *dev = (fz_draw_device*)devp;
	fz_pixmap *temp, *dest;
	fz_irect bbox;
	fz_draw_state *state;

	if (dev->top == 0)
	{
		fz_warn(ctx, "Unexpected draw_end_mask");
		return;
	}
	state = &dev->stack[dev->top-1];
	STACK_CONVERT("(mask)");

#ifdef DUMP_GROUP_BLENDS
	dump_spaces(dev->top-1, "Mask -> Clip: ");
	fz_dump_blend(ctx, "Mask ", state[1].dest);
	if (state[1].shape)
		fz_dump_blend(ctx, "/S=", state[1].shape);
	if (state[1].group_alpha)
		fz_dump_blend(ctx, "/GA=", state[1].group_alpha);
#endif
	fz_try(ctx)
	{
		/* convert to alpha mask */
		temp = fz_alpha_from_gray(ctx, state[1].dest);
		if (state[1].mask != state[0].mask)
			fz_drop_pixmap(ctx, state[1].mask);
		state[1].mask = temp;
		if (state[1].dest != state[0].dest)
			fz_drop_pixmap(ctx, state[1].dest);
		state[1].dest = NULL;
		if (state[1].shape != state[0].shape)
			fz_drop_pixmap(ctx, state[1].shape);
		state[1].shape = NULL;
		if (state[1].group_alpha != state[0].group_alpha)
			fz_drop_pixmap(ctx, state[1].group_alpha);
		state[1].group_alpha = NULL;

#ifdef DUMP_GROUP_BLENDS
		fz_dump_blend(ctx, "-> Clip ", temp);
		printf("\n");
#endif

		/* create new dest scratch buffer */
		fz_pixmap_bbox(ctx, temp, &bbox);
		dest = fz_new_pixmap_with_bbox(ctx, state->dest->colorspace, &bbox, state->dest->seps, state->dest->alpha);
		fz_copy_pixmap_rect(ctx, dest, state->dest, &bbox, dev->default_cs);

		/* push soft mask as clip mask */
		state[1].dest = dest;
		state[1].blendmode |= FZ_BLEND_ISOLATED;
		/* If we have a shape, then it'll need to be masked with the
		 * clip mask when we pop. So create a new shape now. */
		if (state[0].shape)
		{
			state[1].shape = fz_new_pixmap_with_bbox(ctx, NULL, &bbox, NULL, 1);
			fz_clear_pixmap(ctx, state[1].shape);
		}
		if (state[0].group_alpha)
		{
			state[1].group_alpha = fz_new_pixmap_with_bbox(ctx, NULL, &bbox, NULL, 1);
			fz_clear_pixmap(ctx, state[1].group_alpha);
		}
		state[1].scissor = bbox;
	}
	fz_catch(ctx)
	{
		emergency_pop_stack(ctx, dev, state);
	}
}

static void
fz_draw_begin_group(fz_context *ctx, fz_device *devp, const fz_rect *rect, fz_colorspace *cs, int isolated, int knockout, int blendmode, float alpha)
{
	fz_draw_device *dev = (fz_draw_device*)devp;
	fz_irect bbox;
	fz_pixmap *dest;
	fz_draw_state *state = &dev->stack[dev->top];
	fz_colorspace *model = state->dest->colorspace;
	fz_rect trect = *rect;

	if (dev->top == 0 && dev->resolve_spots)
		state = push_group_for_separations(ctx, dev, fz_default_color_params(ctx)/* FIXME */, dev->default_cs);

	if (cs != NULL)
		model = fz_default_colorspace(ctx, dev->default_cs, cs);

	if (state->blendmode & FZ_BLEND_KNOCKOUT)
		fz_knockout_begin(ctx, dev);

	state = push_stack(ctx, dev);
	STACK_PUSHED("group");
	fz_transform_rect(&trect, &dev->transform);
	fz_intersect_irect(fz_irect_from_rect(&bbox, &trect), &state->scissor);

	fz_try(ctx)
	{
#ifndef ATTEMPT_KNOCKOUT_AND_ISOLATED
		knockout = 0;
		isolated = 1;
#endif

		state[1].dest = dest = fz_new_pixmap_with_bbox(ctx, model, &bbox, state[0].dest->seps, state[0].dest->alpha || isolated);

		if (isolated)
		{
			fz_clear_pixmap(ctx, dest);
			state[1].group_alpha = NULL;
		}
		else
		{
			fz_copy_pixmap_rect(ctx, dest, state[0].dest, &bbox, dev->default_cs);
			state[1].group_alpha = fz_new_pixmap_with_bbox(ctx, NULL, &bbox, NULL, 1);
			fz_clear_pixmap(ctx, state[1].group_alpha);
		}

		/* shape is inherited from the previous group */
		state[1].alpha = alpha;
#ifdef DUMP_GROUP_BLENDS
		dump_spaces(dev->top-1, "");
		{
			char text[240];
			char atext[80];
			char btext[80];
			if (alpha != 1)
				sprintf(atext, " (alpha %g)", alpha);
			else
				atext[0] = 0;
			if (blendmode != 0)
				sprintf(btext, " (blend %d)", blendmode);
			else
				btext[0] = 0;
			sprintf(text, "Group begin%s%s%s%s: background is ", isolated ? " (isolated)" : "", knockout ? " (knockout)" : "", atext, btext);
			fz_dump_blend(ctx, text, state[1].dest);
		}
		if (state[1].shape)
			fz_dump_blend(ctx, "/S=", state[1].shape);
		if (state[1].group_alpha)
			fz_dump_blend(ctx, "/GA=", state[1].group_alpha);
		printf("\n");
#endif

		state[1].scissor = bbox;
		state[1].blendmode = blendmode | (isolated ? FZ_BLEND_ISOLATED : 0) | (knockout ? FZ_BLEND_KNOCKOUT : 0);
	}
	fz_catch(ctx)
	{
		emergency_pop_stack(ctx, dev, state);
	}
}

static void
fz_draw_end_group(fz_context *ctx, fz_device *devp)
{
	fz_draw_device *dev = (fz_draw_device*)devp;
	int blendmode;
	int isolated;
	float alpha;
	fz_draw_state *state;

	if (dev->top == 0)
	{
		fz_warn(ctx, "Unexpected end_group");
		return;
	}

	state = &dev->stack[--dev->top];
	STACK_POPPED("group");

	alpha = state[1].alpha;
	blendmode = state[1].blendmode & FZ_BLEND_MODEMASK;
	isolated = state[1].blendmode & FZ_BLEND_ISOLATED;
#ifdef DUMP_GROUP_BLENDS
	dump_spaces(dev->top, "");
	fz_dump_blend(ctx, "Group end: blending ", state[1].dest);
	if (state[1].shape)
		fz_dump_blend(ctx, "/S=", state[1].shape);
	if (state[1].group_alpha)
		fz_dump_blend(ctx, "/GA=", state[1].group_alpha);
	fz_dump_blend(ctx, " onto ", state[0].dest);
	if (state[0].shape)
		fz_dump_blend(ctx, "/S=", state[0].shape);
	if (state[0].group_alpha)
		fz_dump_blend(ctx, "/GA=", state[0].group_alpha);
	if (alpha != 1.0f)
		printf(" (alpha %g)", alpha);
	if (blendmode != 0)
		printf(" (blend %d)", blendmode);
	if (isolated != 0)
		printf(" (isolated)");
	if (state[1].blendmode & FZ_BLEND_KNOCKOUT)
		printf(" (knockout)");
#endif

	fz_try(ctx)
	{
		if (state[0].dest->colorspace != state[1].dest->colorspace)
		{
			fz_pixmap *converted = fz_convert_pixmap(ctx, state[1].dest, state[0].dest->colorspace, NULL, dev->default_cs, fz_default_color_params(ctx), 1);
			fz_drop_pixmap(ctx, state[1].dest);
			state[1].dest = converted;
		}

		if ((blendmode == 0) && (state[0].shape == state[1].shape) && (state[0].group_alpha == state[1].group_alpha))
			fz_paint_pixmap(state[0].dest, state[1].dest, alpha * 255);
		else
			fz_blend_pixmap(ctx, state[0].dest, state[1].dest, alpha * 255, blendmode, isolated, state[1].group_alpha);

		if (state[0].shape != state[1].shape)
		{
			/* The 'D' on page 7 of Altona_Technical_v20_x4.pdf goes wrong if this
			 * isn't alpha * 255, as the blend back fails to take account of alpha. */
			if (state[0].shape)
			{
				if (state[1].shape)
					fz_paint_pixmap(state[0].shape, state[1].shape, alpha * 255);
				else
					fz_paint_pixmap_alpha(state[0].shape, state[1].dest, alpha * 255);
			}
		}
		assert(state[0].group_alpha == NULL || state[0].group_alpha != state[1].group_alpha);
		if (state[0].group_alpha && state[0].group_alpha != state[1].group_alpha)
		{
			/* The 'D' on page 7 of Altona_Technical_v20_x4.pdf uses an isolated group,
			 * and goes wrong if this is 255 * alpha, as an alpha effectively gets
			 * applied twice. CATX5233 page 7 uses a non-isolated group, and goes wrong
			 * if alpha isn't applied here. */
			if (state[1].group_alpha)
				fz_paint_pixmap(state[0].group_alpha, state[1].group_alpha, isolated ? 255 : alpha * 255);
			else
				fz_paint_pixmap_alpha(state[0].group_alpha, state[1].dest, isolated ? 255 : alpha * 255);
		}

		assert(state[0].dest != state[1].dest);

#ifdef DUMP_GROUP_BLENDS
		fz_dump_blend(ctx, " to get ", state[0].dest);
		if (state[0].shape)
			fz_dump_blend(ctx, "/S=", state[0].shape);
		if (state[0].group_alpha)
			fz_dump_blend(ctx, "/GA=", state[0].group_alpha);
		printf("\n");
#endif
	}
	fz_always(ctx)
	{
		if (state[0].shape != state[1].shape)
			fz_drop_pixmap(ctx, state[1].shape);
		fz_drop_pixmap(ctx, state[1].group_alpha);
		/* The following test should not be required, but just occasionally
		 * errors can cause the stack to get out of sync, and this might save
		 * our bacon. */
		if (state[0].dest != state[1].dest)
			fz_drop_pixmap(ctx, state[1].dest);

		if (state[0].blendmode & FZ_BLEND_KNOCKOUT)
			fz_knockout_end(ctx, dev);
	}
	fz_catch(ctx)
	{
		fz_rethrow(ctx);
	}

}

typedef struct
{
	int refs;
	float ctm[4];
	int id;
	fz_colorspace *cs;
} tile_key;

typedef struct
{
	fz_storable storable;
	fz_pixmap *dest;
	fz_pixmap *shape;
	fz_pixmap *group_alpha;
} tile_record;

static int
fz_make_hash_tile_key(fz_context *ctx, fz_store_hash *hash, void *key_)
{
	tile_key *key = key_;

	hash->u.im.id = key->id;
	hash->u.im.m[0] = key->ctm[0];
	hash->u.im.m[1] = key->ctm[1];
	hash->u.im.m[2] = key->ctm[2];
	hash->u.im.m[3] = key->ctm[3];
	hash->u.im.ptr = key->cs;
	return 1;
}

static void *
fz_keep_tile_key(fz_context *ctx, void *key_)
{
	tile_key *key = key_;
	return fz_keep_imp(ctx, key, &key->refs);
}

static void
fz_drop_tile_key(fz_context *ctx, void *key_)
{
	tile_key *key = key_;
	if (fz_drop_imp(ctx, key, &key->refs))
	{
		fz_drop_colorspace_store_key(ctx, key->cs);
		fz_free(ctx, key);
	}
}

static int
fz_cmp_tile_key(fz_context *ctx, void *k0_, void *k1_)
{
	tile_key *k0 = k0_;
	tile_key *k1 = k1_;
	return k0->id == k1->id &&
		k0->ctm[0] == k1->ctm[0] &&
		k0->ctm[1] == k1->ctm[1] &&
		k0->ctm[2] == k1->ctm[2] &&
		k0->ctm[3] == k1->ctm[3] &&
		k0->cs == k1->cs;
}

static void
fz_format_tile_key(fz_context *ctx, char *s, int n, void *key_)
{
	tile_key *key = (tile_key *)key_;
	fz_snprintf(s, n, "(tile id=%x, ctm=%g %g %g %g, cs=%x)",
			key->id, key->ctm[0], key->ctm[1], key->ctm[2], key->ctm[3], key->cs);
}

static const fz_store_type fz_tile_store_type =
{
	fz_make_hash_tile_key,
	fz_keep_tile_key,
	fz_drop_tile_key,
	fz_cmp_tile_key,
	fz_format_tile_key,
	NULL
};

static void
fz_drop_tile_record_imp(fz_context *ctx, fz_storable *storable)
{
	tile_record *tr = (tile_record *)storable;
	fz_drop_pixmap(ctx, tr->dest);
	fz_drop_pixmap(ctx, tr->shape);
	fz_drop_pixmap(ctx, tr->group_alpha);
	fz_free(ctx, tr);
}

static void
fz_drop_tile_record(fz_context *ctx, tile_record *tile)
{
	fz_drop_storable(ctx, &tile->storable);
}

static tile_record *
fz_new_tile_record(fz_context *ctx, fz_pixmap *dest, fz_pixmap *shape, fz_pixmap *group_alpha)
{
	tile_record *tile = fz_malloc_struct(ctx, tile_record);
	FZ_INIT_STORABLE(tile, 1, fz_drop_tile_record_imp);
	tile->dest = fz_keep_pixmap(ctx, dest);
	tile->shape = fz_keep_pixmap(ctx, shape);
	tile->group_alpha = fz_keep_pixmap(ctx, group_alpha);
	return tile;
}

size_t
fz_tile_size(fz_context *ctx, tile_record *tile)
{
	if (!tile)
		return 0;
	return sizeof(*tile) + fz_pixmap_size(ctx, tile->dest) + fz_pixmap_size(ctx, tile->shape) + fz_pixmap_size(ctx, tile->group_alpha);
}

static int
fz_draw_begin_tile(fz_context *ctx, fz_device *devp, const fz_rect *area, const fz_rect *view, float xstep, float ystep, const fz_matrix *in_ctm, int id)
{
	fz_draw_device *dev = (fz_draw_device*)devp;
	fz_matrix ctm = concat(in_ctm, &dev->transform);
	fz_pixmap *dest = NULL;
	fz_pixmap *shape, *group_alpha;
	fz_irect bbox;
	fz_draw_state *state = &dev->stack[dev->top];
	fz_colorspace *model = state->dest->colorspace;
	fz_rect local_view = *view;

	if (dev->top == 0 && dev->resolve_spots)
		state = push_group_for_separations(ctx, dev, fz_default_color_params(ctx)/* FIXME */, dev->default_cs);

	/* area, view, xstep, ystep are in pattern space */
	/* ctm maps from pattern space to device space */

	if (state->blendmode & FZ_BLEND_KNOCKOUT)
		fz_knockout_begin(ctx, dev);

	state = push_stack(ctx, dev);
	STACK_PUSHED("tile");
	fz_irect_from_rect(&bbox, fz_transform_rect(&local_view, &ctm));
	/* We should never have a bbox that entirely covers our destination.
	 * If we do, then the check for only 1 tile being visible above has
	 * failed. Actually, this *can* fail due to the round_rect, at extreme
	 * resolutions, so disable this assert.
	 * assert(bbox.x0 > state->dest->x || bbox.x1 < state->dest->x + state->dest->w ||
	 *	bbox.y0 > state->dest->y || bbox.y1 < state->dest->y + state->dest->h);
	 */

	/* Check to see if we have one cached */
	if (id)
	{
		tile_key tk;
		tile_record *tile;
		tk.ctm[0] = ctm.a;
		tk.ctm[1] = ctm.b;
		tk.ctm[2] = ctm.c;
		tk.ctm[3] = ctm.d;
		tk.id = id;
		tk.cs = state[1].dest->colorspace;

		tile = fz_find_item(ctx, fz_drop_tile_record_imp, &tk, &fz_tile_store_type);
		if (tile)
		{
			state[1].dest = fz_keep_pixmap(ctx, tile->dest);
			state[1].shape = fz_keep_pixmap(ctx, tile->shape);
			state[1].group_alpha = fz_keep_pixmap(ctx, tile->group_alpha);
			state[1].blendmode |= FZ_BLEND_ISOLATED;
			state[1].xstep = xstep;
			state[1].ystep = ystep;
			state[1].id = id;
			state[1].encache = 0;
			fz_irect_from_rect(&state[1].area, area);
			state[1].ctm = ctm;
#ifdef DUMP_GROUP_BLENDS
			dump_spaces(dev->top-1, "Tile begin (cached)\n");
#endif

			state[1].scissor = bbox;
			fz_drop_tile_record(ctx, tile);
			return 1;
		}
	}

	fz_try(ctx)
	{
		/* Patterns can be transparent, so we need to have an alpha here. */
		state[1].dest = dest = fz_new_pixmap_with_bbox(ctx, model, &bbox, state[0].dest->seps, 1);
		fz_clear_pixmap(ctx, dest);
		shape = state[0].shape;
		if (shape)
		{
			state[1].shape = shape = fz_new_pixmap_with_bbox(ctx, NULL, &bbox, NULL, 1);
			fz_clear_pixmap(ctx, shape);
		}
		group_alpha = state[0].group_alpha;
		if (group_alpha)
		{
			state[1].group_alpha = group_alpha = fz_new_pixmap_with_bbox(ctx, NULL, &bbox, NULL, 1);
			fz_clear_pixmap(ctx, group_alpha);
		}
		state[1].blendmode |= FZ_BLEND_ISOLATED;
		state[1].xstep = xstep;
		state[1].ystep = ystep;
		state[1].id = id;
		state[1].encache = 1;
		fz_irect_from_rect(&state[1].area, area);
		state[1].ctm = ctm;
#ifdef DUMP_GROUP_BLENDS
		dump_spaces(dev->top-1, "Tile begin\n");
#endif

		state[1].scissor = bbox;
	}
	fz_catch(ctx)
	{
		emergency_pop_stack(ctx, dev, state);
	}

	return 0;
}

static void
fz_draw_end_tile(fz_context *ctx, fz_device *devp)
{
	fz_draw_device *dev = (fz_draw_device*)devp;
	float xstep, ystep;
	fz_matrix ttm, ctm, shapectm, gactm;
	fz_irect area, scissor, tile_bbox;
	fz_rect scissor_tmp, tile_tmp;
	int x0, y0, x1, y1, x, y, extra_x, extra_y;
	fz_draw_state *state;
	fz_pixmap *dest = NULL;
	fz_pixmap *shape = NULL;
	fz_pixmap *group_alpha = NULL;

	if (dev->top == 0)
	{
		fz_warn(ctx, "Unexpected end_tile");
		return;
	}

	state = &dev->stack[--dev->top];
	STACK_PUSHED("tile");
	xstep = state[1].xstep;
	ystep = state[1].ystep;
	area = state[1].area;
	ctm = state[1].ctm;

	/* Fudge the scissor bbox a little to allow for inaccuracies in the
	 * matrix inversion. */
	fz_rect_from_irect(&scissor_tmp, &state[0].scissor);
	fz_transform_rect(fz_expand_rect(&scissor_tmp, 1), fz_invert_matrix(&ttm, &ctm));
	fz_intersect_irect(&area, fz_irect_from_rect(&scissor, &scissor_tmp));

	tile_bbox.x0 = state[1].dest->x;
	tile_bbox.y0 = state[1].dest->y;
	tile_bbox.x1 = state[1].dest->w + tile_bbox.x0;
	tile_bbox.y1 = state[1].dest->h + tile_bbox.y0;
	fz_rect_from_irect(&tile_tmp, &tile_bbox);
	fz_transform_rect(fz_expand_rect(&tile_tmp, 1), &ttm);

	/* FIXME: area is a bbox, so FP not appropriate here */
	/* In PDF files xstep/ystep can be smaller than view (the area of a
	 * single tile) (see fts_15_1506.pdf for an example). This means that
	 * we have to bias the left hand/bottom edge calculations by the
	 * difference between the step and the width/height of the tile. */
	/* scissor, xstep and area are all in pattern space. */
	extra_x = tile_tmp.x1 - tile_tmp.x0 - xstep;
	if (extra_x < 0)
		extra_x = 0;
	extra_y = tile_tmp.y1 - tile_tmp.y0 - ystep;
	if (extra_y < 0)
		extra_y = 0;
	x0 = floorf((area.x0 - tile_tmp.x0 - extra_x) / xstep);
	y0 = floorf((area.y0 - tile_tmp.y0 - extra_y) / ystep);
	x1 = ceilf((area.x1 - tile_tmp.x0 + extra_x) / xstep);
	y1 = ceilf((area.y1 - tile_tmp.y0 + extra_y) / ystep);

	ctm.e = state[1].dest->x;
	ctm.f = state[1].dest->y;
	if (state[1].shape)
	{
		shapectm = ctm;
		shapectm.e = state[1].shape->x;
		shapectm.f = state[1].shape->y;
	}
	if (state[1].group_alpha)
	{
		gactm = ctm;
		gactm.e = state[1].group_alpha->x;
		gactm.f = state[1].group_alpha->y;
	}

#ifdef DUMP_GROUP_BLENDS
	dump_spaces(dev->top, "");
	fz_dump_blend(ctx, "Tiling ", state[1].dest);
	if (state[1].shape)
		fz_dump_blend(ctx, "/S=", state[1].shape);
	if (state[1].group_alpha)
		fz_dump_blend(ctx, "/GA=", state[1].group_alpha);
	fz_dump_blend(ctx, " onto ", state[0].dest);
	if (state[0].shape)
		fz_dump_blend(ctx, "/S=", state[0].shape);
	if (state[0].group_alpha)
		fz_dump_blend(ctx, "/GA=", state[0].group_alpha);
#endif
	dest = fz_new_pixmap_from_pixmap(ctx, state[1].dest, NULL);

	fz_var(shape);
	fz_var(group_alpha);

	fz_try(ctx)
	{
		shape = fz_new_pixmap_from_pixmap(ctx, state[1].shape, NULL);
		group_alpha = fz_new_pixmap_from_pixmap(ctx, state[1].group_alpha, NULL);

		for (y = y0; y < y1; y++)
		{
			for (x = x0; x < x1; x++)
			{
				ttm = ctm;
				fz_pre_translate(&ttm, x * xstep, y * ystep);
				dest->x = ttm.e;
				dest->y = ttm.f;
				/* Check for overflow due to float -> int conversions */
				if (dest->x > 0 && dest->x + dest->w < 0)
					continue;
				if (dest->y > 0 && dest->y + dest->h < 0)
					continue;
				fz_paint_pixmap_with_bbox(state[0].dest, dest, 255, state[0].scissor);
				if (shape)
				{
					ttm = shapectm;
					fz_pre_translate(&ttm, x * xstep, y * ystep);
					shape->x = ttm.e;
					shape->y = ttm.f;
					fz_paint_pixmap_with_bbox(state[0].shape, shape, 255, state[0].scissor);
				}
				if (group_alpha)
				{
					ttm = gactm;
					fz_pre_translate(&ttm, x * xstep, y * ystep);
					group_alpha->x = ttm.e;
					group_alpha->y = ttm.f;
					fz_paint_pixmap_with_bbox(state[0].group_alpha, group_alpha, 255, state[0].scissor);
				}
			}
		}
	}
	fz_always(ctx)
	{
		fz_drop_pixmap(ctx, dest);
		fz_drop_pixmap(ctx, shape);
		fz_drop_pixmap(ctx, group_alpha);
	}
	fz_catch(ctx)
		fz_rethrow(ctx);

	/* Now we try to cache the tiles. Any failure here will just result in us not caching. */
	if (state[1].encache && state[1].id != 0)
	{
		tile_record *tile = NULL;
		tile_key *key = NULL;
		fz_var(tile);
		fz_var(key);
		fz_try(ctx)
		{
			tile_record *existing_tile;

			tile = fz_new_tile_record(ctx, state[1].dest, state[1].shape, state[1].group_alpha);

			key = fz_malloc_struct(ctx, tile_key);
			key->refs = 1;
			key->id = state[1].id;
			key->ctm[0] = ctm.a;
			key->ctm[1] = ctm.b;
			key->ctm[2] = ctm.c;
			key->ctm[3] = ctm.d;
			key->cs = fz_keep_colorspace_store_key(ctx, state[1].dest->colorspace);
			existing_tile = fz_store_item(ctx, key, tile, fz_tile_size(ctx, tile), &fz_tile_store_type);
			if (existing_tile)
			{
				/* We already have a tile. This will either have been
				 * produced by a racing thread, or there is already
				 * an entry for this one in the store. */
				fz_drop_tile_record(ctx, tile);
				tile = existing_tile;
			}
		}
		fz_always(ctx)
		{
			fz_drop_tile_key(ctx, key);
			fz_drop_tile_record(ctx, tile);
		}
		fz_catch(ctx)
		{
			/* Do nothing */
		}
	}

	/* The following tests should not be required, but just occasionally
	 * errors can cause the stack to get out of sync, and this might save
	 * our bacon. */
	if (state[0].dest != state[1].dest)
		fz_drop_pixmap(ctx, state[1].dest);
	if (state[0].shape != state[1].shape)
		fz_drop_pixmap(ctx, state[1].shape);
	if (state[0].group_alpha != state[1].group_alpha)
		fz_drop_pixmap(ctx, state[1].group_alpha);
#ifdef DUMP_GROUP_BLENDS
	fz_dump_blend(ctx, " to get ", state[0].dest);
	if (state[0].shape)
		fz_dump_blend(ctx, "/S=", state[0].shape);
	if (state[0].group_alpha)
		fz_dump_blend(ctx, "/GA=", state[0].group_alpha);
	printf("\n");
#endif

	if (state->blendmode & FZ_BLEND_KNOCKOUT)
		fz_knockout_end(ctx, dev);
}

static void
fz_draw_render_flags(fz_context *ctx, fz_device *devp, int set, int clear)
{
	fz_draw_device *dev = (fz_draw_device*)devp;
	dev->flags = (dev->flags | set ) & ~clear;
}

static void
fz_draw_set_default_colorspaces(fz_context *ctx, fz_device *devp, fz_default_colorspaces *default_cs)
{
	fz_draw_device *dev = (fz_draw_device*)devp;
	fz_drop_default_colorspaces(ctx, dev->default_cs);
	dev->default_cs = fz_keep_default_colorspaces(ctx, default_cs);
}

static void
fz_draw_close_device(fz_context *ctx, fz_device *devp)
{
	fz_draw_device *dev = (fz_draw_device*)devp;

	/* pop and free the stacks */
	if (dev->top > dev->resolve_spots)
		fz_warn(ctx, "items left on stack in draw device: %d", dev->top);

	while(dev->top > dev->resolve_spots)
	{
		fz_draw_state *state = &dev->stack[--dev->top];
		if (state[1].mask != state[0].mask)
			fz_drop_pixmap(ctx, state[1].mask);
		if (state[1].dest != state[0].dest)
			fz_drop_pixmap(ctx, state[1].dest);
		if (state[1].shape != state[0].shape)
			fz_drop_pixmap(ctx, state[1].shape);
		if (state[1].group_alpha != state[0].group_alpha)
			fz_drop_pixmap(ctx, state[1].group_alpha);
	}

	if (dev->resolve_spots && dev->top)
	{
		fz_draw_state *state = &dev->stack[--dev->top];
		fz_copy_pixmap_area_converting_seps(ctx, state[0].dest, state[1].dest, fz_default_color_params(ctx)/* FIXME */, dev->proof_cs, dev->default_cs);
		fz_drop_pixmap(ctx, state[1].dest);
		assert(state[1].mask == NULL);
		assert(state[1].shape == NULL);
		assert(state[1].group_alpha == NULL);
	}
}

static void
fz_draw_drop_device(fz_context *ctx, fz_device *devp)
{
	fz_draw_device *dev = (fz_draw_device*)devp;
	fz_rasterizer *rast = dev->rast;

	fz_drop_default_colorspaces(ctx, dev->default_cs);
	fz_drop_colorspace(ctx, dev->proof_cs);

	/* pop and free the stacks */
	if (dev->top > 0)
		fz_warn(ctx, "items left on stack in draw device: %d", dev->top);

	while(dev->top-- > 0)
	{
		fz_draw_state *state = &dev->stack[dev->top];
		if (state[1].mask != state[0].mask)
			fz_drop_pixmap(ctx, state[1].mask);
		if (state[1].dest != state[0].dest)
			fz_drop_pixmap(ctx, state[1].dest);
		if (state[1].shape != state[0].shape)
			fz_drop_pixmap(ctx, state[1].shape);
		if (state[1].group_alpha != state[0].group_alpha)
			fz_drop_pixmap(ctx, state[1].group_alpha);
	}

	/* We never free the dest/mask/shape at level 0, as:
	 * 1) dest is passed in and ownership remains with the caller.
	 * 2) shape and mask are NULL at level 0.
	 */
	if (dev->stack != &dev->init_stack[0])
		fz_free(ctx, dev->stack);
	fz_drop_scale_cache(ctx, dev->cache_x);
	fz_drop_scale_cache(ctx, dev->cache_y);
	fz_drop_rasterizer(ctx, rast);
}

fz_device *
new_draw_device(fz_context *ctx, const fz_matrix *transform, fz_pixmap *dest, const fz_aa_context *aa, const fz_irect *clip, fz_colorspace *proof_cs)
{
	fz_draw_device *dev = fz_new_derived_device(ctx, fz_draw_device);

	dev->super.drop_device = fz_draw_drop_device;
	dev->super.close_device = fz_draw_close_device;

	dev->super.fill_path = fz_draw_fill_path;
	dev->super.stroke_path = fz_draw_stroke_path;
	dev->super.clip_path = fz_draw_clip_path;
	dev->super.clip_stroke_path = fz_draw_clip_stroke_path;

	dev->super.fill_text = fz_draw_fill_text;
	dev->super.stroke_text = fz_draw_stroke_text;
	dev->super.clip_text = fz_draw_clip_text;
	dev->super.clip_stroke_text = fz_draw_clip_stroke_text;
	dev->super.ignore_text = fz_draw_ignore_text;

	dev->super.fill_image_mask = fz_draw_fill_image_mask;
	dev->super.clip_image_mask = fz_draw_clip_image_mask;
	dev->super.fill_image = fz_draw_fill_image;
	dev->super.fill_shade = fz_draw_fill_shade;

	dev->super.pop_clip = fz_draw_pop_clip;

	dev->super.begin_mask = fz_draw_begin_mask;
	dev->super.end_mask = fz_draw_end_mask;
	dev->super.begin_group = fz_draw_begin_group;
	dev->super.end_group = fz_draw_end_group;

	dev->super.begin_tile = fz_draw_begin_tile;
	dev->super.end_tile = fz_draw_end_tile;

	dev->super.render_flags = fz_draw_render_flags;
	dev->super.set_default_colorspaces = fz_draw_set_default_colorspaces;

	dev->proof_cs = fz_keep_colorspace(ctx, proof_cs);
	dev->transform = transform ? *transform : fz_identity;
	dev->flags = 0;
	dev->resolve_spots = 0;
	dev->top = 0;
	dev->stack = &dev->init_stack[0];
	dev->stack_cap = STACK_SIZE;
	dev->stack[0].dest = dest;
	dev->stack[0].shape = NULL;
	dev->stack[0].group_alpha = NULL;
	dev->stack[0].mask = NULL;
	dev->stack[0].blendmode = 0;
	dev->stack[0].scissor.x0 = dest->x;
	dev->stack[0].scissor.y0 = dest->y;
	dev->stack[0].scissor.x1 = dest->x + dest->w;
	dev->stack[0].scissor.y1 = dest->y + dest->h;

	if (clip)
	{
		if (clip->x0 > dev->stack[0].scissor.x0)
			dev->stack[0].scissor.x0 = clip->x0;
		if (clip->x1 < dev->stack[0].scissor.x1)
			dev->stack[0].scissor.x1 = clip->x1;
		if (clip->y0 > dev->stack[0].scissor.y0)
			dev->stack[0].scissor.y0 = clip->y0;
		if (clip->y1 < dev->stack[0].scissor.y1)
			dev->stack[0].scissor.y1 = clip->y1;
	}

	/* If we have no separations structure at all, then we want a
	 * simple composite rendering (with no overprint simulation).
	 * If we do have a separations structure, so: 1) Any
	 * 'disabled' separations are ignored. 2) Any 'composite'
	 * separations means we will need to do an overprint
	 * simulation.
	 *
	 * The supplied pixmaps 's' will match the number of
	 * 'spots' separations. If we have any 'composite'
	 * separations therefore, we'll need to make a new pixmap
	 * with a new (completely 'spots') separations structure,
	 * render to that, and then map down at the end.
	 *
	 * Unfortunately we can't produce this until we know what
	 * the default_colorspaces etc are, so set a flag for us
	 * to trigger on later.
	 */
	if (dest->seps || dev->proof_cs != NULL)
#ifdef FZ_ENABLE_SPOT_RENDERING
		dev->resolve_spots = 1;
#else
		fz_throw(ctx, FZ_ERROR_GENERIC, "Spot rendering (and overprint/overprint simulation) not available in this build");
#endif

	fz_try(ctx)
	{
		dev->rast = fz_new_rasterizer(ctx, aa);
		dev->cache_x = fz_new_scale_cache(ctx);
		dev->cache_y = fz_new_scale_cache(ctx);
	}
	fz_catch(ctx)
	{
		fz_drop_device(ctx, (fz_device*)dev);
		fz_rethrow(ctx);
	}

	return (fz_device*)dev;
}

fz_device *
fz_new_draw_device(fz_context *ctx, const fz_matrix *transform, fz_pixmap *dest)
{
	return new_draw_device(ctx, transform, dest, NULL, NULL, NULL);
}

fz_device *
fz_new_draw_device_with_bbox(fz_context *ctx, const fz_matrix *transform, fz_pixmap *dest, const fz_irect *clip)
{
	return new_draw_device(ctx, transform, dest, NULL, clip, NULL);
}

fz_device *
fz_new_draw_device_with_proof(fz_context *ctx, const fz_matrix *transform, fz_pixmap *dest, fz_colorspace *cs)
{
	return new_draw_device(ctx, transform, dest, NULL, NULL, cs);
}

fz_device *
fz_new_draw_device_with_bbox_proof(fz_context *ctx, const fz_matrix *transform, fz_pixmap *dest, const fz_irect *clip, fz_colorspace *cs)
{
	return new_draw_device(ctx, transform, dest, NULL, clip, cs);
}

fz_device *
fz_new_draw_device_type3(fz_context *ctx, const fz_matrix *transform, fz_pixmap *dest)
{
	fz_draw_device *dev = (fz_draw_device*)fz_new_draw_device(ctx, transform, dest);
	dev->flags |= FZ_DRAWDEV_FLAGS_TYPE3;
	return (fz_device*)dev;
}

fz_irect *
fz_bound_path_accurate(fz_context *ctx, fz_irect *bbox, const fz_irect *scissor, const fz_path *path, const fz_stroke_state *stroke, const fz_matrix *ctm, float flatness, float linewidth)
{
	fz_rasterizer *rast = fz_new_rasterizer(ctx, NULL);

	fz_try(ctx)
	{
		if (stroke)
			(void)fz_flatten_stroke_path(ctx, rast, path, stroke, ctm, flatness, linewidth, scissor, bbox);
		else
			(void)fz_flatten_fill_path(ctx, rast, path, ctm, flatness, scissor, bbox);
	}
	fz_always(ctx)
		fz_drop_rasterizer(ctx, rast);
	fz_catch(ctx)
		fz_rethrow(ctx);

	return bbox;
}

const char *fz_draw_options_usage =
	"Raster output options:\n"
	"\trotate=N: rotate rendered pages N degrees counterclockwise\n"
	"\tresolution=N: set both X and Y resolution in pixels per inch\n"
	"\tx-resolution=N: X resolution of rendered pages in pixels per inch\n"
	"\ty-resolution=N: Y resolution of rendered pages in pixels per inch\n"
	"\twidth=N: render pages to fit N pixels wide (ignore resolution option)\n"
	"\theight=N: render pages to fit N pixels tall (ignore resolution option)\n"
	"\tcolorspace=(gray|rgb|cmyk): render using specified colorspace\n"
	"\talpha: render pages with alpha channel and transparent background\n"
	"\tgraphics=(aaN|cop|app): set the rasterizer to use\n"
	"\ttext=(aaN|cop|app): set the rasterizer to use for text\n"
	"\t\taaN=antialias with N bits (0 to 8)\n"
	"\t\tcop=center of pixel\n"
	"\t\tapp=any part of pixel\n"
	"\n";

static int parse_aa_opts(const char *val)
{
	if (fz_option_eq(val, "cop"))
		return 9;
	if (fz_option_eq(val, "app"))
		return 10;
	if (val[0] == 'a' && val[1] == 'a' && val[2] >= '0' && val[2] <= '9')
		return  fz_clampi(fz_atoi(&val[2]), 0, 8);
	return 8;
}

fz_draw_options *
fz_parse_draw_options(fz_context *ctx, fz_draw_options *opts, const char *args)
{
	const char *val;

	memset(opts, 0, sizeof *opts);

	opts->x_resolution = 96;
	opts->y_resolution = 96;
	opts->rotate = 0;
	opts->width = 0;
	opts->height = 0;
	opts->colorspace = fz_device_rgb(ctx);
	opts->alpha = 0;
	opts->graphics = fz_aa_level(ctx);
	opts->text = fz_text_aa_level(ctx);

	if (fz_has_option(ctx, args, "rotate", &val))
		opts->rotate = fz_atoi(val);
	if (fz_has_option(ctx, args, "resolution", &val))
		opts->x_resolution = opts->y_resolution = fz_atoi(val);
	if (fz_has_option(ctx, args, "x-resolution", &val))
		opts->x_resolution = fz_atoi(val);
	if (fz_has_option(ctx, args, "y-resolution", &val))
		opts->y_resolution = fz_atoi(val);
	if (fz_has_option(ctx, args, "width", &val))
		opts->width = fz_atoi(val);
	if (fz_has_option(ctx, args, "height", &val))
		opts->height = fz_atoi(val);
	if (fz_has_option(ctx, args, "colorspace", &val))
	{
		if (fz_option_eq(val, "gray") || fz_option_eq(val, "grey") || fz_option_eq(val, "mono"))
			opts->colorspace = fz_device_gray(ctx);
		else if (fz_option_eq(val, "rgb"))
			opts->colorspace = fz_device_rgb(ctx);
		else if (fz_option_eq(val, "cmyk"))
			opts->colorspace = fz_device_cmyk(ctx);
		else
			fz_throw(ctx, FZ_ERROR_GENERIC, "unknown colorspace in options");
	}
	if (fz_has_option(ctx, args, "alpha", &val))
		opts->alpha = fz_option_eq(val, "yes");
	if (fz_has_option(ctx, args, "graphics", &val))
		opts->text = opts->graphics = parse_aa_opts(val);
	if (fz_has_option(ctx, args, "text", &val))
		opts->text = parse_aa_opts(val);

	/* Sanity check values */
	if (opts->x_resolution <= 0) opts->x_resolution = 96;
	if (opts->y_resolution <= 0) opts->y_resolution = 96;
	if (opts->width < 0) opts->width = 0;
	if (opts->height < 0) opts->height = 0;

	return opts;
}

fz_device *
fz_new_draw_device_with_options(fz_context *ctx, const fz_draw_options *opts, const fz_rect *mediabox, fz_pixmap **pixmap)
{
	float x_zoom = opts->x_resolution / 72.0f;
	float y_zoom = opts->y_resolution / 72.0f;
	int w = opts->width;
	int h = opts->height;
	fz_rect bounds;
	fz_irect ibounds;
	fz_matrix transform;
	fz_device *dev = NULL;
	fz_aa_context aa = *ctx->aa;

	fz_set_rasterizer_graphics_aa_level(ctx, &aa, opts->graphics);
	fz_set_rasterizer_text_aa_level(ctx, &aa, opts->text);

	fz_pre_rotate(fz_scale(&transform, x_zoom, y_zoom), opts->rotate);
	bounds = *mediabox;
	fz_round_rect(&ibounds, fz_transform_rect(&bounds, &transform));

	/* If width or height are set, we may need to adjust the transform */
	if (w || h)
	{
		float scalex = 1;
		float scaley = 1;
		if (w != 0)
			scalex = w / (bounds.x1 - bounds.x0);
		if (h != 0)
			scaley = h / (bounds.y1 - bounds.y0);
		if (scalex != scaley)
		{
			if (w == 0)
				scalex = scaley;
			else if (h == 0)
				scaley = scalex;
			else if (scalex > scaley)
				scalex = scaley;
			else
				scaley = scalex;
		}
		if (scalex != 1 || scaley != 1)
		{
			fz_pre_scale(&transform, scalex, scaley);
			bounds = *mediabox;
			fz_round_rect(&ibounds, fz_transform_rect(&bounds, &transform));
		}
	}

	*pixmap = fz_new_pixmap_with_bbox(ctx, opts->colorspace, &ibounds, NULL/* FIXME */, opts->alpha);
	fz_try(ctx)
	{
		fz_set_pixmap_resolution(ctx, *pixmap, opts->x_resolution, opts->y_resolution);
		if (opts->alpha)
			fz_clear_pixmap(ctx, *pixmap);
		else
			fz_clear_pixmap_with_value(ctx, *pixmap, 255);

		dev = new_draw_device(ctx, &transform, *pixmap, &aa, NULL, NULL);
	}
	fz_catch(ctx)
	{
		fz_drop_pixmap(ctx, *pixmap);
		*pixmap = NULL;
		fz_rethrow(ctx);
	}
	return dev;
}