summaryrefslogtreecommitdiff
path: root/src/cairo-quartz-surface.c
blob: 9628c877ed56db225e8c62e8d70f717547609757 (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
/* -*- Mode: c; c-basic-offset: 4; indent-tabs-mode: t; tab-width: 8; -*- */
/* cairo - a vector graphics library with display and print output
 *
 * Copyright � 2006, 2007 Mozilla Corporation
 *
 * This library is free software; you can redistribute it and/or
 * modify it either under the terms of the GNU Lesser General Public
 * License version 2.1 as published by the Free Software Foundation
 * (the "LGPL") or, at your option, under the terms of the Mozilla
 * Public License Version 1.1 (the "MPL"). If you do not alter this
 * notice, a recipient may use your version of this file under either
 * the MPL or the LGPL.
 *
 * You should have received a copy of the LGPL along with this library
 * in the file COPYING-LGPL-2.1; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Suite 500, Boston, MA 02110-1335, USA
 * You should have received a copy of the MPL along with this library
 * in the file COPYING-MPL-1.1
 *
 * The contents of this file are subject to the Mozilla Public License
 * Version 1.1 (the "License"); you may not use this file except in
 * compliance with the License. You may obtain a copy of the License at
 * http://www.mozilla.org/MPL/
 *
 * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY
 * OF ANY KIND, either express or implied. See the LGPL or the MPL for
 * the specific language governing rights and limitations.
 *
 * The Original Code is the cairo graphics library.
 *
 * The Initial Developer of the Original Code is Mozilla Foundation.
 *
 * Contributor(s):
 *	Vladimir Vukicevic <vladimir@mozilla.com>
 */

#define _GNU_SOURCE /* required for RTLD_DEFAULT */
#include "cairoint.h"

#include "cairo-quartz-private.h"

#include "cairo-default-context-private.h"
#include "cairo-error-private.h"
#include "cairo-pattern-private.h"
#include "cairo-surface-clipper-private.h"

#include <dlfcn.h>

#ifndef RTLD_DEFAULT
#define RTLD_DEFAULT ((void *) 0)
#endif

#include <limits.h>

#undef QUARTZ_DEBUG

#ifdef QUARTZ_DEBUG
#define ND(_x)	fprintf _x
#else
#define ND(_x)	do {} while(0)
#endif

#define IS_EMPTY(s) ((s)->extents.width == 0 || (s)->extents.height == 0)

/**
 * SECTION:cairo-quartz
 * @Title: Quartz Surfaces
 * @Short_Description: Rendering to Quartz surfaces
 * @See_Also: #cairo_surface_t
 *
 * The Quartz surface is used to render cairo graphics targeting the
 * Apple OS X Quartz rendering system.
 */

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

#if __MAC_OS_X_VERSION_MIN_REQUIRED < 1050
/* This method is private, but it exists.  Its params are are exposed
 * as args to the NS* method, but not as CG.
 */
enum PrivateCGCompositeMode {
    kPrivateCGCompositeClear		= 0,
    kPrivateCGCompositeCopy		= 1,
    kPrivateCGCompositeSourceOver	= 2,
    kPrivateCGCompositeSourceIn		= 3,
    kPrivateCGCompositeSourceOut	= 4,
    kPrivateCGCompositeSourceAtop	= 5,
    kPrivateCGCompositeDestinationOver	= 6,
    kPrivateCGCompositeDestinationIn	= 7,
    kPrivateCGCompositeDestinationOut	= 8,
    kPrivateCGCompositeDestinationAtop	= 9,
    kPrivateCGCompositeXOR		= 10,
    kPrivateCGCompositePlusDarker	= 11, // (max (0, (1-d) + (1-s)))
    kPrivateCGCompositePlusLighter	= 12, // (min (1, s + d))
};
typedef enum PrivateCGCompositeMode PrivateCGCompositeMode;
CG_EXTERN void CGContextSetCompositeOperation (CGContextRef, PrivateCGCompositeMode);
#endif

/* Some of these are present in earlier versions of the OS than where
 * they are public; other are not public at all
 */
/* public since 10.5 */
static void (*CGContextDrawTiledImagePtr) (CGContextRef, CGRect, CGImageRef) = NULL;

/* public since 10.6 */
static CGPathRef (*CGContextCopyPathPtr) (CGContextRef) = NULL;
static void (*CGContextSetAllowsFontSmoothingPtr) (CGContextRef, bool) = NULL;

/* not yet public */
static unsigned int (*CGContextGetTypePtr) (CGContextRef) = NULL;
static bool (*CGContextGetAllowsFontSmoothingPtr) (CGContextRef) = NULL;

static cairo_bool_t _cairo_quartz_symbol_lookup_done = FALSE;

/*
 * Utility functions
 */

#ifdef QUARTZ_DEBUG
static void quartz_surface_to_png (cairo_quartz_surface_t *nq, char *dest);
static void quartz_image_to_png (CGImageRef, char *dest);
#endif

static cairo_quartz_surface_t *
_cairo_quartz_surface_create_internal (CGContextRef cgContext,
				       cairo_content_t content,
				       unsigned int width,
				       unsigned int height);

static cairo_bool_t
_cairo_surface_is_quartz (const cairo_surface_t *surface);

/* Load all extra symbols */
static void quartz_ensure_symbols (void)
{
    if (likely (_cairo_quartz_symbol_lookup_done))
	return;

    CGContextDrawTiledImagePtr = dlsym (RTLD_DEFAULT, "CGContextDrawTiledImage");
    CGContextGetTypePtr = dlsym (RTLD_DEFAULT, "CGContextGetType");
    CGContextCopyPathPtr = dlsym (RTLD_DEFAULT, "CGContextCopyPath");
    CGContextGetAllowsFontSmoothingPtr = dlsym (RTLD_DEFAULT, "CGContextGetAllowsFontSmoothing");
    CGContextSetAllowsFontSmoothingPtr = dlsym (RTLD_DEFAULT, "CGContextSetAllowsFontSmoothing");

    _cairo_quartz_symbol_lookup_done = TRUE;
}

CGImageRef
_cairo_quartz_create_cgimage (cairo_format_t format,
			      unsigned int width,
			      unsigned int height,
			      unsigned int stride,
			      void *data,
			      cairo_bool_t interpolate,
			      CGColorSpaceRef colorSpaceOverride,
			      CGDataProviderReleaseDataCallback releaseCallback,
			      void *releaseInfo)
{
    CGImageRef image = NULL;
    CGDataProviderRef dataProvider = NULL;
    CGColorSpaceRef colorSpace = colorSpaceOverride;
    CGBitmapInfo bitinfo = kCGBitmapByteOrder32Host;
    int bitsPerComponent, bitsPerPixel;

    switch (format) {
	case CAIRO_FORMAT_ARGB32:
	    if (colorSpace == NULL)
		colorSpace = CGColorSpaceCreateDeviceRGB ();
	    bitinfo |= kCGImageAlphaPremultipliedFirst;
	    bitsPerComponent = 8;
	    bitsPerPixel = 32;
	    break;

	case CAIRO_FORMAT_RGB24:
	    if (colorSpace == NULL)
		colorSpace = CGColorSpaceCreateDeviceRGB ();
	    bitinfo |= kCGImageAlphaNoneSkipFirst;
	    bitsPerComponent = 8;
	    bitsPerPixel = 32;
	    break;

	case CAIRO_FORMAT_A8:
	    bitsPerComponent = 8;
	    bitsPerPixel = 8;
	    break;

	case CAIRO_FORMAT_A1:
#ifdef WORDS_BIGENDIAN
	    bitsPerComponent = 1;
	    bitsPerPixel = 1;
	    break;
#endif

        case CAIRO_FORMAT_RGB16_565:
        case CAIRO_FORMAT_INVALID:
	default:
	    return NULL;
    }

    dataProvider = CGDataProviderCreateWithData (releaseInfo,
						 data,
						 height * stride,
						 releaseCallback);

    if (unlikely (!dataProvider)) {
	// manually release
	if (releaseCallback)
	    releaseCallback (releaseInfo, data, height * stride);
	goto FINISH;
    }

    if (format == CAIRO_FORMAT_A8 || format == CAIRO_FORMAT_A1) {
	cairo_quartz_float_t decode[] = {1.0, 0.0};
	image = CGImageMaskCreate (width, height,
				   bitsPerComponent,
				   bitsPerPixel,
				   stride,
				   dataProvider,
				   decode,
				   interpolate);
    } else
	image = CGImageCreate (width, height,
			       bitsPerComponent,
			       bitsPerPixel,
			       stride,
			       colorSpace,
			       bitinfo,
			       dataProvider,
			       NULL,
			       interpolate,
			       kCGRenderingIntentDefault);

FINISH:

    CGDataProviderRelease (dataProvider);

    if (colorSpace != colorSpaceOverride)
	CGColorSpaceRelease (colorSpace);

    return image;
}

static inline cairo_bool_t
_cairo_quartz_is_cgcontext_bitmap_context (CGContextRef cgc)
{
    if (unlikely (cgc == NULL))
	return FALSE;

    if (likely (CGContextGetTypePtr)) {
	/* 4 is the type value of a bitmap context */
	return CGContextGetTypePtr (cgc) == 4;
    }

    /* This will cause a (harmless) warning to be printed if called on a non-bitmap context */
    return CGBitmapContextGetBitsPerPixel (cgc) != 0;
}

/* CoreGraphics limitation with flipped CTM surfaces: height must be less than signed 16-bit max */

#define CG_MAX_HEIGHT   SHRT_MAX
#define CG_MAX_WIDTH    USHRT_MAX

/* is the desired size of the surface within bounds? */
cairo_bool_t
_cairo_quartz_verify_surface_size (int width, int height)
{
    /* hmmm, allow width, height == 0 ? */
    if (width < 0 || height < 0)
	return FALSE;

    if (width > CG_MAX_WIDTH || height > CG_MAX_HEIGHT)
	return FALSE;

    return TRUE;
}

/*
 * Cairo path -> Quartz path conversion helpers
 */

/* cairo path -> execute in context */
static cairo_status_t
_cairo_path_to_quartz_context_move_to (void *closure,
				       const cairo_point_t *point)
{
    //ND ((stderr, "moveto: %f %f\n", _cairo_fixed_to_double (point->x), _cairo_fixed_to_double (point->y)));
    double x = _cairo_fixed_to_double (point->x);
    double y = _cairo_fixed_to_double (point->y);

    CGContextMoveToPoint (closure, x, y);
    return CAIRO_STATUS_SUCCESS;
}

static cairo_status_t
_cairo_path_to_quartz_context_line_to (void *closure,
				       const cairo_point_t *point)
{
    //ND ((stderr, "lineto: %f %f\n",  _cairo_fixed_to_double (point->x), _cairo_fixed_to_double (point->y)));
    double x = _cairo_fixed_to_double (point->x);
    double y = _cairo_fixed_to_double (point->y);

    CGContextAddLineToPoint (closure, x, y);
    return CAIRO_STATUS_SUCCESS;
}

static cairo_status_t
_cairo_path_to_quartz_context_curve_to (void *closure,
					const cairo_point_t *p0,
					const cairo_point_t *p1,
					const cairo_point_t *p2)
{
    //ND ((stderr, "curveto: %f,%f %f,%f %f,%f\n",
    //		   _cairo_fixed_to_double (p0->x), _cairo_fixed_to_double (p0->y),
    //		   _cairo_fixed_to_double (p1->x), _cairo_fixed_to_double (p1->y),
    //		   _cairo_fixed_to_double (p2->x), _cairo_fixed_to_double (p2->y)));
    double x0 = _cairo_fixed_to_double (p0->x);
    double y0 = _cairo_fixed_to_double (p0->y);
    double x1 = _cairo_fixed_to_double (p1->x);
    double y1 = _cairo_fixed_to_double (p1->y);
    double x2 = _cairo_fixed_to_double (p2->x);
    double y2 = _cairo_fixed_to_double (p2->y);

    CGContextAddCurveToPoint (closure, x0, y0, x1, y1, x2, y2);
    return CAIRO_STATUS_SUCCESS;
}

static cairo_status_t
_cairo_path_to_quartz_context_close_path (void *closure)
{
    //ND ((stderr, "closepath\n"));
    CGContextClosePath (closure);
    return CAIRO_STATUS_SUCCESS;
}

static void
_cairo_quartz_cairo_path_to_quartz_context (cairo_path_fixed_t *path,
					    CGContextRef closure)
{
    cairo_status_t status;

    CGContextBeginPath (closure);
    status = _cairo_path_fixed_interpret (path,
					  _cairo_path_to_quartz_context_move_to,
					  _cairo_path_to_quartz_context_line_to,
					  _cairo_path_to_quartz_context_curve_to,
					  _cairo_path_to_quartz_context_close_path,
					  closure);

    assert (status == CAIRO_STATUS_SUCCESS);
}

/*
 * Misc helpers/callbacks
 */

#if __MAC_OS_X_VERSION_MIN_REQUIRED < 1050
static PrivateCGCompositeMode
_cairo_quartz_cairo_operator_to_quartz_composite (cairo_operator_t op)
{
    switch (op) {
	case CAIRO_OPERATOR_CLEAR:
	    return kPrivateCGCompositeClear;
	case CAIRO_OPERATOR_SOURCE:
	    return kPrivateCGCompositeCopy;
	case CAIRO_OPERATOR_OVER:
	    return kPrivateCGCompositeSourceOver;
	case CAIRO_OPERATOR_IN:
	    return kPrivateCGCompositeSourceIn;
	case CAIRO_OPERATOR_OUT:
	    return kPrivateCGCompositeSourceOut;
	case CAIRO_OPERATOR_ATOP:
	    return kPrivateCGCompositeSourceAtop;
	case CAIRO_OPERATOR_DEST_OVER:
	    return kPrivateCGCompositeDestinationOver;
	case CAIRO_OPERATOR_DEST_IN:
	    return kPrivateCGCompositeDestinationIn;
	case CAIRO_OPERATOR_DEST_OUT:
	    return kPrivateCGCompositeDestinationOut;
	case CAIRO_OPERATOR_DEST_ATOP:
	    return kPrivateCGCompositeDestinationAtop;
	case CAIRO_OPERATOR_XOR:
	    return kPrivateCGCompositeXOR;
	case CAIRO_OPERATOR_ADD:
	    return kPrivateCGCompositePlusLighter;

	case CAIRO_OPERATOR_DEST:
	case CAIRO_OPERATOR_SATURATE:
	case CAIRO_OPERATOR_MULTIPLY:
	case CAIRO_OPERATOR_SCREEN:
	case CAIRO_OPERATOR_OVERLAY:
	case CAIRO_OPERATOR_DARKEN:
	case CAIRO_OPERATOR_LIGHTEN:
	case CAIRO_OPERATOR_COLOR_DODGE:
	case CAIRO_OPERATOR_COLOR_BURN:
	case CAIRO_OPERATOR_HARD_LIGHT:
	case CAIRO_OPERATOR_SOFT_LIGHT:
	case CAIRO_OPERATOR_DIFFERENCE:
	case CAIRO_OPERATOR_EXCLUSION:
	case CAIRO_OPERATOR_HSL_HUE:
	case CAIRO_OPERATOR_HSL_SATURATION:
	case CAIRO_OPERATOR_HSL_COLOR:
	case CAIRO_OPERATOR_HSL_LUMINOSITY:
        default:
	    ASSERT_NOT_REACHED;
    }
}
#endif

static CGBlendMode
_cairo_quartz_cairo_operator_to_quartz_blend (cairo_operator_t op)
{
    switch (op) {
	case CAIRO_OPERATOR_MULTIPLY:
	    return kCGBlendModeMultiply;
	case CAIRO_OPERATOR_SCREEN:
	    return kCGBlendModeScreen;
	case CAIRO_OPERATOR_OVERLAY:
	    return kCGBlendModeOverlay;
	case CAIRO_OPERATOR_DARKEN:
	    return kCGBlendModeDarken;
	case CAIRO_OPERATOR_LIGHTEN:
	    return kCGBlendModeLighten;
	case CAIRO_OPERATOR_COLOR_DODGE:
	    return kCGBlendModeColorDodge;
	case CAIRO_OPERATOR_COLOR_BURN:
	    return kCGBlendModeColorBurn;
	case CAIRO_OPERATOR_HARD_LIGHT:
	    return kCGBlendModeHardLight;
	case CAIRO_OPERATOR_SOFT_LIGHT:
	    return kCGBlendModeSoftLight;
	case CAIRO_OPERATOR_DIFFERENCE:
	    return kCGBlendModeDifference;
	case CAIRO_OPERATOR_EXCLUSION:
	    return kCGBlendModeExclusion;
	case CAIRO_OPERATOR_HSL_HUE:
	    return kCGBlendModeHue;
	case CAIRO_OPERATOR_HSL_SATURATION:
	    return kCGBlendModeSaturation;
	case CAIRO_OPERATOR_HSL_COLOR:
	    return kCGBlendModeColor;
	case CAIRO_OPERATOR_HSL_LUMINOSITY:
	    return kCGBlendModeLuminosity;

#if __MAC_OS_X_VERSION_MIN_REQUIRED >= 1050
	case CAIRO_OPERATOR_CLEAR:
	    return kCGBlendModeClear;
	case CAIRO_OPERATOR_SOURCE:
	    return kCGBlendModeCopy;
	case CAIRO_OPERATOR_OVER:
	    return kCGBlendModeNormal;
	case CAIRO_OPERATOR_IN:
	    return kCGBlendModeSourceIn;
	case CAIRO_OPERATOR_OUT:
	    return kCGBlendModeSourceOut;
	case CAIRO_OPERATOR_ATOP:
	    return kCGBlendModeSourceAtop;
	case CAIRO_OPERATOR_DEST_OVER:
	    return kCGBlendModeDestinationOver;
	case CAIRO_OPERATOR_DEST_IN:
	    return kCGBlendModeDestinationIn;
	case CAIRO_OPERATOR_DEST_OUT:
	    return kCGBlendModeDestinationOut;
	case CAIRO_OPERATOR_DEST_ATOP:
	    return kCGBlendModeDestinationAtop;
	case CAIRO_OPERATOR_XOR:
	    return kCGBlendModeXOR;
	case CAIRO_OPERATOR_ADD:
	    return kCGBlendModePlusLighter;
#else
	case CAIRO_OPERATOR_CLEAR:
	case CAIRO_OPERATOR_SOURCE:
	case CAIRO_OPERATOR_OVER:
	case CAIRO_OPERATOR_IN:
	case CAIRO_OPERATOR_OUT:
	case CAIRO_OPERATOR_ATOP:
	case CAIRO_OPERATOR_DEST_OVER:
	case CAIRO_OPERATOR_DEST_IN:
	case CAIRO_OPERATOR_DEST_OUT:
	case CAIRO_OPERATOR_DEST_ATOP:
	case CAIRO_OPERATOR_XOR:
	case CAIRO_OPERATOR_ADD:
#endif

	case CAIRO_OPERATOR_DEST:
	case CAIRO_OPERATOR_SATURATE:
        default:
	    ASSERT_NOT_REACHED;
    }
}

static cairo_int_status_t
_cairo_cgcontext_set_cairo_operator (CGContextRef context, cairo_operator_t op)
{
    CGBlendMode blendmode;

    if (op == CAIRO_OPERATOR_DEST)
	return CAIRO_INT_STATUS_NOTHING_TO_DO;

    /* Quartz doesn't support SATURATE at all. COLOR_DODGE and
     * COLOR_BURN in Quartz follow the ISO32000 definition, but cairo
     * uses the definition from the Adobe Supplement.
     */
    if (op == CAIRO_OPERATOR_SATURATE ||
	op == CAIRO_OPERATOR_COLOR_DODGE ||
	op == CAIRO_OPERATOR_COLOR_BURN)
    {
	return CAIRO_INT_STATUS_UNSUPPORTED;
    }

#if __MAC_OS_X_VERSION_MIN_REQUIRED < 1050
    if (op <= CAIRO_OPERATOR_ADD) {
	PrivateCGCompositeMode compmode;

	compmode = _cairo_quartz_cairo_operator_to_quartz_composite (op);
	CGContextSetCompositeOperation (context, compmode);
	return CAIRO_STATUS_SUCCESS;
    }
#endif

    blendmode = _cairo_quartz_cairo_operator_to_quartz_blend (op);
    CGContextSetBlendMode (context, blendmode);
    return CAIRO_STATUS_SUCCESS;
}

static cairo_int_status_t
_cairo_quartz_surface_set_cairo_operator (cairo_quartz_surface_t *surface, cairo_operator_t op)
{
    ND((stderr, "%p _cairo_quartz_surface_set_cairo_operator %d\n", surface, op));

    /* When the destination has no color components, we can avoid some
     * fallbacks, but we have to workaround operators which behave
     * differently in Quartz. */
    if (surface->base.content == CAIRO_CONTENT_ALPHA) {
	if (op == CAIRO_OPERATOR_ATOP)
	    return CAIRO_INT_STATUS_NOTHING_TO_DO;

	if (op == CAIRO_OPERATOR_SOURCE ||
	    op == CAIRO_OPERATOR_IN ||
	    op == CAIRO_OPERATOR_OUT ||
	    op == CAIRO_OPERATOR_DEST_IN ||
	    op == CAIRO_OPERATOR_DEST_ATOP ||
	    op == CAIRO_OPERATOR_XOR)
	{
	    return CAIRO_INT_STATUS_UNSUPPORTED;
	}

	if (op == CAIRO_OPERATOR_DEST_OVER)
	    op = CAIRO_OPERATOR_OVER;
	else if (op == CAIRO_OPERATOR_SATURATE)
	    op = CAIRO_OPERATOR_ADD;
	else if (op == CAIRO_OPERATOR_COLOR_DODGE)
	    op = CAIRO_OPERATOR_OVER;
	else if (op == CAIRO_OPERATOR_COLOR_BURN)
	    op = CAIRO_OPERATOR_OVER;
    }

    return _cairo_cgcontext_set_cairo_operator (surface->cgContext, op);
}

static inline CGLineCap
_cairo_quartz_cairo_line_cap_to_quartz (cairo_line_cap_t ccap)
{
    switch (ccap) {
    default:
	ASSERT_NOT_REACHED;

    case CAIRO_LINE_CAP_BUTT:
	return kCGLineCapButt;

    case CAIRO_LINE_CAP_ROUND:
	return kCGLineCapRound;

    case CAIRO_LINE_CAP_SQUARE:
	return kCGLineCapSquare;
    }
}

static inline CGLineJoin
_cairo_quartz_cairo_line_join_to_quartz (cairo_line_join_t cjoin)
{
    switch (cjoin) {
    default:
	ASSERT_NOT_REACHED;

    case CAIRO_LINE_JOIN_MITER:
	return kCGLineJoinMiter;

    case CAIRO_LINE_JOIN_ROUND:
	return kCGLineJoinRound;

    case CAIRO_LINE_JOIN_BEVEL:
	return kCGLineJoinBevel;
    }
}

static inline CGInterpolationQuality
_cairo_quartz_filter_to_quartz (cairo_filter_t filter)
{
    switch (filter) {
    case CAIRO_FILTER_NEAREST:
    case CAIRO_FILTER_FAST:
	return kCGInterpolationNone;

    case CAIRO_FILTER_BEST:
    case CAIRO_FILTER_GOOD:
    case CAIRO_FILTER_BILINEAR:
    case CAIRO_FILTER_GAUSSIAN:
	return kCGInterpolationDefault;

    default:
	ASSERT_NOT_REACHED;
	return kCGInterpolationDefault;
    }
}

static inline void
_cairo_quartz_cairo_matrix_to_quartz (const cairo_matrix_t *src,
				      CGAffineTransform *dst)
{
    dst->a = src->xx;
    dst->b = src->yx;
    dst->c = src->xy;
    dst->d = src->yy;
    dst->tx = src->x0;
    dst->ty = src->y0;
}


/*
 * Source -> Quartz setup and finish functions
 */

static void
ComputeGradientValue (void *info,
                      const cairo_quartz_float_t *in,
                      cairo_quartz_float_t *out)
{
    double fdist = *in;
    const cairo_gradient_pattern_t *grad = (cairo_gradient_pattern_t*) info;
    unsigned int i;

    /* Put fdist back in the 0.0..1.0 range if we're doing
     * REPEAT/REFLECT
     */
    if (grad->base.extend == CAIRO_EXTEND_REPEAT) {
	fdist = fdist - floor (fdist);
    } else if (grad->base.extend == CAIRO_EXTEND_REFLECT) {
	fdist = fmod (fabs (fdist), 2.0);
	if (fdist > 1.0)
	    fdist = 2.0 - fdist;
    }

    for (i = 0; i < grad->n_stops; i++)
	if (grad->stops[i].offset > fdist)
	    break;

    if (i == 0 || i == grad->n_stops) {
	if (i == grad->n_stops)
	    --i;
	out[0] = grad->stops[i].color.red;
	out[1] = grad->stops[i].color.green;
	out[2] = grad->stops[i].color.blue;
	out[3] = grad->stops[i].color.alpha;
    } else {
	cairo_quartz_float_t ax = grad->stops[i-1].offset;
	cairo_quartz_float_t bx = grad->stops[i].offset - ax;
	cairo_quartz_float_t bp = (fdist - ax)/bx;
	cairo_quartz_float_t ap = 1.0 - bp;

	out[0] =
	    grad->stops[i-1].color.red * ap +
	    grad->stops[i].color.red * bp;
	out[1] =
	    grad->stops[i-1].color.green * ap +
	    grad->stops[i].color.green * bp;
	out[2] =
	    grad->stops[i-1].color.blue * ap +
	    grad->stops[i].color.blue * bp;
	out[3] =
	    grad->stops[i-1].color.alpha * ap +
	    grad->stops[i].color.alpha * bp;
    }
}

static const cairo_quartz_float_t gradient_output_value_ranges[8] = {
    0.f, 1.f, 0.f, 1.f, 0.f, 1.f, 0.f, 1.f
};
static const CGFunctionCallbacks gradient_callbacks = {
    0, ComputeGradientValue, (CGFunctionReleaseInfoCallback) cairo_pattern_destroy
};

/* Quartz computes a small number of samples of the gradient color
 * function. On MacOS X 10.5 it apparently computes only 1024
 * samples. */
#define MAX_GRADIENT_RANGE 1024

static CGFunctionRef
_cairo_quartz_create_gradient_function (const cairo_gradient_pattern_t *gradient,
					const cairo_rectangle_int_t *extents,
					cairo_circle_double_t       *start,
					cairo_circle_double_t       *end)
{
    cairo_pattern_t *pat;
    cairo_quartz_float_t input_value_range[2];

    if (gradient->base.extend != CAIRO_EXTEND_NONE) {
	double bounds_x1, bounds_x2, bounds_y1, bounds_y2;
	double t[2], tolerance;

	tolerance = fabs (_cairo_matrix_compute_determinant (&gradient->base.matrix));
	tolerance /= _cairo_matrix_transformed_circle_major_axis (&gradient->base.matrix, 1);

	bounds_x1 = extents->x;
	bounds_y1 = extents->y;
	bounds_x2 = extents->x + extents->width;
	bounds_y2 = extents->y + extents->height;
	_cairo_matrix_transform_bounding_box (&gradient->base.matrix,
					      &bounds_x1, &bounds_y1,
					      &bounds_x2, &bounds_y2,
					      NULL);

	_cairo_gradient_pattern_box_to_parameter (gradient,
						  bounds_x1, bounds_y1,
						  bounds_x2, bounds_y2,
						  tolerance,
						  t);

	if (gradient->base.extend == CAIRO_EXTEND_PAD) {
	    t[0] = MAX (t[0], -0.5);
	    t[1] = MIN (t[1],  1.5);
	} else if (t[1] - t[0] > MAX_GRADIENT_RANGE)
	    return NULL;

	/* set the input range for the function -- the function knows how
	   to map values outside of 0.0 .. 1.0 to the correct color */
	input_value_range[0] = t[0];
	input_value_range[1] = t[1];
    } else {
	input_value_range[0] = 0;
	input_value_range[1] = 1;
    }

    _cairo_gradient_pattern_interpolate (gradient, input_value_range[0], start);
    _cairo_gradient_pattern_interpolate (gradient, input_value_range[1], end);

    if (_cairo_pattern_create_copy (&pat, &gradient->base))
	return NULL;

    return CGFunctionCreate (pat,
			     1,
			     input_value_range,
			     4,
			     gradient_output_value_ranges,
			     &gradient_callbacks);
}

/* Obtain a CGImageRef from a #cairo_surface_t * */

typedef struct {
    cairo_surface_t *surface;
    cairo_image_surface_t *image_out;
    void *image_extra;
} quartz_source_image_t;

static void
DataProviderReleaseCallback (void *info, const void *data, size_t size)
{
    quartz_source_image_t *source_img = info;
    _cairo_surface_release_source_image (source_img->surface, source_img->image_out, source_img->image_extra);
    free (source_img);
}

static cairo_status_t
_cairo_surface_to_cgimage (cairo_surface_t *source,
			   CGImageRef *image_out)
{
    cairo_status_t status;
    quartz_source_image_t *source_img;

    if (source->backend && source->backend->type == CAIRO_SURFACE_TYPE_QUARTZ_IMAGE) {
	cairo_quartz_image_surface_t *surface = (cairo_quartz_image_surface_t *) source;
	*image_out = CGImageRetain (surface->image);
	return CAIRO_STATUS_SUCCESS;
    }

    if (_cairo_surface_is_quartz (source)) {
	cairo_quartz_surface_t *surface = (cairo_quartz_surface_t *) source;
	if (IS_EMPTY (surface)) {
	    *image_out = NULL;
	    return CAIRO_STATUS_SUCCESS;
	}

	if (_cairo_quartz_is_cgcontext_bitmap_context (surface->cgContext)) {
	    *image_out = CGBitmapContextCreateImage (surface->cgContext);
	    if (*image_out)
		return CAIRO_STATUS_SUCCESS;
	}
    }

    source_img = malloc (sizeof (quartz_source_image_t));
    if (unlikely (source_img == NULL))
	return _cairo_error (CAIRO_STATUS_NO_MEMORY);

    source_img->surface = source;

    status = _cairo_surface_acquire_source_image (source_img->surface, &source_img->image_out, &source_img->image_extra);
    if (unlikely (status)) {
	free (source_img);
	return status;
    }

    if (source_img->image_out->width == 0 || source_img->image_out->height == 0) {
	*image_out = NULL;
	DataProviderReleaseCallback (source_img,
				     source_img->image_out->data,
				     source_img->image_out->height * source_img->image_out->stride);
    } else {
	*image_out = _cairo_quartz_create_cgimage (source_img->image_out->format,
						   source_img->image_out->width,
						   source_img->image_out->height,
						   source_img->image_out->stride,
						   source_img->image_out->data,
						   TRUE,
						   NULL,
						   DataProviderReleaseCallback,
						   source_img);

	/* TODO: differentiate memory error and unsupported surface type */
	if (unlikely (*image_out == NULL))
	    status = CAIRO_INT_STATUS_UNSUPPORTED;
    }

    return status;
}

/* Generic #cairo_pattern_t -> CGPattern function */

typedef struct {
    CGImageRef image;
    CGRect imageBounds;
    cairo_bool_t do_reflect;
} SurfacePatternDrawInfo;

static void
SurfacePatternDrawFunc (void *ainfo, CGContextRef context)
{
    SurfacePatternDrawInfo *info = (SurfacePatternDrawInfo*) ainfo;

    CGContextTranslateCTM (context, 0, info->imageBounds.size.height);
    CGContextScaleCTM (context, 1, -1);

    CGContextDrawImage (context, info->imageBounds, info->image);
    if (info->do_reflect) {
	/* draw 3 more copies of the image, flipped.
	 * DrawImage draws the image according to the current Y-direction into the rectangle given
	 * (imageBounds); at the time of the first DrawImage above, the origin is at the bottom left
	 * of the base image position, and the Y axis is extending upwards.
	 */

	/* Make the y axis extend downwards, and draw a flipped image below */
	CGContextScaleCTM (context, 1, -1);
	CGContextDrawImage (context, info->imageBounds, info->image);

	/* Shift over to the right, and flip vertically (translation is 2x,
	 * since we'll be flipping and thus rendering the rectangle "backwards"
	 */
	CGContextTranslateCTM (context, 2 * info->imageBounds.size.width, 0);
	CGContextScaleCTM (context, -1, 1);
	CGContextDrawImage (context, info->imageBounds, info->image);

	/* Then unflip the Y-axis again, and draw the image above the point. */
	CGContextScaleCTM (context, 1, -1);
	CGContextDrawImage (context, info->imageBounds, info->image);
    }
}

static void
SurfacePatternReleaseInfoFunc (void *ainfo)
{
    SurfacePatternDrawInfo *info = (SurfacePatternDrawInfo*) ainfo;

    CGImageRelease (info->image);
    free (info);
}

static cairo_int_status_t
_cairo_quartz_cairo_repeating_surface_pattern_to_quartz (cairo_quartz_surface_t *dest,
							 const cairo_pattern_t *apattern,
							 CGPatternRef *cgpat)
{
    cairo_surface_pattern_t *spattern;
    cairo_surface_t *pat_surf;
    cairo_rectangle_int_t extents;

    CGImageRef image;
    CGRect pbounds;
    CGAffineTransform ptransform, stransform;
    CGPatternCallbacks cb = { 0,
			      SurfacePatternDrawFunc,
			      SurfacePatternReleaseInfoFunc };
    SurfacePatternDrawInfo *info;
    cairo_quartz_float_t rw, rh;
    cairo_status_t status;
    cairo_bool_t is_bounded;

    cairo_matrix_t m;

    /* SURFACE is the only type we'll handle here */
    assert (apattern->type == CAIRO_PATTERN_TYPE_SURFACE);

    spattern = (cairo_surface_pattern_t *) apattern;
    pat_surf = spattern->surface;

    is_bounded = _cairo_surface_get_extents (pat_surf, &extents);
    assert (is_bounded);

    status = _cairo_surface_to_cgimage (pat_surf, &image);
    if (unlikely (status))
	return status;
    if (unlikely (image == NULL))
	return CAIRO_INT_STATUS_NOTHING_TO_DO;

    info = malloc (sizeof (SurfacePatternDrawInfo));
    if (unlikely (!info))
	return CAIRO_STATUS_NO_MEMORY;

    /* XXX -- if we're printing, we may need to call CGImageCreateCopy to make sure
     * that the data will stick around for this image when the printer gets to it.
     * Otherwise, the underlying data store may disappear from under us!
     *
     * _cairo_surface_to_cgimage will copy when it converts non-Quartz surfaces,
     * since the Quartz surfaces have a higher chance of sticking around.  If the
     * source is a quartz image surface, then it's set up to retain a ref to the
     * image surface that it's backed by.
     */
    info->image = image;
    info->imageBounds = CGRectMake (0, 0, extents.width, extents.height);
    info->do_reflect = FALSE;

    pbounds.origin.x = 0;
    pbounds.origin.y = 0;

    if (spattern->base.extend == CAIRO_EXTEND_REFLECT) {
	pbounds.size.width = 2.0 * extents.width;
	pbounds.size.height = 2.0 * extents.height;
	info->do_reflect = TRUE;
    } else {
	pbounds.size.width = extents.width;
	pbounds.size.height = extents.height;
    }
    rw = pbounds.size.width;
    rh = pbounds.size.height;

    m = spattern->base.matrix;
    cairo_matrix_invert (&m);
    _cairo_quartz_cairo_matrix_to_quartz (&m, &stransform);

    /* The pattern matrix is relative to the bottom left, again; the
     * incoming cairo pattern matrix is relative to the upper left.
     * So we take the pattern matrix and the original context matrix,
     * which gives us the correct base translation/y flip.
     */
    ptransform = CGAffineTransformConcat (stransform, dest->cgContextBaseCTM);

#ifdef QUARTZ_DEBUG
    ND ((stderr, "  pbounds: %f %f %f %f\n", pbounds.origin.x, pbounds.origin.y, pbounds.size.width, pbounds.size.height));
    ND ((stderr, "  pattern xform: t: %f %f xx: %f xy: %f yx: %f yy: %f\n", ptransform.tx, ptransform.ty, ptransform.a, ptransform.b, ptransform.c, ptransform.d));
    CGAffineTransform xform = CGContextGetCTM (dest->cgContext);
    ND ((stderr, "  context xform: t: %f %f xx: %f xy: %f yx: %f yy: %f\n", xform.tx, xform.ty, xform.a, xform.b, xform.c, xform.d));
#endif

    *cgpat = CGPatternCreate (info,
			      pbounds,
			      ptransform,
			      rw, rh,
			      kCGPatternTilingConstantSpacing, /* kCGPatternTilingNoDistortion, */
			      TRUE,
			      &cb);

    return CAIRO_STATUS_SUCCESS;
}

/* State used during a drawing operation. */
typedef struct {
    /* The destination of the mask */
    CGContextRef cgMaskContext;

    /* The destination of the drawing of the source */
    CGContextRef cgDrawContext;

    /* The filter to be used when drawing the source */
    CGInterpolationQuality filter;

    /* Action type */
    cairo_quartz_action_t action;

    /* Destination rect */
    CGRect rect;

    /* Used with DO_SHADING, DO_IMAGE and DO_TILED_IMAGE */
    CGAffineTransform transform;

    /* Used with DO_IMAGE and DO_TILED_IMAGE */
    CGImageRef image;

    /* Used with DO_SHADING */
    CGShadingRef shading;

    /* Temporary destination for unbounded operations */
    CGLayerRef layer;
    CGRect clipRect;
} cairo_quartz_drawing_state_t;

/*
Quartz does not support repeating radients. We handle repeating gradients
by manually extending the gradient and repeating color stops. We need to
minimize the number of repetitions since Quartz seems to sample our color
function across the entire range, even if part of that range is not needed
for the visible area of the gradient, and it samples with some fixed resolution,
so if the gradient range is too large it samples with very low resolution and
the gradient is very coarse. _cairo_quartz_create_gradient_function computes
the number of repetitions needed based on the extents.
*/
static cairo_int_status_t
_cairo_quartz_setup_gradient_source (cairo_quartz_drawing_state_t *state,
				     const cairo_gradient_pattern_t *gradient,
				     const cairo_rectangle_int_t *extents)
{
    cairo_matrix_t mat;
    cairo_circle_double_t start, end;
    CGFunctionRef gradFunc;
    CGColorSpaceRef rgb;
    bool extend = gradient->base.extend != CAIRO_EXTEND_NONE;

    assert (gradient->n_stops > 0);

    mat = gradient->base.matrix;
    cairo_matrix_invert (&mat);
    _cairo_quartz_cairo_matrix_to_quartz (&mat, &state->transform);

    gradFunc = _cairo_quartz_create_gradient_function (gradient,
						       extents,
						       &start,
						       &end);

    if (unlikely (gradFunc == NULL))
	return CAIRO_INT_STATUS_UNSUPPORTED;

    rgb = CGColorSpaceCreateDeviceRGB ();

    if (gradient->base.type == CAIRO_PATTERN_TYPE_LINEAR) {
	state->shading = CGShadingCreateAxial (rgb,
					       CGPointMake (start.center.x,
							    start.center.y),
					       CGPointMake (end.center.x,
							    end.center.y),
					       gradFunc,
					       extend, extend);
    } else {
	state->shading = CGShadingCreateRadial (rgb,
						CGPointMake (start.center.x,
							     start.center.y),
						MAX (start.radius, 0),
						CGPointMake (end.center.x,
							     end.center.y),
						MAX (end.radius, 0),
						gradFunc,
						extend, extend);
    }

    CGColorSpaceRelease (rgb);
    CGFunctionRelease (gradFunc);

    state->action = DO_SHADING;
    return CAIRO_STATUS_SUCCESS;
}

static cairo_int_status_t
_cairo_quartz_setup_state (cairo_quartz_drawing_state_t *state,
			   cairo_quartz_surface_t       *surface,
			   cairo_operator_t              op,
			   const cairo_pattern_t        *source,
			   cairo_clip_t                 *clip)
{
    cairo_bool_t needs_temp;
    cairo_status_t status;

    state->layer = NULL;
    state->image = NULL;
    state->shading = NULL;
    state->cgDrawContext = NULL;
    state->cgMaskContext = NULL;

    status = _cairo_surface_clipper_set_clip (&surface->clipper, clip);
    if (unlikely (status))
	return status;

    status = _cairo_quartz_surface_set_cairo_operator (surface, op);
    if (unlikely (status))
	return status;

    /* Save before we change the pattern, colorspace, etc. so that
     * we can restore and make sure that quartz releases our
     * pattern (which may be stack allocated)
     */

    CGContextSaveGState (surface->cgContext);
    state->clipRect = CGContextGetClipBoundingBox (surface->cgContext);
    state->clipRect = CGRectIntegral (state->clipRect);
    state->rect = state->clipRect;

    state->cgMaskContext = surface->cgContext;
    state->cgDrawContext = state->cgMaskContext;

    state->filter = _cairo_quartz_filter_to_quartz (source->filter);

    if (op == CAIRO_OPERATOR_CLEAR) {
	CGContextSetRGBFillColor (state->cgDrawContext, 0, 0, 0, 1);

	state->action = DO_DIRECT;
	return CAIRO_STATUS_SUCCESS;
    }

    /*
     * To implement mask unbounded operations Quartz needs a temporary
     * surface which will be composited entirely (ignoring the mask).
     * To implement source unbounded operations Quartz needs a
     * temporary surface which allows extending the source to a size
     * covering the whole mask, but there are some optimization
     * opportunities:
     *
     * - CLEAR completely ignores the source, thus we can just use a
     *   solid color fill.
     *
     * - SOURCE can be implemented by drawing the source and clearing
     *   outside of the source as long as the two regions have no
     *   intersection. This happens when the source is a pixel-aligned
     *   rectangle. If the source is at least as big as the
     *   intersection between the clip rectangle and the mask
     *   rectangle, no clear operation is needed.
     */
    needs_temp = ! _cairo_operator_bounded_by_mask (op);

    if (needs_temp) {
	state->layer = CGLayerCreateWithContext (surface->cgContext,
						 state->clipRect.size,
						 NULL);
	state->cgDrawContext = CGLayerGetContext (state->layer);
	state->cgMaskContext = state->cgDrawContext;
	CGContextTranslateCTM (state->cgDrawContext,
			       -state->clipRect.origin.x,
			       -state->clipRect.origin.y);
    }

    if (source->type == CAIRO_PATTERN_TYPE_SOLID) {
	cairo_solid_pattern_t *solid = (cairo_solid_pattern_t *) source;

	CGContextSetRGBStrokeColor (state->cgDrawContext,
				    solid->color.red,
				    solid->color.green,
				    solid->color.blue,
				    solid->color.alpha);
	CGContextSetRGBFillColor (state->cgDrawContext,
				  solid->color.red,
				  solid->color.green,
				  solid->color.blue,
				  solid->color.alpha);

	state->action = DO_DIRECT;
	return CAIRO_STATUS_SUCCESS;
    }

    if (source->type == CAIRO_PATTERN_TYPE_LINEAR ||
	source->type == CAIRO_PATTERN_TYPE_RADIAL)
    {
	const cairo_gradient_pattern_t *gpat = (const cairo_gradient_pattern_t *)source;
	cairo_rectangle_int_t extents;

	extents = surface->virtual_extents;
	extents.x -= surface->base.device_transform.x0;
	extents.y -= surface->base.device_transform.y0;
	_cairo_rectangle_union (&extents, &surface->extents);

	return _cairo_quartz_setup_gradient_source (state, gpat, &extents);
    }

    if (source->type == CAIRO_PATTERN_TYPE_SURFACE &&
	(source->extend == CAIRO_EXTEND_NONE || (CGContextDrawTiledImagePtr && source->extend == CAIRO_EXTEND_REPEAT)))
    {
	const cairo_surface_pattern_t *spat = (const cairo_surface_pattern_t *) source;
	cairo_surface_t *pat_surf = spat->surface;
	CGImageRef img;
	cairo_matrix_t m = spat->base.matrix;
	cairo_rectangle_int_t extents;
	CGAffineTransform xform;
	CGRect srcRect;
	cairo_fixed_t fw, fh;
	cairo_bool_t is_bounded;

	status = _cairo_surface_to_cgimage (pat_surf, &img);
	if (unlikely (status))
	    return status;
	if (unlikely (img == NULL))
	    return CAIRO_INT_STATUS_NOTHING_TO_DO;

	state->image = img;

	if (state->filter == kCGInterpolationNone && _cairo_matrix_is_translation (&m)) {
	    m.x0 = -ceil (m.x0 - 0.5);
	    m.y0 = -ceil (m.y0 - 0.5);
	} else {
	    cairo_matrix_invert (&m);
	}

	_cairo_quartz_cairo_matrix_to_quartz (&m, &state->transform);

	is_bounded = _cairo_surface_get_extents (pat_surf, &extents);
	assert (is_bounded);

	srcRect = CGRectMake (0, 0, extents.width, extents.height);

	if (source->extend == CAIRO_EXTEND_NONE) {
	    int x, y;
	    if (op == CAIRO_OPERATOR_SOURCE &&
		(pat_surf->content == CAIRO_CONTENT_ALPHA ||
		 ! _cairo_matrix_is_integer_translation (&m, &x, &y)))
	    {
		state->layer = CGLayerCreateWithContext (surface->cgContext,
							 state->clipRect.size,
							 NULL);
		state->cgDrawContext = CGLayerGetContext (state->layer);
		CGContextTranslateCTM (state->cgDrawContext,
				       -state->clipRect.origin.x,
				       -state->clipRect.origin.y);
	    }

	    CGContextSetRGBFillColor (state->cgDrawContext, 0, 0, 0, 1);

	    state->rect = srcRect;
	    state->action = DO_IMAGE;
	    return CAIRO_STATUS_SUCCESS;
	}

	CGContextSetRGBFillColor (state->cgDrawContext, 0, 0, 0, 1);

	/* Quartz seems to tile images at pixel-aligned regions only -- this
	 * leads to seams if the image doesn't end up scaling to fill the
	 * space exactly.  The CGPattern tiling approach doesn't have this
	 * problem.  Check if we're going to fill up the space (within some
	 * epsilon), and if not, fall back to the CGPattern type.
	 */

	xform = CGAffineTransformConcat (CGContextGetCTM (state->cgDrawContext),
					 state->transform);

	srcRect = CGRectApplyAffineTransform (srcRect, xform);

	fw = _cairo_fixed_from_double (srcRect.size.width);
	fh = _cairo_fixed_from_double (srcRect.size.height);

	if ((fw & CAIRO_FIXED_FRAC_MASK) <= CAIRO_FIXED_EPSILON &&
	    (fh & CAIRO_FIXED_FRAC_MASK) <= CAIRO_FIXED_EPSILON)
	{
	    /* We're good to use DrawTiledImage, but ensure that
	     * the math works out */

	    srcRect.size.width = round (srcRect.size.width);
	    srcRect.size.height = round (srcRect.size.height);

	    xform = CGAffineTransformInvert (xform);

	    srcRect = CGRectApplyAffineTransform (srcRect, xform);

	    state->rect = srcRect;
	    state->action = DO_TILED_IMAGE;
	    return CAIRO_STATUS_SUCCESS;
	}

	/* Fall through to generic SURFACE case */
    }

    if (source->type == CAIRO_PATTERN_TYPE_SURFACE) {
	cairo_quartz_float_t patternAlpha = 1.0f;
	CGColorSpaceRef patternSpace;
	CGPatternRef pattern = NULL;
	cairo_int_status_t status;

	status = _cairo_quartz_cairo_repeating_surface_pattern_to_quartz (surface, source, &pattern);
	if (unlikely (status))
	    return status;

	patternSpace = CGColorSpaceCreatePattern (NULL);
	CGContextSetFillColorSpace (state->cgDrawContext, patternSpace);
	CGContextSetFillPattern (state->cgDrawContext, pattern, &patternAlpha);
	CGContextSetStrokeColorSpace (state->cgDrawContext, patternSpace);
	CGContextSetStrokePattern (state->cgDrawContext, pattern, &patternAlpha);
	CGColorSpaceRelease (patternSpace);

	/* Quartz likes to munge the pattern phase (as yet unexplained
	 * why); force it to 0,0 as we've already baked in the correct
	 * pattern translation into the pattern matrix
	 */
	CGContextSetPatternPhase (state->cgDrawContext, CGSizeMake (0, 0));

	CGPatternRelease (pattern);

	state->action = DO_DIRECT;
	return CAIRO_STATUS_SUCCESS;
    }

    return CAIRO_INT_STATUS_UNSUPPORTED;
}

static void
_cairo_quartz_teardown_state (cairo_quartz_drawing_state_t *state,
			      cairo_quartz_surface_t       *surface)
{
    if (state->layer) {
	CGContextDrawLayerInRect (surface->cgContext,
				  state->clipRect,
				  state->layer);
	CGContextRelease (state->cgDrawContext);
	CGLayerRelease (state->layer);
    }

    if (state->cgMaskContext)
	CGContextRestoreGState (surface->cgContext);

    if (state->image)
	CGImageRelease (state->image);

    if (state->shading)
	CGShadingRelease (state->shading);
}

static void
_cairo_quartz_draw_source (cairo_quartz_drawing_state_t *state,
			   cairo_operator_t              op)
{
    CGContextSetShouldAntialias (state->cgDrawContext, state->filter != kCGInterpolationNone);
    CGContextSetInterpolationQuality(state->cgDrawContext, state->filter);

    if (state->action == DO_DIRECT) {
	CGContextFillRect (state->cgDrawContext, state->rect);
	return;
    }

    CGContextConcatCTM (state->cgDrawContext, state->transform);

    if (state->action == DO_SHADING) {
	CGContextDrawShading (state->cgDrawContext, state->shading);
	return;
    }

    CGContextTranslateCTM (state->cgDrawContext, 0, state->rect.size.height);
    CGContextScaleCTM (state->cgDrawContext, 1, -1);

    if (state->action == DO_IMAGE) {
	CGContextDrawImage (state->cgDrawContext, state->rect, state->image);
	if (op == CAIRO_OPERATOR_SOURCE &&
	    state->cgDrawContext == state->cgMaskContext)
	{
	    CGContextBeginPath (state->cgDrawContext);
	    CGContextAddRect (state->cgDrawContext, state->rect);

	    CGContextTranslateCTM (state->cgDrawContext, 0, state->rect.size.height);
	    CGContextScaleCTM (state->cgDrawContext, 1, -1);
	    CGContextConcatCTM (state->cgDrawContext,
				CGAffineTransformInvert (state->transform));

	    CGContextAddRect (state->cgDrawContext, state->clipRect);

	    CGContextSetRGBFillColor (state->cgDrawContext, 0, 0, 0, 0);
	    CGContextEOFillPath (state->cgDrawContext);
	}
    } else {
	CGContextDrawTiledImagePtr (state->cgDrawContext, state->rect, state->image);
    }
}


/*
 * get source/dest image implementation
 */

/* Read the image from the surface's front buffer */
static cairo_int_status_t
_cairo_quartz_get_image (cairo_quartz_surface_t *surface,
			 cairo_image_surface_t **image_out)
{
    unsigned char *imageData;
    cairo_image_surface_t *isurf;

    if (IS_EMPTY (surface)) {
	*image_out = (cairo_image_surface_t*) cairo_image_surface_create (CAIRO_FORMAT_ARGB32, 0, 0);
	return CAIRO_STATUS_SUCCESS;
    }

    if (surface->imageSurfaceEquiv) {
	*image_out = (cairo_image_surface_t*) cairo_surface_reference (surface->imageSurfaceEquiv);
	return CAIRO_STATUS_SUCCESS;
    }

    if (_cairo_quartz_is_cgcontext_bitmap_context (surface->cgContext)) {
	unsigned int stride;
	unsigned int bitinfo;
	unsigned int bpc, bpp;
	CGColorSpaceRef colorspace;
	unsigned int color_comps;

	imageData = (unsigned char *) CGBitmapContextGetData (surface->cgContext);

	bitinfo = CGBitmapContextGetBitmapInfo (surface->cgContext);
	stride = CGBitmapContextGetBytesPerRow (surface->cgContext);
	bpp = CGBitmapContextGetBitsPerPixel (surface->cgContext);
	bpc = CGBitmapContextGetBitsPerComponent (surface->cgContext);

	// let's hope they don't add YUV under us
	colorspace = CGBitmapContextGetColorSpace (surface->cgContext);
	color_comps = CGColorSpaceGetNumberOfComponents (colorspace);

	// XXX TODO: We can handle all of these by converting to
	// pixman masks, including non-native-endian masks
	if (bpc != 8)
	    return CAIRO_INT_STATUS_UNSUPPORTED;

	if (bpp != 32 && bpp != 8)
	    return CAIRO_INT_STATUS_UNSUPPORTED;

	if (color_comps != 3 && color_comps != 1)
	    return CAIRO_INT_STATUS_UNSUPPORTED;

	if (bpp == 32 && color_comps == 3 &&
	    (bitinfo & kCGBitmapAlphaInfoMask) == kCGImageAlphaPremultipliedFirst &&
	    (bitinfo & kCGBitmapByteOrderMask) == kCGBitmapByteOrder32Host)
	{
	    isurf = (cairo_image_surface_t *)
		cairo_image_surface_create_for_data (imageData,
						     CAIRO_FORMAT_ARGB32,
						     surface->extents.width,
						     surface->extents.height,
						     stride);
	} else if (bpp == 32 && color_comps == 3 &&
		   (bitinfo & kCGBitmapAlphaInfoMask) == kCGImageAlphaNoneSkipFirst &&
		   (bitinfo & kCGBitmapByteOrderMask) == kCGBitmapByteOrder32Host)
	{
	    isurf = (cairo_image_surface_t *)
		cairo_image_surface_create_for_data (imageData,
						     CAIRO_FORMAT_RGB24,
						     surface->extents.width,
						     surface->extents.height,
						     stride);
	} else if (bpp == 8 && color_comps == 1)
	{
	    isurf = (cairo_image_surface_t *)
		cairo_image_surface_create_for_data (imageData,
						     CAIRO_FORMAT_A8,
						     surface->extents.width,
						     surface->extents.height,
						     stride);
	} else {
	    return CAIRO_INT_STATUS_UNSUPPORTED;
	}
    } else {
	return CAIRO_INT_STATUS_UNSUPPORTED;
    }

    *image_out = isurf;
    return CAIRO_STATUS_SUCCESS;
}

/*
 * Cairo surface backend implementations
 */

static cairo_status_t
_cairo_quartz_surface_finish (void *abstract_surface)
{
    cairo_quartz_surface_t *surface = (cairo_quartz_surface_t *) abstract_surface;

    ND ((stderr, "_cairo_quartz_surface_finish[%p] cgc: %p\n", surface, surface->cgContext));

    if (IS_EMPTY (surface))
	return CAIRO_STATUS_SUCCESS;

    /* Restore our saved gstate that we use to reset clipping */
    CGContextRestoreGState (surface->cgContext);
    _cairo_surface_clipper_reset (&surface->clipper);

    CGContextRelease (surface->cgContext);

    surface->cgContext = NULL;

    if (surface->imageSurfaceEquiv) {
	cairo_surface_destroy (surface->imageSurfaceEquiv);
	surface->imageSurfaceEquiv = NULL;
    }

    if (surface->imageData) {
	free (surface->imageData);
	surface->imageData = NULL;
    }

    return CAIRO_STATUS_SUCCESS;
}

static cairo_status_t
_cairo_quartz_surface_acquire_source_image (void *abstract_surface,
					     cairo_image_surface_t **image_out,
					     void **image_extra)
{
    cairo_int_status_t status;
    cairo_quartz_surface_t *surface = (cairo_quartz_surface_t *) abstract_surface;

    //ND ((stderr, "%p _cairo_quartz_surface_acquire_source_image\n", surface));

    status = _cairo_quartz_get_image (surface, image_out);
    if (unlikely (status))
	return _cairo_error (CAIRO_STATUS_NO_MEMORY);

    *image_extra = NULL;

    return CAIRO_STATUS_SUCCESS;
}

static cairo_surface_t *
_cairo_quartz_surface_snapshot (void *abstract_surface)
{
    cairo_int_status_t status;
    cairo_quartz_surface_t *surface = abstract_surface;
    cairo_image_surface_t *image;

    if (surface->imageSurfaceEquiv)
	return NULL;

    status = _cairo_quartz_get_image (surface, &image);
    if (unlikely (status))
        return _cairo_surface_create_in_error (CAIRO_STATUS_NO_MEMORY);

    return &image->base;
}

static void
_cairo_quartz_surface_release_source_image (void *abstract_surface,
					    cairo_image_surface_t *image,
					    void *image_extra)
{
    cairo_surface_destroy (&image->base);
}


static cairo_status_t
_cairo_quartz_surface_acquire_dest_image (void *abstract_surface,
					  cairo_rectangle_int_t *interest_rect,
					  cairo_image_surface_t **image_out,
					  cairo_rectangle_int_t *image_rect,
					  void **image_extra)
{
    cairo_quartz_surface_t *surface = (cairo_quartz_surface_t *) abstract_surface;
    cairo_int_status_t status;

    ND ((stderr, "%p _cairo_quartz_surface_acquire_dest_image\n", surface));

    status = _cairo_quartz_get_image (surface, image_out);
    if (unlikely (status))
	return _cairo_error (CAIRO_STATUS_NO_MEMORY);

    *image_rect = surface->extents;
    *image_extra = NULL;

    return CAIRO_STATUS_SUCCESS;
}

static void
_cairo_quartz_surface_release_dest_image (void *abstract_surface,
					  cairo_rectangle_int_t *interest_rect,
					  cairo_image_surface_t *image,
					  cairo_rectangle_int_t *image_rect,
					  void *image_extra)
{
    //cairo_quartz_surface_t *surface = (cairo_quartz_surface_t *) abstract_surface;

    //ND ((stderr, "%p _cairo_quartz_surface_release_dest_image\n", surface));

    cairo_surface_destroy (&image->base);
}

static cairo_surface_t *
_cairo_quartz_surface_create_similar (void *abstract_surface,
				      cairo_content_t content,
				      int width,
				      int height)
{
    cairo_quartz_surface_t *surface, *similar_quartz;
    cairo_surface_t *similar;
    cairo_format_t format;

    if (content == CAIRO_CONTENT_COLOR_ALPHA)
	format = CAIRO_FORMAT_ARGB32;
    else if (content == CAIRO_CONTENT_COLOR)
	format = CAIRO_FORMAT_RGB24;
    else if (content == CAIRO_CONTENT_ALPHA)
	format = CAIRO_FORMAT_A8;
    else
	return NULL;

    // verify width and height of surface
    if (!_cairo_quartz_verify_surface_size (width, height)) {
	return _cairo_surface_create_in_error (_cairo_error
					       (CAIRO_STATUS_INVALID_SIZE));
    }

    similar = cairo_quartz_surface_create (format, width, height);
    if (unlikely (similar->status))
	return similar;

    surface = (cairo_quartz_surface_t *) abstract_surface;
    similar_quartz = (cairo_quartz_surface_t *) similar;
    similar_quartz->virtual_extents = surface->virtual_extents;

    return similar;
}

static cairo_status_t
_cairo_quartz_surface_clone_similar (void *abstract_surface,
				     cairo_surface_t *src,
				     int              src_x,
				     int              src_y,
				     int              width,
				     int              height,
				     int             *clone_offset_x,
				     int             *clone_offset_y,
				     cairo_surface_t **clone_out)
{
    cairo_quartz_surface_t *new_surface = NULL;
    cairo_format_t new_format;
    CGImageRef quartz_image = NULL;
    cairo_status_t status;

    *clone_out = NULL;

    // verify width and height of surface
    if (!_cairo_quartz_verify_surface_size (width, height))
	return CAIRO_INT_STATUS_UNSUPPORTED;

    if (width == 0 || height == 0) {
	*clone_out = &_cairo_quartz_surface_create_internal (NULL, CAIRO_CONTENT_COLOR_ALPHA,
							     width, height)->base;
	*clone_offset_x = 0;
	*clone_offset_y = 0;
	return CAIRO_STATUS_SUCCESS;
    }

    if (_cairo_surface_is_quartz (src)) {
	cairo_quartz_surface_t *qsurf = (cairo_quartz_surface_t *) src;

	if (IS_EMPTY (qsurf)) {
	    *clone_out = &_cairo_quartz_surface_create_internal (NULL,
								 CAIRO_CONTENT_COLOR_ALPHA,
								 qsurf->extents.width,
								 qsurf->extents.height)->base;
	    *clone_offset_x = 0;
	    *clone_offset_y = 0;
	    return CAIRO_STATUS_SUCCESS;
	}
    }

    status = _cairo_surface_to_cgimage (src, &quartz_image);
    if (unlikely (status))
	return CAIRO_INT_STATUS_UNSUPPORTED;

    new_format = CAIRO_FORMAT_ARGB32;  /* assumed */
    if (_cairo_surface_is_image (src))
	new_format = ((cairo_image_surface_t *) src)->format;

    new_surface = (cairo_quartz_surface_t *)
	cairo_quartz_surface_create (new_format, width, height);

    if (quartz_image == NULL)
	goto FINISH;

    if (!new_surface || new_surface->base.status) {
	CGImageRelease (quartz_image);
	return CAIRO_INT_STATUS_UNSUPPORTED;
    }

    CGContextSaveGState (new_surface->cgContext);

    _cairo_quartz_surface_set_cairo_operator (new_surface, CAIRO_OPERATOR_SOURCE);

    CGContextTranslateCTM (new_surface->cgContext, -src_x, -src_y);
    CGContextDrawImage (new_surface->cgContext,
			CGRectMake (0, 0, CGImageGetWidth (quartz_image), CGImageGetHeight (quartz_image)),
			quartz_image);

    CGContextRestoreGState (new_surface->cgContext);

    CGImageRelease (quartz_image);

FINISH:
    *clone_offset_x = src_x;
    *clone_offset_y = src_y;
    *clone_out = &new_surface->base;

    return CAIRO_STATUS_SUCCESS;
}

static cairo_bool_t
_cairo_quartz_surface_get_extents (void *abstract_surface,
				   cairo_rectangle_int_t *extents)
{
    cairo_quartz_surface_t *surface = (cairo_quartz_surface_t *) abstract_surface;

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

static cairo_int_status_t
_cairo_quartz_surface_paint_cg (cairo_quartz_surface_t *surface,
				cairo_operator_t op,
				const cairo_pattern_t *source,
				cairo_clip_t *clip)
{
    cairo_quartz_drawing_state_t state;
    cairo_int_status_t rv = CAIRO_STATUS_SUCCESS;

    ND ((stderr, "%p _cairo_quartz_surface_paint op %d source->type %d\n", surface, op, source->type));

    if (IS_EMPTY (surface))
	return CAIRO_INT_STATUS_NOTHING_TO_DO;

    rv = _cairo_quartz_setup_state (&state, surface, op, source, clip);
    if (unlikely (rv))
	goto BAIL;

    _cairo_quartz_draw_source (&state, op);

BAIL:
    _cairo_quartz_teardown_state (&state, surface);

    ND ((stderr, "-- paint\n"));
    return rv;
}

static cairo_int_status_t
_cairo_quartz_surface_paint (void *abstract_surface,
			     cairo_operator_t op,
			     const cairo_pattern_t *source,
			     cairo_clip_t *clip)
{
    cairo_quartz_surface_t *surface = (cairo_quartz_surface_t *) abstract_surface;
    cairo_int_status_t rv;
    cairo_image_surface_t *image;

    rv = _cairo_quartz_surface_paint_cg (surface,
					 op,
					 source,
					 clip);

    if (likely (rv != CAIRO_INT_STATUS_UNSUPPORTED))
	return rv;

    rv = _cairo_quartz_get_image (surface, &image);
    if (likely (rv == CAIRO_STATUS_SUCCESS)) {
	rv = _cairo_surface_paint (&image->base, op, source, clip);
	cairo_surface_destroy (&image->base);
    }

    return rv;
}

static cairo_int_status_t
_cairo_quartz_surface_fill_cg (cairo_quartz_surface_t *surface,
			       cairo_operator_t op,
			       const cairo_pattern_t *source,
			       cairo_path_fixed_t *path,
			       cairo_fill_rule_t fill_rule,
			       double tolerance,
			       cairo_antialias_t antialias,
			       cairo_clip_t *clip)
{
    cairo_quartz_drawing_state_t state;
    cairo_int_status_t rv = CAIRO_STATUS_SUCCESS;

    ND ((stderr, "%p _cairo_quartz_surface_fill op %d source->type %d\n", surface, op, source->type));

    if (IS_EMPTY (surface))
	return CAIRO_INT_STATUS_NOTHING_TO_DO;

    rv = _cairo_quartz_setup_state (&state, surface, op, source, clip);
    if (unlikely (rv))
	goto BAIL;

    CGContextSetShouldAntialias (state.cgMaskContext, (antialias != CAIRO_ANTIALIAS_NONE));

    _cairo_quartz_cairo_path_to_quartz_context (path, state.cgMaskContext);

    if (state.action == DO_DIRECT) {
	assert (state.cgDrawContext == state.cgMaskContext);
	if (fill_rule == CAIRO_FILL_RULE_WINDING)
	    CGContextFillPath (state.cgMaskContext);
	else
	    CGContextEOFillPath (state.cgMaskContext);
    } else {
	if (fill_rule == CAIRO_FILL_RULE_WINDING)
	    CGContextClip (state.cgMaskContext);
	else
	    CGContextEOClip (state.cgMaskContext);

	_cairo_quartz_draw_source (&state, op);
    }

BAIL:
    _cairo_quartz_teardown_state (&state, surface);

    ND ((stderr, "-- fill\n"));
    return rv;
}

static cairo_int_status_t
_cairo_quartz_surface_fill (void *abstract_surface,
			    cairo_operator_t op,
			    const cairo_pattern_t *source,
			    cairo_path_fixed_t *path,
			    cairo_fill_rule_t fill_rule,
			    double tolerance,
			    cairo_antialias_t antialias,
			    cairo_clip_t *clip)
{
    cairo_quartz_surface_t *surface = (cairo_quartz_surface_t *) abstract_surface;
    cairo_int_status_t rv;
    cairo_image_surface_t *image;

    rv = _cairo_quartz_surface_fill_cg (surface,
					op,
					source,
					path,
					fill_rule,
					tolerance,
					antialias,
					clip);

    if (likely (rv != CAIRO_INT_STATUS_UNSUPPORTED))
	return rv;

    rv = _cairo_quartz_get_image (surface, &image);
    if (likely (rv == CAIRO_STATUS_SUCCESS)) {
	rv = _cairo_surface_fill (&image->base, op, source,
				  path, fill_rule, tolerance, antialias,
				  clip);
	cairo_surface_destroy (&image->base);
    }

    return rv;
}

static cairo_int_status_t
_cairo_quartz_surface_stroke_cg (cairo_quartz_surface_t *surface,
				 cairo_operator_t op,
				 const cairo_pattern_t *source,
				 cairo_path_fixed_t *path,
				 const cairo_stroke_style_t *style,
				 const cairo_matrix_t *ctm,
				 const cairo_matrix_t *ctm_inverse,
				 double tolerance,
				 cairo_antialias_t antialias,
				 cairo_clip_t *clip)
{
    cairo_quartz_drawing_state_t state;
    cairo_int_status_t rv = CAIRO_STATUS_SUCCESS;
    CGAffineTransform strokeTransform, invStrokeTransform;

    ND ((stderr, "%p _cairo_quartz_surface_stroke op %d source->type %d\n", surface, op, source->type));

    if (IS_EMPTY (surface))
	return CAIRO_INT_STATUS_NOTHING_TO_DO;

    rv = _cairo_quartz_setup_state (&state, surface, op, source, clip);
    if (unlikely (rv))
	goto BAIL;

    // Turning antialiasing off used to cause misrendering with
    // single-pixel lines (e.g. 20,10.5 -> 21,10.5 end up being rendered as 2 pixels).
    // That's been since fixed in at least 10.5, and in the latest 10.4 dot releases.
    CGContextSetShouldAntialias (state.cgMaskContext, (antialias != CAIRO_ANTIALIAS_NONE));
    CGContextSetLineWidth (state.cgMaskContext, style->line_width);
    CGContextSetLineCap (state.cgMaskContext, _cairo_quartz_cairo_line_cap_to_quartz (style->line_cap));
    CGContextSetLineJoin (state.cgMaskContext, _cairo_quartz_cairo_line_join_to_quartz (style->line_join));
    CGContextSetMiterLimit (state.cgMaskContext, style->miter_limit);

    if (style->dash && style->num_dashes) {
	cairo_quartz_float_t sdash[CAIRO_STACK_ARRAY_LENGTH (cairo_quartz_float_t)];
	cairo_quartz_float_t *fdash = sdash;
	unsigned int max_dashes = style->num_dashes;
	unsigned int k;

	if (style->num_dashes%2)
	    max_dashes *= 2;
	if (max_dashes > ARRAY_LENGTH (sdash))
	    fdash = _cairo_malloc_ab (max_dashes, sizeof (cairo_quartz_float_t));
	if (unlikely (fdash == NULL)) {
	    rv = _cairo_error (CAIRO_STATUS_NO_MEMORY);
	    goto BAIL;
	}

	for (k = 0; k < max_dashes; k++)
	    fdash[k] = (cairo_quartz_float_t) style->dash[k % style->num_dashes];

	CGContextSetLineDash (state.cgMaskContext, style->dash_offset, fdash, max_dashes);
	if (fdash != sdash)
	    free (fdash);
    } else
	CGContextSetLineDash (state.cgMaskContext, 0, NULL, 0);

    _cairo_quartz_cairo_path_to_quartz_context (path, state.cgMaskContext);

    _cairo_quartz_cairo_matrix_to_quartz (ctm, &strokeTransform);
    CGContextConcatCTM (state.cgMaskContext, strokeTransform);

    if (state.action == DO_DIRECT) {
	assert (state.cgDrawContext == state.cgMaskContext);
	CGContextStrokePath (state.cgMaskContext);
    } else {
	CGContextReplacePathWithStrokedPath (state.cgMaskContext);
	CGContextClip (state.cgMaskContext);

	_cairo_quartz_cairo_matrix_to_quartz (ctm_inverse, &invStrokeTransform);
	CGContextConcatCTM (state.cgMaskContext, invStrokeTransform);

	_cairo_quartz_draw_source (&state, op);
    }

BAIL:
    _cairo_quartz_teardown_state (&state, surface);

    ND ((stderr, "-- stroke\n"));
    return rv;
}

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

    rv = _cairo_quartz_surface_stroke_cg (surface, op, source,
					  path, style, ctm, ctm_inverse,
					  tolerance, antialias,
					  clip);

    if (likely (rv != CAIRO_INT_STATUS_UNSUPPORTED))
	return rv;

    rv = _cairo_quartz_get_image (surface, &image);
    if (likely (rv == CAIRO_STATUS_SUCCESS)) {
	rv = _cairo_surface_stroke (&image->base, op, source,
				    path, style, ctm, ctm_inverse,
				    tolerance, antialias,
				    clip);
	cairo_surface_destroy (&image->base);
    }

    return rv;
}

#if CAIRO_HAS_QUARTZ_FONT
static cairo_int_status_t
_cairo_quartz_surface_show_glyphs_cg (cairo_quartz_surface_t *surface,
				      cairo_operator_t op,
				      const cairo_pattern_t *source,
				      cairo_glyph_t *glyphs,
				      int num_glyphs,
				      cairo_scaled_font_t *scaled_font,
				      cairo_clip_t *clip,
				      int *remaining_glyphs)
{
    CGAffineTransform textTransform, invTextTransform;
    CGGlyph glyphs_static[CAIRO_STACK_ARRAY_LENGTH (CGSize)];
    CGSize cg_advances_static[CAIRO_STACK_ARRAY_LENGTH (CGSize)];
    CGGlyph *cg_glyphs = &glyphs_static[0];
    CGSize *cg_advances = &cg_advances_static[0];
    COMPILE_TIME_ASSERT (sizeof (CGGlyph) <= sizeof (CGSize));

    cairo_quartz_drawing_state_t state;
    cairo_int_status_t rv = CAIRO_STATUS_SUCCESS;
    cairo_quartz_float_t xprev, yprev;
    int i;
    CGFontRef cgfref = NULL;

    cairo_bool_t didForceFontSmoothing = FALSE;

    if (IS_EMPTY (surface))
	return CAIRO_INT_STATUS_NOTHING_TO_DO;

    if (num_glyphs <= 0)
	return CAIRO_INT_STATUS_NOTHING_TO_DO;

    if (cairo_scaled_font_get_type (scaled_font) != CAIRO_FONT_TYPE_QUARTZ)
	return CAIRO_INT_STATUS_UNSUPPORTED;

    rv = _cairo_quartz_setup_state (&state, surface, op, source, clip);
    if (unlikely (rv))
	goto BAIL;

    if (state.action == DO_DIRECT) {
	assert (state.cgDrawContext == state.cgMaskContext);
	CGContextSetTextDrawingMode (state.cgMaskContext, kCGTextFill);
    } else {
	CGContextSetTextDrawingMode (state.cgMaskContext, kCGTextClip);
    }

    /* this doesn't addref */
    cgfref = _cairo_quartz_scaled_font_get_cg_font_ref (scaled_font);
    CGContextSetFont (state.cgMaskContext, cgfref);
    CGContextSetFontSize (state.cgMaskContext, 1.0);

    switch (scaled_font->options.antialias) {
	case CAIRO_ANTIALIAS_SUBPIXEL:
	    CGContextSetShouldAntialias (state.cgMaskContext, TRUE);
	    CGContextSetShouldSmoothFonts (state.cgMaskContext, TRUE);
	    if (CGContextSetAllowsFontSmoothingPtr &&
		!CGContextGetAllowsFontSmoothingPtr (state.cgMaskContext))
	    {
		didForceFontSmoothing = TRUE;
		CGContextSetAllowsFontSmoothingPtr (state.cgMaskContext, TRUE);
	    }
	    break;
	case CAIRO_ANTIALIAS_NONE:
	    CGContextSetShouldAntialias (state.cgMaskContext, FALSE);
	    break;
	case CAIRO_ANTIALIAS_GRAY:
	    CGContextSetShouldAntialias (state.cgMaskContext, TRUE);
	    CGContextSetShouldSmoothFonts (state.cgMaskContext, FALSE);
	    break;
	case CAIRO_ANTIALIAS_DEFAULT:
	    /* Don't do anything */
	    break;
    }

    if (num_glyphs > ARRAY_LENGTH (glyphs_static)) {
	cg_glyphs = (CGGlyph*) _cairo_malloc_ab (num_glyphs, sizeof (CGGlyph) + sizeof (CGSize));
	if (unlikely (cg_glyphs == NULL)) {
	    rv = _cairo_error (CAIRO_STATUS_NO_MEMORY);
	    goto BAIL;
	}

	cg_advances = (CGSize*) (cg_glyphs + num_glyphs);
    }

    /* scale(1,-1) * scaled_font->scale */
    textTransform = CGAffineTransformMake (scaled_font->scale.xx,
					   scaled_font->scale.yx,
					   -scaled_font->scale.xy,
					   -scaled_font->scale.yy,
					   0.0, 0.0);

    /* scaled_font->scale_inverse * scale(1,-1) */
    invTextTransform = CGAffineTransformMake (scaled_font->scale_inverse.xx,
					      -scaled_font->scale_inverse.yx,
					      scaled_font->scale_inverse.xy,
					      -scaled_font->scale_inverse.yy,
					      0.0, 0.0);

    CGContextSetTextPosition (state.cgMaskContext, 0.0, 0.0);
    CGContextSetTextMatrix (state.cgMaskContext, CGAffineTransformIdentity);

    /* Convert our glyph positions to glyph advances.  We need n-1 advances,
     * since the advance at index 0 is applied after glyph 0. */
    xprev = glyphs[0].x;
    yprev = glyphs[0].y;

    cg_glyphs[0] = glyphs[0].index;

    for (i = 1; i < num_glyphs; i++) {
	cairo_quartz_float_t xf = glyphs[i].x;
	cairo_quartz_float_t yf = glyphs[i].y;
	cg_glyphs[i] = glyphs[i].index;
	cg_advances[i - 1] = CGSizeApplyAffineTransform (CGSizeMake (xf - xprev, yf - yprev), invTextTransform);
	xprev = xf;
	yprev = yf;
    }

    /* Translate to the first glyph's position before drawing */
    CGContextTranslateCTM (state.cgMaskContext, glyphs[0].x, glyphs[0].y);
    CGContextConcatCTM (state.cgMaskContext, textTransform);

    CGContextShowGlyphsWithAdvances (state.cgMaskContext,
				     cg_glyphs,
				     cg_advances,
				     num_glyphs);

    CGContextConcatCTM (state.cgMaskContext, invTextTransform);
    CGContextTranslateCTM (state.cgMaskContext, -glyphs[0].x, -glyphs[0].y);

    if (state.action != DO_DIRECT)
	_cairo_quartz_draw_source (&state, op);

BAIL:
    if (didForceFontSmoothing)
	CGContextSetAllowsFontSmoothingPtr (state.cgMaskContext, FALSE);

    _cairo_quartz_teardown_state (&state, surface);

    if (cg_glyphs != glyphs_static)
	free (cg_glyphs);

    return rv;
}
#endif /* CAIRO_HAS_QUARTZ_FONT */

static cairo_int_status_t
_cairo_quartz_surface_show_glyphs (void *abstract_surface,
				   cairo_operator_t op,
				   const cairo_pattern_t *source,
				   cairo_glyph_t *glyphs,
				   int num_glyphs,
				   cairo_scaled_font_t *scaled_font,
				   cairo_clip_t *clip,
				   int *remaining_glyphs)
{
    cairo_quartz_surface_t *surface = (cairo_quartz_surface_t *) abstract_surface;
    cairo_int_status_t rv = CAIRO_INT_STATUS_UNSUPPORTED;
    cairo_image_surface_t *image;

#if CAIRO_HAS_QUARTZ_FONT
    rv = _cairo_quartz_surface_show_glyphs_cg (surface, op, source,
					       glyphs, num_glyphs,
					       scaled_font, clip, remaining_glyphs);

    if (likely (rv != CAIRO_INT_STATUS_UNSUPPORTED))
	return rv;

#endif

    rv = _cairo_quartz_get_image (surface, &image);
    if (likely (rv == CAIRO_STATUS_SUCCESS)) {
	rv = _cairo_surface_show_text_glyphs (&image->base, op, source,
					      NULL, 0,
					      glyphs, num_glyphs,
					      NULL, 0, 0,
					      scaled_font, clip);
	cairo_surface_destroy (&image->base);
    }

    return rv;
}

static cairo_int_status_t
_cairo_quartz_surface_mask_with_surface (cairo_quartz_surface_t *surface,
					 cairo_operator_t        op,
					 const cairo_pattern_t  *source,
					 cairo_surface_t        *mask_surf,
					 const cairo_matrix_t   *mask_mat,
					 CGInterpolationQuality filter,
					 cairo_clip_t           *clip)
{
    CGRect rect;
    CGImageRef img;
    cairo_status_t status = CAIRO_STATUS_SUCCESS;
    CGAffineTransform mask_matrix;
    cairo_quartz_drawing_state_t state;

    if (IS_EMPTY (surface))
	return CAIRO_INT_STATUS_NOTHING_TO_DO;

    status = _cairo_surface_to_cgimage (mask_surf, &img);
    if (unlikely (status))
	return status;

    status = _cairo_quartz_setup_state (&state, surface, op, source, clip);
    if (unlikely (status))
	goto BAIL;

    if (unlikely (img == NULL))
	goto BAIL;

    rect = CGRectMake (0.0, 0.0, CGImageGetWidth (img), CGImageGetHeight (img));
    _cairo_quartz_cairo_matrix_to_quartz (mask_mat, &mask_matrix);

    /* ClipToMask is essentially drawing an image, so we need to flip the CTM
     * to get the image to appear oriented the right way */
    CGContextConcatCTM (state.cgMaskContext, CGAffineTransformInvert (mask_matrix));
    CGContextTranslateCTM (state.cgMaskContext, 0.0, rect.size.height);
    CGContextScaleCTM (state.cgMaskContext, 1.0, -1.0);

    state.filter = filter;

    CGContextSetInterpolationQuality (state.cgMaskContext, filter);
    CGContextSetShouldAntialias (state.cgMaskContext, filter != kCGInterpolationNone);

    CGContextClipToMask (state.cgMaskContext, rect, img);

    CGContextScaleCTM (state.cgMaskContext, 1.0, -1.0);
    CGContextTranslateCTM (state.cgMaskContext, 0.0, -rect.size.height);
    CGContextConcatCTM (state.cgMaskContext, mask_matrix);

    _cairo_quartz_draw_source (&state, op);

BAIL:
    _cairo_quartz_teardown_state (&state, surface);

    CGImageRelease (img);

    return status;
}

static cairo_int_status_t
_cairo_quartz_surface_mask_with_solid (cairo_quartz_surface_t *surface,
				       cairo_operator_t        op,
				       const cairo_pattern_t  *source,
				       double                  alpha,
				       cairo_clip_t *clip)
{
    cairo_quartz_drawing_state_t state;
    cairo_status_t status;

    status = _cairo_quartz_setup_state (&state, surface, op, source, clip);
    if (unlikely (status))
	goto BAIL;

    CGContextSetAlpha (surface->cgContext, alpha);
    _cairo_quartz_draw_source (&state, op);

BAIL:
    _cairo_quartz_teardown_state (&state, surface);

    return status;
}

static cairo_int_status_t
_cairo_quartz_surface_mask_cg (cairo_quartz_surface_t *surface,
			       cairo_operator_t op,
			       const cairo_pattern_t *source,
			       const cairo_pattern_t *mask,
			       cairo_clip_t *clip)
{
    cairo_surface_t *mask_surf;
    cairo_matrix_t matrix;
    cairo_status_t status;
    cairo_bool_t need_temp;
    CGInterpolationQuality filter;

    ND ((stderr, "%p _cairo_quartz_surface_mask op %d source->type %d mask->type %d\n", surface, op, source->type, mask->type));

    if (IS_EMPTY (surface))
	return CAIRO_INT_STATUS_NOTHING_TO_DO;

    if (mask->type == CAIRO_PATTERN_TYPE_SOLID) {
	const cairo_solid_pattern_t *mask_solid;

	mask_solid = (const cairo_solid_pattern_t *) mask;
	return _cairo_quartz_surface_mask_with_solid (surface, op, source,
						      mask_solid->color.alpha,
						      clip);
    }

    need_temp = (mask->type   != CAIRO_PATTERN_TYPE_SURFACE ||
		 mask->extend != CAIRO_EXTEND_NONE);

    filter = _cairo_quartz_filter_to_quartz (source->filter);

    if (! need_temp) {
	mask_surf = ((const cairo_surface_pattern_t *) mask)->surface;

	/* When an opaque surface used as a mask in Quartz, its
	 * luminosity is used as the alpha value, so we con only use
	 * surfaces with alpha without creating a temporary mask. */
	need_temp = ! (mask_surf->content & CAIRO_CONTENT_ALPHA);
    }

    if (! need_temp) {
	CGInterpolationQuality mask_filter;
	cairo_bool_t simple_transform;

	matrix = mask->matrix;

	mask_filter = _cairo_quartz_filter_to_quartz (mask->filter);
	if (mask_filter == kCGInterpolationNone) {
	    simple_transform = _cairo_matrix_is_translation (&matrix);
	    if (simple_transform) {
		matrix.x0 = ceil (matrix.x0 - 0.5);
		matrix.y0 = ceil (matrix.y0 - 0.5);
	    }
	} else {
	    simple_transform = _cairo_matrix_is_integer_translation (&matrix,
								     NULL,
								     NULL);
	}

	/* Quartz only allows one interpolation to be set for mask and
	 * source, so we can skip the temp surface only if the source
	 * filtering makes the mask look correct. */
	if (source->type == CAIRO_PATTERN_TYPE_SURFACE)
	    need_temp = ! (simple_transform || filter == mask_filter);
	else
	    filter = mask_filter;
    }

    if (need_temp) {
	/* Render the mask to a surface */
	mask_surf = _cairo_quartz_surface_create_similar (surface,
							  CAIRO_CONTENT_ALPHA,
							  surface->extents.width,
							  surface->extents.height);
	status = mask_surf->status;
	if (unlikely (status))
	    goto BAIL;

	/* mask_surf is clear, so use OVER instead of SOURCE to avoid a
	 * temporary layer or fallback to cairo-image. */
	status = _cairo_surface_paint (mask_surf, CAIRO_OPERATOR_OVER, mask, NULL);
	if (unlikely (status))
	    goto BAIL;

	cairo_matrix_init_identity (&matrix);
    }

    status = _cairo_quartz_surface_mask_with_surface (surface, op, source,
						      mask_surf,
						      &matrix,
						      filter,
						      clip);

BAIL:

    if (need_temp)
	cairo_surface_destroy (mask_surf);

    return status;
}

static cairo_int_status_t
_cairo_quartz_surface_mask (void *abstract_surface,
			    cairo_operator_t op,
			    const cairo_pattern_t *source,
			    const cairo_pattern_t *mask,
			    cairo_clip_t *clip)
{
    cairo_quartz_surface_t *surface = (cairo_quartz_surface_t *) abstract_surface;
    cairo_int_status_t rv;
    cairo_image_surface_t *image;

    rv = _cairo_quartz_surface_mask_cg (surface,
					op,
					source,
					mask,
					clip);

    if (likely (rv != CAIRO_INT_STATUS_UNSUPPORTED))
	return rv;

    rv = _cairo_quartz_get_image (surface, &image);
    if (likely (rv == CAIRO_STATUS_SUCCESS)) {
	rv = _cairo_surface_mask (&image->base, op, source, mask, clip);
	cairo_surface_destroy (&image->base);
    }

    return rv;
}

static cairo_status_t
_cairo_quartz_surface_clipper_intersect_clip_path (cairo_surface_clipper_t *clipper,
						   cairo_path_fixed_t *path,
						   cairo_fill_rule_t fill_rule,
						   double tolerance,
						   cairo_antialias_t antialias)
{
    cairo_quartz_surface_t *surface =
	cairo_container_of (clipper, cairo_quartz_surface_t, clipper);

    ND ((stderr, "%p _cairo_quartz_surface_intersect_clip_path path: %p\n", surface, path));

    if (IS_EMPTY (surface))
	return CAIRO_STATUS_SUCCESS;

    if (path == NULL) {
	/* If we're being asked to reset the clip, we can only do it
	 * by restoring the gstate to our previous saved one, and
	 * saving it again.
	 *
	 * Note that this assumes that ALL quartz surface creation
	 * functions will do a SaveGState first; we do this in create_internal.
	 */
	CGContextRestoreGState (surface->cgContext);
	CGContextSaveGState (surface->cgContext);
    } else {
	CGContextSetShouldAntialias (surface->cgContext, (antialias != CAIRO_ANTIALIAS_NONE));

	_cairo_quartz_cairo_path_to_quartz_context (path, surface->cgContext);

	if (fill_rule == CAIRO_FILL_RULE_WINDING)
	    CGContextClip (surface->cgContext);
	else
	    CGContextEOClip (surface->cgContext);
    }

    ND ((stderr, "-- intersect_clip_path\n"));

    return CAIRO_STATUS_SUCCESS;
}

// XXXtodo implement show_page; need to figure out how to handle begin/end

static const struct _cairo_surface_backend cairo_quartz_surface_backend = {
    CAIRO_SURFACE_TYPE_QUARTZ,
    _cairo_default_context_create,

    _cairo_quartz_surface_create_similar,
    _cairo_quartz_surface_finish,
    _cairo_quartz_surface_acquire_source_image,
    _cairo_quartz_surface_release_source_image,
    _cairo_quartz_surface_acquire_dest_image,
    _cairo_quartz_surface_release_dest_image,
    _cairo_quartz_surface_clone_similar,
    NULL, /* composite */
    NULL, /* fill_rectangles */
    NULL, /* composite_trapezoids */
    NULL, /* create_span_renderer */
    NULL, /* check_span_renderer */
    NULL, /* copy_page */
    NULL, /* show_page */
    _cairo_quartz_surface_get_extents,
    NULL, /* old_show_glyphs */
    NULL, /* get_font_options */
    NULL, /* flush */
    NULL, /* mark_dirty_rectangle */
    NULL, /* scaled_font_fini */
    NULL, /* scaled_glyph_fini */

    _cairo_quartz_surface_paint,
    _cairo_quartz_surface_mask,
    _cairo_quartz_surface_stroke,
    _cairo_quartz_surface_fill,
    _cairo_quartz_surface_show_glyphs,

    _cairo_quartz_surface_snapshot,
    NULL, /* is_similar */
    NULL  /* fill_stroke */
};

cairo_quartz_surface_t *
_cairo_quartz_surface_create_internal (CGContextRef cgContext,
				       cairo_content_t content,
				       unsigned int width,
				       unsigned int height)
{
    cairo_quartz_surface_t *surface;

    quartz_ensure_symbols ();

    /* Init the base surface */
    surface = malloc (sizeof (cairo_quartz_surface_t));
    if (unlikely (surface == NULL))
	return (cairo_quartz_surface_t*) _cairo_surface_create_in_error (_cairo_error (CAIRO_STATUS_NO_MEMORY));

    memset (surface, 0, sizeof (cairo_quartz_surface_t));

    _cairo_surface_init (&surface->base,
			 &cairo_quartz_surface_backend,
			 NULL, /* device */
			 content);

    _cairo_surface_clipper_init (&surface->clipper,
				 _cairo_quartz_surface_clipper_intersect_clip_path);

    /* Save our extents */
    surface->extents.x = surface->extents.y = 0;
    surface->extents.width = width;
    surface->extents.height = height;
    surface->virtual_extents = surface->extents;

    if (IS_EMPTY (surface)) {
	surface->cgContext = NULL;
	surface->cgContextBaseCTM = CGAffineTransformIdentity;
	surface->imageData = NULL;
	return surface;
    }

    /* Save so we can always get back to a known-good CGContext -- this is
     * required for proper behaviour of intersect_clip_path(NULL)
     */
    CGContextSaveGState (cgContext);

    surface->cgContext = cgContext;
    surface->cgContextBaseCTM = CGContextGetCTM (cgContext);

    surface->imageData = NULL;
    surface->imageSurfaceEquiv = NULL;

    return surface;
}

/**
 * cairo_quartz_surface_create_for_cg_context
 * @cgContext: the existing CGContext for which to create the surface
 * @width: width of the surface, in pixels
 * @height: height of the surface, in pixels
 *
 * Creates a Quartz surface that wraps the given CGContext.  The
 * CGContext is assumed to be in the standard Cairo coordinate space
 * (that is, with the origin at the upper left and the Y axis
 * increasing downward).  If the CGContext is in the Quartz coordinate
 * space (with the origin at the bottom left), then it should be
 * flipped before this function is called.  The flip can be accomplished
 * using a translate and a scale; for example:
 *
 * <informalexample><programlisting>
 * CGContextTranslateCTM (cgContext, 0.0, height);
 * CGContextScaleCTM (cgContext, 1.0, -1.0);
 * </programlisting></informalexample>
 *
 * All Cairo operations are implemented in terms of Quartz operations,
 * as long as Quartz-compatible elements are used (such as Quartz fonts).
 *
 * Return value: the newly created Cairo surface.
 *
 * Since: 1.4
 **/

cairo_surface_t *
cairo_quartz_surface_create_for_cg_context (CGContextRef cgContext,
					    unsigned int width,
					    unsigned int height)
{
    cairo_quartz_surface_t *surf;

    surf = _cairo_quartz_surface_create_internal (cgContext, CAIRO_CONTENT_COLOR_ALPHA,
						  width, height);
    if (likely (!surf->base.status))
	CGContextRetain (cgContext);

    return &surf->base;
}

/**
 * cairo_quartz_surface_create
 * @format: format of pixels in the surface to create
 * @width: width of the surface, in pixels
 * @height: height of the surface, in pixels
 *
 * Creates a Quartz surface backed by a CGBitmap.  The surface is
 * created using the Device RGB (or Device Gray, for A8) color space.
 * All Cairo operations, including those that require software
 * rendering, will succeed on this surface.
 *
 * Return value: the newly created surface.
 *
 * Since: 1.4
 **/
cairo_surface_t *
cairo_quartz_surface_create (cairo_format_t format,
			     unsigned int width,
			     unsigned int height)
{
    cairo_quartz_surface_t *surf;
    CGContextRef cgc;
    CGColorSpaceRef cgColorspace;
    CGBitmapInfo bitinfo;
    void *imageData;
    int stride;
    int bitsPerComponent;

    // verify width and height of surface
    if (!_cairo_quartz_verify_surface_size (width, height))
	return _cairo_surface_create_in_error (_cairo_error (CAIRO_STATUS_INVALID_SIZE));

    if (width == 0 || height == 0) {
	return &_cairo_quartz_surface_create_internal (NULL, _cairo_content_from_format (format),
						       width, height)->base;
    }

    if (format == CAIRO_FORMAT_ARGB32 ||
	format == CAIRO_FORMAT_RGB24)
    {
	cgColorspace = CGColorSpaceCreateDeviceRGB ();
	bitinfo = kCGBitmapByteOrder32Host;
	if (format == CAIRO_FORMAT_ARGB32)
	    bitinfo |= kCGImageAlphaPremultipliedFirst;
	else
	    bitinfo |= kCGImageAlphaNoneSkipFirst;
	bitsPerComponent = 8;
	stride = width * 4;
    } else if (format == CAIRO_FORMAT_A8) {
	cgColorspace = NULL;
	stride = width;
	bitinfo = kCGImageAlphaOnly;
	bitsPerComponent = 8;
    } else if (format == CAIRO_FORMAT_A1) {
	/* I don't think we can usefully support this, as defined by
	 * cairo_format_t -- these are 1-bit pixels stored in 32-bit
	 * quantities.
	 */
	return _cairo_surface_create_in_error (_cairo_error (CAIRO_STATUS_INVALID_FORMAT));
    } else {
	return _cairo_surface_create_in_error (_cairo_error (CAIRO_STATUS_INVALID_FORMAT));
    }

    /* The Apple docs say that for best performance, the stride and the data
     * pointer should be 16-byte aligned.  malloc already aligns to 16-bytes,
     * so we don't have to anything special on allocation.
     */
    stride = (stride + 15) & ~15;

    imageData = _cairo_malloc_ab (height, stride);
    if (unlikely (!imageData)) {
	CGColorSpaceRelease (cgColorspace);
	return _cairo_surface_create_in_error (_cairo_error (CAIRO_STATUS_NO_MEMORY));
    }

    /* zero the memory to match the image surface behaviour */
    memset (imageData, 0, height * stride);

    cgc = CGBitmapContextCreate (imageData,
				 width,
				 height,
				 bitsPerComponent,
				 stride,
				 cgColorspace,
				 bitinfo);
    CGColorSpaceRelease (cgColorspace);

    if (!cgc) {
	free (imageData);
	return _cairo_surface_create_in_error (_cairo_error (CAIRO_STATUS_NO_MEMORY));
    }

    /* flip the Y axis */
    CGContextTranslateCTM (cgc, 0.0, height);
    CGContextScaleCTM (cgc, 1.0, -1.0);

    surf = _cairo_quartz_surface_create_internal (cgc, _cairo_content_from_format (format),
						  width, height);
    if (surf->base.status) {
	CGContextRelease (cgc);
	free (imageData);
	// create_internal will have set an error
	return &surf->base;
    }

    surf->imageData = imageData;
    surf->imageSurfaceEquiv = cairo_image_surface_create_for_data (imageData, format, width, height, stride);

    return &surf->base;
}

/**
 * cairo_quartz_surface_get_cg_context
 * @surface: the Cairo Quartz surface
 *
 * Returns the CGContextRef that the given Quartz surface is backed
 * by.
 *
 * A call to cairo_surface_flush() is required before using the
 * CGContextRef to ensure that all pending drawing operations are
 * finished and to restore any temporary modification cairo has made
 * to its state. A call to cairo_surface_mark_dirty() is required
 * after the state or the content of the CGContextRef has been
 * modified.
 *
 * Return value: the CGContextRef for the given surface.
 *
 * Since: 1.4
 **/
CGContextRef
cairo_quartz_surface_get_cg_context (cairo_surface_t *surface)
{
    if (surface && _cairo_surface_is_quartz (surface)) {
	cairo_quartz_surface_t *quartz = (cairo_quartz_surface_t *) surface;
	return quartz->cgContext;
    } else
	return NULL;
}

static cairo_bool_t
_cairo_surface_is_quartz (const cairo_surface_t *surface)
{
    return surface->backend == &cairo_quartz_surface_backend;
}

/* Debug stuff */

#ifdef QUARTZ_DEBUG

#include <Movies.h>

void ExportCGImageToPNGFile (CGImageRef inImageRef, char* dest)
{
    Handle  dataRef = NULL;
    OSType  dataRefType;
    CFStringRef inPath = CFStringCreateWithCString (NULL, dest, kCFStringEncodingASCII);

    GraphicsExportComponent grex = 0;
    unsigned long sizeWritten;

    ComponentResult result;

    // create the data reference
    result = QTNewDataReferenceFromFullPathCFString (inPath, kQTNativeDefaultPathStyle,
						     0, &dataRef, &dataRefType);

    if (NULL != dataRef && noErr == result) {
	// get the PNG exporter
	result = OpenADefaultComponent (GraphicsExporterComponentType, kQTFileTypePNG,
					&grex);

	if (grex) {
	    // tell the exporter where to find its source image
	    result = GraphicsExportSetInputCGImage (grex, inImageRef);

	    if (noErr == result) {
		// tell the exporter where to save the exporter image
		result = GraphicsExportSetOutputDataReference (grex, dataRef,
							       dataRefType);

		if (noErr == result) {
		    // write the PNG file
		    result = GraphicsExportDoExport (grex, &sizeWritten);
		}
	    }

	    // remember to close the component
	    CloseComponent (grex);
	}

	// remember to dispose of the data reference handle
	DisposeHandle (dataRef);
    }
}

void
quartz_image_to_png (CGImageRef imgref, char *dest)
{
    static int sctr = 0;
    char sptr[] = "/Users/vladimir/Desktop/barXXXXX.png";

    if (dest == NULL) {
	fprintf (stderr, "** Writing %p to bar%d\n", imgref, sctr);
	sprintf (sptr, "/Users/vladimir/Desktop/bar%d.png", sctr);
	sctr++;
	dest = sptr;
    }

    ExportCGImageToPNGFile (imgref, dest);
}

void
quartz_surface_to_png (cairo_quartz_surface_t *nq, char *dest)
{
    static int sctr = 0;
    char sptr[] = "/Users/vladimir/Desktop/fooXXXXX.png";

    if (nq->base.type != CAIRO_SURFACE_TYPE_QUARTZ) {
	fprintf (stderr, "** quartz_surface_to_png: surface %p isn't quartz!\n", nq);
	return;
    }

    if (dest == NULL) {
	fprintf (stderr, "** Writing %p to foo%d\n", nq, sctr);
	sprintf (sptr, "/Users/vladimir/Desktop/foo%d.png", sctr);
	sctr++;
	dest = sptr;
    }

    CGImageRef imgref = CGBitmapContextCreateImage (nq->cgContext);
    if (imgref == NULL) {
	fprintf (stderr, "quartz surface at %p is not a bitmap context!\n", nq);
	return;
    }

    ExportCGImageToPNGFile (imgref, dest);

    CGImageRelease (imgref);
}

#endif /* QUARTZ_DEBUG */