summaryrefslogtreecommitdiff
path: root/src/cairo-svg-surface.c
blob: 2240f24aadbacd9190056941fd1f70736b78dc80 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
/* cairo - a vector graphics library with display and print output
 *
 * Copyright © 2004 Red Hat, Inc
 * Copyright © 2005-2006 Emmanuel Pacaud <emmanuel.pacaud@free.fr>
 *
 * This library is free software; you can redistribute it and/or
 * modify it either under the terms of the GNU Lesser General Public
 * License version 2.1 as published by the Free Software Foundation
 * (the "LGPL") or, at your option, under the terms of the Mozilla
 * Public License Version 1.1 (the "MPL"). If you do not alter this
 * notice, a recipient may use your version of this file under either
 * the MPL or the LGPL.
 *
 * You should have received a copy of the LGPL along with this library
 * in the file COPYING-LGPL-2.1; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
 * You should have received a copy of the MPL along with this library
 * in the file COPYING-MPL-1.1
 *
 * The contents of this file are subject to the Mozilla Public License
 * Version 1.1 (the "License"); you may not use this file except in
 * compliance with the License. You may obtain a copy of the License at
 * http://www.mozilla.org/MPL/
 *
 * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY
 * OF ANY KIND, either express or implied. See the LGPL or the MPL for
 * the specific language governing rights and limitations.
 *
 * The Original Code is the cairo graphics library.
 *
 * The Initial Developer of the Original Code is University of Southern
 * California.
 *
 * Contributor(s):
 *	Kristian Høgsberg <krh@redhat.com>
 * 	Emmanuel Pacaud <emmanuel.pacaud@univ-poitiers.fr>
 */

#include "cairoint.h"
#include "cairo-svg.h"
#include "cairo-path-fixed-private.h"
#include "cairo-ft-private.h"
#include "cairo-meta-surface-private.h"
#include "cairo-paginated-surface-private.h"

#include <libxml/tree.h>

#define CC2XML(s) ((const xmlChar *)(s))
#define C2XML(s) ((xmlChar *)(s))

#define CAIRO_SVG_DTOSTR_BUFFER_LEN 30

#define CAIRO_SVG_DEFAULT_DPI 300

typedef enum {
    CAIRO_SVG_VERSION_1_1,
    CAIRO_SVG_VERSION_1_2
} cairo_svg_version_t;

typedef struct cairo_svg_document cairo_svg_document_t;
typedef struct cairo_svg_surface cairo_svg_surface_t;

struct cairo_svg_document {
    cairo_output_stream_t *output_stream;
    unsigned long refcount;
    cairo_surface_t *owner;
    cairo_bool_t finished;

    double width;
    double height;
    double x_dpi;
    double y_dpi;

    xmlDocPtr	xml_doc;
    xmlNodePtr	xml_node_defs;
    xmlNodePtr  xml_node_main;

    unsigned int surface_id;
    unsigned int linear_pattern_id;
    unsigned int radial_pattern_id;
    unsigned int pattern_id;
    unsigned int filter_id;
    unsigned int clip_id;
    unsigned int mask_id;

    cairo_bool_t alpha_filter;

    cairo_array_t pattern_snapshots;

    cairo_svg_version_t svg_version;
};

struct cairo_svg_surface {
    cairo_surface_t base;

    cairo_content_t content;

    unsigned int id;

    double width;
    double height;

    cairo_svg_document_t *document;

    xmlNodePtr  xml_node;
    xmlNodePtr  xml_root_node;

    unsigned int clip_level;

    cairo_paginated_mode_t paginated_mode;
};

static cairo_svg_document_t *
_cairo_svg_document_create (cairo_output_stream_t	*stream,
			    double			width,
			    double			height);

static void
_cairo_svg_document_destroy (cairo_svg_document_t *document);

static cairo_status_t
_cairo_svg_document_finish (cairo_svg_document_t *document);

static void
_cairo_svg_document_reference (cairo_svg_document_t *document);

static cairo_surface_t *
_cairo_svg_surface_create_for_document (cairo_svg_document_t	*document,
					cairo_content_t		 content,
					double			 width,
					double			 height);

static void
_cairo_svg_set_paginated_mode (cairo_surface_t *target,
			       cairo_paginated_mode_t mode);

static const cairo_surface_backend_t cairo_svg_surface_backend;

static cairo_surface_t *
_cairo_svg_surface_create_for_stream_internal (cairo_output_stream_t	*stream,
					       double			width,
					       double			height)
{
    cairo_svg_document_t *document;
    cairo_surface_t *surface;

    document = _cairo_svg_document_create (stream, width, height);
    if (document == NULL) {
	_cairo_error (CAIRO_STATUS_NO_MEMORY);
	return (cairo_surface_t *) &_cairo_surface_nil;
    }

    surface = _cairo_svg_surface_create_for_document (document, CAIRO_CONTENT_COLOR_ALPHA, 
						      width, height);

    document->owner = surface;
    _cairo_svg_document_destroy (document);

    return _cairo_paginated_surface_create (surface,
					    CAIRO_CONTENT_COLOR_ALPHA,
					    width, height,
					    _cairo_svg_set_paginated_mode);
}

/**
 * cairo_svg_surface_create_for_stream:
 * @write: a #cairo_write_func_t to accept the output data
 * @closure: the closure argument for @write
 * @width_in_points: width of the surface, in points (1 point == 1/72.0 inch)
 * @height_in_points: height of the surface, in points (1 point == 1/72.0 inch)
 * 
 * Creates a SVG surface of the specified size in points to be written
 * incrementally to the stream represented by @write and @closure.
 *
 * Return value: a pointer to the newly created surface. The caller
 * owns the surface and should call cairo_surface_destroy when done
 * with it.
 *
 * This function always returns a valid pointer, but it will return a
 * pointer to a "nil" surface if an error such as out of memory
 * occurs. You can use cairo_surface_status() to check for this.
 */
cairo_surface_t *
cairo_svg_surface_create_for_stream (cairo_write_func_t		write,
				     void			*closure,
				     double			width,
				     double			height)
{
    cairo_status_t status;
    cairo_output_stream_t *stream;

    stream = _cairo_output_stream_create (write, NULL, closure);
    status = _cairo_output_stream_get_status (stream);
    if (status) {
	_cairo_error (status);
	return (cairo_surface_t *) &_cairo_surface_nil;
    }

    return _cairo_svg_surface_create_for_stream_internal (stream, width, height);
}

/**
 * cairo_svg_surface_create:
 * @filename: a filename for the SVG output (must be writable)
 * @width_in_points: width of the surface, in points (1 point == 1/72.0 inch)
 * @height_in_points: height of the surface, in points (1 point == 1/72.0 inch)
 * 
 * Creates a SVG surface of the specified size in points to be written
 * to @filename.
 * 
 * Return value: a pointer to the newly created surface. The caller
 * owns the surface and should call cairo_surface_destroy when done
 * with it.
 *
 * This function always returns a valid pointer, but it will return a
 * pointer to a "nil" surface if an error such as out of memory
 * occurs. You can use cairo_surface_status() to check for this.
 **/
cairo_surface_t *
cairo_svg_surface_create (const char	*filename,
			  double	width,
			  double	height)
{
    cairo_status_t status;
    cairo_output_stream_t *stream;

    stream = _cairo_output_stream_create_for_filename (filename);
    status = _cairo_output_stream_get_status (stream);
    if (status) {
	_cairo_error (status);
	return (cairo_surface_t *) &_cairo_surface_nil;
    }

    return _cairo_svg_surface_create_for_stream_internal (stream, width, height);
}

static cairo_bool_t
_cairo_surface_is_svg (cairo_surface_t *surface)
{
    return surface->backend == &cairo_svg_surface_backend;
}

/**
 * cairo_svg_surface_set_dpi:
 * @surface: a svg cairo_surface_t
 * @x_dpi: horizontal dpi
 * @y_dpi: vertical dpi
 * 
 * Set the horizontal and vertical resolution for image fallbacks.
 * When the svg backend needs to fall back to image overlays, it will
 * use this resolution. These DPI values are not used for any other
 * purpose, (in particular, they do not have any bearing on the size
 * passed to cairo_pdf_surface_create() nor on the CTM).
 **/

void
cairo_svg_surface_set_dpi (cairo_surface_t	*surface,
			   double		x_dpi,
			   double		y_dpi)
{
    cairo_surface_t *target;
    cairo_svg_surface_t *svg_surface;

    if (!_cairo_surface_is_paginated (surface)) {
	_cairo_error (CAIRO_STATUS_SURFACE_TYPE_MISMATCH);
	return;
    }

    target = _cairo_paginated_surface_get_target (surface);

    if (!_cairo_surface_is_svg (target)) {
	_cairo_error (CAIRO_STATUS_SURFACE_TYPE_MISMATCH);
	return;
    }

    svg_surface = (cairo_svg_surface_t *) target;

    svg_surface->document->x_dpi = x_dpi;    
    svg_surface->document->y_dpi = y_dpi;    
}

static cairo_surface_t *
_cairo_svg_surface_create_for_document (cairo_svg_document_t	*document,
					cairo_content_t		 content,
					double			 width,
					double			 height)
{
    cairo_svg_surface_t *surface;
    xmlNodePtr clip, rect;
    int clip_id;
    char buffer[CAIRO_SVG_DTOSTR_BUFFER_LEN];

    surface = malloc (sizeof (cairo_svg_surface_t));
    if (surface == NULL)
	return NULL;

    _cairo_surface_init (&surface->base, &cairo_svg_surface_backend);

    surface->width = width;
    surface->height = height;

    _cairo_svg_document_reference (document);
    surface->document = document;

    surface->clip_level = 0;

    surface->id = document->surface_id++;
    clip_id = document->clip_id++;
    
    clip = xmlNewChild (document->xml_node_defs, NULL, CC2XML ("clipPath"), NULL);
    snprintf (buffer, sizeof buffer, "clip%d", clip_id);
    xmlSetProp (clip, CC2XML ("id"), C2XML (buffer));
    rect = xmlNewChild (clip, NULL, CC2XML ("rect"), NULL);
    _cairo_dtostr (buffer, sizeof buffer, width);
    xmlSetProp (rect, CC2XML ("width"), C2XML (buffer));
    _cairo_dtostr (buffer, sizeof buffer, height);
    xmlSetProp (rect, CC2XML ("height"), C2XML (buffer));
    
    surface->xml_node = xmlNewNode (NULL, CC2XML ("g"));
    surface->xml_root_node = surface->xml_node;
	
    snprintf (buffer, sizeof buffer, "surface%d", surface->id);
    xmlSetProp (surface->xml_node, CC2XML ("id"), C2XML (buffer));
    snprintf (buffer, sizeof buffer, "url(#clip%d)", clip_id);
    xmlSetProp (surface->xml_node, CC2XML ("clip-path"), C2XML (buffer));

    if (content == CAIRO_CONTENT_COLOR) {
	rect = xmlNewChild (surface->xml_node, NULL, CC2XML ("rect"), NULL);
	_cairo_dtostr (buffer, sizeof buffer, width);
	xmlSetProp (rect, CC2XML ("width"), C2XML (buffer));
	_cairo_dtostr (buffer, sizeof buffer, height);
	xmlSetProp (rect, CC2XML ("height"), C2XML (buffer));
	xmlSetProp (rect, CC2XML ("style"), CC2XML ("opacity:1; stroke:none; fill:rgb(0,0,0);"));
    }

    surface->content = content;

    surface->paginated_mode = CAIRO_PAGINATED_MODE_ANALYZE;
    
    return &surface->base;
}

static cairo_int_status_t
_operation_supported (cairo_svg_surface_t *surface,
		      cairo_operator_t op,
		      const cairo_pattern_t *pattern)
{
    cairo_svg_document_t *document = surface->document;
    
    if (document->svg_version < CAIRO_SVG_VERSION_1_2)
	if (op != CAIRO_OPERATOR_OVER)
	    return FALSE;

    return TRUE;
}

static cairo_int_status_t
_analyze_operation (cairo_svg_surface_t *surface,
		    cairo_operator_t op,
		    const cairo_pattern_t *pattern)
{
    if (_operation_supported (surface, op, pattern))
	return CAIRO_STATUS_SUCCESS;
    else
	return CAIRO_INT_STATUS_UNSUPPORTED;
}

static cairo_surface_t *
_cairo_svg_surface_create_similar (void			*abstract_src,
				   cairo_content_t	 content,
				   int			 width,
				   int			 height)
{
    return _cairo_meta_surface_create (content, width, height);
}

static cairo_status_t
_cairo_svg_surface_finish (void *abstract_surface)
{
    cairo_status_t status;
    cairo_svg_surface_t *surface = abstract_surface;
    cairo_svg_document_t *document = surface->document;
    
    if (document->owner == &surface->base) {
	xmlAddChild (document->xml_node_main, xmlCopyNode (surface->xml_root_node, 1));
	status = _cairo_svg_document_finish (document);
    } else
	status = CAIRO_STATUS_SUCCESS;

    _cairo_svg_document_destroy (document);

    xmlFreeNode (surface->xml_root_node);
    surface->xml_node = NULL;
    surface->xml_root_node = NULL;

    return status;
}

static void
emit_alpha_filter (cairo_svg_document_t *document)
{
    if (!document->alpha_filter) {
	xmlNodePtr node;
	xmlNodePtr child;

	node = xmlNewChild (document->xml_node_defs, NULL,
			    CC2XML ("filter"), NULL);
	xmlSetProp (node, CC2XML ("id"), CC2XML ("alpha"));
	xmlSetProp (node, CC2XML ("filterUnits"), CC2XML ("objectBoundingBox"));
	xmlSetProp (node, CC2XML ("x"), CC2XML ("0%"));
	xmlSetProp (node, CC2XML ("y"), CC2XML ("0%"));
	xmlSetProp (node, CC2XML ("width"), CC2XML ("100%"));
	xmlSetProp (node, CC2XML ("height"), CC2XML ("100%"));
	child = xmlNewChild (node, NULL, CC2XML ("feColorMatrix"), NULL);
	xmlSetProp (child, CC2XML("type"), CC2XML ("matrix"));
	xmlSetProp (child, CC2XML("in"), CC2XML ("SourceGraphic"));
	xmlSetProp (child, CC2XML("values"), CC2XML ("0 0 0 0 1 0 0 0 0 1 0 0 0 0 1 0 0 0 1 0")); 
	document->alpha_filter = TRUE;
    }
}

static void
emit_transform (xmlNodePtr node, 
		char const *attribute_str, 
		cairo_matrix_t *matrix)
{
    xmlBufferPtr matrix_buffer;
    char buffer[CAIRO_SVG_DTOSTR_BUFFER_LEN];
    
    matrix_buffer = xmlBufferCreate ();
    xmlBufferCat (matrix_buffer, CC2XML ("matrix("));
    _cairo_dtostr (buffer, sizeof buffer, matrix->xx);
    xmlBufferCat (matrix_buffer, C2XML (buffer));
    xmlBufferCat (matrix_buffer, CC2XML (","));
    _cairo_dtostr (buffer, sizeof buffer, matrix->yx);
    xmlBufferCat (matrix_buffer, C2XML (buffer));
    xmlBufferCat (matrix_buffer, CC2XML (","));
    _cairo_dtostr (buffer, sizeof buffer, matrix->xy);
    xmlBufferCat (matrix_buffer, C2XML (buffer));
    xmlBufferCat (matrix_buffer, CC2XML (","));
    _cairo_dtostr (buffer, sizeof buffer, matrix->yy);
    xmlBufferCat (matrix_buffer, C2XML (buffer));
    xmlBufferCat (matrix_buffer, CC2XML (","));
    _cairo_dtostr (buffer, sizeof buffer, matrix->x0);
    xmlBufferCat (matrix_buffer, C2XML (buffer));
    xmlBufferCat (matrix_buffer, CC2XML(","));
    _cairo_dtostr (buffer, sizeof buffer, matrix->y0);
    xmlBufferCat (matrix_buffer, C2XML (buffer));
    xmlBufferCat (matrix_buffer, CC2XML (")"));
    xmlSetProp (node, CC2XML (attribute_str), C2XML (xmlBufferContent (matrix_buffer)));
    xmlBufferFree (matrix_buffer);
}

typedef struct {
    xmlBufferPtr buffer;
    unsigned int in_mem;
    unsigned char src[3];
    unsigned char dst[5];
    unsigned int trailing;
} base64_write_closure_t;

static char const *base64_table =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";

static cairo_status_t
base64_write_func (void *closure, 
		   const unsigned char *data,
		   unsigned int length)
{
    base64_write_closure_t *info = (base64_write_closure_t *) closure;
    unsigned int i;
    unsigned char *src, *dst;

    dst = info->dst;
    src = info->src;

    if (info->in_mem + length < 3) {
	for (i = 0; i < length; i++) { 
	    src[i + info->in_mem] = *data;
	    data++;
	}
	info->in_mem += length;
	return CAIRO_STATUS_SUCCESS;
    }

    while (info->in_mem + length >= 3) {
	for (i = 0; i < 3 - info->in_mem; i++) {
	    src[i + info->in_mem] = *data;
	    data++;
	    length--;
	}
	dst[0] = base64_table[src[0] >> 2];
	dst[1] = base64_table[(src[0] & 0x03) << 4 | src[1] >> 4];
	dst[2] = base64_table[(src[1] & 0x0f) << 2 | src[2] >> 6];
	dst[3] = base64_table[src[2] & 0xfc >> 2];
	/* Special case for the last missing bits */
	switch (info->trailing) {
	    case 2:
		dst[2] = '=';
	    case 1:
		dst[3] = '=';
	    default:
		break;
	}
	xmlBufferCat (info->buffer, dst);
	info->in_mem = 0;
    }

    for (i = 0; i < length; i++) { 
	src[i] = *data;
	data++;
    }
    info->in_mem = length;

    return CAIRO_STATUS_SUCCESS;
}

static cairo_int_status_t
_cairo_surface_base64_encode (cairo_surface_t *surface,
			      xmlBufferPtr *buffer)
{
    cairo_status_t status;
    base64_write_closure_t info;
    unsigned int i;

    if (buffer == NULL)
	return CAIRO_STATUS_NULL_POINTER;
    
    info.buffer = xmlBufferCreate();
    info.in_mem = 0;
    info.trailing = 0;
    memset (info.dst, '\x0', 5);
    *buffer = info.buffer;

    xmlBufferCat (info.buffer, CC2XML ("data:image/png;base64,"));

    status = cairo_surface_write_to_png_stream (surface, base64_write_func, 
						(void *) &info);

    if (status) {
	xmlBufferFree (*buffer);
	*buffer = NULL;
	return status;
    }
    
    if (info.in_mem > 0) {
	for (i = info.in_mem; i < 3; i++)
	    info.src[i] = '\x0';
	info.trailing = 3 - info.in_mem;
	info.in_mem = 3;
	base64_write_func (&info, NULL, 0);
    }
    
    return CAIRO_STATUS_SUCCESS;
}

static xmlNodePtr
emit_composite_image_pattern (xmlNodePtr node,
			      cairo_surface_pattern_t *pattern,
			      double *width,
			      double *height,
			      cairo_bool_t is_pattern)
{
    cairo_surface_t *surface = pattern->surface;
    cairo_image_surface_t *image;
    cairo_status_t status;
    cairo_matrix_t p2u;
    xmlNodePtr child;
    xmlBufferPtr image_buffer;
    char buffer[CAIRO_SVG_DTOSTR_BUFFER_LEN];
    void *image_extra;

    status = _cairo_surface_acquire_source_image (surface, &image, &image_extra);
    if (status)
	return NULL;

    status = _cairo_surface_base64_encode (surface, &image_buffer);
    if (status)
	return NULL;

    child = xmlNewChild (node, NULL, CC2XML ("image"), NULL);
    _cairo_dtostr (buffer, sizeof buffer, image->width);
    xmlSetProp (child, CC2XML ("width"), C2XML (buffer));
    _cairo_dtostr (buffer, sizeof buffer, image->height);
    xmlSetProp (child, CC2XML ("height"), C2XML (buffer));
    xmlSetProp (child, CC2XML ("xlink:href"), C2XML (xmlBufferContent (image_buffer)));
		
    xmlBufferFree (image_buffer);

    if (!is_pattern) {
	p2u = pattern->base.matrix;
	cairo_matrix_invert (&p2u);
	emit_transform (child, "transform", &p2u);
    }

    if (width != NULL)
	    *width = image->width;
    if (height != NULL)
	    *height = image->height;

    _cairo_surface_release_source_image (pattern->surface, image, image_extra);

    return child;
}

typedef struct {
    unsigned int id;
    cairo_meta_surface_t *meta;
} pattern_snapshot_t;

static int
_emit_meta_surface_with_snapshot (cairo_svg_document_t *document,
				  cairo_meta_surface_t *surface)
{
    cairo_meta_surface_t *meta;
    pattern_snapshot_t *pattern_snapshot;
    int num_elements;
    unsigned int i, id;

    num_elements = document->pattern_snapshots.num_elements;
    for (i = 0; i < num_elements; i++) {
	pattern_snapshot = _cairo_array_index (&document->pattern_snapshots, i);
	meta = pattern_snapshot->meta;
	if (meta->commands.num_elements == surface->commands.num_elements &&
	    _cairo_array_index (&meta->commands, 0) == _cairo_array_index (&surface->commands, 0)) {
	    id = pattern_snapshot->id;
	    break;
	}
    }
    
    if (i >= num_elements) {
	cairo_surface_t *paginated_surface;
	cairo_surface_t *svg_surface;
	pattern_snapshot_t snapshot;
	xmlNodePtr child;

	meta = (cairo_meta_surface_t *) _cairo_surface_snapshot ((cairo_surface_t *)surface);
	svg_surface = _cairo_svg_surface_create_for_document (document,
							      meta->content,
							      meta->width_pixels, 
							      meta->height_pixels);
	paginated_surface = _cairo_paginated_surface_create (svg_surface,
							     meta->content,
							     meta->width_pixels, 
							     meta->height_pixels,
							     &cairo_svg_surface_paginated_backend);
	_cairo_meta_surface_replay ((cairo_surface_t *)meta, paginated_surface);
	_cairo_surface_show_page (paginated_surface);
	
	snapshot.meta = meta;
	snapshot.id = ((cairo_svg_surface_t *) svg_surface)->id;
	_cairo_array_append (&document->pattern_snapshots, &snapshot);
	
	if (meta->content == CAIRO_CONTENT_ALPHA) 
	    emit_alpha_filter (document);
	child = xmlAddChild (document->xml_node_defs, 
			     xmlCopyNode (((cairo_svg_surface_t *) svg_surface)->xml_root_node, 1));
	if (meta->content == CAIRO_CONTENT_ALPHA) 
	    xmlSetProp (child, CC2XML ("filter"), CC2XML("url(#alpha)"));

	id = snapshot.id;

	cairo_surface_destroy (paginated_surface);
    }

    return id;
}

static xmlNodePtr
emit_composite_meta_pattern (xmlNodePtr node, 
			     cairo_svg_surface_t	*surface,
			     cairo_surface_pattern_t	*pattern,
			     double *width, 
			     double *height,
			     cairo_bool_t is_pattern)
{
    cairo_svg_document_t *document = surface->document;
    cairo_meta_surface_t *meta_surface;
    cairo_matrix_t p2u;
    xmlNodePtr child;
    int id;
    char buffer[CAIRO_SVG_DTOSTR_BUFFER_LEN];

    meta_surface = (cairo_meta_surface_t *) pattern->surface;
    
    id = _emit_meta_surface_with_snapshot (document, meta_surface);
    
    child = xmlNewChild (node, NULL, CC2XML("use"), NULL);
    snprintf (buffer, sizeof buffer, "#surface%d", id);
    xmlSetProp (child, CC2XML ("xlink:href"), C2XML (buffer));

    if (!is_pattern) {
	p2u = pattern->base.matrix;
	cairo_matrix_invert (&p2u);
	emit_transform (child, "transform", &p2u);
    }

    if (width != NULL)
	    *width = meta_surface->width_pixels;
    if (height != NULL)
	    *height = meta_surface->height_pixels;

    return child;
}

static xmlNodePtr
emit_composite_pattern (xmlNodePtr node, 
			cairo_svg_surface_t	*surface,
			cairo_surface_pattern_t *pattern,
			double *width,
			double *height,
			int is_pattern)
{

    if (_cairo_surface_is_meta (pattern->surface)) { 
	return emit_composite_meta_pattern (node, surface, pattern, width, height, is_pattern);
    }

    return emit_composite_image_pattern (node, pattern, width, height, is_pattern);
}

/* FIXME: Here we use a SVG 1.2 feature. We should probably have
 * an API to limit output SVG version, and fallback to image when
 * necessary. */

static void
emit_operator (xmlNodePtr node, cairo_operator_t op)
{
    char const *op_str[] = {
	"clear",
	
	"src",		"src-over",	"src-in",
	"src-out",	"src-atop",
	
	"dst",		"dst-over",	"dst-in",
	"dst-out",	"dst-atop",	
	
	"xor", "plus",	
	"color-dodge"	/* FIXME: saturate ? */
    };

    xmlSetProp (node, CC2XML ("comp-op"), C2XML (op_str[op]));
}

static void
emit_color (cairo_color_t const *color, xmlBufferPtr style,
	    char const *color_str, char const *opacity_str)
{
    char buffer[CAIRO_SVG_DTOSTR_BUFFER_LEN];

    xmlBufferCat (style, CC2XML (color_str));
    xmlBufferCat (style, CC2XML (": rgb("));
    _cairo_dtostr (buffer, sizeof buffer, color->red * 100.0);
    xmlBufferCat (style, C2XML (buffer));
    xmlBufferCat (style, CC2XML ("%,"));
    _cairo_dtostr (buffer, sizeof buffer, color->green * 100.0);
    xmlBufferCat (style, C2XML (buffer));
    xmlBufferCat (style, CC2XML ("%,"));
    _cairo_dtostr (buffer, sizeof buffer, color->blue * 100.0);
    xmlBufferCat (style, C2XML (buffer));
    xmlBufferCat (style, CC2XML ("%); "));
    xmlBufferCat (style, CC2XML (opacity_str));
    xmlBufferCat (style, CC2XML (": "));
    _cairo_dtostr (buffer, sizeof buffer, color->alpha);
    xmlBufferCat (style, CC2XML (buffer));
    xmlBufferCat (style, CC2XML (";"));
}

static void
emit_solid_pattern (cairo_svg_surface_t *surface,
		    cairo_solid_pattern_t *pattern,
		    xmlBufferPtr style, int is_stroke)
{
    emit_color (&pattern->color, 
		style, is_stroke ? "stroke" : "fill", 
		"opacity");
}

static void
emit_surface_pattern (cairo_svg_surface_t *surface,
		      cairo_surface_pattern_t *pattern,
		      xmlBufferPtr style, int is_stroke)
{
    cairo_svg_document_t *document = surface->document;
    xmlNodePtr child;
    xmlBufferPtr id;
    cairo_matrix_t p2u;
    double width, height;
    char buffer[CAIRO_SVG_DTOSTR_BUFFER_LEN];
    
    child = xmlNewChild (document->xml_node_defs, NULL, CC2XML ("pattern"), NULL);
    
    id = xmlBufferCreate ();
    xmlBufferCat (id, CC2XML ("pattern"));
    snprintf (buffer, sizeof buffer, "%d", document->pattern_id);
    xmlBufferCat (id, C2XML (buffer));
    xmlSetProp (child, CC2XML ("id"), C2XML (xmlBufferContent (id)));

    xmlBufferCat (style, CC2XML (is_stroke ? "color: url(#" : "fill: url(#"));
    xmlBufferCat (style, xmlBufferContent (id));
    xmlBufferCat (style, CC2XML (");"));
    xmlBufferFree (id);

    document->pattern_id++;

    emit_composite_pattern (child, surface, pattern, &width, &height, TRUE);

    _cairo_dtostr (buffer, sizeof buffer, width);
    xmlSetProp (child, CC2XML ("width"), C2XML (buffer));
    _cairo_dtostr (buffer, sizeof buffer, height);
    xmlSetProp (child, CC2XML ("height"), C2XML (buffer));

    p2u = pattern->base.matrix;
    cairo_matrix_invert (&p2u);

    emit_transform (child, "patternTransform", &p2u);

    xmlSetProp (child, CC2XML ("patternUnits"), CC2XML ("userSpaceOnUse"));
}

static void 
emit_pattern_stops (xmlNodePtr parent,
		    cairo_gradient_pattern_t const *pattern, 
		    double start_offset)
{
    xmlNodePtr child;
    xmlBufferPtr style;
    char buffer[CAIRO_SVG_DTOSTR_BUFFER_LEN];
    cairo_color_t color;
    int i;

    for (i = 0; i < pattern->n_stops; i++) {
	child = xmlNewChild (parent, NULL, CC2XML ("stop"), NULL);
	_cairo_dtostr (buffer, sizeof buffer, 
		       start_offset + (1 - start_offset ) *
		       _cairo_fixed_to_double (pattern->stops[i].x));
	xmlSetProp (child, CC2XML ("offset"), C2XML (buffer));
	style = xmlBufferCreate ();
	_cairo_color_init_rgba (&color,
				pattern->stops[i].color.red   / 65535.0,
				pattern->stops[i].color.green / 65535.0,
				pattern->stops[i].color.blue  / 65535.0,
				pattern->stops[i].color.alpha / 65535.0);
	emit_color (&color, style, "stop-color", "stop-opacity");
	xmlSetProp (child, CC2XML ("style"), xmlBufferContent (style));
	xmlBufferFree (style);
    }
}

static void
emit_pattern_extend (xmlNodePtr node, cairo_extend_t extend)
{
    char const *value = NULL;

    switch (extend) {
	case CAIRO_EXTEND_REPEAT:
	    value = "repeat"; 
	    break;
	case CAIRO_EXTEND_REFLECT:
	    value = "reflect"; 
	    break;
	case CAIRO_EXTEND_NONE:
	    break;
	case CAIRO_EXTEND_PAD:
	    /* FIXME not implemented */
	    break;
    }
    
    if (value != NULL)
	xmlSetProp (node, CC2XML ("spreadMethod"), CC2XML (value));
}

static void
emit_linear_pattern (cairo_svg_surface_t *surface, 
		     cairo_linear_pattern_t *pattern,
		     xmlBufferPtr style, int is_stroke)
{
    cairo_svg_document_t *document = surface->document;
    xmlNodePtr child;
    xmlBufferPtr id;
    double x0, y0, x1, y1;
    cairo_matrix_t p2u;
    char buffer[CAIRO_SVG_DTOSTR_BUFFER_LEN];
    
    child = xmlNewChild (document->xml_node_defs, NULL, CC2XML ("linearGradient"), NULL);
    
    id = xmlBufferCreate ();
    xmlBufferCat (id, CC2XML ("linear"));
    snprintf (buffer, sizeof buffer, "%d", document->linear_pattern_id);
    xmlBufferCat (id, C2XML (buffer));
    xmlSetProp (child, CC2XML ("id"), C2XML (xmlBufferContent (id)));
    xmlSetProp (child, CC2XML ("gradientUnits"), CC2XML ("userSpaceOnUse"));
    emit_pattern_extend (child, pattern->base.base.extend);

    xmlBufferCat (style, CC2XML (is_stroke ? "color: url(#" : "fill: url(#"));
    xmlBufferCat (style, xmlBufferContent (id));
    xmlBufferCat (style, CC2XML (");"));

    xmlBufferFree (id);

    document->linear_pattern_id++;

    emit_pattern_stops (child ,&pattern->base, 0.0);

    x0 = _cairo_fixed_to_double (pattern->gradient.p1.x);
    y0 = _cairo_fixed_to_double (pattern->gradient.p1.y);
    x1 = _cairo_fixed_to_double (pattern->gradient.p2.x);
    y1 = _cairo_fixed_to_double (pattern->gradient.p2.y);
    
    _cairo_dtostr (buffer, sizeof buffer, x0);
    xmlSetProp (child, CC2XML ("x1"), C2XML (buffer));
    _cairo_dtostr (buffer, sizeof buffer, y0);
    xmlSetProp (child, CC2XML ("y1"), C2XML (buffer));
    _cairo_dtostr (buffer, sizeof buffer, x1);
    xmlSetProp (child, CC2XML ("x2"), C2XML (buffer));
    _cairo_dtostr (buffer, sizeof buffer, y1);
    xmlSetProp (child, CC2XML ("y2"), C2XML (buffer));
    
    p2u = pattern->base.base.matrix;
    cairo_matrix_invert (&p2u);

    emit_transform (child, "gradientTransform", &p2u);
}
	
static void
emit_radial_pattern (cairo_svg_surface_t *surface, 
		     cairo_radial_pattern_t *pattern,
		     xmlBufferPtr style, int is_stroke)
{
    cairo_svg_document_t *document = surface->document;
    cairo_matrix_t p2u;
    xmlNodePtr child;
    xmlBufferPtr id;
    double x0, y0, x1, y1, r0, r1;
    double fx, fy;
    char buffer[CAIRO_SVG_DTOSTR_BUFFER_LEN];
    
    child = xmlNewChild (document->xml_node_defs, NULL, CC2XML ("radialGradient"), NULL);
    
    id = xmlBufferCreate ();
    xmlBufferCat (id, CC2XML ("radial"));
    snprintf (buffer, sizeof buffer, "%d", document->radial_pattern_id);
    xmlBufferCat (id, C2XML (buffer));
    xmlSetProp (child, CC2XML ("id"), C2XML (xmlBufferContent (id)));
    xmlSetProp (child, CC2XML ("gradientUnits"), CC2XML ("userSpaceOnUse"));
    emit_pattern_extend (child, pattern->base.base.extend);
    
    xmlBufferCat (style, CC2XML (is_stroke ? "color: url(#" : "fill: url(#"));
    xmlBufferCat (style, xmlBufferContent (id));
    xmlBufferCat (style, CC2XML (");"));

    xmlBufferFree (id);

    document->radial_pattern_id++;

    x0 = _cairo_fixed_to_double (pattern->gradient.inner.x);
    y0 = _cairo_fixed_to_double (pattern->gradient.inner.y);
    r0 = _cairo_fixed_to_double (pattern->gradient.inner.radius);
    x1 = _cairo_fixed_to_double (pattern->gradient.outer.x);
    y1 = _cairo_fixed_to_double (pattern->gradient.outer.y);
    r1 = _cairo_fixed_to_double (pattern->gradient.outer.radius);

    /* SVG doesn't have a start radius, so computing now SVG focal coordinates
     * and emulating start radius by translating color stops.
     * FIXME: We also need to emulate cairo behaviour inside start circle when
     * extend != CAIRO_EXTEND_NONE.
     * FIXME: Handle radius1 <= radius0 */
    fx = (r1 * x0 - r0 * x1) / (r1 - r0);
    fy = (r1 * y0 - r0 * y1) / (r1 - r0);

    emit_pattern_stops (child, &pattern->base, r0 / r1);

    _cairo_dtostr (buffer, sizeof buffer, x1);
    xmlSetProp (child, CC2XML ("cx"), C2XML (buffer));
    _cairo_dtostr (buffer, sizeof buffer, y1);
    xmlSetProp (child, CC2XML ("cy"), C2XML (buffer));
    _cairo_dtostr (buffer, sizeof buffer, fx);
    xmlSetProp (child, CC2XML ("fx"), C2XML (buffer));
    _cairo_dtostr (buffer, sizeof buffer, fy);
    xmlSetProp (child, CC2XML ("fy"), C2XML (buffer));
    _cairo_dtostr (buffer, sizeof buffer, r1);
    xmlSetProp (child, CC2XML ("r"), C2XML (buffer));

    p2u = pattern->base.base.matrix;
    cairo_matrix_invert (&p2u);

    emit_transform (child, "gradientTransform", &p2u);
}
	
static void
emit_pattern (cairo_svg_surface_t *surface, cairo_pattern_t *pattern, 
	      xmlBufferPtr style, int is_stroke)
{
    switch (pattern->type) {
    case CAIRO_PATTERN_TYPE_SOLID:	
	emit_solid_pattern (surface, (cairo_solid_pattern_t *) pattern, style, is_stroke);
	break;

    case CAIRO_PATTERN_TYPE_SURFACE:
	emit_surface_pattern (surface, (cairo_surface_pattern_t *) pattern, style, is_stroke);
	break;

    case CAIRO_PATTERN_TYPE_LINEAR:
	emit_linear_pattern (surface, (cairo_linear_pattern_t *) pattern, style, is_stroke);
	break;

    case CAIRO_PATTERN_TYPE_RADIAL:
	emit_radial_pattern (surface, (cairo_radial_pattern_t *) pattern, style, is_stroke);
	break;	    
    }
}

typedef struct
{
    cairo_svg_document_t *document;
    xmlBufferPtr path;
} svg_path_info_t;

static cairo_status_t
_cairo_svg_path_move_to (void *closure, cairo_point_t *point)
{
    svg_path_info_t *info = closure;
    xmlBufferPtr path = info->path;
    char buffer[CAIRO_SVG_DTOSTR_BUFFER_LEN];

    xmlBufferCat (path, CC2XML ("M "));
    _cairo_dtostr (buffer, sizeof buffer, _cairo_fixed_to_double (point->x));
    xmlBufferCat (path, CC2XML (buffer));
    xmlBufferCat (path, CC2XML (" "));
    _cairo_dtostr (buffer, sizeof buffer, _cairo_fixed_to_double (point->y));
    xmlBufferCat (path, CC2XML (buffer));
    xmlBufferCat (path, CC2XML (" "));

    return CAIRO_STATUS_SUCCESS;
}

    static cairo_status_t
_cairo_svg_path_line_to (void *closure, cairo_point_t *point)
{
    svg_path_info_t *info = closure;
    xmlBufferPtr path = info->path;
    char buffer[CAIRO_SVG_DTOSTR_BUFFER_LEN];

    xmlBufferCat (path, CC2XML ("L "));

    _cairo_dtostr (buffer, sizeof buffer, _cairo_fixed_to_double (point->x));
    xmlBufferCat (path, CC2XML (buffer));
    xmlBufferCat (path, CC2XML (" "));
    _cairo_dtostr (buffer, sizeof buffer, _cairo_fixed_to_double (point->y));
    xmlBufferCat (path, CC2XML (buffer));
    xmlBufferCat (path, CC2XML (" "));

    return CAIRO_STATUS_SUCCESS;
}

static cairo_status_t
_cairo_svg_path_curve_to (void          *closure,
			  cairo_point_t *b,
			  cairo_point_t *c,
			  cairo_point_t *d)
{
    svg_path_info_t *info = closure;
    xmlBufferPtr path = info->path;
    char buffer[CAIRO_SVG_DTOSTR_BUFFER_LEN];

    xmlBufferCat (path, CC2XML ("C "));
    _cairo_dtostr (buffer, sizeof buffer, _cairo_fixed_to_double (b->x));
    xmlBufferCat (path, CC2XML (buffer));
    xmlBufferCat (path, CC2XML (" "));
    _cairo_dtostr (buffer, sizeof buffer, _cairo_fixed_to_double (b->y));
    xmlBufferCat (path, CC2XML (buffer));
    xmlBufferCat (path, CC2XML (" "));
    _cairo_dtostr (buffer, sizeof buffer, _cairo_fixed_to_double (c->x));
    xmlBufferCat (path, CC2XML (buffer));
    xmlBufferCat (path, CC2XML (" "));
    _cairo_dtostr (buffer, sizeof buffer, _cairo_fixed_to_double (c->y));
    xmlBufferCat (path, CC2XML (buffer));
    xmlBufferCat (path, CC2XML (" "));
    _cairo_dtostr (buffer, sizeof buffer, _cairo_fixed_to_double (d->x));
    xmlBufferCat (path, CC2XML (buffer));
    xmlBufferCat (path, CC2XML (" "));
    _cairo_dtostr (buffer, sizeof buffer, _cairo_fixed_to_double (d->y));
    xmlBufferCat (path, CC2XML (buffer));
    xmlBufferCat (path, CC2XML (" "));

    return CAIRO_STATUS_SUCCESS;
}

static cairo_status_t
_cairo_svg_path_close_path (void *closure)
{
    svg_path_info_t *info = closure;

    xmlBufferCat (info->path, CC2XML ("Z "));

    return CAIRO_STATUS_SUCCESS;
}

static cairo_int_status_t
_cairo_svg_surface_fill (void			*abstract_surface,
			 cairo_operator_t	 op,
			 cairo_pattern_t	*source,
			 cairo_path_fixed_t	*path,
			 cairo_fill_rule_t	 fill_rule,
			 double			 tolerance,
			 cairo_antialias_t	 antialias)
{
    cairo_svg_surface_t *surface = abstract_surface;
    cairo_svg_document_t *document = surface->document;
    cairo_status_t status;
    svg_path_info_t info;
    xmlNodePtr child;
    xmlBufferPtr style;

    if (surface->paginated_mode == CAIRO_PAGINATED_MODE_ANALYZE)
	return _analyze_operation (surface, op, source);

    assert (_operation_supported (surface, op, source));

    info.document = document;
    info.path = xmlBufferCreate ();
    
    style = xmlBufferCreate ();
    emit_pattern (surface, source, style, 0);
    xmlBufferCat (style, CC2XML (" stroke: none;"));
    xmlBufferCat (style, CC2XML (" fill-rule: "));
    xmlBufferCat (style, fill_rule == CAIRO_FILL_RULE_EVEN_ODD ? CC2XML("evenodd;") : CC2XML ("nonzero;"));

    status = _cairo_path_fixed_interpret (path,
					  CAIRO_DIRECTION_FORWARD,
					  _cairo_svg_path_move_to,
					  _cairo_svg_path_line_to,
					  _cairo_svg_path_curve_to,
					  _cairo_svg_path_close_path,
					  &info);

    child = xmlNewChild (surface->xml_node, NULL, CC2XML ("path"), NULL);
    xmlSetProp (child, CC2XML ("d"), xmlBufferContent (info.path));
    xmlSetProp (child, CC2XML ("style"), xmlBufferContent (style));
    emit_operator (child, op);

    xmlBufferFree (info.path);
    xmlBufferFree (style);

    return status;
}

static cairo_int_status_t
_cairo_svg_surface_get_extents (void		  *abstract_surface,
				cairo_rectangle_t *rectangle)
{
    cairo_svg_surface_t *surface = abstract_surface;

    rectangle->x = 0;
    rectangle->y = 0;

    /* XXX: The conversion to integers here is pretty bogus, (not to
     * mention the aribitray limitation of width to a short(!). We
     * may need to come up with a better interface for get_size.
     */
    rectangle->width  = (int) ceil (surface->width);
    rectangle->height = (int) ceil (surface->height);

    return CAIRO_STATUS_SUCCESS;
}

static xmlNodePtr
emit_paint (xmlNodePtr node,
	    cairo_svg_surface_t	*surface,
	    cairo_operator_t	 op,
	    cairo_pattern_t	*source)
{
    xmlNodePtr child;
    xmlBufferPtr style;
    char buffer[CAIRO_SVG_DTOSTR_BUFFER_LEN];

    if (source->type == CAIRO_PATTERN_TYPE_SURFACE && 
	source->extend == CAIRO_EXTEND_NONE)
	return emit_composite_pattern (node, 
				       surface,
				       (cairo_surface_pattern_t *) source, 
				       NULL, NULL, FALSE);

    style = xmlBufferCreate ();
    emit_pattern (surface, source, style, 0);
    xmlBufferCat (style, CC2XML (" stroke: none;"));

    child = xmlNewChild (node, NULL, CC2XML ("rect"), NULL);
    xmlSetProp (child, CC2XML ("x"), CC2XML ("0"));
    xmlSetProp (child, CC2XML ("y"), CC2XML ("0"));
    _cairo_dtostr (buffer, sizeof buffer, surface->width);
    xmlSetProp (child, CC2XML ("width"), C2XML (buffer));
    _cairo_dtostr (buffer, sizeof buffer, surface->height);
    xmlSetProp (child, CC2XML ("height"), C2XML (buffer));
    xmlSetProp (child, CC2XML ("style"), xmlBufferContent (style));
    emit_operator (child, op);

    xmlBufferFree (style);

    return child;
}

static cairo_int_status_t
_cairo_svg_surface_paint (void		    *abstract_surface,
			  cairo_operator_t   op,
			  cairo_pattern_t   *source)
{
    cairo_svg_surface_t *surface = abstract_surface;
    
    if (surface->paginated_mode == CAIRO_PAGINATED_MODE_ANALYZE)
	return _analyze_operation (surface, op, source);

    /* XXX: It would be nice to be able to assert this condition
     * here. But, we actually allow one 'cheat' that is used when
     * painting the final image-based fallbacks. The final fallbacks
     * do have alpha which we support by blending with white. This is
     * possible only because there is nothing between the fallback
     * images and the paper, nor is anything painted above. */
    /*
    assert (_operation_supported (surface, op, source));
    */

#if 0
    /* Emulation of clear and source operators, when no clipping region
     * is defined. We just delete existing content of surface root node,
     * and exit early if operator is clear. */ 
    if (surface->clip_level == 0 &&
	(op == CAIRO_OPERATOR_CLEAR ||
	 op == CAIRO_OPERATOR_SOURCE)) {
	xmlNodePtr child = surface->xml_root_node->children;
	
	while (child != NULL) {
	    xmlUnlinkNode (child);
	    xmlFreeNode (child);
	    child = surface->xml_root_node->children;
	}

	if (op == CAIRO_OPERATOR_CLEAR) {
	    if (surface->content == CAIRO_CONTENT_COLOR) {
		xmlNodePtr rect;
		char buffer[CAIRO_SVG_DTOSTR_BUFFER_LEN];

		rect = xmlNewChild (surface->xml_node, NULL, CC2XML ("rect"), NULL);
		_cairo_dtostr (buffer, sizeof buffer, surface->width);
		xmlSetProp (rect, CC2XML ("width"), C2XML (buffer));
		_cairo_dtostr (buffer, sizeof buffer, surface->height);
		xmlSetProp (rect, CC2XML ("height"), C2XML (buffer));
		xmlSetProp (rect, CC2XML ("style"), CC2XML ("opacity:1; stroke:none; fill:rgb(0,0,0);"));
	    } 
	    return CAIRO_STATUS_SUCCESS;
	}
    }
#endif

    emit_paint (surface->xml_node, surface, op, source);
    
    return CAIRO_STATUS_SUCCESS;
}

static cairo_int_status_t
_cairo_svg_surface_mask (void		    *abstract_surface,
			cairo_operator_t     op,
			cairo_pattern_t	    *source,
			cairo_pattern_t	    *mask)
{
    cairo_svg_surface_t *surface = abstract_surface;
    cairo_svg_document_t *document = surface->document;
    xmlNodePtr child, mask_node;
    char buffer[CAIRO_SVG_DTOSTR_BUFFER_LEN];

    emit_alpha_filter (document);

    if (surface->paginated_mode == CAIRO_PAGINATED_MODE_ANALYZE)
	return _analyze_operation (surface, op, source);

    assert (_operation_supported (surface, op, source));
    
    mask_node = xmlNewNode (NULL, CC2XML ("mask"));
    snprintf (buffer, sizeof buffer, "mask%d", document->mask_id);
    xmlSetProp (mask_node, CC2XML ("id"), C2XML (buffer));
    child = xmlNewChild (mask_node, NULL, CC2XML ("g"), NULL);
    xmlSetProp (child, CC2XML ("filter"), CC2XML ("url(#alpha)"));
    emit_paint (child, surface, op, mask);

    xmlAddChild (document->xml_node_defs, mask_node);

    child = emit_paint (surface->xml_node, surface, op, source);

    if (child) {
	snprintf (buffer, sizeof buffer, "url(#mask%d)", document->mask_id);
	xmlSetProp (child, CC2XML ("mask"), C2XML (buffer));
    }

    document->mask_id++;

    return CAIRO_STATUS_SUCCESS;
}

static cairo_int_status_t
_cairo_svg_surface_stroke (void			*abstract_dst,
			   cairo_operator_t      op,
			   cairo_pattern_t	*source,
			   cairo_path_fixed_t	*path,
			   cairo_stroke_style_t *stroke_style,
			   cairo_matrix_t	*ctm,
			   cairo_matrix_t	*ctm_inverse,
			   double		 tolerance,
			   cairo_antialias_t	 antialias)
{
    cairo_svg_surface_t *surface = abstract_dst;
    cairo_svg_document_t *document = surface->document;
    cairo_status_t status;
    xmlBufferPtr style;
    xmlNodePtr child;
    svg_path_info_t info;
    double rx, ry;
    unsigned int i;
    char buffer[CAIRO_SVG_DTOSTR_BUFFER_LEN];
    
    if (surface->paginated_mode == CAIRO_PAGINATED_MODE_ANALYZE)
	return _analyze_operation (surface, op, source);

    assert (_operation_supported (surface, op, source));

    info.document = document;
    info.path = xmlBufferCreate ();

    rx = ry = stroke_style->line_width;
    cairo_matrix_transform_distance (ctm, &rx, &ry);

    style = xmlBufferCreate ();
    emit_pattern (surface, source, style, 1);
    xmlBufferCat (style, CC2XML ("fill: none; stroke-width: "));
    _cairo_dtostr (buffer, sizeof buffer, sqrt ((rx * rx + ry * ry) / 2.0));
    xmlBufferCat (style, C2XML (buffer)); 
    xmlBufferCat (style, CC2XML (";"));
    
    switch (stroke_style->line_cap) {
	    case CAIRO_LINE_CAP_BUTT:
		    xmlBufferCat (style, CC2XML ("stroke-linecap: butt;"));
		    break;
	    case CAIRO_LINE_CAP_ROUND:
		    xmlBufferCat (style, CC2XML ("stroke-linecap: round;"));
		    break;
	    case CAIRO_LINE_CAP_SQUARE:
		    xmlBufferCat (style, CC2XML ("stroke-linecap: square;"));
		    break;
    }

    switch (stroke_style->line_join) {
	    case CAIRO_LINE_JOIN_MITER:
		    xmlBufferCat (style, CC2XML ("stroke-linejoin: miter;"));
		    break; 
	    case CAIRO_LINE_JOIN_ROUND:
		    xmlBufferCat (style, CC2XML ("stroke-linejoin: round;"));
		    break; 
	    case CAIRO_LINE_JOIN_BEVEL:
		    xmlBufferCat (style, CC2XML ("stroke-linejoin: bevel;"));
		    break; 
    }

    if (stroke_style->num_dashes > 0) {
	xmlBufferCat (style, CC2XML (" stroke-dasharray: "));
	for (i = 0; i < stroke_style->num_dashes; i++) {
	    if (i != 0)
		xmlBufferCat (style, CC2XML (","));
	    /* FIXME: Is is really what we want ? */
	    rx = ry = stroke_style->dash[i];
	    cairo_matrix_transform_distance (ctm, &rx, &ry);
	    _cairo_dtostr (buffer, sizeof buffer, sqrt ((rx * rx + ry * ry) / 2.0));
	    xmlBufferCat (style, C2XML (buffer));
	}
	xmlBufferCat (style, CC2XML (";"));
	if (stroke_style->dash_offset != 0.0) {
	    xmlBufferCat (style, CC2XML (" stroke-dashoffset: "));
	    rx = ry = stroke_style->dash_offset;
	    cairo_matrix_transform_distance (ctm, &rx, &ry);
	    _cairo_dtostr (buffer, sizeof buffer, sqrt ((rx * rx + ry * ry) / 2.0));
	    xmlBufferCat (style, C2XML (buffer));
	    xmlBufferCat (style, CC2XML (";"));
	}
    }

    xmlBufferCat (style, CC2XML (" stroke-miterlimit: "));
    _cairo_dtostr (buffer, sizeof buffer, stroke_style->miter_limit);
    xmlBufferCat (style, C2XML (buffer));
    xmlBufferCat (style, CC2XML (";"));

    status = _cairo_path_fixed_interpret (path,
					  CAIRO_DIRECTION_FORWARD,
					  _cairo_svg_path_move_to,
					  _cairo_svg_path_line_to,
					  _cairo_svg_path_curve_to,
					  _cairo_svg_path_close_path,
					  &info);
    
    child = xmlNewChild (surface->xml_node, NULL, CC2XML ("path"), NULL);
    xmlSetProp (child, CC2XML ("d"), xmlBufferContent (info.path));
    xmlSetProp (child, CC2XML ("style"), xmlBufferContent (style));
    emit_operator (child, op);
    
    xmlBufferFree (info.path);
    xmlBufferFree (style);

    return status;
}

static cairo_int_status_t
_cairo_svg_surface_show_glyphs (void			*abstract_surface,
				cairo_operator_t	 op,
				cairo_pattern_t		*pattern,
				const cairo_glyph_t	*glyphs,
				int			 num_glyphs,
				cairo_scaled_font_t	*scaled_font)
{
    cairo_svg_surface_t *surface = abstract_surface;
    cairo_path_fixed_t path;
    cairo_status_t status;
    
    if (surface->paginated_mode == CAIRO_PAGINATED_MODE_ANALYZE)
	return _analyze_operation (surface, op, pattern);

    assert (_operation_supported (surface, op, pattern));

    /* FIXME: We don't really want to keep this as is. There's to possibilities:
     *   - Use SVG fonts. But support for them seems very rare in SVG renderers.
     *   - Or store glyph outlines in <symbol> or <g> elements.
     * 
     * It would be also useful to add an early fallback in cairo_show_text and just
     * use <text> element.
     **/
    
    _cairo_path_fixed_init (&path);

    status = _cairo_scaled_font_glyph_path (scaled_font,(cairo_glyph_t *) glyphs, num_glyphs, &path);

    if (status)
	    return status;

    status = _cairo_svg_surface_fill (abstract_surface, op, pattern,
				      &path, CAIRO_FILL_RULE_WINDING, 0.0, CAIRO_ANTIALIAS_SUBPIXEL); 

    _cairo_path_fixed_fini (&path);

    return status;
}

static cairo_int_status_t
_cairo_svg_surface_intersect_clip_path (void			*dst,
					cairo_path_fixed_t	*path,
					cairo_fill_rule_t	 fill_rule,
					double			 tolerance,
					cairo_antialias_t	 antialias)
{
    cairo_svg_surface_t *surface = dst;
    cairo_svg_document_t *document = surface->document;
    cairo_status_t status;
    xmlNodePtr group, clip, clip_path;
    svg_path_info_t info;
    char buffer[CAIRO_SVG_DTOSTR_BUFFER_LEN];

    if (path == NULL) {
	surface->xml_node = surface->xml_root_node;
	surface->clip_level = 0;
	return CAIRO_STATUS_SUCCESS;
    }

    if (path != NULL) {
	info.document = document;
	info.path = xmlBufferCreate ();

	group = xmlNewChild (surface->xml_node, NULL, CC2XML ("g"), NULL);
	clip = xmlNewChild (document->xml_node_defs, NULL, CC2XML ("clipPath"), NULL);
	snprintf (buffer, sizeof buffer, "clip%d", document->clip_id);
	xmlSetProp (clip, CC2XML ("id"), C2XML (buffer));

	clip_path = xmlNewChild (clip, NULL, CC2XML ("path"), NULL);
	status = _cairo_path_fixed_interpret (path,
					      CAIRO_DIRECTION_FORWARD,
					      _cairo_svg_path_move_to,
					      _cairo_svg_path_line_to,
					      _cairo_svg_path_curve_to,
					      _cairo_svg_path_close_path,
					      &info);
	xmlSetProp (clip_path, CC2XML ("d"), xmlBufferContent (info.path));
	xmlBufferFree (info.path);

	snprintf (buffer, sizeof buffer, "url(#clip%d)", document->clip_id);
	xmlSetProp (group, CC2XML ("clip-path"), C2XML (buffer));
	xmlSetProp (group, CC2XML ("clip-rule"), 
		    fill_rule == CAIRO_FILL_RULE_EVEN_ODD ? 
		    CC2XML ("evenodd") : CC2XML ("nonzero"));

	document->clip_id++;
	surface->xml_node = group;
	surface->clip_level++;
    } 

    return status;
}

static void
_cairo_svg_surface_get_font_options (void                  *abstract_surface,
				     cairo_font_options_t  *options)
{
  _cairo_font_options_init_default (options);

  cairo_font_options_set_hint_style (options, CAIRO_HINT_STYLE_NONE);
  cairo_font_options_set_hint_metrics (options, CAIRO_HINT_METRICS_OFF);
}


static const cairo_surface_backend_t cairo_svg_surface_backend = {
	CAIRO_SURFACE_TYPE_SVG,
	_cairo_svg_surface_create_similar,
	_cairo_svg_surface_finish,
	NULL, /* acquire_source_image */
	NULL, /* release_source_image */
	NULL, /* acquire_dest_image */
	NULL, /* release_dest_image */
	NULL, /* clone_similar */
	NULL, /* _cairo_svg_surface_composite, */
	NULL, /* _cairo_svg_surface_fill_rectangles, */
	NULL, /* _cairo_svg_surface_composite_trapezoids,*/
	NULL, /* copy_page */
	NULL, /* show_page */
	NULL, /* set_clip_region */
	_cairo_svg_surface_intersect_clip_path,
	_cairo_svg_surface_get_extents,
	NULL, /* _cairo_svg_surface_old_show_glyphs, */
	_cairo_svg_surface_get_font_options,
	NULL, /* flush */
	NULL, /* mark dirty rectangle */
	NULL, /* scaled font fini */
	NULL, /* scaled glyph fini */
	_cairo_svg_surface_paint,
	_cairo_svg_surface_mask,
	_cairo_svg_surface_stroke,
	_cairo_svg_surface_fill,
	_cairo_svg_surface_show_glyphs
};

static cairo_svg_document_t *
_cairo_svg_document_create (cairo_output_stream_t	*output_stream,
			    double			width,
			    double			height)
{
    cairo_svg_document_t *document;
    xmlDocPtr doc;
    xmlNodePtr node;
    char buffer[CAIRO_SVG_DTOSTR_BUFFER_LEN];

    document = malloc (sizeof (cairo_svg_document_t));
    if (document == NULL)
	return NULL;

    document->output_stream = output_stream;
    document->refcount = 1;
    document->owner = NULL;
    document->finished = FALSE;
    document->width = width;
    document->height = height;
    document->x_dpi = CAIRO_SVG_DEFAULT_DPI;
    document->y_dpi = CAIRO_SVG_DEFAULT_DPI;

    document->surface_id = 0;
    document->linear_pattern_id = 0;
    document->radial_pattern_id = 0;
    document->pattern_id = 0;
    document->filter_id = 0;
    document->clip_id = 0;
    document->mask_id = 0;

    doc = xmlNewDoc (CC2XML ("1.0")); 
    node = xmlNewNode (NULL, CC2XML ("svg"));

    xmlDocSetRootElement (doc, node);

    document->xml_doc = doc;
    document->xml_node_main = node;
    document->xml_node_defs = xmlNewChild (node, NULL, CC2XML ("defs"), NULL); 

    _cairo_dtostr (buffer, sizeof buffer, width);
    xmlSetProp (node, CC2XML ("width"), CC2XML (buffer));
    _cairo_dtostr (buffer, sizeof buffer, height);
    xmlSetProp (node, CC2XML ("height"), CC2XML (buffer));
    xmlSetProp (node, CC2XML ("xmlns"), CC2XML ("http://www.w3.org/2000/svg"));
    xmlSetProp (node, CC2XML ("xmlns:xlink"), CC2XML ("http://www.w3.org/1999/xlink"));
    xmlSetProp (node, CC2XML ("version"), CC2XML ("1.2"));

    document->alpha_filter = FALSE;

    _cairo_array_init (&document->pattern_snapshots, sizeof (pattern_snapshot_t));

    document->svg_version = CAIRO_SVG_VERSION_1_1;
    
    return document;
}

static void
_cairo_svg_document_reference (cairo_svg_document_t *document)
{
    document->refcount++;
}

static void
_cairo_svg_document_destroy (cairo_svg_document_t *document)
{
    document->refcount--;
    if (document->refcount > 0)
      return;

    _cairo_svg_document_finish (document);

    free (document);
}

static int
_cairo_svg_document_write (cairo_output_stream_t *output_stream,
			   const char * buffer,
			   int len)
{
    cairo_status_t status;
    
    _cairo_output_stream_write (output_stream, buffer, len);
    status = _cairo_output_stream_get_status (output_stream);
    if (status) {
	_cairo_error (status);
	return -1;
    }

    return len;
}

static cairo_status_t
_cairo_svg_document_finish (cairo_svg_document_t *document)
{
    cairo_status_t status;
    cairo_output_stream_t *output = document->output_stream;
    pattern_snapshot_t *pattern_snapshot;
    xmlOutputBufferPtr xml_output_buffer;
    unsigned int i;

    if (document->finished)
	return CAIRO_STATUS_SUCCESS;

    xml_output_buffer = xmlOutputBufferCreateIO ((xmlOutputWriteCallback) _cairo_svg_document_write,
						 (xmlOutputCloseCallback) NULL,
						 (void *) document->output_stream, 
						 NULL);
    xmlSaveFormatFileTo (xml_output_buffer, document->xml_doc, "UTF-8", 1);

    xmlFreeDoc (document->xml_doc);

    status = _cairo_output_stream_get_status (output);
    _cairo_output_stream_destroy (output);

    for (i = 0; i < document->pattern_snapshots.num_elements; i++) {
	pattern_snapshot = _cairo_array_index (&document->pattern_snapshots, i);
	cairo_surface_destroy ((cairo_surface_t *) pattern_snapshot->meta);
    }
    _cairo_array_fini (&document->pattern_snapshots);

    document->finished = TRUE;

    return status;
}

static void
_cairo_svg_set_paginated_mode (cairo_surface_t *target,
			       cairo_paginated_mode_t paginated_mode)
{
    cairo_svg_surface_t *surface = (cairo_svg_surface_t *) target;

    surface->paginated_mode = paginated_mode;
}