File: ABCGI.pyx

package info (click to toggle)
python-enable 4.1.0-1
  • links: PTS, VCS
  • area: main
  • in suites: wheezy
  • size: 7,220 kB
  • sloc: cpp: 57,417; python: 28,437; makefile: 314; sh: 43
file content (2932 lines) | stat: -rw-r--r-- 96,577 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
# :Author:    Robert Kern
# :Copyright: 2004, 2007, Enthought, Inc.
# :License:   BSD Style


include "Python.pxi"
include "CoreFoundation.pxi"
include "CoreGraphics.pxi"
include "QuickDraw.pxi"
include "ATS.pxi"
include "ATSUI.pxi"

cimport c_numpy

import os
import warnings

from ATSFont import default_font_info

cdef extern from "math.h":
    double sqrt(double arg)
    int isnan(double arg)


cdef CFURLRef url_from_filename(char* filename) except NULL:
    cdef CFStringRef filePath
    filePath = CFStringCreateWithCString(NULL, filename,
        kCFStringEncodingUTF8)
    if filePath == NULL:
        raise RuntimeError("could not create CFStringRef")

    cdef CFURLRef cfurl
    cfurl = CFURLCreateWithFileSystemPath(NULL, filePath,
        kCFURLPOSIXPathStyle, 0)
    CFRelease(filePath)
    if cfurl == NULL:
        raise RuntimeError("could not create a CFURLRef")
    return cfurl

# Enumerations

class LineCap:
    butt = kCGLineCapButt
    round = kCGLineCapRound
    square = kCGLineCapSquare

class LineJoin:
    miter = kCGLineJoinMiter
    round = kCGLineJoinRound
    bevel = kCGLineJoinBevel

class PathDrawingMode:
    fill = kCGPathFill
    eof_fill = kCGPathEOFill
    stroke = kCGPathStroke
    fill_stroke = kCGPathFillStroke
    eof_fill_stroke = kCGPathEOFillStroke

class RectEdge:
    min_x_edge = CGRectMinXEdge
    min_y_edge = CGRectMinYEdge
    max_x_edge = CGRectMaxXEdge
    max_y_edge = CGRectMaxYEdge

class ColorRenderingIntent:
    default = kCGRenderingIntentDefault
    absolute_colorimetric = kCGRenderingIntentAbsoluteColorimetric
    realative_colorimetric = kCGRenderingIntentRelativeColorimetric
    perceptual = kCGRenderingIntentPerceptual
    saturation = kCGRenderingIntentSaturation

#class ColorSpaces:
#    gray = kCGColorSpaceUserGray
#    rgb = kCGColorSpaceUserRGB
#    cmyk = kCGColorSpaceUserCMYK

class FontEnum:
    index_max  = kCGFontIndexMax
    index_invalid  = kCGFontIndexInvalid
    glyph_max  = kCGGlyphMax

class TextDrawingMode:
    fill = kCGTextFill
    stroke = kCGTextStroke
    fill_stroke = kCGTextFillStroke
    invisible = kCGTextInvisible
    fill_clip = kCGTextFillClip
    stroke_clip = kCGTextStrokeClip
    fill_stroke_clip = kCGTextFillStrokeClip
    clip = kCGTextClip

class TextEncodings:
    font_specific = kCGEncodingFontSpecific
    mac_roman = kCGEncodingMacRoman

class ImageAlphaInfo:
    none = kCGImageAlphaNone
    premultiplied_last = kCGImageAlphaPremultipliedLast
    premultiplied_first = kCGImageAlphaPremultipliedFirst
    last = kCGImageAlphaLast
    first = kCGImageAlphaFirst
    none_skip_last = kCGImageAlphaNoneSkipLast
    none_skip_first = kCGImageAlphaNoneSkipFirst
    only = kCGImageAlphaOnly

class InterpolationQuality:
    default = kCGInterpolationDefault
    none = kCGInterpolationNone
    low = kCGInterpolationLow
    high = kCGInterpolationHigh

class PathElementType:
    move_to = kCGPathElementMoveToPoint,
    line_to = kCGPathElementAddLineToPoint,
    quad_curve_to = kCGPathElementAddQuadCurveToPoint,
    curve_to = kCGPathElementAddCurveToPoint,
    close_path = kCGPathElementCloseSubpath

class StringEncoding:
    mac_roman  = kCFStringEncodingMacRoman
    windows_latin1  = kCFStringEncodingWindowsLatin1
    iso_latin1  = kCFStringEncodingISOLatin1
    nextstep_latin  = kCFStringEncodingNextStepLatin
    ascii  = kCFStringEncodingASCII
    unicode  = kCFStringEncodingUnicode
    utf8  = kCFStringEncodingUTF8
    nonlossy_ascii  = kCFStringEncodingNonLossyASCII

class URLPathStyle:
    posix = kCFURLPOSIXPathStyle
    hfs = kCFURLHFSPathStyle
    windows = kCFURLWindowsPathStyle

c_numpy.import_array()
import numpy

from kiva import constants

cap_style = {}
cap_style[constants.CAP_ROUND]  = kCGLineCapRound
cap_style[constants.CAP_SQUARE] = kCGLineCapSquare
cap_style[constants.CAP_BUTT]   = kCGLineCapButt

join_style = {}
join_style[constants.JOIN_ROUND] = kCGLineJoinRound
join_style[constants.JOIN_BEVEL] = kCGLineJoinBevel
join_style[constants.JOIN_MITER] = kCGLineJoinMiter

draw_modes = {}
draw_modes[constants.FILL]            = kCGPathFill
draw_modes[constants.EOF_FILL]        = kCGPathEOFill
draw_modes[constants.STROKE]          = kCGPathStroke
draw_modes[constants.FILL_STROKE]     = kCGPathFillStroke
draw_modes[constants.EOF_FILL_STROKE] = kCGPathEOFillStroke

text_modes = {}
text_modes[constants.TEXT_FILL]             = kCGTextFill
text_modes[constants.TEXT_STROKE]           = kCGTextStroke
text_modes[constants.TEXT_FILL_STROKE]      = kCGTextFillStroke
text_modes[constants.TEXT_INVISIBLE]        = kCGTextInvisible
text_modes[constants.TEXT_FILL_CLIP]        = kCGTextFillClip
text_modes[constants.TEXT_STROKE_CLIP]      = kCGTextStrokeClip
text_modes[constants.TEXT_FILL_STROKE_CLIP] = kCGTextFillStrokeClip
text_modes[constants.TEXT_CLIP]             = kCGTextClip
# this last one doesn't exist in Quartz
text_modes[constants.TEXT_OUTLINE]          = kCGTextStroke

cdef class CGContext
cdef class CGContextInABox(CGContext)
cdef class CGImage
cdef class CGPDFDocument
cdef class Rect
cdef class CGLayerContext(CGContextInABox)
cdef class CGGLContext(CGContextInABox)
cdef class CGBitmapContext(CGContext)
cdef class CGPDFContext(CGContext)
cdef class CGImageMask(CGImage)
cdef class CGAffine
cdef class CGMutablePath
cdef class Shading
cdef class ShadingFunction

cdef class CGContext:
    cdef CGContextRef context
    cdef long can_release
    cdef object current_font
    cdef ATSUStyle current_style
    cdef CGAffineTransform text_matrix
    cdef object style_cache

    def __cinit__(self, *args, **kwds):
        self.context = NULL
        self.current_style = NULL
        self.can_release = 0
        self.text_matrix = CGAffineTransformMake(1.0, 0.0, 0.0, 1.0, 0.0, 0.0)

    def __init__(self, long context, long can_release=0):
        self.context = <CGContextRef>context

        self.can_release = can_release

        self._setup_color_space()
        self._setup_fonts()

    def _setup_color_space(self):
        # setup an RGB color space
        cdef CGColorSpaceRef space

        space = CGColorSpaceCreateDeviceRGB()
        CGContextSetFillColorSpace(self.context, space)
        CGContextSetStrokeColorSpace(self.context, space)
        CGColorSpaceRelease(space)

    def _setup_fonts(self):
        self.style_cache = {}
        self.select_font("Helvetica", 12)
        CGContextSetShouldSmoothFonts(self.context, 1)
        CGContextSetShouldAntialias(self.context, 1)

    #----------------------------------------------------------------
    # Coordinate Transform Matrix Manipulation
    #----------------------------------------------------------------

    def scale_ctm(self, float sx, float sy):
        """ Set the coordinate system scale to the given values, (sx,sy).

            sx:float -- The new scale factor for the x axis
            sy:float -- The new scale factor for the y axis
        """
        CGContextScaleCTM(self.context, sx, sy)

    def translate_ctm(self, float tx, float ty):
        """ Translate the coordinate system by the given value by (tx,ty)

            tx:float --  The distance to move in the x direction
            ty:float --   The distance to move in the y direction
        """
        CGContextTranslateCTM(self.context, tx, ty)

    def rotate_ctm(self, float angle):
        """ Rotates the coordinate space for drawing by the given angle.

            angle:float -- the angle, in radians, to rotate the coordinate
                           system
        """
        CGContextRotateCTM(self.context, angle)

    def concat_ctm(self, object transform):
        """ Concatenate the transform to current coordinate transform matrix.

            transform:affine_matrix -- the transform matrix to concatenate with
                                       the current coordinate matrix.
        """
        cdef float a,b,c,d,tx,ty
        a,b,c,d,tx,ty = transform

        cdef CGAffineTransform atransform
        atransform = CGAffineTransformMake(a,b,c,d,tx,ty)

        CGContextConcatCTM(self.context, atransform)

    def get_ctm(self):
        """ Return the current coordinate transform matrix.
        """
        cdef CGAffineTransform t
        t = CGContextGetCTM(self.context)
        return (t.a, t.b, t.c, t.d, t.tx, t.ty)

    def get_ctm_scale(self):
        """ Returns the average scaling factor of the transform matrix.

        This isn't really part of the GC interface, but it is a convenience
        method to make up for us not having full AffineMatrix support in the
        Mac backend.
        """
        cdef CGAffineTransform t
        t = CGContextGetCTM(self.context)
        x = sqrt(2.0) / 2.0 * (t.a + t.b)
        y = sqrt(2.0) / 2.0 * (t.c + t.d)
        return sqrt(x*x + y*y)



    #----------------------------------------------------------------
    # Save/Restore graphics state.
    #----------------------------------------------------------------

    def save_state(self):
        """ Save the current graphic's context state.

            This should always be paired with a restore_state
        """
        CGContextSaveGState(self.context)

    def restore_state(self):
        """ Restore the previous graphics state.
        """
        CGContextRestoreGState(self.context)

    #----------------------------------------------------------------
    # context manager interface
    #----------------------------------------------------------------

    def __enter__(self):
        self.save_state()

    def __exit__(self, object type, object value, object traceback):
        self.restore_state()

    #----------------------------------------------------------------
    # Manipulate graphics state attributes.
    #----------------------------------------------------------------

    def set_antialias(self, bool value):
        """ Set/Unset antialiasing for bitmap graphics context.
        """
        CGContextSetShouldAntialias(self.context, value)

    def set_line_width(self, float width):
        """ Set the line width for drawing

            width:float -- The new width for lines in user space units.
        """
        CGContextSetLineWidth(self.context, width)

    def set_line_join(self, object style):
        """ Set style for joining lines in a drawing.

            style:join_style -- The line joining style.  The available
                                styles are JOIN_ROUND, JOIN_BEVEL, JOIN_MITER.
        """
        try:
            sjoin = join_style[style]
        except KeyError:
            msg = "Invalid line join style.  See documentation for valid styles"
            raise ValueError(msg)
        CGContextSetLineJoin(self.context, sjoin)

    def set_miter_limit(self, float limit):
        """ Specifies limits on line lengths for mitering line joins.

            If line_join is set to miter joins, the limit specifies which
            line joins should actually be mitered.  If lines aren't mitered,
            they are joined with a bevel.  The line width is divided by
            the length of the miter.  If the result is greater than the
            limit, the bevel style is used.

            limit:float -- limit for mitering joins.
        """
        CGContextSetMiterLimit(self.context, limit)

    def set_line_cap(self, object style):
        """ Specify the style of endings to put on line ends.

            style:cap_style -- the line cap style to use. Available styles
                               are CAP_ROUND,CAP_BUTT,CAP_SQUARE
        """
        try:
            scap = cap_style[style]
        except KeyError:
            msg = "Invalid line cap style.  See documentation for valid styles"
            raise ValueError(msg)
        CGContextSetLineCap(self.context, scap)

    def set_line_dash(self, object lengths, float phase=0.0):
        """
            lengths:float array -- An array of floating point values
                                   specifing the lengths of on/off painting
                                   pattern for lines.
            phase:float -- Specifies how many units into dash pattern
                           to start.  phase defaults to 0.
        """
        cdef int n
        cdef int i
        cdef float *flengths

        if lengths is None:
            # No dash; solid line.
            CGContextSetLineDash(self.context, 0.0, NULL, 0)
            return
        else:
            n = len(lengths)
            flengths = <float*>PyMem_Malloc(n*sizeof(float))
            if flengths == NULL:
                raise MemoryError("could not allocate %s floats" % n)
            for i from 0 <= i < n:
                flengths[i] = lengths[i]
            CGContextSetLineDash(self.context, phase, flengths, n)
            PyMem_Free(flengths)

    def set_flatness(self, float flatness):
        """
            It is device dependent and therefore not recommended by
            the PDF documentation.
        """
        CGContextSetFlatness(self.context, flatness)

    #----------------------------------------------------------------
    # Sending drawing data to a device
    #----------------------------------------------------------------

    def flush(self):
        """ Send all drawing data to the destination device.
        """
        CGContextFlush(self.context)

    def synchronize(self):
        """ Prepares drawing data to be updated on a destination device.
        """
        CGContextSynchronize(self.context)

    #----------------------------------------------------------------
    # Page Definitions
    #----------------------------------------------------------------

    def begin_page(self, media_box=None):
        """ Create a new page within the graphics context.
        """
        cdef CGRect mbox
        cdef CGRect* mbox_ptr
        if media_box is not None:
            mbox = CGRectMakeFromPython(media_box)
            mbox_ptr = &mbox
        else:
            mbox_ptr = NULL

        CGContextBeginPage(self.context, mbox_ptr)

    def end_page(self):
        """ End drawing in the current page of the graphics context.
        """
        CGContextEndPage(self.context)

    #----------------------------------------------------------------
    # Building paths (contours that are drawn)
    #
    # + Currently, nothing is drawn as the path is built.  Instead, the
    #   instructions are stored and later drawn.  Should this be changed?
    #   We will likely draw to a buffer instead of directly to the canvas
    #   anyway.
    #
    #   Hmmm. No.  We have to keep the path around for storing as a
    #   clipping region and things like that.
    #
    # + I think we should keep the current_path_point hanging around.
    #
    #----------------------------------------------------------------

    def begin_path(self):
        """ Clear the current drawing path and begin a new one.
        """
        CGContextBeginPath(self.context)

    def move_to(self, float x, float y):
        """ Start a new drawing subpath at place the current point at (x,y).
        """
        CGContextMoveToPoint(self.context, x,y)

    def line_to(self, float x, float y):
        """ Add a line from the current point to the given point (x,y).

            The current point is moved to (x,y).
        """
        CGContextAddLineToPoint(self.context, x,y)

    def lines(self, object points):
        """ Add a series of lines as a new subpath.

            Points is an Nx2 array of x,y pairs.

            current_point is moved to the last point in points
        """

        cdef int n
        cdef int i
        cdef c_numpy.ndarray apoints
        cdef float x, y

        n = len(points)

        # Shortcut for the 0 and 1 point case
        if n < 2:
            return

        apoints = <c_numpy.ndarray>(numpy.asarray(points, dtype=numpy.float32))

        if apoints.nd != 2 or apoints.dimensions[1] != 2:
            msg = "must pass array of 2-D points"
            raise ValueError(msg)

        x = (<float*>c_numpy.PyArray_GETPTR2(apoints, 0, 0))[0]
        y = (<float*>c_numpy.PyArray_GETPTR2(apoints, 0, 1))[0]
        CGContextMoveToPoint(self.context, x, y)
        for i from 1 <= i < n:
            x = (<float*>c_numpy.PyArray_GETPTR2(apoints, i, 0))[0]
            y = (<float*>c_numpy.PyArray_GETPTR2(apoints, i, 1))[0]
            CGContextAddLineToPoint(self.context, x, y)

    def line_set(self, object starts, object ends):
        """ Adds a series of disconnected line segments as a new subpath.

            starts and ends are Nx2 arrays of (x,y) pairs indicating the
            starting and ending points of each line segment.

            current_point is moved to the last point in ends
        """
        cdef int n
        n = len(starts)
        if len(ends) < n:
            n = len(ends)

        cdef int i
        for i from 0 <= i < n:
            CGContextMoveToPoint(self.context, starts[i][0], starts[i][1])
            CGContextAddLineToPoint(self.context, ends[i][0], ends[i][1])

    def rect(self, float x, float y, float sx, float sy):
        """ Add a rectangle as a new subpath.
        """
        CGContextAddRect(self.context, CGRectMake(x,y,sx,sy))

    def rects(self, object rects):
        """ Add multiple rectangles as separate subpaths to the path.
        """
        cdef int n
        n = len(rects)
        cdef int i
        for i from 0 <= i < n:
            CGContextAddRect(self.context, CGRectMakeFromPython(rects[i]))

    def close_path(self):
        """ Close the path of the current subpath.
        """
        CGContextClosePath(self.context)

    def curve_to(self, float cp1x, float cp1y, float cp2x, float cp2y,
        float x, float y):
        """
        """
        CGContextAddCurveToPoint(self.context, cp1x, cp1y, cp2x, cp2y, x, y )

    def quad_curve_to(self, float cpx, float cpy, float x, float y):
        """
        """
        CGContextAddQuadCurveToPoint(self.context, cpx, cpy, x, y)

    def arc(self, float x, float y, float radius, float start_angle,
        float end_angle, bool clockwise=False):
        """
        """
        CGContextAddArc(self.context, x, y, radius, start_angle, end_angle,
                           clockwise)

    def arc_to(self, float x1, float y1, float x2, float y2, float radius):
        """
        """
        CGContextAddArcToPoint(self.context, x1, y1, x2, y2, radius)

    def add_path(self, CGMutablePath path not None):
        """
        """
        CGContextAddPath(self.context, path.path)

    #----------------------------------------------------------------
    # Getting information on paths
    #----------------------------------------------------------------

    def is_path_empty(self):
        """ Test to see if the current drawing path is empty
        """
        return CGContextIsPathEmpty(self.context)

    def get_path_current_point(self):
        """ Return the current point from the graphics context.

            Note: This should be a tuple or array.

        """
        cdef CGPoint result
        result = CGContextGetPathCurrentPoint(self.context)
        return result.x, result.y

    def get_path_bounding_box(self):
        """
            should return a tuple or array instead of a strange object.
        """
        cdef CGRect result
        result = CGContextGetPathBoundingBox(self.context)
        return (result.origin.x, result.origin.y,
                result.size.width, result.size.height)

    #----------------------------------------------------------------
    # Clipping path manipulation
    #----------------------------------------------------------------

    def clip(self):
        """
        """
        CGContextClip(self.context)

    def even_odd_clip(self):
        """
        """
        CGContextEOClip(self.context)

    def clip_to_rect(self, float x, float y, float width, float height):
        """ Clip context to the given rectangular region.
        """
        CGContextClipToRect(self.context, CGRectMake(x,y,width,height))

    def clip_to_rects(self, object rects):
        """
        """
        cdef int n
        n = len(rects)
        cdef int i
        cdef CGRect* cgrects

        cgrects = <CGRect*>PyMem_Malloc(n*sizeof(CGRect))
        if cgrects == NULL:
            raise MemoryError("could not allocate memory for CGRects")

        for i from 0 <= i < n:
            cgrects[i] = CGRectMakeFromPython(rects[i])
        CGContextClipToRects(self.context, cgrects, n)
        PyMem_Free(cgrects)


    #----------------------------------------------------------------
    # Color space manipulation
    #
    # I'm not sure we'll mess with these at all.  They seem to
    # be for setting the color system.  Hard coding to RGB or
    # RGBA for now sounds like a reasonable solution.
    #----------------------------------------------------------------

    def set_fill_color_space(self):
        """
        """
        msg = "set_fill_color_space not implemented on Macintosh yet."
        raise NotImplementedError(msg)

    def set_stroke_color_space(self):
        """
        """
        msg = "set_stroke_color_space not implemented on Macintosh yet."
        raise NotImplementedError(msg)

    def set_rendering_intent(self, intent):
        """
        """
        CGContextSetRenderingIntent(self.context, intent)

    #----------------------------------------------------------------
    # Color manipulation
    #----------------------------------------------------------------

    def set_fill_color(self, object color):
        """
        """
        r,g,b = color[:3]
        try:
            a = color[3]
        except IndexError:
            a = 1.0
        CGContextSetRGBFillColor(self.context, r, g, b, a)

    def set_stroke_color(self, object color):
        """
        """
        r,g,b = color[:3]
        try:
            a = color[3]
        except IndexError:
            a = 1.0
        CGContextSetRGBStrokeColor(self.context, r, g, b, a)

    def set_alpha(self, float alpha):
        """
        """
        CGContextSetAlpha(self.context, alpha)

    #def set_gray_fill_color(self):
    #    """
    #    """
    #    pass

    #def set_gray_stroke_color(self):
    #    """
    #    """
    #    pass

    #def set_rgb_fill_color(self):
    #    """
    #    """
    #    pass

    #def set_rgb_stroke_color(self):
    #    """
    #    """
    #    pass

    #def cmyk_fill_color(self):
    #    """
    #    """
    #    pass

    #def cmyk_stroke_color(self):
    #    """
    #    """
    #    pass

    #----------------------------------------------------------------
    # Drawing Images
    #----------------------------------------------------------------

    def draw_image(self, object image, object rect=None):
        """ Draw an image or another CGContext onto a region.
        """
        if rect is None:
            rect = (0, 0, self.width(), self.height())
        if isinstance(image, numpy.ndarray):
            self._draw_cgimage(CGImage(image), rect)
        elif isinstance(image, CGImage):
            self._draw_cgimage(image, rect)
        elif hasattr(image, 'bmp_array'):
            self._draw_cgimage(CGImage(image.bmp_array), rect)
        elif isinstance(image, CGLayerContext):
            self._draw_cglayer(image, rect)
        else:
            raise TypeError("could not recognize image %r" % type(image))

    def _draw_cgimage(self, CGImage image, object rect):
        """ Draw a CGImage into a region.
        """
        CGContextDrawImage(self.context, CGRectMakeFromPython(rect),
            image.image)

    def _draw_cglayer(self, CGLayerContext layer, object rect):
        """ Draw a CGLayer into a region.
        """
        CGContextDrawLayerInRect(self.context, CGRectMakeFromPython(rect),
            layer.layer)

    def set_interpolation_quality(self, quality):
        CGContextSetInterpolationQuality(self.context, quality)

    #----------------------------------------------------------------
    # Drawing PDF documents
    #----------------------------------------------------------------

    def draw_pdf_document(self, object rect, CGPDFDocument document not None,
        int page=1):
        """
            rect:(x,y,width,height) -- rectangle to draw into
            document:CGPDFDocument -- PDF file to read from
            page=1:int -- page number of PDF file
        """
        cdef CGRect cgrect
        cgrect = CGRectMakeFromPython(rect)

        CGContextDrawPDFDocument(self.context, cgrect, document.document, page)


    #----------------------------------------------------------------
    # Drawing Text
    #----------------------------------------------------------------

    def select_font(self, object name, float size, style='regular'):
        """
        """
        cdef ATSUStyle atsu_style

        key = (name, size, style)
        if key not in self.style_cache:
            font = default_font_info.lookup(name, style=style)
            self.current_font = font
            ps_name = font.postscript_name

            atsu_style = _create_atsu_style(ps_name, size)
            if atsu_style == NULL:
                raise RuntimeError("could not create style for font %r" % ps_name)
            self.style_cache[key] = PyCObject_FromVoidPtr(<void*>atsu_style,
                <cobject_destr>ATSUDisposeStyle)

        atsu_style = <ATSUStyle>PyCObject_AsVoidPtr(self.style_cache[key])
        self.current_style = atsu_style

    def set_font(self, font):
        """ Set the font for the current graphics context.

            I need to figure out this one.
        """

        style = {
            constants.NORMAL: 'regular',
            constants.BOLD: 'bold',
            constants.ITALIC: 'italic',
            constants.BOLD_ITALIC: 'bold italic',
        }[font.weight | font.style]
        self.select_font(font.face_name, font.size, style=style)

    def set_font_size(self, float size):
        """
        """
        cdef ATSUAttributeTag attr_tag
        cdef ByteCount attr_size
        cdef ATSUAttributeValuePtr attr_value
        cdef Fixed fixed_size
        cdef OSStatus err

        if self.current_style == NULL:
            return

        attr_tag = kATSUSizeTag
        attr_size = sizeof(Fixed)
        fixed_size = FloatToFixed(size)
        attr_value = <ATSUAttributeValuePtr>&fixed_size
        err = ATSUSetAttributes(self.current_style, 1, &attr_tag, &attr_size, &attr_value)
        if err:
            raise RuntimeError("could not set font size on current style")

    def set_character_spacing(self, float spacing):
        """
        """

        # XXX: This does not fit in with ATSUI, really.
        CGContextSetCharacterSpacing(self.context, spacing)

    def set_text_drawing_mode(self, object mode):
        """
        """
        try:
            cgmode = text_modes[mode]
        except KeyError:
            msg = "Invalid text drawing mode.  See documentation for valid modes"
            raise ValueError(msg)
        CGContextSetTextDrawingMode(self.context, cgmode)

    def set_text_position(self, float x,float y):
        """
        """
        self.text_matrix.tx = x
        self.text_matrix.ty = y

    def get_text_position(self):
        """
        """
        return self.text_matrix.tx, self.text_matrix.ty

    def set_text_matrix(self, object ttm):
        """
        """
        cdef float a,b,c,d,tx,ty

        # Handle both matrices that this class returns and agg._AffineMatrix
        # instances.
        try:
            ((a,  b,  _),
             (c,  d,  _),
             (tx, ty, _)) = ttm
        except:
            a,b,c,d,tx,ty = ttm

        cdef CGAffineTransform transform
        transform = CGAffineTransformMake(a,b,c,d,tx,ty)
        self.text_matrix = transform

    def get_text_matrix(self):
        """
        """
        return ((self.text_matrix.a, self.text_matrix.b, 0.0),
                (self.text_matrix.c, self.text_matrix.d, 0.0),
                (self.text_matrix.tx,self.text_matrix.ty,1.0))

    def get_text_extent(self, object text):
        """ Measure the space taken up by given text using the current font.
        """
        cdef CGPoint start
        cdef CGPoint stop
        cdef ATSFontMetrics metrics
        cdef OSStatus status
        cdef ATSUTextLayout layout
        cdef double x1, x2, y1, y2
        cdef ATSUTextMeasurement before, after, ascent, descent
        cdef ByteCount actual_size

        layout = NULL
        try:
            if not text:
                # ATSUGetUnjustifiedBounds does not handle empty strings.
                text = " "
                empty = True
            else:
                empty = False
            _create_atsu_layout(text, self.current_style, &layout)
            status = ATSUGetUnjustifiedBounds(layout, 0, len(text), &before,
                &after, &ascent, &descent)
            if status:
                raise RuntimeError("could not calculate font metrics")

            if empty:
                x1 = 0.0
                x2 = 0.0
            else:
                x1 = FixedToFloat(before)
                x2 = FixedToFloat(after)

            y1 = -FixedToFloat(descent)
            y2 = -y1 + FixedToFloat(ascent)

        finally:
            if layout != NULL:
                ATSUDisposeTextLayout(layout)

        return x1, y1, x2, y2

    def get_full_text_extent(self, object text):
        """ Backwards compatibility API over .get_text_extent() for Enable.
        """

        x1, y1, x2, y2 = self.get_text_extent(text)

        return x2, y2, y1, x1


    def show_text(self, object text, object xy=None):
        """ Draw text on the device at current text position.

            This is also used for showing text at a particular point
            specified by xy == (x, y).
        """
        cdef float x
        cdef float y
        cdef CGAffineTransform text_matrix
        cdef ATSUTextLayout layout

        if not text:
            # I don't think we can draw empty strings using the ATSU API.
            return

        if xy is None:
            x = 0.0
            y = 0.0
        else:
            x = xy[0]
            y = xy[1]

        self.save_state()
        try:
            CGContextConcatCTM(self.context, self.text_matrix)
            _create_atsu_layout(text, self.current_style, &layout)
            _set_cgcontext_for_layout(self.context, layout)
            ATSUDrawText(layout, 0, len(text), FloatToFixed(x), FloatToFixed(y))
        finally:
            self.restore_state()
            if layout != NULL:
                ATSUDisposeTextLayout(layout)

    def show_text_at_point(self, object text, float x, float y):
        """ Draw text on the device at a given text position.
        """
        self.show_text(text, (x, y))

    def show_glyphs(self):
        """
        """
        msg = "show_glyphs not implemented on Macintosh yet."
        raise NotImplementedError(msg)

    #----------------------------------------------------------------
    # Painting paths (drawing and filling contours)
    #----------------------------------------------------------------

    def stroke_path(self):
        """
        """
        CGContextStrokePath(self.context)

    def fill_path(self):
        """
        """
        CGContextFillPath(self.context)

    def eof_fill_path(self):
        """
        """
        CGContextEOFillPath(self.context)

    def stroke_rect(self, object rect):
        """
        """
        CGContextStrokeRect(self.context, CGRectMakeFromPython(rect))

    def stroke_rect_with_width(self, object rect, float width):
        """
        """
        CGContextStrokeRectWithWidth(self.context, CGRectMakeFromPython(rect), width)

    def fill_rect(self, object rect):
        """
        """
        CGContextFillRect(self.context, CGRectMakeFromPython(rect))

    def fill_rects(self, object rects):
        """
        """
        cdef int n
        n = len(rects)
        cdef int i
        cdef CGRect* cgrects

        cgrects = <CGRect*>PyMem_Malloc(n*sizeof(CGRect))
        if cgrects == NULL:
            raise MemoryError("could not allocate memory for CGRects")

        for i from 0 <= i < n:
            cgrects[i] = CGRectMakeFromPython(rects[i])

        CGContextFillRects(self.context, cgrects, n)

    def clear_rect(self, object rect):
        """
        """
        CGContextClearRect(self.context, CGRectMakeFromPython(rect))

    def draw_path(self, object mode=constants.FILL_STROKE):
        """ Walk through all the drawing subpaths and draw each element.

            Each subpath is drawn separately.
        """

        cg_mode = draw_modes[mode]
        CGContextDrawPath(self.context, cg_mode)

    def draw_rect(self, rect, object mode=constants.FILL_STROKE):
        """ Draw a rectangle with the given mode.
        """

        self.save_state()
        CGContextBeginPath(self.context)
        CGContextAddRect(self.context, CGRectMakeFromPython(rect))
        cg_mode = draw_modes[mode]
        CGContextDrawPath(self.context, cg_mode)
        self.restore_state()

    def get_empty_path(self):
        """ Return a path object that can be built up and then reused.
        """

        return CGMutablePath()

    def draw_path_at_points(self, points, CGMutablePath marker not None,
        object mode=constants.FILL_STROKE):

        cdef int i
        cdef int n
        cdef c_numpy.ndarray apoints
        cdef float x, y

        apoints = <c_numpy.ndarray>(numpy.asarray(points, dtype=numpy.float32))

        if apoints.nd != 2 or apoints.dimensions[1] != 2:
            msg = "must pass array of 2-D points"
            raise ValueError(msg)

        cg_mode = draw_modes[mode]

        n = len(points)
        for i from 0 <= i < n:
            x = (<float*>c_numpy.PyArray_GETPTR2(apoints, i, 0))[0]
            y = (<float*>c_numpy.PyArray_GETPTR2(apoints, i, 1))[0]
            CGContextSaveGState(self.context)
            CGContextTranslateCTM(self.context, x, y)
            CGContextAddPath(self.context, marker.path)
            CGContextDrawPath(self.context, cg_mode)
            CGContextRestoreGState(self.context)

    def linear_gradient(self, x1, y1, x2, y2, stops, spread_method, units='userSpaceOnUse'):
        cdef CGRect path_rect
        if units == 'objectBoundingBox':
            # transform from relative coordinates
            path_rect = CGContextGetPathBoundingBox(self.context)
            x1 = path_rect.origin.x + x1 * path_rect.size.width
            x2 = path_rect.origin.x + x2 * path_rect.size.width
            y1 = path_rect.origin.y + y1 * path_rect.size.height
            y2 = path_rect.origin.y + y2 * path_rect.size.height

        stops_list = stops.transpose().tolist()
        func = PiecewiseLinearColorFunction(stops_list)

        # Shadings fill the current clip path
        self.clip()
        if spread_method == 'pad' or spread_method == '':
            shading = AxialShading(func, (x1,y1), (x2,y2),
                                   extend_start=1, extend_end=1)
            self.draw_shading(shading)
        else:
            self.repeat_linear_shading(x1, y1, x2, y2, stops, spread_method, func)

    def repeat_linear_shading(self, x1, y1, x2, y2, stops, spread_method,
                              ShadingFunction func not None):
        cdef CGRect clip_rect = CGContextGetClipBoundingBox(self.context)
        cdef double dirx, diry, slope
        cdef double startx, starty, endx, endy
        cdef int func_index = 0

        if spread_method == 'reflect':
            # generate the mirrored color function
            stops_list = stops[::-1].transpose()
            stops_list[0] = 1-stops_list[0]
            funcs = [func, PiecewiseLinearColorFunction(stops_list.tolist())]
        else:
            funcs = [func, func]

        dirx, diry = x2-x1, y2-y1
        startx, starty = x1, y1
        endx, endy = x2, y2
        if dirx == 0. and diry == 0.:
            slope = float('nan')
            diry = 100.0
        elif diry == 0.:
            slope = 0.
        else:
            # perpendicular slope
            slope = -dirx/diry
        while _line_intersects_cgrect(startx, starty, slope, clip_rect):
            shading = AxialShading(funcs[func_index&1],
                                   (startx, starty), (endx, endy),
                                   extend_start=0, extend_end=0)
            self.draw_shading(shading)
            startx, starty = endx, endy
            endx, endy = endx+dirx, endy+diry
            func_index += 1

        # reverse direction
        dirx, diry = x1-x2, y1-y2
        startx, starty = x1+dirx, y1+diry
        endx, endy = x1, y1
        func_index = 1
        if dirx == 0. and diry == 0.:
            slope = float('nan')
            diry = 100.0
        elif diry == 0.:
            slope = 0.
        else:
            # perpendicular slope
            slope = -dirx/diry
        while _line_intersects_cgrect(endx, endy, slope, clip_rect):
            shading = AxialShading(funcs[func_index&1],
                                   (startx, starty), (endx, endy),
                                   extend_start=0, extend_end=0)
            self.draw_shading(shading)
            endx, endy = startx, starty
            startx, starty = endx+dirx, endy+diry
            func_index += 1

    def radial_gradient(self, cx, cy, r, fx, fy,  stops, spread_method, units='userSpaceOnUse'):
        cdef CGRect path_rect
        if units == 'objectBoundingBox':
            # transform from relative coordinates
            path_rect = CGContextGetPathBoundingBox(self.context)
            r = r * path_rect.size.width
            cx = path_rect.origin.x + cx * path_rect.size.width
            fx = path_rect.origin.x + fx * path_rect.size.width
            cy = path_rect.origin.y + cy * path_rect.size.height
            fy = path_rect.origin.y + fy * path_rect.size.height

        stops_list = stops.transpose().tolist()
        func = PiecewiseLinearColorFunction(stops_list)

        # 12/11/2010 John Wiggins - In order to avoid a bug in Quartz,
        # the radius of a radial gradient must be greater than the distance
        # between the center and the focus. When input runs afoul of this bug,
        # the focus point will be moved towards the center so that the distance
        # is less than the radius. This matches the behavior of AGG.
        cdef double dx = fx-cx
        cdef double dy = fy-cy
        cdef double dist = sqrt(dx*dx + dy*dy)
        if r <= dist:
            newdist = r-0.001
            fx = cx+newdist*dx/dist
            fy = cy+newdist*dy/dist

        # Shadings fill the current clip path
        self.clip()
        if spread_method == 'pad' or spread_method == '':
            shading = RadialShading(func, (fx, fy), 0.0, (cx, cy), r,
                                   extend_start=1, extend_end=1)
            self.draw_shading(shading)
        else:
            # 'reflect' and 'repeat' need to iterate
            self.repeat_radial_shading(cx, cy, r, fx, fy, stops, spread_method, func)

    def repeat_radial_shading(self, cx, cy, r, fx, fy, stops, spread_method,
                              ShadingFunction func not None):
        cdef CGRect clip_rect = CGContextGetClipBoundingBox(self.context)
        cdef double rad = 0., dirx = 0., diry = 0.
        cdef double startx, starty, endx, endy
        cdef int func_index = 0

        if spread_method == 'reflect':
            # generate the mirrored color function
            stops_list = stops[::-1].transpose()
            stops_list[0] = 1-stops_list[0]
            funcs = [func, PiecewiseLinearColorFunction(stops_list.tolist())]
        else:
            funcs = [func, func]

        dirx, diry = cx-fx, cy-fy
        startx, starty = fx,fy
        endx, endy = cx, cy
        while not _cgrect_within_circle(clip_rect, endx, endy, rad):
            shading = RadialShading(funcs[func_index & 1],
                                    (startx, starty), rad, (endx, endy), rad+r,
                                    extend_start=0, extend_end=0)
            self.draw_shading(shading)
            startx, starty = endx, endy
            endx, endy = endx+dirx, endy+diry
            rad += r
            func_index += 1

    def draw_shading(self, Shading shading not None):
        CGContextDrawShading(self.context, shading.shading)


    #----------------------------------------------------------------
    # Extra routines that aren't part of DisplayPDF
    #
    # Some access to font metrics are needed for laying out text.
    # Not sure how to handle this yet.  The candidates below are
    # from Piddle.  Perhaps there is another alternative?
    #
    #----------------------------------------------------------------

    #def font_height(self):
    #    '''Find the total height (ascent + descent) of the given font.'''
    #    #return self.font_ascent() + self.font_descent()

    #def font_ascent(self):
    #    '''Find the ascent (height above base) of the given font.'''
    #    pass

    #def font_descent(self):
    #    '''Find the descent (extent below base) of the given font.'''
    #    extents = self.dc.GetFullTextExtent(' ', wx_font)
    #    return extents[2]

    def __dealloc__(self):
        if self.context != NULL and self.can_release:
            CGContextRelease(self.context)
            self.context = NULL

    # The following are Quartz APIs not in Kiva

    def set_pattern_phase(self, float tx, float ty):
        """
            tx,ty:floats -- A translation in user-space to apply to a
                           pattern before it is drawn
        """
        CGContextSetPatternPhase(self.context, CGSizeMake(tx, ty))

    def set_should_smooth_fonts(self, bool value):
        """
            value:bool -- specify whether to enable font smoothing or not
        """
        CGContextSetShouldSmoothFonts(self.context, value)

cdef class CGContextInABox(CGContext):
    """ A CGContext that knows its size.
    """
    cdef readonly object size
    cdef readonly int _width
    cdef readonly int _height

    def __init__(self, object size, long context, long can_release=0,
                 *args, **kwargs):
        self.context = <CGContextRef>context

        self.can_release = can_release

        self._width, self._height = size

        self._setup_color_space()
        self._setup_fonts()

    def clear(self, object clear_color=(1.0,1.0,1.0,1.0)):
        self.save_state()
        # Reset the transformation matrix back to the identity.
        CGContextConcatCTM(self.context,
            CGAffineTransformInvert(CGContextGetCTM(self.context)))
        self.set_fill_color(clear_color)
        CGContextFillRect(self.context, CGRectMake(0,0,self._width,self._height))
        self.restore_state()

    def width(self):
        return self._width

    def height(self):
        return self._height


cdef class CGLayerContext(CGContextInABox):
    cdef CGLayerRef layer
    cdef object gc

    def __init__(self, object size, CGContext gc not None, *args, **kwargs):
        self.gc = <object>gc
        self.layer = CGLayerCreateWithContext(gc.context,
            CGSizeMake(size[0], size[1]), NULL)
        self.context = CGLayerGetContext(self.layer)
        self.size = size
        self._width, self._height = size
        self.can_release = 1

        self._setup_color_space()
        self._setup_fonts()

    def __dealloc__(self):
        if self.layer != NULL:
            CGLayerRelease(self.layer)
            self.layer = NULL
            # The documentation doesn't say whether I need to release the
            # context derived from the layer or not. I believe that means
            # I don't.
            self.context = NULL
        self.gc = None

    def save(self, object filename, file_format=None, pil_options=None):
        """ Save the GraphicsContext to a file.  Output files are always saved
        in RGB or RGBA format; if this GC is not in one of these formats, it is
        automatically converted.

        If filename includes an extension, the image format is inferred from it.
        file_format is only required if the format can't be inferred from the
        filename (e.g. if you wanted to save a PNG file as a .dat or .bin).

        filename may also be "file-like" object such as a StringIO, in which
        case a file_format must be supplied.

        pil_options is a dict of format-specific options that are passed down to
        the PIL image file writer.  If a writer doesn't recognize an option, it
        is silently ignored.

        If the image has an alpha channel and the specified output file format
        does not support alpha, the image is saved in rgb24 format.
        """

        cdef CGBitmapContext bmp

        # Create a CGBitmapContext from this layer, draw to it, then let it save
        # itself out.
        rect = (0, 0) + self.size
        bmp = CGBitmapContext(self.size)
        CGContextDrawLayerInRect(bmp.context,  CGRectMakeFromPython(rect), self.layer)
        bmp.save(filename, file_format=file_format, pil_options=pil_options)


cdef class CGContextFromSWIG(CGContext):
    def __init__(self, swig_obj):
        self.can_release = False
        ptr = int(swig_obj.this.split('_')[1], 16)
        CGContext.__init__(self, ptr)

cdef class CGContextForPort(CGContextInABox):
    cdef readonly long port
    cdef readonly int _begun

    def __init__(self, long port):
        cdef OSStatus status

#        status = QDBeginCGContext(<CGrafPtr>port, &(self.context))
#        if status:
#            self.port = 0
#            raise RuntimeError("QuickDraw could not make CGContext")

        self.context = NULL
        self.can_release = 0
        self._begun = 0

        self.port = port

        cdef QDRect r
        GetPortBounds(<CGrafPtr>port, &r)

        self._width = r.right - r.left
        self._height = r.bottom - r.top
        self.size = (self._width, self._height)

        #self.begin()

    def begin(self):
        cdef OSStatus status
        cdef QDRect port_rect
        if not self._begun:
            status = QDBeginCGContext(<CGrafPtr>self.port, &(self.context))
            if status != noErr:
                raise RuntimeError("QuickDraw could not make CGContext")
            SyncCGContextOriginWithPort(self.context, <CGrafPtr>self.port)
            self._setup_color_space()
            self._setup_fonts()

            #GetPortBounds(<CGrafPtr>self.port, &port_rect)
            #CGContextTranslateCTM(self.context, 0, (port_rect.bottom - port_rect.top))
            #CGContextScaleCTM(self.context, 1.0, -1.0)
            self._begun = 1

    def end(self):
        if self.port and self.context is not NULL and self._begun:
            CGContextFlush(self.context)
            QDEndCGContext(<CGrafPtr>(self.port), &(self.context))
            self._begun = 0

    def clear(self, object clear_color=(1.0,1.0,1.0,1.0)):
        already_begun = self._begun
        self.begin()
        CGContextInABox.clear(self, clear_color)
        if not already_begun:
            self.end()

    def __dealloc__(self):
        self.end()
        #if self.port and self.context and self._begun:
        #    QDEndCGContext(<CGrafPtr>(self.port), &(self.context))
        #if self.context and self.can_release:
        #    CGContextRelease(self.context)
        #    self.context = NULL



cdef class CGGLContext(CGContextInABox):
    cdef readonly long glcontext

    def __init__(self, long glcontext, int width, int height):
        if glcontext == 0:
            raise ValueError("Need a valid pointer")

        self.glcontext = glcontext

        self.context = CGGLContextCreate(<void*>glcontext,
            CGSizeMake(width, height), NULL)
        if self.context == NULL:
            raise RuntimeError("could not create CGGLContext")
        self.can_release = 1

        self._width = width
        self._height = height
        self.size = (self._width, self._height)

        self._setup_color_space()
        self._setup_fonts()


    def resize(self, int width, int height):
        CGGLContextUpdateViewportSize(self.context, CGSizeMake(width, height))
        self._width = width
        self._height = height
        self.size = (width, height)



cdef class CGPDFContext(CGContext):
    cdef readonly char* filename
    cdef CGRect media_box
    def __init__(self, char* filename, rect=None):
        cdef CFURLRef cfurl
        cfurl = url_from_filename(filename)
        cdef CGRect cgrect
        cdef CGRect* cgrect_ptr

        if rect is None:
            cgrect = CGRectMake(0,0,612,792)
            cgrect_ptr = &cgrect
        else:
            cgrect = CGRectMakeFromPython(rect)
            cgrect_ptr = &cgrect
        self.context = CGPDFContextCreateWithURL(cfurl, cgrect_ptr, NULL)
        CFRelease(cfurl)

        self.filename = filename
        self.media_box = cgrect

        if self.context == NULL:
            raise RuntimeError("could not create CGPDFContext")
        self.can_release = 1

        self._setup_color_space()
        self._setup_fonts()

        CGContextBeginPage(self.context, cgrect_ptr)

    def begin_page(self, media_box=None):
        cdef CGRect* box_ptr
        cdef CGRect box
        if media_box is None:
            box_ptr = &(self.media_box)
        else:
            box = CGRectMakeFromPython(media_box)
            box_ptr = &box
        CGContextBeginPage(self.context, box_ptr)

    def flush(self, end_page=True):
        if end_page:
            self.end_page()
        CGContextFlush(self.context)

    def begin_transparency_layer(self):
        CGContextBeginTransparencyLayer(self.context, NULL)

    def end_transparency_layer(self):
        CGContextEndTransparencyLayer(self.context)

cdef class CGBitmapContext(CGContext):
    cdef void* data

    def __cinit__(self, *args, **kwds):
        self.data = NULL

    def __init__(self, object size_or_array, bool grey_scale=0,
        int bits_per_component=8, int bytes_per_row=-1,
        alpha_info=kCGImageAlphaPremultipliedLast):

        cdef int bits_per_pixel
        cdef CGColorSpaceRef colorspace
        cdef void* dataptr

        if hasattr(size_or_array, '__array_interface__'):
            # It's an array.
            arr = numpy.asarray(size_or_array, order='C')
            typestr = arr.dtype.str
            if typestr != '|u1':
                raise ValueError("expecting an array of unsigned bytes; got %r"
                    % typestr)
            shape = arr.shape
            if len(shape) != 3 or shape[-1] not in (3, 4):
                raise ValueError("expecting a shape (width, height, depth) "
                    "with depth either 3 or 4; got %r" % shape)
            height, width, depth = shape
            if depth == 3:
                # Need to add an alpha channel.
                alpha = numpy.empty((height, width), dtype=numpy.uint8)
                alpha.fill(255)
                arr = numpy.dstack([arr, alpha])
                depth = 4
            ptr, readonly = arr.__array_interface__['data']
            dataptr = <void*><long>ptr
        else:
            # It's a size tuple.
            width, height = size_or_array
            arr = None

        if grey_scale:
            alpha_info = kCGImageAlphaNone
            bits_per_component = 8
            bits_per_pixel = 8
            colorspace = CGColorSpaceCreateWithName(kCGColorSpaceGenericGray)
        elif bits_per_component == 5:
            alpha_info = kCGImageAlphaNoneSkipFirst
            bits_per_pixel = 16
            colorspace = CGColorSpaceCreateWithName(kCGColorSpaceGenericRGB)
        elif bits_per_component == 8:
            if alpha_info not in (kCGImageAlphaNoneSkipFirst,
                                  kCGImageAlphaNoneSkipLast,
                                  kCGImageAlphaPremultipliedFirst,
                                  kCGImageAlphaPremultipliedLast,
                                 ):
                raise ValueError("not a valid alpha_info")
            bits_per_pixel = 32
            colorspace = CGColorSpaceCreateWithName(kCGColorSpaceGenericRGB)
        else:
            raise ValueError("bits_per_component must be 5 or 8")

        cdef int min_bytes
        min_bytes = (width*bits_per_pixel + 7) / 8
        if bytes_per_row < min_bytes:
            bytes_per_row = min_bytes

        self.data = PyMem_Malloc(height*bytes_per_row)
        if self.data == NULL:
            CGColorSpaceRelease(colorspace)
            raise MemoryError("could not allocate memory")
        if arr is not None:
            # Copy the data from the array.
            memcpy(self.data, dataptr, width*height*depth)

        self.context = CGBitmapContextCreate(self.data, width, height,
            bits_per_component, bytes_per_row, colorspace, alpha_info)
        CGColorSpaceRelease(colorspace)

        if self.context == NULL:
            raise RuntimeError("could not create CGBitmapContext")
        self.can_release = 1

        self._setup_fonts()


    def __dealloc__(self):
        if self.context != NULL and self.can_release:
            CGContextRelease(self.context)
            self.context = NULL
        if self.data != NULL:
            # Hmm, this could be tricky if anything in Quartz retained a
            # reference to self.context
            PyMem_Free(self.data)
            self.data = NULL

    property alpha_info:
        def __get__(self):
            return CGBitmapContextGetAlphaInfo(self.context)

    property bits_per_component:
        def __get__(self):
            return CGBitmapContextGetBitsPerComponent(self.context)

    property bits_per_pixel:
        def __get__(self):
            return CGBitmapContextGetBitsPerPixel(self.context)

    property bytes_per_row:
        def __get__(self):
            return CGBitmapContextGetBytesPerRow(self.context)

#    property colorspace:
#        def __get__(self):
#            return CGBitmapContextGetColorSpace(self.context)

    def height(self):
        return CGBitmapContextGetHeight(self.context)

    def width(self):
        return CGBitmapContextGetWidth(self.context)

    def __getsegcount__(self, void* tmp):
        cdef int *lenp
        lenp = <int *>tmp
        if lenp != NULL:
            lenp[0] = self.height()*self.bytes_per_row
        return 1

    def __getreadbuffer__(self, int segment, void** ptr):
        # ignore invalid segment; the caller can't mean anything but the only
        # segment available; we're all adults
        ptr[0] = self.data
        return self.height()*self.bytes_per_row

    def __getwritebuffer__(self, int segment, void** ptr):
        # ignore invalid segment; the caller can't mean anything but the only
        # segment available; we're all adults
        ptr[0] = self.data
        return self.height()*self.bytes_per_row

    def __getcharbuffer__(self, int segment, char** ptr):
        # ignore invalid segment; the caller can't mean anything but the only
        # segment available; we're all adults
        ptr[0] = <char*>(self.data)
        return self.height()*self.bytes_per_row

    def clear(self, object clear_color=(1.0, 1.0, 1.0, 1.0)):
        """Paint over the whole image with a solid color.
        """

        self.save_state()
        # Reset the transformation matrix back to the identity.
        CGContextConcatCTM(self.context,
            CGAffineTransformInvert(CGContextGetCTM(self.context)))

        self.set_fill_color(clear_color)
        CGContextFillRect(self.context, CGRectMake(0, 0, self.width(), self.height()))
        self.restore_state()

    def save(self, object filename, file_format=None, pil_options=None):
        """ Save the GraphicsContext to a file.  Output files are always saved
        in RGB or RGBA format; if this GC is not in one of these formats, it is
        automatically converted.

        If filename includes an extension, the image format is inferred from it.
        file_format is only required if the format can't be inferred from the
        filename (e.g. if you wanted to save a PNG file as a .dat or .bin).

        filename may also be "file-like" object such as a StringIO, in which
        case a file_format must be supplied.

        pil_options is a dict of format-specific options that are passed down to
        the PIL image file writer.  If a writer doesn't recognize an option, it
        is silently ignored.

        If the image has an alpha channel and the specified output file format
        does not support alpha, the image is saved in rgb24 format.
        """

        try:
            import Image
        except ImportError:
            raise ImportError("need PIL to save images")

        if self.bits_per_pixel == 32:
            if self.alpha_info == kCGImageAlphaPremultipliedLast:
                mode = 'RGBA'
            elif self.alpha_info == kCGImageAlphaPremultipliedFirst:
                mode = 'ARGB'
            else:
                raise ValueError("cannot save this pixel format")
        elif self.bits_per_pixel == 8:
            mode = 'L'
        else:
            raise ValueError("cannot save this pixel format")

        if file_format is None:
            file_format = ''

        img = Image.fromstring(mode, (self.width(), self.height()), self)
        if 'A' in mode:
            # Check the output format to see if it can handle an alpha channel.
            no_alpha_formats = ('jpg', 'bmp', 'eps', 'jpeg')
            if ((isinstance(filename, basestring) and
                 os.path.splitext(filename)[1][1:] in no_alpha_formats) or
                (file_format.lower() in no_alpha_formats)):
                img = img.convert('RGB')

        img.save(filename, format=file_format, options=pil_options)

cdef class CGImage:
    cdef CGImageRef image
    cdef void* data
    cdef readonly c_numpy.ndarray bmp_array

    def __cinit__(self, *args, **kwds):
        self.image = NULL

    property width:
        def __get__(self):
            return CGImageGetWidth(self.image)

    property height:
        def __get__(self):
            return CGImageGetHeight(self.image)

    property bits_per_component:
        def __get__(self):
            return CGImageGetBitsPerComponent(self.image)

    property bits_per_pixel:
        def __get__(self):
            return CGImageGetBitsPerPixel(self.image)

    property bytes_per_row:
        def __get__(self):
            return CGImageGetBytesPerRow(self.image)

    property alpha_info:
        def __get__(self):
            return CGImageGetAlphaInfo(self.image)

    property should_interpolate:
        def __get__(self):
            return CGImageGetShouldInterpolate(self.image)

    property is_mask:
        def __get__(self):
            return CGImageIsMask(self.image)

    def __init__(self, object size_or_array, bool grey_scale=0,
        int bits_per_component=8, int bytes_per_row=-1,
        alpha_info=kCGImageAlphaLast, int should_interpolate=1):

        cdef int bits_per_pixel
        cdef CGColorSpaceRef colorspace

        if hasattr(size_or_array, '__array_interface__'):
            # It's an array.
            arr = size_or_array
            typestr = arr.__array_interface__['typestr']
            if typestr != '|u1':
                raise ValueError("expecting an array of unsigned bytes; got %r"
                    % typestr)
            shape = arr.__array_interface__['shape']
            if grey_scale:
                if (len(shape) == 3 and shape[-1] != 1) or (len(shape) != 2):
                    raise ValueError("with grey_scale, expecting a shape "
                        "(height, width) or (height, width, 1); got "
                        "%r" % (shape,))
                height, width = shape[:2]
                depth = 1
            else:
                if len(shape) != 3 or shape[-1] not in (3, 4):
                    raise ValueError("expecting a shape (height, width, depth) "
                        "with depth either 3 or 4; got %r" % (shape,))
                height, width, depth = shape
            if depth in (1, 3):
                alpha_info = kCGImageAlphaNone
            else:
                # Make a copy.
                arr = numpy.array(arr)
                alpha_info = kCGImageAlphaPremultipliedLast
        else:
            # It's a size tuple.
            width, height = size_or_array
            if grey_scale:
                lastdim = 1
                alpha_info = kCGImageAlphaNone
            else:
                lastdim = 4
                alpha_info = kCGImageAlphaPremultipliedLast
            arr = numpy.zeros((height, width, lastdim), dtype=numpy.uint8)

        self.bmp_array = <c_numpy.ndarray>arr
        Py_INCREF(self.bmp_array)
        self.data = <void*>c_numpy.PyArray_DATA(self.bmp_array)

        if grey_scale:
            alpha_info = kCGImageAlphaNone
            bits_per_component = 8
            bits_per_pixel = 8
            colorspace = CGColorSpaceCreateDeviceGray()
        elif bits_per_component == 5:
            alpha_info = kCGImageAlphaNoneSkipFirst
            bits_per_pixel = 16
            colorspace = CGColorSpaceCreateDeviceRGB()
        elif bits_per_component == 8:
            if alpha_info in (kCGImageAlphaNoneSkipFirst,
                              kCGImageAlphaNoneSkipLast,
                              kCGImageAlphaPremultipliedFirst,
                              kCGImageAlphaPremultipliedLast,
                              kCGImageAlphaFirst,
                              kCGImageAlphaLast,
                             ):
                bits_per_pixel = 32
            elif alpha_info == kCGImageAlphaNone:
                bits_per_pixel = 24
            colorspace = CGColorSpaceCreateDeviceRGB()
        else:
            raise ValueError("bits_per_component must be 5 or 8")

        cdef int min_bytes
        min_bytes = (width*bits_per_pixel + 7) / 8
        if bytes_per_row < min_bytes:
            bytes_per_row = min_bytes

        cdef CGDataProviderRef provider
        provider = CGDataProviderCreateWithData(
            NULL, self.data, c_numpy.PyArray_SIZE(self.bmp_array), NULL)
        if provider == NULL:
            raise RuntimeError("could not make provider")

        cdef CGColorSpaceRef space
        space = CGColorSpaceCreateDeviceRGB()

        self.image = CGImageCreate(width, height, bits_per_component,
            bits_per_pixel, bytes_per_row, space, alpha_info, provider, NULL,
            should_interpolate, kCGRenderingIntentDefault)
        CGColorSpaceRelease(space)
        CGDataProviderRelease(provider)

        if self.image == NULL:
            raise RuntimeError("could not make image")

    def __dealloc__(self):
        if self.image != NULL:
            CGImageRelease(self.image)
            self.image = NULL
        Py_XDECREF(self.bmp_array)

cdef class CGImageFile(CGImage):
    def __init__(self, object image_or_filename, int should_interpolate=1):
        cdef int width, height, bits_per_component, bits_per_pixel, bytes_per_row
        cdef CGImageAlphaInfo alpha_info

        import Image
        import types

        if type(image_or_filename) is str:
            img = Image.open(image_or_filename)
            img.load()
        elif isinstance(image_or_filename, Image.Image):
            img = image_or_filename
        else:
            raise ValueError("need a PIL Image or a filename")

        width, height = img.size
        mode = img.mode

        if mode not in ["L", "RGB","RGBA"]:
            img = img.convert(mode="RGBA")
            mode = 'RGBA'

        bits_per_component = 8

        if mode == 'RGB':
            bits_per_pixel = 24
            alpha_info = kCGImageAlphaNone
        elif mode == 'RGBA':
            bits_per_pixel = 32
            alpha_info = kCGImageAlphaPremultipliedLast
        elif mode == 'L':
            bits_per_pixel = 8
            alpha_info = kCGImageAlphaNone

        bytes_per_row = (bits_per_pixel*width + 7)/ 8

        cdef char* data
        cdef char* py_data
        cdef int dims[3]
        dims[0] = height
        dims[1] = width
        dims[2] = bits_per_pixel/bits_per_component

        self.bmp_array = c_numpy.PyArray_SimpleNew(3, &(dims[0]), c_numpy.NPY_UBYTE)

        data = self.bmp_array.data
        s = img.tostring()
        py_data = PyString_AsString(s)

        memcpy(<void*>data, <void*>py_data, len(s))

        self.data = data

        cdef CGDataProviderRef provider
        provider = CGDataProviderCreateWithData(
            NULL, <void*>data, len(data), NULL)

        if provider == NULL:
            raise RuntimeError("could not make provider")

        cdef CGColorSpaceRef space
        space = CGColorSpaceCreateDeviceRGB()

        self.image = CGImageCreate(width, height, bits_per_component,
            bits_per_pixel, bytes_per_row, space, alpha_info, provider, NULL,
            should_interpolate, kCGRenderingIntentDefault)
        CGColorSpaceRelease(space)
        CGDataProviderRelease(provider)

        if self.image == NULL:
            raise RuntimeError("could not make image")

    def __dealloc__(self):
        if self.image != NULL:
            CGImageRelease(self.image)
            self.image = NULL
        Py_XDECREF(self.bmp_array)

cdef class CGImageMask(CGImage):
    def __init__(self, char* data, int width, int height,
        int bits_per_component, int bits_per_pixel, int bytes_per_row,
        int should_interpolate=1):

        cdef CGDataProviderRef provider
        provider = CGDataProviderCreateWithData(
            NULL, <void*>data, len(data), NULL)

        if provider == NULL:
            raise RuntimeError("could not make provider")

        self.image = CGImageMaskCreate(width, height, bits_per_component,
            bits_per_pixel, bytes_per_row, provider, NULL,
            should_interpolate)
        CGDataProviderRelease(provider)

        if self.image == NULL:
            raise RuntimeError("could not make image")

cdef class CGPDFDocument:
    cdef CGPDFDocumentRef document

    property number_of_pages:
        def __get__(self):
            return CGPDFDocumentGetNumberOfPages(self.document)

    property allows_copying:
        def __get__(self):
            return CGPDFDocumentAllowsCopying(self.document)

    property allows_printing:
        def __get__(self):
            return CGPDFDocumentAllowsPrinting(self.document)

    property is_encrypted:
        def __get__(self):
            return CGPDFDocumentIsEncrypted(self.document)

    property is_unlocked:
        def __get__(self):
            return CGPDFDocumentIsUnlocked(self.document)

    def __init__(self, char* filename):
        import os
        if not os.path.exists(filename) or not os.path.isfile(filename):
            raise ValueError("%s is not a file" % filename)

        cdef CFURLRef cfurl
        cfurl = url_from_filename(filename)

        self.document = CGPDFDocumentCreateWithURL(cfurl)
        CFRelease(cfurl)
        if self.document == NULL:
            raise RuntimeError("could not create CGPDFDocument")

    def unlock_with_password(self, char* password):
        return CGPDFDocumentUnlockWithPassword(self.document, password)

    def get_media_box(self, int page):
        cdef CGRect cgrect
        cgrect = CGPDFDocumentGetMediaBox(self.document, page)
        return (cgrect.origin.x, cgrect.origin.y,
                cgrect.size.width, cgrect.size.height)

    def get_crop_box(self, int page):
        cdef CGRect cgrect
        cgrect = CGPDFDocumentGetCropBox(self.document, page)
        return (cgrect.origin.x, cgrect.origin.y,
                cgrect.size.width, cgrect.size.height)

    def get_bleed_box(self, int page):
        cdef CGRect cgrect
        cgrect = CGPDFDocumentGetBleedBox(self.document, page)
        return (cgrect.origin.x, cgrect.origin.y,
                cgrect.size.width, cgrect.size.height)

    def get_trim_box(self, int page):
        cdef CGRect cgrect
        cgrect = CGPDFDocumentGetTrimBox(self.document, page)
        return (cgrect.origin.x, cgrect.origin.y,
                cgrect.size.width, cgrect.size.height)

    def get_art_box(self, int page):
        cdef CGRect cgrect
        cgrect = CGPDFDocumentGetArtBox(self.document, page)
        return (cgrect.origin.x, cgrect.origin.y,
                cgrect.size.width, cgrect.size.height)

    def get_rotation_angle(self, int page):
        cdef int angle
        angle = CGPDFDocumentGetRotationAngle(self.document, page)
        if angle == 0:
            raise ValueError("page %d does not exist" % page)

    def __dealloc__(self):
        if self.document != NULL:
            CGPDFDocumentRelease(self.document)
            self.document = NULL

cdef CGDataProviderRef CGDataProviderFromFilename(char* string) except NULL:
    cdef CFURLRef cfurl
    cdef CGDataProviderRef result

    cfurl = url_from_filename(string)
    if cfurl == NULL:
        raise RuntimeError("could not create CFURLRef")

    result = CGDataProviderCreateWithURL(cfurl)
    CFRelease(cfurl)
    if result == NULL:
        raise RuntimeError("could not create CGDataProviderRef")
    return result

cdef class CGAffine:
    cdef CGAffineTransform real_transform

    property a:
        def __get__(self):
            return self.real_transform.a
        def __set__(self, float value):
            self.real_transform.a = value

    property b:
        def __get__(self):
            return self.real_transform.b
        def __set__(self, float value):
            self.real_transform.b = value

    property c:
        def __get__(self):
            return self.real_transform.c
        def __set__(self, float value):
            self.real_transform.c = value

    property d:
        def __get__(self):
            return self.real_transform.d
        def __set__(self, float value):
            self.real_transform.d = value

    property tx:
        def __get__(self):
            return self.real_transform.tx
        def __set__(self, float value):
            self.real_transform.tx = value

    property ty:
        def __get__(self):
            return self.real_transform.ty
        def __set__(self, float value):
            self.real_transform.ty = value

    def __init__(self, float a=1.0, float b=0.0, float c=0.0, float d=1.0,
        float tx=0.0, float ty=0.0):
        self.real_transform = CGAffineTransformMake(a,b,c,d,tx,ty)

    def translate(self, float tx, float ty):
        self.real_transform = CGAffineTransformTranslate(self.real_transform,
            tx, ty)
        return self

    def rotate(self, float angle):
        self.real_transform = CGAffineTransformRotate(self.real_transform,
            angle)
        return self

    def scale(self, float sx, float sy):
        self.real_transform = CGAffineTransformScale(self.real_transform, sx,
            sy)
        return self

    def invert(self):
        self.real_transform = CGAffineTransformInvert(self.real_transform)
        return self

    def concat(self, CGAffine other not None):
        self.real_transform = CGAffineTransformConcat(self.real_transform,
            other.real_transform)
        return self

    def __mul__(CGAffine x not None, CGAffine y not None):
        cdef CGAffineTransform new_transform
        new_transform = CGAffineTransformConcat(x.real_transform,
            y.real_transform)
        new_affine = CGAffine()
        set_affine_transform(new_affine, new_transform)
        return new_affine

    cdef void init_from_cgaffinetransform(self, CGAffineTransform t):
        self.real_transform = t

    def __div__(CGAffine x not None, CGAffine y not None):
        cdef CGAffineTransform new_transform
        new_transform = CGAffineTransformInvert(y.real_transform)
        new_affine = CGAffine()
        set_affine_transform(new_affine, CGAffineTransformConcat(x.real_transform, new_transform))
        return new_affine

    def apply_to_point(self, float x, float y):
        cdef CGPoint oldpoint
        oldpoint = CGPointMake(x, y)
        cdef CGPoint newpoint
        newpoint = CGPointApplyAffineTransform(oldpoint,
            self.real_transform)
        return newpoint.x, newpoint.y

    def apply_to_size(self, float width, float height):
        cdef CGSize oldsize
        oldsize = CGSizeMake(width, height)
        cdef CGSize newsize
        newsize = CGSizeApplyAffineTransform(oldsize, self.real_transform)
        return newsize.width, newsize.height

    def __repr__(self):
        return "CGAffine(%r, %r, %r, %r, %r, %r)" % (self.a, self.b, self.c,
            self.d, self.tx, self.ty)

    def as_matrix(self):
        return ((self.a, self.b, 0.0),
                (self.c, self.d, 0.0),
                (self.tx,self.ty,1.0))

cdef set_affine_transform(CGAffine t, CGAffineTransform newt):
    t.init_from_cgaffinetransform(newt)

##cdef class Point:
##    cdef CGPoint real_point
##
##    property x:
##        def __get__(self):
##            return self.real_point.x
##        def __set__(self, float value):
##            self.real_point.x = value
##
##    property y:
##        def __get__(self):
##            return self.real_point.y
##        def __set__(self, float value):
##            self.real_point.y = value
##
##    def __init__(self, float x, float y):
##        self.real_point = CGPointMake(x, y)
##
##    def apply_transform(self, CGAffine transform not None):
##        self.real_point = CGPointApplyTransform(self.real_point,
##            transform.real_transform)

cdef class Rect:
    cdef CGRect real_rect

    property x:
        def __get__(self):
            return self.real_rect.origin.x
        def __set__(self, float value):
            self.real_rect.origin.x = value

    property y:
        def __get__(self):
            return self.real_rect.origin.y
        def __set__(self, float value):
            self.real_rect.origin.y = value

    property width:
        def __get__(self):
            return self.real_rect.size.width
        def __set__(self, float value):
            self.real_rect.size.width = value

    property height:
        def __get__(self):
            return self.real_rect.size.height
        def __set__(self, float value):
            self.real_rect.size.height = value

    property min_x:
        def __get__(self):
            return CGRectGetMinX(self.real_rect)

    property max_x:
        def __get__(self):
            return CGRectGetMaxX(self.real_rect)

    property min_y:
        def __get__(self):
            return CGRectGetMinY(self.real_rect)

    property max_y:
        def __get__(self):
            return CGRectGetMaxY(self.real_rect)

    property mid_x:
        def __get__(self):
            return CGRectGetMidX(self.real_rect)

    property mid_y:
        def __get__(self):
            return CGRectGetMidY(self.real_rect)

    property is_null:
        def __get__(self):
            return CGRectIsNull(self.real_rect)

    property is_empty:
        def __get__(self):
            return CGRectIsEmpty(self. real_rect)

    def __init__(self, float x=0.0, float y=0.0, float width=0.0, float
        height=0.0):
        self.real_rect = CGRectMake(x,y,width,height)

    def intersects(self, Rect other not None):
        return CGRectIntersectsRect(self.real_rect, other.real_rect)

    def contains_rect(self, Rect other not None):
        return CGRectContainsRect(self.real_rect, other.real_rect)

    def contains_point(self, float x, float y):
        return CGRectContainsPoint(self.real_rect, CGPointMake(x,y))

    def __richcmp__(Rect x not None, Rect y not None, int op):
        if op == 2:
            return CGRectEqualToRect(x.real_rect, y.real_rect)
        elif op == 3:
            return not CGRectEqualToRect(x.real_rect, y.real_rect)
        else:
            raise NotImplementedError("only (in)equality can be tested")

    def standardize(self):
        self.real_rect = CGRectStandardize(self.real_rect)
        return self

    def inset(self, float x, float y):
        cdef CGRect new_rect
        new_rect = CGRectInset(self.real_rect, x, y)
        rect = Rect()
        set_rect(rect, new_rect)
        return rect

    def offset(self, float x, float y):
        cdef CGRect new_rect
        new_rect = CGRectOffset(self.real_rect, x, y)
        rect = Rect()
        set_rect(rect, new_rect)
        return rect

    def integral(self):
        self.real_rect = CGRectIntegral(self.real_rect)
        return self

    def __add__(Rect x not None, Rect y not None):
        cdef CGRect new_rect
        new_rect = CGRectUnion(x.real_rect, y.real_rect)
        rect = Rect()
        set_rect(rect, new_rect)
        return rect

    def union(self, Rect other not None):
        cdef CGRect new_rect
        new_rect = CGRectUnion(self.real_rect, other.real_rect)
        rect = Rect()
        set_rect(rect, new_rect)
        return rect

    def intersection(self, Rect other not None):
        cdef CGRect new_rect
        new_rect = CGRectIntersection(self.real_rect, other.real_rect)
        rect = Rect()
        set_rect(rect, new_rect)
        return rect

    def divide(self, float amount, edge):
        cdef CGRect slice
        cdef CGRect remainder
        CGRectDivide(self.real_rect, &slice, &remainder, amount, edge)
        pyslice = Rect()
        set_rect(pyslice, slice)
        pyrem = Rect()
        set_rect(pyrem, remainder)
        return pyslice, pyrem

    cdef init_from_cgrect(self, CGRect cgrect):
        self.real_rect = cgrect

    def __repr__(self):
        return "Rect(%r, %r, %r, %r)" % (self.x, self.y, self.width,
            self.height)

cdef set_rect(Rect pyrect, CGRect cgrect):
    pyrect.init_from_cgrect(cgrect)

cdef class CGMutablePath:
    cdef CGMutablePathRef path

    def __init__(self, CGMutablePath path=None):
        if path is not None:
            self.path = CGPathCreateMutableCopy(path.path)
        else:
            self.path = CGPathCreateMutable()

    def begin_path(self):
        return

    def move_to(self, float x, float y, CGAffine transform=None):
        cdef CGAffineTransform *ptr
        ptr = NULL
        if transform is not None:
            ptr = &(transform.real_transform)
        CGPathMoveToPoint(self.path, ptr, x, y)

    def arc(self, float x, float y, float r, float startAngle, float endAngle,
        bool clockwise=False, CGAffine transform=None):

        cdef CGAffineTransform *ptr
        ptr = NULL
        if transform is not None:
            ptr = &(transform.real_transform)

        CGPathAddArc(self.path, ptr, x, y, r, startAngle, endAngle, clockwise)

    def arc_to(self, float x1, float y1, float x2, float y2, float r,
        CGAffine transform=None):

        cdef CGAffineTransform *ptr
        ptr = NULL
        if transform is not None:
            ptr = &(transform.real_transform)

        CGPathAddArcToPoint(self.path, ptr, x1,y1, x2,y2, r)

    def curve_to(self, float cx1, float cy1, float cx2, float cy2, float x,
        float y, CGAffine transform=None):

        cdef CGAffineTransform *ptr
        ptr = NULL
        if transform is not None:
            ptr = &(transform.real_transform)

        CGPathAddCurveToPoint(self.path, ptr, cx1, cy1, cx2, cy2, x, y)

    def line_to(self, float x, float y, CGAffine transform=None):
        cdef CGAffineTransform *ptr
        ptr = NULL
        if transform is not None:
            ptr = &(transform.real_transform)

        CGPathAddLineToPoint(self.path, ptr, x, y)

    def lines(self, points, CGAffine transform=None):
        cdef CGAffineTransform *ptr
        ptr = NULL
        if transform is not None:
            ptr = &(transform.real_transform)

        cdef int n
        n = len(points)
        cdef int i

        CGPathMoveToPoint(self.path, ptr, points[0][0], points[0][1])

        for i from 1 <= i < n:
            CGPathAddLineToPoint(self.path, ptr, points[i][0], points[i][1])

    def add_path(self, CGMutablePath other_path not None, CGAffine transform=None):
        cdef CGAffineTransform *ptr
        ptr = NULL
        if transform is not None:
            ptr = &(transform.real_transform)

        CGPathAddPath(self.path, ptr, other_path.path)

    def quad_curve_to(self, float cx, float cy, float x, float y, CGAffine transform=None):
        cdef CGAffineTransform *ptr
        ptr = NULL
        if transform is not None:
            ptr = &(transform.real_transform)

        CGPathAddQuadCurveToPoint(self.path, ptr, cx, cy, x, y)

    def rect(self, float x, float y, float sx, float sy, CGAffine transform=None):
        cdef CGAffineTransform *ptr
        ptr = NULL
        if transform is not None:
            ptr = &(transform.real_transform)

        CGPathAddRect(self.path, ptr, CGRectMake(x,y,sx,sy))

    def rects(self, rects, CGAffine transform=None):
        cdef CGAffineTransform *ptr
        ptr = NULL
        if transform is not None:
            ptr = &(transform.real_transform)

        cdef int n
        n = len(rects)
        cdef int i
        for i from 0 <= i < n:
            CGPathAddRect(self.path, ptr, CGRectMakeFromPython(rects[i]))

    def close_path(self):
        CGPathCloseSubpath(self.path)

    def is_empty(self):
        return CGPathIsEmpty(self.path)

    def get_current_point(self):
        cdef CGPoint point
        point = CGPathGetCurrentPoint(self.path)
        return point.x, point.y

    def get_bounding_box(self):
        cdef CGRect rect
        rect = CGPathGetBoundingBox(self.path)
        return (rect.origin.x, rect.origin.y,
                rect.size.width, rect.size.height)

    def __richcmp__(CGMutablePath x not None, CGMutablePath y not None, int op):
        if op == 2:
            # testing for equality
            return CGPathEqualToPath(x.path, y.path)
        elif op == 3:
            # testing for inequality
            return not CGPathEqualToPath(x.path, y.path)
        else:
            raise NotImplementedError("only (in)equality tests are allowed")

    def __dealloc__(self):
        if self.path != NULL:
            CGPathRelease(self.path)
            self.path = NULL

cdef class _Markers:

    def get_marker(self, int marker_type, float size=1.0):
        """ Return the CGMutablePath corresponding to the given marker
        enumeration.

          Marker.get_marker(marker_type, size=1.0)

        Parameters
        ----------
        marker_type : int
            One of the enumerated marker types in kiva.constants.
        size : float, optional
            The linear size in points of the marker. Some markers (e.g. dot)
            ignore this.

        Returns
        -------
        path : CGMutablePath
        """

        if marker_type == constants.NO_MARKER:
            return CGMutablePath()
        elif marker_type == constants.SQUARE_MARKER:
            return self.square(size)
        elif marker_type == constants.DIAMOND_MARKER:
            return self.diamond(size)
        elif marker_type == constants.CIRCLE_MARKER:
            return self.circle(size)
        elif marker_type == constants.CROSSED_CIRCLE_MARKER:
            raise NotImplementedError
        elif marker_type == constants.CROSS_MARKER:
            return self.cross(size)
        elif marker_type == constants.TRIANGLE_MARKER:
            raise NotImplementedError
        elif marker_type == constants.INVERTED_TRIANGLE_MARKER:
            raise NotImplementedError
        elif marker_type == constants.PLUS_MARKER:
            raise NotImplementedError
        elif marker_type == constants.DOT_MARKER:
            raise NotImplementedError
        elif marker_type == constants.PIXEL_MARKER:
            raise NotImplementedError


    def square(self, float size):
        cdef float half
        half = size / 2

        m = CGMutablePath()
        m.rect(-half,-half,size,size)
        return m

    def diamond(self, float size):
        cdef float half
        half = size / 2

        m = CGMutablePath()
        m.move_to(0.0, -half)
        m.line_to(-half, 0.0)
        m.line_to(0.0, half)
        m.line_to(half, 0.0)
        m.close_path()
        return m

    def x(self, float size):
        cdef float half
        half = size / 2

        m = CGMutablePath()
        m.move_to(-half,-half)
        m.line_to(half,half)
        m.move_to(-half,half)
        m.line_to(half,-half)
        return m

    def cross(self, float size):
        cdef float half
        half = size / 2

        m = CGMutablePath()
        m.move_to(0.0, -half)
        m.line_to(0.0, half)
        m.move_to(-half, 0.0)
        m.line_to(half, 0.0)
        return m

    def dot(self):
        m = CGMutablePath()
        m.rect(-0.5,-0.5,1.0,1.0)
        return m

    def circle(self, float size):
        cdef float half
        half = size / 2
        m = CGMutablePath()
        m.arc(0.0, 0.0, half, 0.0, 6.2831853071795862, 1)
        return m

Markers = _Markers()

cdef class ShadingFunction:
    cdef CGFunctionRef function

    cdef void _setup_function(self, CGFunctionEvaluateCallback callback):
        cdef int i
        cdef CGFunctionCallbacks callbacks
        callbacks.version = 0
        callbacks.releaseInfo = NULL
        callbacks.evaluate = <CGFunctionEvaluateCallback>callback

        cdef float domain_bounds[2]
        cdef float range_bounds[8]

        domain_bounds[0] = 0.0
        domain_bounds[1] = 1.0
        for i from 0 <= i < 4:
            range_bounds[2*i] = 0.0
            range_bounds[2*i+1] = 1.0

        self.function = CGFunctionCreate(<void*>self, 1, domain_bounds,
            4, range_bounds, &callbacks)
        if self.function == NULL:
            raise RuntimeError("could not make CGFunctionRef")

cdef void shading_callback(object self, float* in_data, float* out_data):
    cdef int i
    out = self(in_data[0])
    for i from 0 <= i < self.n_dims:
        out_data[i] = out[i]

cdef class Shading:
    cdef CGShadingRef shading
    cdef public object function
    cdef int n_dims

    def __init__(self, ShadingFunction func not None):
        raise NotImplementedError("use AxialShading or RadialShading")

    def __dealloc__(self):
        if self.shading != NULL:
            CGShadingRelease(self.shading)

cdef class AxialShading(Shading):
    def __init__(self, ShadingFunction func not None, object start, object end,
        int extend_start=0, int extend_end=0):

        self.n_dims = 4

        cdef CGPoint start_point, end_point
        start_point = CGPointMake(start[0], start[1])
        end_point = CGPointMake(end[0], end[1])

        self.function = func

        cdef CGColorSpaceRef space
        space = CGColorSpaceCreateDeviceRGB()
        self.shading = CGShadingCreateAxial(space, start_point, end_point,
            func.function, extend_start, extend_end)
        CGColorSpaceRelease(space)
        if self.shading == NULL:
            raise RuntimeError("could not make CGShadingRef")

cdef class RadialShading(Shading):
    def __init__(self, ShadingFunction func not None, object start,
        float start_radius, object end, float end_radius, int extend_start=0,
        int extend_end=0):

        self.n_dims = 4

        cdef CGPoint start_point, end_point
        start_point = CGPointMake(start[0], start[1])
        end_point = CGPointMake(end[0], end[1])

        self.function = func

        cdef CGColorSpaceRef space
        space = CGColorSpaceCreateDeviceRGB()
        self.shading = CGShadingCreateRadial(space, start_point, start_radius,
            end_point, end_radius, func.function, extend_start, extend_end)
        CGColorSpaceRelease(space)
        if self.shading == NULL:
            raise RuntimeError("could not make CGShadingRef")

cdef void safe_free(void* mem):
    if mem != NULL:
        PyMem_Free(mem)

cdef class PiecewiseLinearColorFunction(ShadingFunction):
    cdef int num_stops
    cdef float* stops
    cdef float* red
    cdef float* green
    cdef float* blue
    cdef float* alpha

    def __init__(self, object stop_colors):
        cdef c_numpy.ndarray stop_array
        cdef int i

        stop_colors = numpy.array(stop_colors).astype(numpy.float32)

        if not (4 <= stop_colors.shape[0] <= 5) or len(stop_colors.shape) != 2:
            raise ValueError("need array [stops, red, green, blue[, alpha]]")

        if stop_colors[0,0] != 0.0 or stop_colors[0,-1] != 1.0:
            raise ValueError("stops need to start with 0.0 and end with 1.0")

        if not numpy.greater_equal(numpy.diff(stop_colors[0]), 0.0).all():
            raise ValueError("stops must be sorted and unique")

        self.num_stops = stop_colors.shape[1]
        self.stops = <float*>PyMem_Malloc(sizeof(float)*self.num_stops)
        self.red = <float*>PyMem_Malloc(sizeof(float)*self.num_stops)
        self.green = <float*>PyMem_Malloc(sizeof(float)*self.num_stops)
        self.blue = <float*>PyMem_Malloc(sizeof(float)*self.num_stops)
        self.alpha = <float*>PyMem_Malloc(sizeof(float)*self.num_stops)

        has_alpha = stop_colors.shape[0] == 5
        for i from 0 <= i < self.num_stops:
            self.stops[i] = stop_colors[0,i]
            self.red[i] = stop_colors[1,i]
            self.green[i] = stop_colors[2,i]
            self.blue[i] = stop_colors[3,i]
            if has_alpha:
                self.alpha[i] = stop_colors[4,i]
            else:
                self.alpha[i] = 1.0

        self._setup_function(piecewise_callback)

    def dump(self):
        cdef int i
        print 'PiecewiseLinearColorFunction'
        print '  num_stops = %i' % self.num_stops
        print '  stops = ',
        for i from 0 <= i < self.num_stops:
            print self.stops[i],
        print
        print '  red = ',
        for i from 0 <= i < self.num_stops:
            print self.red[i],
        print
        print '  green = ',
        for i from 0 <= i < self.num_stops:
            print self.green[i],
        print
        print '  blue = ',
        for i from 0 <= i < self.num_stops:
            print self.blue[i],
        print
        print '  alpha = ',
        for i from 0 <= i < self.num_stops:
            print self.alpha[i],
        print

    def __dealloc__(self):
        safe_free(self.stops)
        safe_free(self.red)
        safe_free(self.green)
        safe_free(self.blue)
        safe_free(self.alpha)


cdef int bisect_left(PiecewiseLinearColorFunction self, float t):
    cdef int lo, hi, mid
    cdef float stop

    hi = self.num_stops
    lo = 0
    while lo < hi:
        mid = (lo + hi)/2
        stop = self.stops[mid]
        if t < stop:
            hi = mid
        else:
            lo = mid + 1
    return lo

cdef void piecewise_callback(void* obj, float* t, float* out):
   cdef int i
   cdef float eps
   cdef PiecewiseLinearColorFunction self

   self = <PiecewiseLinearColorFunction>obj

   eps = 1e-6

   if fabs(t[0]) < eps:
       out[0] = self.red[0]
       out[1] = self.green[0]
       out[2] = self.blue[0]
       out[3] = self.alpha[0]
       return
   if fabs(t[0] - 1.0) < eps:
       i = self.num_stops - 1
       out[0] = self.red[i]
       out[1] = self.green[i]
       out[2] = self.blue[i]
       out[3] = self.alpha[i]
       return

   i = bisect_left(self, t[0])

   cdef float f, g, dx
   dx = self.stops[i] - self.stops[i-1]

   if dx > eps:
       f = (t[0]-self.stops[i-1])/dx
   else:
       f = 1.0

   g = 1.0 - f

   out[0] = f*self.red[i] + g*self.red[i-1]
   out[1] = f*self.green[i] + g*self.green[i-1]
   out[2] = f*self.blue[i] + g*self.blue[i-1]
   out[3] = f*self.alpha[i] + g*self.alpha[i-1]

cdef double _point_distance(double x1, double y1, double x2, double y2):
    cdef double dx = x1-x2
    cdef double dy = y1-y2
    return sqrt(dx*dx+dy*dy)

cdef bool _cgrect_within_circle(CGRect rect, double cx, double cy, double rad):
    cdef double d1 = _point_distance(cx,cy, rect.origin.x, rect.origin.y)
    cdef double d2 = _point_distance(cx,cy, rect.origin.x+rect.size.width, rect.origin.y)
    cdef double d3 = _point_distance(cx,cy, rect.origin.x+rect.size.width, rect.origin.y+rect.size.height)
    cdef double d4 = _point_distance(cx,cy, rect.origin.x, rect.origin.y+rect.size.height)
    return (d1<rad and d2<rad and d3<rad and d4<rad)

cdef bool _line_intersects_cgrect(double x, double y, double slope, CGRect rect):
    if slope == 0.:
        return rect.origin.x <= x <= (rect.origin.x+rect.size.width)
    elif isnan(slope):
        return rect.origin.y <= y <= (rect.origin.y+rect.size.height)
    # intersect the all sides
    cdef double left = rect.origin.x
    cdef double right = left + rect.size.width
    cdef double bottom = rect.origin.y
    cdef double top = bottom + rect.size.height
    if bottom <= (y + slope*(left-x)) <= top:
        return True
    if bottom <= (y + slope*(right-x)) <= top:
        return True
    if left <= (x + 1./slope*(top-y)) <= right:
        return True
    if left <= (x + 1./slope*(bottom-y)) <= right:
        return True
    return False


#### Font utilities ####

cdef ATSUStyle _create_atsu_style(object postscript_name, float font_size):
    cdef OSStatus err
    cdef ATSUStyle atsu_style
    cdef ATSUFontID atsu_font
    cdef Fixed atsu_size
    cdef char* c_ps_name

    # Create the attribute arrays.
    cdef ATSUAttributeTag attr_tags[2]
    cdef ByteCount attr_sizes[2]
    cdef ATSUAttributeValuePtr attr_values[2]

    err = noErr
    atsu_style = NULL
    atsu_font = 0
    atsu_size = FloatToFixed(font_size)

    # Look up the ATSUFontID for the given PostScript name of the font.
    postscript_name = postscript_name.encode('utf-8')
    c_ps_name = PyString_AsString(postscript_name)
    err = ATSUFindFontFromName(<void*>c_ps_name, len(postscript_name),
        kFontPostscriptName, kFontNoPlatformCode, kFontNoScriptCode,
        kFontNoLanguageCode, &atsu_font)
    if err:
        return NULL

    # Set the ATSU font in the attribute arrays.
    attr_tags[0] = kATSUFontTag
    attr_sizes[0] = sizeof(ATSUFontID)
    attr_values[0] = &atsu_font

    # Set the font size in the attribute arrays.
    attr_tags[1] = kATSUSizeTag
    attr_sizes[1] = sizeof(Fixed)
    attr_values[1] = &atsu_size

    # Create the ATSU style.
    err = ATSUCreateStyle(&atsu_style)
    if err:
        if atsu_style != NULL:
            ATSUDisposeStyle(atsu_style)
        return NULL

    # Set the style attributes.
    err = ATSUSetAttributes(atsu_style, 2, attr_tags, attr_sizes, attr_values)
    if err:
        if atsu_style != NULL:
            ATSUDisposeStyle(atsu_style)
        return NULL

    return atsu_style


cdef object _create_atsu_layout(object the_string, ATSUStyle style, ATSUTextLayout* layout):
    cdef ATSUTextLayout atsu_layout
    cdef CFIndex text_length
    cdef OSStatus err
    cdef UniChar *uni_buffer
    cdef CFRange uni_range
    cdef CFStringRef cf_string
    cdef char* c_string

    layout[0] = atsu_layout = NULL
    if len(the_string) == 0:
        return

    err = noErr
    the_string = the_string.encode('utf-8')
    c_string = PyString_AsString(the_string)

    cf_string = CFStringCreateWithCString(NULL, c_string, kCFStringEncodingUTF8)
    text_length = CFStringGetLength(cf_string)

    # Extract the Unicode data from the CFStringRef.
    uni_range = CFRangeMake(0, text_length)
    uni_buffer = <UniChar*>PyMem_Malloc(text_length * sizeof(UniChar))
    if uni_buffer == NULL:
        raise MemoryError("could not allocate %d bytes of memory" % (text_length * sizeof(UniChar)))
    CFStringGetCharacters(cf_string, uni_range, uni_buffer)

    # Create the ATSUI layout.
    err = ATSUCreateTextLayoutWithTextPtr(<ConstUniCharArrayPtr>uni_buffer, 0, text_length, text_length, 1, <UniCharCount*>&text_length, &style, &atsu_layout)
    if err:
        PyMem_Free(uni_buffer)
        raise RuntimeError("could not create an ATSUI layout")

    layout[0] = atsu_layout
    return


cdef object _set_cgcontext_for_layout(CGContextRef context, ATSUTextLayout layout):
    cdef ATSUAttributeTag tag
    cdef ByteCount size
    cdef ATSUAttributeValuePtr value
    cdef OSStatus err

    tag = kATSUCGContextTag
    size = sizeof(CGContextRef)
    value = &context

    err = ATSUSetLayoutControls(layout, 1, &tag, &size, &value)
    if err:
        raise RuntimeError("could not assign the CGContextRef to the ATSUTextLayout")
    return

#### EOF #######################################################################