File: cairo.py

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 (1376 lines) | stat: -rw-r--r-- 45,644 bytes parent folder | download | duplicates (3)
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
""" Implementation of the core2d drawing library, using cairo for rendering

    :Author:      Bryan Cole (bryan@cole.uklinux.net)
    :Copyright:   Bryan Cole (except parts copied from basecore2d)
    :License:     BSD Style

    This is currently under development and is not yet fully functional.

"""
from __future__ import absolute_import
import cairo
import copy
from itertools import izip
import numpy
import warnings

from .arc_conversion import arc_to_tangent_points
from . import basecore2d, constants


line_join = {constants.JOIN_BEVEL: cairo.LINE_JOIN_BEVEL,
             constants.JOIN_MITER: cairo.LINE_JOIN_MITER,
             constants.JOIN_ROUND: cairo.LINE_JOIN_ROUND
            }

line_cap = {constants.CAP_BUTT: cairo.LINE_CAP_BUTT,
            constants.CAP_ROUND: cairo.LINE_CAP_ROUND,
            constants.CAP_SQUARE: cairo.LINE_CAP_SQUARE
           }

font_slant = {"regular":cairo.FONT_SLANT_NORMAL,
              "bold":cairo.FONT_SLANT_NORMAL,
              "italic":cairo.FONT_SLANT_ITALIC,
              "bold italic":cairo.FONT_SLANT_ITALIC
             }

font_weight = {"regular":cairo.FONT_WEIGHT_NORMAL,
               "bold":cairo.FONT_WEIGHT_BOLD,
               "italic":cairo.FONT_WEIGHT_NORMAL,
               "bold italic":cairo.FONT_WEIGHT_BOLD
              }

spread_methods = {"pad":cairo.EXTEND_PAD,
                  "reflect":cairo.EXTEND_REFLECT,
                  "repeat":cairo.EXTEND_REPEAT
                 }

text_draw_modes = {'FILL': (constants.TEXT_FILL,
                            constants.TEXT_FILL_CLIP,
                            constants.TEXT_FILL_STROKE,
                            constants.TEXT_FILL_STROKE_CLIP),
                   'STROKE':(constants.TEXT_FILL_STROKE,
                            constants.TEXT_FILL_STROKE_CLIP,
                            constants.TEXT_STROKE,
                            constants.TEXT_STROKE_CLIP),
                   'CLIP':(constants.TEXT_CLIP,
                            constants.TEXT_FILL_CLIP,
                            constants.TEXT_FILL_STROKE_CLIP,
                            constants.TEXT_STROKE_CLIP),
                   'INVISIBLE': constants.TEXT_INVISIBLE
                  }

class PixelMap(object):

    def __init__(self, surface, width, height):
        self.surface = surface
        self.width = width
        self.height = height

    def draw_to_wxwindow(self, window, x, y):
        import wx
        window_dc = getattr(window,'_dc',None)
        if window_dc is None:
            window_dc = wx.PaintDC(window)
        arr = self.convert_to_rgbarray()
        image = wx.EmptyImage(self.width, self.height)
        image.SetDataBuffer(arr.data)
        bmp = wx.BitmapFromImage(image, depth=-1)

        window_dc.BeginDrawing()
        window_dc.DrawBitmap(bmp,x,y)
        window_dc.EndDrawing()
        return

    def convert_to_rgbarray(self):
        pixels = numpy.frombuffer(self.surface.get_data(), numpy.uint8)

        red = pixels[2::4]
        green = pixels[1::4]
        blue = pixels[0::4]
        return numpy.vstack((red, green, blue)).T.flatten()

    def convert_to_argbarray(self, flip=False):
        pixels = numpy.frombuffer(self.surface.get_data(), numpy.uint8)

        alpha = pixels[0::4]
        red = pixels[1::4]
        green = pixels[2::4]
        blue = pixels[3::4]
        if flip:
            return numpy.vstack((alpha, red, green, blue)).T\
                        .reshape((self.height, self.width, 4))[::-1,...].flatten()
        # no flip
        return numpy.vstack((alpha, red, green, blue)).T.flatten()

class GraphicsState(object):
    """ Holds information used by a graphics context when drawing.

        The Cairo state stores the following:

        * Operator (the blend mode)
        * Tolerance
        * Antialias (bool)
        * stroke style (line width, cap, join, mitre-limit, dash-style)
        * fill rule
        * font face
        * scaled font
        * font matrix (includes font size)
        * font options (antialias, subpixel order, hint style, hint metrics)
        * clip region
        * target surface and previous target surface
        * CTM, CTM-inverse, source CTM

        The Quartz2D state (which kiva follows AFAIK) includes:

        * CTM
        * stroke style (line width, cap, join, mitre, dash)
        * clip region
        * tolerance (accuracy)
        * anti-alias
        * \*fill- and stroke- colors
        * \*fill- and stroke- Color Space (RGB, HSV, CMYK etc.)
        * \*Rendering intent (something to do with Color Spaces)
        * \*alpha value
        * blend mode
        * text font
        * text font size
        * \*text drawing mode (stroked, filled, clipped and combinations of these)
        * \*text character spacing (extra space between glyphs)

        \*: items in the Quartz2D state that Cairo doesn't support directly.

        basecore2d GraphicsState includes:

        * ctm
        * line_color
        * line_width
        * line_join
        * line_cap
        * line_dash
        * fill_color
        * alpha
        * font
        * \*text_matrix
        * clipping_path
        * \*current_point
        * should_antialias
        * miter_limit
        * flatness
        * character_spacing
        * text_drawing_mode
        * rendering_intent (not yet implemented)

        \*: discrepancies compared to Quartz2D

    """
    def __init__(self):
        self.fill_color = [1,1,1]
        self.stroke_color = [1,1,1]
        self.alpha = 1.0
        self.text_drawing_mode = constants.TEXT_FILL
        self.has_gradient = False

        #not implemented yet...
        self.text_character_spacing = None
        self.fill_colorspace = None
        self.stroke_colorspace = None
        self.rendering_intent = None

    def copy(self):
        return copy.deepcopy(self)

class GraphicsContext(basecore2d.GraphicsContextBase):
    def __init__(self, size, *args, **kw):
        super(GraphicsContext, self).__init__(size, *args, **kw)
        w,h = size

        self.surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, w, h)
        self.surface.set_device_offset(0,h)

        if 'context' in kw:
            ctx = kw.pop('context')
        else:
            ctx = cairo.Context(self.surface)
            ctx.set_source_rgb(1,1,1)
            ctx.scale(1,-1)

        self._ctx = ctx
        self.state = GraphicsState()
        self.state_stack = []

        #the text-matrix includes the text position
        self.text_matrix = cairo.Matrix(1,0,0,-1,0,0) #not part of the graphics state

        self.pixel_map = PixelMap(self.surface, w, h)

    def clear(self, color=(1,1,1)):
        self.save_state()
        if len(color) == 4:
            self._ctx.set_source_rgba(*color)
        else:
            self._ctx.set_source_rgb(*color)
        self.rect(0, 0, self.width(), self.height())
        self.draw_path(constants.FILL)
        self.restore_state()

    def height(self):
        return self._ctx.get_target().get_height()

    def width(self):
        return self._ctx.get_target().get_width()

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

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

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

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

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

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

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

            Parameters
            ----------
            transform : affine_matrix
                the transform matrix to concatenate with
                the current coordinate matrix.
        """
        try:
            #assume transform is a cairo.Matrix object
            self._ctx.transform(transform)
        except TypeError:
            #now assume transform is a list of matrix elements (floats)
            self._ctx.transform(cairo.Matrix(*transform))


    def get_ctm(self):
        """ Returns the current coordinate transform matrix
            as a list of matrix elements
        """
        return list(self._ctx.get_matrix())

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

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

            Always pair this with a `restore_state()`.
        """
        self._ctx.save()
        self.state_stack.append(self.state)
        self.state = self.state.copy()

    def restore_state(self):
        """ Restores the previous graphics state.
        """
        self._ctx.restore()
        self.state = self.state_stack.pop()

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

    def set_antialias(self,value):
        """ Sets/Unsets anti-aliasing for bitmap graphics context.

            Ignored on most platforms.
        """
        if bool(value):
            val = cairo.ANTIALIAS_DEFAULT
        else:
            val = cairo.ANTIALIAS_NONE
        self._ctx.set_antialias(val)

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

            Parameters
            ----------
            width : float
                The new width for lines in user space units.
        """
        self._ctx.set_line_width(width)

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

            Parameters
            ----------
            style : join_style
                The line joining style.  The available
                styles are JOIN_ROUND, JOIN_BEVEL, JOIN_MITER.
        """
        try:
            self._ctx.set_line_join(line_join[style])
        except KeyError:
            raise ValueError("Invalid line-join style")

    def set_miter_limit(self,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 are not 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.

            This is not implemented on most platforms.

            Parameters
            ----------
            limit : float
                limit for mitering joins. defaults to 1.0.
                (XXX is this the correct default?)
        """
        self._ctx.set_miter_limit(limit)

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

            Parameters
            ----------
            style : cap_style
                The line cap style to use. Available styles
                are CAP_ROUND, CAP_BUTT, CAP_SQUARE.
        """
        try:
            self._ctx.set_line_cap(line_cap[style])
        except KeyError:
            raise ValueError("Invalid line cap style")

    def set_line_dash(self,pattern,phase=0):
        """ Sets the line dash pattern and phase for line painting.

            Parameters
            ----------
            pattern : 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.
        """
        if pattern is not None:
            pattern = list(pattern)
            self._ctx.set_dash(pattern, phase)

    def set_flatness(self,flatness):
        """ Not implemented

            It is device dependent and therefore not recommended by
            the PDF documentation.

            flatness determines how accurately lines are rendered.  Setting it
            to values less than one will result in more accurate drawings, but
            they take longer.  It defaults to None
        """
        self._ctx.set_tolerance(flatness)

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

    def flush(self):
        """ Sends all drawing data to the destination device.

            Currently this is a NOP for wxPython.
        """
        s = self._ctx.get_target()
        s.flush()

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

            Currently this is a NOP for all implementations.
        """
        pass

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

    def begin_page(self):
        """ Creates a new page within the graphics context.

            Currently this is a NOP for all implementations.  The PDF
            backend should probably implement it, but the ReportLab
            Canvas uses the showPage() method to handle both
            begin_page and end_page issues.
        """
        pass

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

            Currently this is a NOP for all implementations.  The PDF
            backend should probably implement it, but the ReportLab
            Canvas uses the showPage() method to handle both
            begin_page and end_page issues.
        """
        pass


    def radial_gradient(self, cx, cy, r, fx, fy, stops, spreadMethod='pad',
                        units='userSpaceOnUse', transforms=None):
        """ Set a radial gradient as the fill color.
        """
        # TODO: handle transforms

        if units == 'objectBoundingBox':
            # transform from relative coordinates
            path_rect = self._ctx.path_extents()
            width = path_rect[2]-path_rect[0]
            height = path_rect[3]-path_rect[1]
            r = r * width
            cx = path_rect[0] + cx * width
            fx = path_rect[0] + fx * width
            cy = path_rect[1] + cy * height
            fy = path_rect[1] + fy * height

        gradient = cairo.RadialGradient(fx, fy, 0.0, cx, cy, r)

        gradient.set_extend(spread_methods.get(spreadMethod, cairo.EXTEND_NONE))

        for stop in stops:
            #FIXME: the stops are possibly being generated wrong if the offset is specified
            if stop.size == 10:
                start = tuple(stop[0:5])
                end = tuple(stop[5:10])
                gradient.add_color_stop_rgba(*start)
                gradient.add_color_stop_rgba(*end)
            else:
                start = tuple(stop[0:5])
                gradient.add_color_stop_rgba(*start)

        self.state.has_gradient = True
        self._ctx.set_source(gradient)

    def linear_gradient(self, x1, y1, x2, y2, stops, spreadMethod='pad',
                        units='userSpaceOnUse', transforms=None):
        """ Set a linear gradient as the fill color.
        """
        # TODO: handle transforms

        if units == 'objectBoundingBox':
            # transform from relative coordinates
            path_rect = self._ctx.path_extents()
            width = path_rect[2]-path_rect[0]
            height = path_rect[3]-path_rect[1]
            x1 = path_rect[0] + x1 * width
            x2 = path_rect[0] + x2 * width
            y1 = path_rect[1] + y1 * height
            y2 = path_rect[1] + y2 * height

        gradient = cairo.LinearGradient(x1, y1, x2, y2)

        gradient.set_extend(spread_methods.get(spreadMethod, cairo.EXTEND_NONE))

        for stop in stops:
            # FIXME: the stops are possibly being generated wrong if the offset is specified
            if stop.size == 10:
                start = tuple(stop[0:5])
                end = tuple(stop[5:10])
                gradient.add_color_stop_rgba(*start)
                gradient.add_color_stop_rgba(*end)
            else:
                start = tuple(stop[0:5])
                gradient.add_color_stop_rgba(*start)

        self.state.has_gradient = True
        self._ctx.set_source(gradient)


    #----------------------------------------------------------------
    # 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):
        """ Clears the current drawing path and begin a new one.
        """
        # Need to check here if the current subpath contains matrix
        # transforms.  If  it does, pull these out, and stick them
        # in the new subpath.
        self._ctx.new_path()

    def move_to(self,x,y):
        """ Starts a new drawing subpath and place the current point at (x,y).

            Notes:
                Not sure how to treat state.current_point.  Should it be the
                value of the point before or after the matrix transformation?
                It looks like before in the PDF specs.
        """
        self._ctx.move_to(x,y)

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

            The current point is moved to (x,y).

            What should happen if move_to hasn't been called? Should it always
            begin at 0,0 or raise an error?

            Notes:
                See note in move_to about the current_point.
        """
        self._ctx.line_to(x,y)

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

            Parameters
            ----------

            points
                an Nx2 array of x,y pairs

            The current_point is moved to the last point in 'points'
        """
        self._ctx.new_sub_path()
        for point in points:
            self._ctx.line_to(*point)

    def line_set(self, starts, ends):
        """ Adds a set of disjoint lines as a new subpath.

            Parameters
            ----------
            starts
                an Nx2 array of x,y pairs
            ends
                an Nx2 array of x,y pairs

            Starts and ends should have the same length.
            The current point is moved to the last point in 'ends'.

            N.B. Cairo cannot make disjointed lines as a single subpath,
            thus each line forms it's own subpath
        """
        for start, end in izip(starts, ends):
            self._ctx.move_to(*start)
            self._ctx.line_to(*end)

    def rect(self,x,y,sx,sy):
        """ Adds a rectangle as a new subpath.
        """
        self._ctx.rectangle(x,y,sx,sy)

#    def draw_rect(self, rect, mode):
#        self.rect(*rect)
#        self.draw_path(mode=mode)
#
#    def rects(self,rects):
#        """ Adds multiple rectangles as separate subpaths to the path.
#
#            Not very efficient -- calls rect multiple times.
#        """
#        for x,y,sx,sy in rects:
#            self.rect(x,y,sx,sy)

    def close_path(self,tag=None):
        """ Closes the path of the current subpath.

            Currently starts a new subpath -- is this what we want?
            ... Cairo starts a new subpath automatically.
        """
        self._ctx.close_path()

    def curve_to(self, x_ctrl1, y_ctrl1, x_ctrl2, y_ctrl2, x_to, y_to):
        """ Draw a cubic bezier curve from the current point.

        Parameters
        ----------
        x_ctrl1 : float
            X-value of the first control point.
        y_ctrl1 : float
            Y-value of the first control point.
        x_ctrl2 : float
            X-value of the second control point.
        y_ctrl2 : float
            Y-value of the second control point.
        x_to : float
            X-value of the ending point of the curve.
        y_to : float
            Y-value of the ending point of the curve.
        """
        self._ctx.curve_to(x_ctrl1, y_ctrl1, x_ctrl2, y_ctrl2, x_to, y_to)

#    def quad_curve_to(self, x_ctrl, y_ctrl, x_to, y_to):
#        """ Draw a quadratic bezier curve from the current point.
#
#        Parameters
#        ----------
#        x_ctrl : float
#            X-value of the control point
#        y_ctrl : float
#            Y-value of the control point.
#        x_to : float
#            X-value of the ending point of the curve
#        y_to : float
#            Y-value of the ending point of the curve.
#        """
#        # A quadratic Bezier curve is just a special case of the cubic. Reuse
#        # its implementation in case it has been implemented for the specific
#        # backend.
#        x0, y0 = self.state.current_point
#        xc1 = (x0 + x_ctrl + x_ctrl) / 3.0
#        yc1 = (y0 + y_ctrl + y_ctrl) / 3.0
#        xc2 = (x_to + x_ctrl + x_ctrl) / 3.0
#        yc2 = (y_to + y_ctrl + y_ctrl) / 3.0
#        self.curve_to(xc1, yc1, xc2, yc2, x_to, y_to)

    def arc(self, x, y, radius, start_angle, end_angle, cw=False):
        """ Draw a circular arc.

        If there is a current path and the current point is not the initial
        point of the arc, a line will be drawn to the start of the arc. If there
        is no current path, then no line will be drawn.

        Parameters
        ----------
        x : float
            X-value of the center of the arc.
        y : float
            Y-value of the center of the arc.
        radius : float
            The radius of the arc.
        start_angle : float
            The angle, in radians, that the starting point makes with respect
            to the positive X-axis from the center point.
        end_angle : float
            The angles, in radians, that the final point makes with
            respect to the positive X-axis from the center point.
        cw : bool, optional
            Whether the arc should be drawn clockwise or not.
        """
        if cw: #not sure if I've got this the right way round
            self._ctx.arc_negative( x, y, radius, start_angle, end_angle)
        else:
            self._ctx.arc( x, y, radius, start_angle, end_angle)

    def arc_to(self, x1, y1, x2, y2, radius):
        """ Draw an arc between the line segments from the current point
            to (x1,y1) and from (x1,y1) to (x2,y2). Straight lines are also
            added from the current point to the start of the curve and from the
            end of the curve to (x2,y2).
        """
        current_point = self.get_path_current_point()

        # Get the endpoints on the curve where it touches the line segments
        t1, t2 = arc_to_tangent_points(current_point, (x1,y1), (x2,y2), radius)

        # draw!
        self._ctx.line_to(*t1)
        self._ctx.curve_to(x1,y1, x1,y1, *t2)
        self._ctx.line_to(x2,y2)

    #----------------------------------------------------------------
    # Getting infomration on paths
    #----------------------------------------------------------------

    def is_path_empty(self):
        """ Tests to see whether the current drawing path is empty

        What does 'empty' mean???
        """
        p = self._ctx.copy_path()
        return any(a[0] for a in p)

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

            Note:
                Currently the current_point is only affected by move_to,
                line_to, and lines.  It should also be affected by text
                operations.  I'm not sure how rect and rects and friends
                should affect it -- will find out on Mac.
        """
        return self._ctx.get_current_point()

    def get_path_bounding_box(self):
        """
        cairo.Context.path_extents not yet implemented on my cairo version.
        It's in new ones though.

        What should this method return?
        """
        if self.is_path_empty():
            return [[0,0],[0,0]]
        p = [a[1] for a in self._ctx.copy_path()]
        p = numpy.array(p)
        return [p.min(axis=1), p.max(axis=1)]


    def add_path(self, path):
        """Draw a compiled path into this gc.
        In this case, a compiled path is a Cairo.Path"""
        if isinstance(path, CompiledPath):
            self.begin_path()
            for op_name, op_args in path.state:
                op = getattr(self, op_name)
                op(*op_args)
            self.close_path()



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

    def clip(self):
        """
        Should this use clip or clip_preserve
        """
        fr = self._ctx.get_fill_rule()
        self._ctx.set_fill_rule(cairo.FILL_RULE_WINDING)
        self._ctx.clip()
        self._ctx.set_fill_rule(fr)

    def even_odd_clip(self):
        """
        """
        fr = self._ctx.get_fill_rule()
        self._ctx.set_fill_rule(cairo.FILL_RULE_EVEN_ODD)
        self._ctx.clip()
        self._ctx.set_fill_rule(fr)


    def clip_to_rect(self,x,y,width,height):
        """
            Sets the clipping path to the intersection of the current clipping
            path with the area defined by the specified rectangle
        """
        ctx = self._ctx
        #get the current path
        p = ctx.copy_path()
        ctx.new_path()
        ctx.rectangle(x,y,width,height)
        ctx.clip()
        ctx.append_path(p)

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

    def clear_clip_path(self):
        self._ctx.reset_clip()

    #----------------------------------------------------------------
    # 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):
    #    """
    #    """
    #    pass

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

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

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

    def _set_source_color(self, color):
        if len(color) == 3:
            self._ctx.set_source_rgb(*color)
        else:
            self._ctx.set_source_rgba(*color)
        # gradients or other source patterns are blown away by set_source_rgb*
        self.state.has_gradient = False

    def set_fill_color(self,color):
        """
            set_fill_color takes a sequences of rgb or rgba values
            between 0.0 and 1.0
        """
        self.state.fill_color = color

    def set_stroke_color(self,color):
        """
            set_stroke_color takes a sequences of rgb or rgba values
            between 0.0 and 1.0
        """
        self.state.stroke_color = color

    def set_alpha(self,alpha):
        """
        """
        self.state.alpha = alpha

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

    def draw_image(self,img,rect=None):
        """
        img is either a N*M*3 or N*M*4 numpy array, or a Kiva image

        rect - what is this? assume it's a tuple (x,y, w, h)
        Only works with numpy arrays. What is a "Kiva Image" anyway?
        Not Yet Tested.
        """
        from kiva import agg

        if type(img) == type(numpy.array([])):
            # Numeric array
            if img.shape[2]==3:
                format = cairo.FORMAT_RGB24
            elif img.shape[2]==4:
                format = cairo.FORMAT_ARGB32
            img_width, img_height = img.shape[:2]
            img_surface = cairo.ImageSurface.create_for_data(img.astype(numpy.uint8),
                                                             format, img_width, img_height)
        elif isinstance(img, agg.GraphicsContextArray):
            converted_img = img.convert_pixel_format('rgba32', inplace=0)
            flipped_array = numpy.flipud(converted_img.bmp_array)
            img_width, img_height = converted_img.width(), converted_img.height()
            img_surface = cairo.ImageSurface.create_for_data(flipped_array.flatten(),
                                                             cairo.FORMAT_RGB24,
                                                             img_width, img_height)
        elif isinstance(img, GraphicsContext):
            # Another cairo kiva context
            img_width, img_height = img.pixel_map.width, img.pixel_map.height
            img_surface = cairo.ImageSurface.create_for_data(img.pixel_map.convert_to_argbarray(flip=True),
                                                             cairo.FORMAT_ARGB32,
                                                             img_width, img_height)
        else:
            warnings.warn("Cannot render image of type '%r' into cairo context." % \
                    type(img))
            return

        ctx = self._ctx
        img_pattern = cairo.SurfacePattern(img_surface)
        if rect:
            x,y,sx,sy = rect
            if sx != img_width or sy != img_height:
                scaler = cairo.Matrix()
                scaler.scale(img_width/float(sx), img_height/float(sy))
                img_pattern.set_matrix(scaler)
                img_pattern.set_filter(cairo.FILTER_BEST)
            ctx.set_source(img_pattern)
            #p = ctx.copy_path() #need to save the path
            ctx.new_path()
            ctx.rectangle(x,y,sx,sy)
            ctx.fill()
        else:
            ctx.set_source(img_pattern)
            ctx.paint()


    #-------------------------------------------------------------------------
    # Drawing Text
    #
    # Font handling needs more attention.
    #
    #-------------------------------------------------------------------------

    def select_font(self,face_name,size=12,style="regular",encoding=None):
        """ Selects a new font for drawing text.

            Parameters
            ----------

            face_name
                The name of a font. E.g.: "Times New Roman"
                !! Need to specify a way to check for all the types
                size
                The font size in points.
            style
                One of "regular", "bold", "italic", "bold italic"
            encoding
                A 4 letter encoding name. Common ones are:

                    * "unic" -- unicode
                    * "armn" -- apple roman
                    * "symb" -- symbol

                 Not all fonts support all encodings.  If none is
                 specified, fonts that have unicode encodings
                 default to unicode.  Symbol is the second choice.
                 If neither are available, the encoding defaults
                 to the first one returned in the FreeType charmap
                 list for the font face.
        """
        # !! should check if name and encoding are valid.
        # self.state.font = freetype.FontInfo(face_name,size,style,encoding)
        self._ctx.select_font_face(face_name, font_slant[style], font_weight[style])
        self._ctx.set_font_size(size)


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

            A device-specific font object. In this case, a cairo FontFace object.
            It's not clear how this can be used right now.
        """
        if font.weight in (constants.BOLD, constants.BOLD_ITALIC):
            weight = cairo.FONT_WEIGHT_BOLD
        else:
            weight = cairo.FONT_WEIGHT_NORMAL

        if font.style in (constants.ITALIC, constants.BOLD_ITALIC):
            style = cairo.FONT_SLANT_ITALIC
        else:
            style = cairo.FONT_SLANT_NORMAL

        face_name = font.face_name

        ctx = self._ctx
        ctx.select_font_face(face_name, style, weight)
        ctx.set_font_size(font.size)
        #facename = font.face_name
        #slant = font.style

        #self._ctx.set_font_face(font)

    def set_font_size(self,size):
        """ Sets the size of the font.

            The size is specified in user space coordinates.
        """
        self._ctx.set_font_size(size)

    def set_character_spacing(self,spacing):
        """ Sets the amount of additional spacing between text characters.

            Parameters
            ----------

            spacing : float
                units of space extra space to add between
                text coordinates.  It is specified in text coordinate
                system.

            Notes
            -----
            1.  I'm assuming this is horizontal spacing?
            2.  Not implemented in wxPython, or cairo (for the time being)
        """
        self.state.character_spacing = spacing


    def set_text_drawing_mode(self, mode):
        """ Specifies whether text is drawn filled or outlined or both.

            Parameters
            ----------

            mode
                determines how text is drawn to the screen.  If
                a CLIP flag is set, the font outline is added to the
                clipping path. Possible values:

                    TEXT_FILL
                        fill the text
                    TEXT_STROKE
                        paint the outline
                    TEXT_FILL_STROKE
                        fill and outline
                    TEXT_INVISIBLE
                        paint it invisibly ??
                    TEXT_FILL_CLIP
                        fill and add outline clipping path
                    TEXT_STROKE_CLIP
                        outline and add outline to clipping path
                    TEXT_FILL_STROKE_CLIP
                        fill, outline, and add to clipping path
                    TEXT_CLIP
                        add text outline to clipping path

            Note:
                wxPython currently ignores all but the INVISIBLE flag.
        """
        if mode not in (TEXT_FILL, TEXT_STROKE, TEXT_FILL_STROKE,
                        TEXT_INVISIBLE, TEXT_FILL_CLIP, TEXT_STROKE_CLIP,
                        TEXT_FILL_STROKE_CLIP, TEXT_CLIP, TEXT_OUTLINE):
            msg = "Invalid text drawing mode.  See documentation for valid modes"
            raise ValueError, msg
        self.state.text_drawing_mode = mode

    def set_text_position(self,x,y):
        """
        """
        m = list(self.text_matrix)
        m[4:6] = x,y
        self.text_matrix = cairo.Matrix(*m)

    def get_text_position(self):
        """
        """
        return tuple(self.text_matrix)[4:6]

    def set_text_matrix(self,ttm):
        """
        """
        if isinstance(ttm, cairo.Matrix):
            m = ttm
        else:
            m = cairo.Matrix(ttm)
        self.text_matrix = m

    def get_text_matrix(self):
        """
        """
        return copy.copy(self.text_matrix)

    def show_text(self,text, point=(0.0,0.0)):
        """ Draws text on the device at the current text position.
            Leaves the current point unchanged.
        """
        self.show_text_at_point(text, point[0], point[1])

    def show_glyphs(self):
        """
        """
        pass

    def show_text_at_point(self, text, x, y):
        """
        """
        ctx = self._ctx
        #print text, list(ctx.get_matrix())
        cur_path = ctx.copy_path()
        ctx.save()
        ctx.transform(self.text_matrix)
        ctx.transform(cairo.Matrix(1,0,0,1,x,y))
        ctx.new_path()
        ctx.text_path(text)
        #need to set up text drawing mode
        #'outline' and  'invisible' modes are not supported.
        mode = self.state.text_drawing_mode
        if mode in text_draw_modes['STROKE']:
            self._set_source_color(self.state.stroke_color)
            ctx.stroke_preserve()
        if mode in text_draw_modes['FILL']:
            self._set_source_color(self.state.fill_color)
            ctx.fill_preserve()
        if mode in text_draw_modes['CLIP']:
            ctx.clip_preserve()

        ctx.restore()
        ctx.new_path()
        ctx.append_path(cur_path)

    def show_glyphs_at_point(self):
        """
        """
        pass

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

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

            Each subpath is drawn separately.

            Parameters
            ----------
            mode
                Specifies how the subpaths are drawn.  The default is
                FILL_STROKE.  The following are valid values.

                    FILL
                        Paint the path using the nonzero winding rule
                        to determine the regions for painting.
                    EOF_FILL
                        Paint the path using the even-odd fill rule.
                    STROKE
                        Draw the outline of the path with the
                        current width, end caps, etc settings.
                    FILL_STROKE
                        First fill the path using the nonzero
                        winding rule, then stroke the path.
                    EOF_FILL_STROKE
                        First fill the path using the even-odd
                        fill method, then stroke the path.
        """
        ctx = self._ctx
        fr = ctx.get_fill_rule()
        if mode in [constants.EOF_FILL, constants.EOF_FILL_STROKE]:
            ctx.set_fill_rule(cairo.FILL_RULE_EVEN_ODD)
        else:
            ctx.set_fill_rule(cairo.FILL_RULE_WINDING)

        if mode in [constants.FILL, constants.EOF_FILL]:
            if not self.state.has_gradient:
                self._set_source_color(self.state.fill_color)
            ctx.fill()
        elif mode == constants.STROKE:
            if not self.state.has_gradient:
                self._set_source_color(self.state.stroke_color)
            ctx.stroke()
        elif mode in [constants.FILL_STROKE, constants.EOF_FILL_STROKE]:
            if not self.state.has_gradient:
                self._set_source_color(self.state.fill_color)
            ctx.fill_preserve()
            if not self.state.has_gradient:
                self._set_source_color(self.state.stroke_color)
            ctx.stroke()

        ctx.set_fill_rule(fr)

    def stroke_rect(self):
        """
        How does this affect the current path?
        """
        pass

    def stroke_rect_with_width(self):
        """
        """
        pass

    def fill_rect(self):
        """
        """
        pass

    def fill_rects(self):
        """
        """
        pass

    def clear_rect(self):
        """
        """
        pass

    def get_text_extent(self,textstring):
        """
            returns the width and height of the rendered text
        """
        xb, yb, w, h, xa, ya = self._ctx.text_extents(textstring)
        return xb, yb, w, h

    def get_full_text_extent(self,textstring):
        """
            How does this differ from 'get_text_extent' ???

            This just calls get_text_extent, for the time being.
        """
        x,y,w,h = self.get_text_extent(textstring)
        ascent, descent, height, maxx, maxy = self._ctx.font_extents()
        return w, ascent+descent, -descent, height

    def render_component(self, component, container_coords=False):
        """ Renders the given component.

        Parameters
        ----------
        component : Component
            The component to be rendered.
        container_coords : Boolean
            Whether to use coordinates of the component's container

        Description
        -----------
        If *container_coords* is False, then the (0,0) coordinate of this
        graphics context corresponds to the lower-left corner of the
        component's **outer_bounds**. If *container_coords* is True, then the
        method draws the component as it appears inside its container, i.e., it
        treats (0,0) of the graphics context as the lower-left corner of the
        container's outer bounds.
        """

        x, y = component.outer_position
        w, h = component.outer_bounds
        if not container_coords:
            x = -x
            y = -y
        self.translate_ctm(x, y)
        component.draw(self, view_bounds=(0, 0, w, h))
        return

    def save(self, filename, file_format=None):
        """ Save the GraphicsContext to a (PNG) file.
            file_format is ignored.
        """
        self.surface.flush()
        self.surface.write_to_png(filename)


class CompiledPath(object):

    def __init__(self):
        self.state = []

    def add_path(self, *args):
        self.state.append(('begin_path', args))

    def rect(self, *args):
        self.state.append(('rect', args))

    def move_to(self, *args):
        self.state.append(('move_to', args))

    def line_to(self, *args):
        self.state.append(('line_to', args))

    def close_path(self, *args):
        self.state.append(('close_path', args))

    def quad_curve_to(self, *args):
        self.state.append(('quad_curve_to', args))

    def curve_to(self, *args):
        self.state.append(('curve_to', args))

    def arc(self, *args):
        self.state.append(('arc', args))

    def total_vertices(self):
        return len(self.state) + 1

    def vertex(self, index):
        return (self.state[index-1][1][0:2],)


def font_metrics_provider():
    return GraphicsContext((1,1))

if __name__=="__main__":
    from numpy import fabs, linspace, pi, sin
    from scipy.special import jn

    from traits.api import false
    from chaco.api import ArrayPlotData, Plot, PlotGraphicsContext
    from chaco.example_support import COLOR_PALETTE

    from itertools import cycle, izip

    DPI = 72.0
    dpi_scale = DPI / 72.0

    def create_plot():
        numpoints = 100
        low = -5
        high = 15.0
        x = linspace(low, high, numpoints)
        pd = ArrayPlotData(index=x)
        p = Plot(pd, bgcolor="lightgray", padding=50, border_visible=True)
        for t,i in izip(cycle(['line','scatter']),range(10)):
            pd.set_data("y" + str(i), jn(i,x))
            p.plot(("index", "y" + str(i)), color=tuple(COLOR_PALETTE[i]),
                   width = 2.0 * dpi_scale, type=t)
        p.x_grid.visible = True
        p.x_grid.line_width *= dpi_scale
        p.y_grid.visible = True
        p.y_grid.line_width *= dpi_scale
        p.legend.visible = True
        return p

    container = create_plot()
    container.outer_bounds = [800,600]
    container.do_layout(force=True)

    def render_cairo_png():
        w,h = 800,600
        scale = 1.0
        s = cairo.ImageSurface(cairo.FORMAT_ARGB32, int(w*scale),int(h*scale))
        s.set_device_offset(0,h*scale)
        ctx = cairo.Context(s)
        ctx.set_source_rgb(1,1,1)
        ctx.paint()
        ctx.scale(1,-1)
        ctx.scale(scale,scale)
        gc = GraphicsContext((w,h), context=ctx)
        gc.render_component(container)
        s.flush()
        s.write_to_png("/tmp/kiva_cairo.png")

    def render_cairo_svg():
        w,h = 800,600
        scale = 1.0
        s = cairo.SVGSurface("/tmp/kiva_cairo.svg", w*scale,h*scale)
        s.set_device_offset(0,h*scale)
        ctx = cairo.Context(s)
        ctx.set_source_rgb(1,1,1)
        ctx.paint()
        ctx.scale(1,-1)
        ctx.scale(scale,scale)
        gc = GraphicsContext((w,h), context=ctx)
        gc.render_component(container)
        s.finish()

    def render_cairo_pdf():
        w,h = 800,600
        scale = 1.0
        s = cairo.PDFSurface("/tmp/kiva_cairo.pdf", w*scale,h*scale)
        s.set_device_offset(0,h*scale)
        ctx = cairo.Context(s)
        ctx.set_source_rgb(1,1,1)
        ctx.paint()
        ctx.scale(1,-1)
        ctx.scale(scale,scale)
        gc = GraphicsContext((w,h), context=ctx)
        gc.render_component(container)
        s.finish()

    def render_agg():
        gc2 = PlotGraphicsContext((800,600), dpi=DPI)
        gc2.render_component(container)
        gc2.save("/tmp/kiva_agg.png")

    #render_agg()
    render_cairo_png()
    render_cairo_svg()
    render_cairo_pdf()
    render_agg()