]> gitweb.michael.orlitzky.com - libsvgtiny-pixbuf.git/blob - io-svg.c
io-svg.c: use libxml2 to implement the <xi:include> parser
[libsvgtiny-pixbuf.git] / io-svg.c
1 #include <string.h> /* memcpy, memset */
2
3 #include <cairo.h>
4 #include <gdk/gdk.h>
5 #include <gdk-pixbuf/gdk-pixbuf.h> /* includes glib.h */
6 #include <glib/gprintf.h>
7 #include <libxml/parser.h>
8 #include <libxml/tree.h>
9 #include <svgtiny.h>
10
11 /*
12 * The width and height of the viewport that we'll render the SVG
13 * into. The final "picture" may not actually be this size; based on
14 * the height, width, viewBox, and preserveAspectRatio attributes in
15 * the SVG itself, libsvgtiny may scale, stretch, offset, etc. the
16 * paths to make them fit nicely into the viewport.
17 */
18 #define VIEWPORT_WIDTH 512
19 #define VIEWPORT_HEIGHT 512
20
21 /* Convenient typedefs for libsvgtiny */
22 typedef struct svgtiny_diagram diagram_t;
23 typedef struct svgtiny_shape shape_t;
24
25
26 typedef struct {
27 GdkPixbufModuleUpdatedFunc updated_func;
28 GdkPixbufModulePreparedFunc prepared_func;
29 GdkPixbufModuleSizeFunc size_func;
30 gpointer user_data;
31
32 /* The SVG "file" that we're building in memory. */
33 gchar* svg_data;
34
35 /* How far into svg_data are we? This should always point to the
36 next empty byte. If (for example) svg_data_size is 2, then
37 svg_data[0] and svg_data[1] are used, but svg_data[2] is free. */
38 size_t svg_data_size;
39
40 } SvgTinyContext;
41
42
43 /**
44 * @brief Render an svgtiny path using cairo.
45 *
46 * @param cr
47 * A pointer to a valid cairo context.
48 *
49 * @param path
50 * A pointer to an svgtiny shape that will be rendered on the
51 * cairo context's target surface.
52 */
53 static void render_path(cairo_t* cr, shape_t* path) {
54 unsigned int j;
55
56 cairo_new_path(cr);
57 for (j = 0; j != path->path_length; ) {
58 switch ((int) path->path[j]) {
59 case svgtiny_PATH_MOVE:
60 cairo_move_to(cr,
61 path->path[j + 1],
62 path->path[j + 2]);
63 j += 3;
64 break;
65 case svgtiny_PATH_CLOSE:
66 cairo_close_path(cr);
67 j += 1;
68 break;
69 case svgtiny_PATH_LINE:
70 cairo_line_to(cr,
71 path->path[j + 1],
72 path->path[j + 2]);
73 j += 3;
74 break;
75 case svgtiny_PATH_BEZIER:
76 cairo_curve_to(cr,
77 path->path[j + 1],
78 path->path[j + 2],
79 path->path[j + 3],
80 path->path[j + 4],
81 path->path[j + 5],
82 path->path[j + 6]);
83 j += 7;
84 }
85 }
86 if (path->fill != svgtiny_TRANSPARENT) {
87 cairo_set_source_rgba(cr,
88 svgtiny_RED(path->fill) / 255.0,
89 svgtiny_GREEN(path->fill) / 255.0,
90 svgtiny_BLUE(path->fill) / 255.0,
91 1);
92 cairo_fill_preserve(cr);
93 }
94 if (path->stroke != svgtiny_TRANSPARENT) {
95 cairo_set_source_rgba(cr,
96 svgtiny_RED(path->stroke) / 255.0,
97 svgtiny_GREEN(path->stroke) / 255.0,
98 svgtiny_BLUE(path->stroke) / 255.0,
99 1);
100 cairo_set_line_width(cr, path->stroke_width);
101 cairo_stroke_preserve(cr);
102 }
103 }
104
105 /**
106 * @brief Parse a buffer of SVG data into a diagram_t structure.
107 *
108 * @param buffer
109 * The buffer containing the SVG document.
110 *
111 * @param bytecount
112 * The number of bytes in @c buffer.
113 *
114 * @return If successful, a pointer to a @c diagram_t structure is
115 * returned; if not, @c NULL is returned. You are expected to @c
116 * svgtiny_free the result if it is valid.
117 */
118 static diagram_t* svgtiny_diagram_from_buffer(const gchar* buffer,
119 gsize bytecount,
120 guint width,
121 guint height,
122 GError** error) {
123 diagram_t* diagram;
124 svgtiny_code code;
125
126 diagram = svgtiny_create();
127 if (!diagram) {
128 g_set_error_literal(error,
129 G_FILE_ERROR,
130 G_FILE_ERROR_NOMEM,
131 "out of memory in svgtiny_create()");
132 return NULL;
133 }
134
135 g_assert((int)width >= 0);
136 g_assert((int)height >= 0);
137 code = svgtiny_parse(diagram,
138 buffer,
139 bytecount, "",
140 (int)width,
141 (int)height);
142
143 switch(code) {
144 case svgtiny_OK:
145 /* The one success case. */
146 return diagram;
147 case svgtiny_OUT_OF_MEMORY:
148 g_set_error_literal(error,
149 G_FILE_ERROR,
150 G_FILE_ERROR_NOMEM,
151 "out of memory in svgtiny_parse()");
152 break;
153 case svgtiny_LIBDOM_ERROR:
154 g_set_error_literal(error,
155 GDK_PIXBUF_ERROR,
156 GDK_PIXBUF_ERROR_CORRUPT_IMAGE,
157 "invalid XML DOM in svgtiny_parse()");
158 break;
159 case svgtiny_NOT_SVG:
160 g_set_error_literal(error,
161 GDK_PIXBUF_ERROR,
162 GDK_PIXBUF_ERROR_CORRUPT_IMAGE,
163 "missing <svg> element in svgtiny_parse()");
164 break;
165 case svgtiny_SVG_ERROR:
166 g_set_error(error,
167 GDK_PIXBUF_ERROR,
168 GDK_PIXBUF_ERROR_CORRUPT_IMAGE,
169 "SVG format error in svgtiny_parse() on line %i: %s",
170 diagram->error_line,
171 diagram->error_message);
172 break;
173 }
174
175 /* All other cases above are failure */
176 return NULL;
177 }
178
179 /**
180 * @brief Create a cairo context from a libsvgtiny diagram.
181 *
182 * @param diagram
183 * A pointer to a valid libsvgtiny diagram.
184 *
185 * @return If successful, a pointer to a @c cairo_t context structure
186 * is returned; if not, @c NULL is returned. You are expected to @c
187 * cairo_destroy the result if it is valid.
188 */
189 static cairo_t* cairo_context_from_diagram(const diagram_t* diagram) {
190 cairo_t* cr;
191 cairo_surface_t* surface;
192 cairo_status_t crs;
193 unsigned int i;
194
195 surface = cairo_image_surface_create(CAIRO_FORMAT_ARGB32,
196 diagram->width,
197 diagram->height);
198
199 crs = cairo_surface_status(surface);
200 if (crs != CAIRO_STATUS_SUCCESS) {
201 g_fprintf(stderr,
202 "cairo_image_surface_create failed: %s\n",
203 cairo_status_to_string(crs));
204 cairo_surface_destroy(surface);
205 return NULL;
206 }
207
208 cr = cairo_create(surface);
209 crs = cairo_status(cr);
210
211 /* Immediately destroy the surface which is now accessible as
212 cr->target */
213 cairo_surface_destroy(surface);
214
215 if (crs != CAIRO_STATUS_SUCCESS) {
216 g_fprintf(stderr,
217 "cairo_create failed: %s\n",
218 cairo_status_to_string(crs));
219 cairo_destroy(cr);
220 return NULL;
221 }
222
223 cairo_set_source_rgba(cr, 0, 0, 0, 0);
224 cairo_paint(cr);
225
226 /* Loop through the shapes in the diagram... */
227 for (i = 0; i != diagram->shape_count; i++) {
228
229 /* If this shape is a path, just render it. */
230 if (diagram->shape[i].path) {
231 render_path(cr, &diagram->shape[i]);
232 }
233
234 /* If this shape is text... */
235 if (diagram->shape[i].text) {
236 /* Figure out what color to use from the R/G/B components of the
237 shape's stroke. */
238 cairo_set_source_rgba(cr,
239 svgtiny_RED(diagram->shape[i].stroke) / 255.0,
240 svgtiny_GREEN(diagram->shape[i].stroke) / 255.0,
241 svgtiny_BLUE(diagram->shape[i].stroke) / 255.0,
242 1);
243 /* Then move to the actual position of the text within the
244 shape... */
245 cairo_move_to(cr,
246 diagram->shape[i].text_x,
247 diagram->shape[i].text_y);
248
249 /* and draw it. */
250 cairo_show_text(cr, diagram->shape[i].text);
251 }
252 }
253
254
255 /* Check the status again just for good measure? */
256 crs = cairo_status(cr);
257 if (crs != CAIRO_STATUS_SUCCESS) {
258 g_fprintf(stderr,
259 "cairo error: %s\n",
260 cairo_status_to_string(crs));
261 cairo_destroy(cr);
262 return NULL;
263 }
264
265 return cr;
266 }
267
268 /**
269 * @brief Create a GdkPixbuf from a buffer of SVG data.
270 *
271 * @param buffer
272 * The buffer containing the SVG document.
273 *
274 * @param bytecount
275 * The number of bytes in @c buffer.
276 *
277 * @param error
278 * The address of a @c GError pointer that we use to return errors.
279 *
280 * @return If successful, a valid pointer to a @c GdkPixbuf is
281 * returned; if not, @c NULL is returned and @c error is populated.
282 */
283 static GdkPixbuf* gdk_pixbuf_from_svg_buffer(const gchar* buffer,
284 gsize bytecount,
285 GError** error) {
286 diagram_t* diagram;
287 cairo_t* cr = 0;
288 GdkPixbuf* pb;
289 GError* sub_error = NULL;
290
291 diagram = svgtiny_diagram_from_buffer(buffer,
292 bytecount,
293 VIEWPORT_WIDTH,
294 VIEWPORT_HEIGHT,
295 &sub_error);
296 if (!diagram) {
297 g_propagate_error(error, sub_error);
298 return NULL;
299 }
300
301 cr = cairo_context_from_diagram(diagram);
302 if (!cr) {
303 svgtiny_free(diagram);
304 g_set_error_literal(error,
305 GDK_PIXBUF_ERROR,
306 GDK_PIXBUF_ERROR_CORRUPT_IMAGE,
307 "could not create Cairo surface from SVG diagram");
308 return NULL;
309 }
310
311
312 /* I've gone back and forth on this about five times: we use the
313 * diagram width and height, and not the viewport width and height.
314 * This can ultimately render an image that's larger than the
315 * viewport size, but I think GDK will resize the final pixbuf
316 * anyway. More importantly, rendering small icons at a larger
317 * (viewport) size seems to make the whole thing go ape-shit.
318 * So for now I'm back in the diagram camp.
319 */
320 pb = gdk_pixbuf_get_from_surface(cairo_get_target(cr),
321 0,
322 0,
323 diagram->width,
324 diagram->height);
325
326
327 if (!pb) {
328 g_set_error_literal(error,
329 GDK_PIXBUF_ERROR,
330 GDK_PIXBUF_ERROR_FAILED,
331 "failed to obtain a GdkPixbuf from Cairo surface");
332 }
333
334 return pb;
335 }
336
337
338 static gpointer gdk_pixbuf_begin_load(GdkPixbufModuleSizeFunc size_func,
339 GdkPixbufModulePreparedFunc prep_func,
340 GdkPixbufModuleUpdatedFunc updated_func,
341 gpointer user_data,
342 GError **error) {
343
344 SvgTinyContext* context = g_new(SvgTinyContext, 1);
345
346 context->size_func = size_func;
347 context->prepared_func = prep_func;
348 context->updated_func = updated_func;
349 context->user_data = user_data;
350
351 context->svg_data = NULL;
352 context->svg_data_size = 0;
353
354 return context;
355 }
356
357 static gboolean gdk_pixbuf_load_increment(gpointer data,
358 const guchar* buf,
359 guint buf_size,
360 GError** error) {
361 SvgTinyContext* context = (SvgTinyContext*)data;
362
363 if (buf_size == 0) {
364 return TRUE;
365 }
366
367 context->svg_data = g_realloc(context->svg_data,
368 context->svg_data_size + buf_size);
369 memcpy(context->svg_data + context->svg_data_size, buf, buf_size);
370 context->svg_data_size += buf_size;
371
372 return TRUE;
373 }
374
375 static void emit_updated(SvgTinyContext* context, GdkPixbuf* pixbuf) {
376 if (context->updated_func != NULL) {
377 (*context->updated_func)(pixbuf,
378 0,
379 0,
380 gdk_pixbuf_get_width(pixbuf),
381 gdk_pixbuf_get_height(pixbuf),
382 context->user_data);
383 }
384 }
385
386 static void emit_prepared(SvgTinyContext* context, GdkPixbuf* pixbuf) {
387 if (context->prepared_func != NULL) {
388 (*context->prepared_func)(pixbuf, NULL, context->user_data);
389 }
390 }
391
392
393
394 /**
395 * @brief Replace one GTK <xi:include> element by its data.
396 *
397 * @param node
398 * A pointer to an <xi:include> element node.
399 *
400 * @return TRUE if we replaced the node, and FALSE otherwise.
401 *
402 */
403 static gboolean process_one_xinclude(xmlNode* node) {
404 xmlChar* href;
405
406 href = xmlGetProp(node, BAD_CAST "href");
407 if (href == NULL) {
408 /* We only process XIncludes with base64 data hrefs */
409 return FALSE;
410 }
411
412 if (xmlStrncmp(href, BAD_CAST "data:text/xml;base64,", 21)) {
413 /* We only process XIncludes with base64 data hrefs */
414 return FALSE;
415 }
416
417 xmlChar* hrefdata = href+21;
418
419 /* Verify that hrefdata is base64-encoded (and that it's safe to
420 cast to a signed gchar pointer). I'm assuming that everyone is
421 using the RFC 4648 encoding? */
422 for (unsigned int i=0; i < xmlStrlen(hrefdata); i++) {
423 if (hrefdata[i] > 'z') {
424 return FALSE;
425 }
426 if (hrefdata[i] < '0' && hrefdata[i] != '+' && hrefdata[i] != '/') {
427 return FALSE;
428 }
429 }
430
431 /* WARNING: the xmlChar and guchar types here are compatible, but
432 the decoded data is not necessarily NULL-terminated, while all of
433 the libxml2 functions that operate on a xmlChar pointer assume
434 that they are. */
435 gsize decoded_size;
436 xmlChar* decoded = g_base64_decode((const gchar*)hrefdata, &decoded_size);
437
438 /* This cast is safe because signed and unsigned chars are the same size,
439 and xmlReadMemory is going to treat the data as binary anyway. */
440 xmlDoc* xinc_doc = xmlReadMemory((const char*)decoded,
441 decoded_size,
442 "xinclude.xml",
443 NULL,
444 0);
445 g_free(decoded);
446
447 if (xinc_doc == NULL) {
448 return FALSE;
449 }
450
451 xmlNode* xinc_root = xmlDocGetRootElement(xinc_doc);
452 if (xinc_root == NULL || xmlStrcmp(xinc_root->name, BAD_CAST "svg")) {
453 return FALSE;
454 }
455
456 /* Replace the original xinclude "node" with the children of this
457 "svg" node. Do the order of the nodes in an SVG matter? I don't
458 know, but we go to a little bit of extra trouble here to ensure
459 that we put the replacement in the right place, i.e. after its
460 previous sibling (if there is one). */
461
462 xmlNode* p = xmlPreviousElementSibling(node);
463 xmlNode* cur_node;
464
465 /* If there is no previous sibling element, do one AddChild()
466 first. Then we're back to the case of a previous sibling. */
467 if (p) {
468 cur_node = xmlFirstElementChild(xinc_root);
469 }
470 else {
471 p = node->parent;
472 cur_node = xmlFirstElementChild(xinc_root);
473 if (cur_node) {
474 /* Without the xmlCopyNode, I get segfaults, and I don't care to
475 investigate why. */
476 p = xmlAddChild(p, xmlCopyNode(cur_node,1));
477 xmlReconciliateNs(p->doc, p);
478
479 cur_node = xmlNextElementSibling(cur_node);
480 }
481 }
482
483 g_assert(p != NULL); /* xmlAddChild didn't fail */
484
485 xmlUnlinkNode(node);
486 xmlFreeNode(node);
487
488 while (cur_node) {
489 p = xmlAddNextSibling(p, xmlCopyNode(cur_node,1));
490 xmlReconciliateNs(p->doc, p);
491 cur_node = xmlNextElementSibling(cur_node);
492 }
493
494 xmlFreeDoc(xinc_doc);
495
496 return TRUE;
497 }
498
499 /**
500 * @brief Replace all GTK <xi:include> elements in a tree by their data.
501 *
502 * @param node
503 * A node pointer, to the root of the tree.
504 *
505 * @return TRUE if we replaced any <xi:include> element nodes, and
506 * FALSE otherwise.
507 *
508 */
509 static gboolean process_child_xincludes(xmlNode* a_node) {
510 gboolean result = FALSE;
511 xmlNode* cur_node = a_node;
512 xmlNode* next_node;
513
514 g_assert(cur_node == NULL || cur_node->type == XML_ELEMENT_NODE);
515
516 while (cur_node) {
517 if (!xmlStrcmp(cur_node->name, BAD_CAST "include")) {
518 /* process_one_xinclude() clobbers this node, so we need
519 to get its successor before calling that function. */
520 next_node = xmlNextElementSibling(cur_node);
521 if (process_one_xinclude(cur_node)) {
522 result = TRUE;
523 }
524 cur_node = next_node;
525 continue;
526 }
527
528 if (process_child_xincludes(xmlFirstElementChild(cur_node))) {
529 result = TRUE;
530 }
531 cur_node = xmlNextElementSibling(cur_node);
532 }
533
534 return result;
535 }
536
537
538 /**
539 * @brief Process GTK <xi:include> elements in an SVG buffer.
540 *
541 * GTK is very cute. Its gtk-encode-symbolic-svg tool wraps your SVG
542 * in its own boilerplate, but then rather than including your SVG
543 * data verbatim, it includes it via a sketchy XInclude that looks
544 * like,
545 *
546 * <xi:include href="data:text/xml;base64,PD94bWwgd..."/>
547 *
548 * Librsvg knows how to parse that, but libxml2 doesn't (the latter
549 * can handle an XInclude, just not a base64-encoded data reference).
550 * Fortunately, you can read the source to gtk-encode-symbolic-svg,
551 * and just see what the format of that line will be. Here we're going
552 * to parse out the base64 data, decode it, strip out its opening
553 * <xml> and <svg> tags, and then replace the original <xi:include>
554 * element with the result.
555 *
556 * @param buffer
557 * A buffer containing SVG file data.
558 *
559 * @param buf_size
560 * The size of @c buffer (which may not be NULL-terminated).
561 *
562 * @param new_size
563 * A pointer to the size of the new buffer, valid only if the
564 * return value is non-NULL.
565 *
566 * @return A pointer to a buffer where the <xi:include> has been
567 * processed. If no replacements were made, the result will be @c
568 * NULL; otherwise, you are expected to @c free it when you are done.
569 */
570 static gchar* process_gtk_symbolic_svg_xinclude(const gchar* buffer,
571 gsize buf_size,
572 gsize* new_size) {
573
574 xmlDoc* doc = xmlReadMemory(buffer,buf_size,"symbolic.xml",NULL,0);
575 if (doc == NULL) {
576 return NULL;
577 }
578
579 xmlNode* root_element = xmlDocGetRootElement(doc);
580 if (root_element == NULL) {
581 return NULL;
582 }
583
584 gchar* result = NULL;
585 if (process_child_xincludes(root_element)) {
586 /* If we actually replaced something, we need to return the new
587 document in a buffer. */
588 xmlChar *xmlbuf;
589 int xmlbuf_size;
590 xmlDocDumpFormatMemory(doc, &xmlbuf, &xmlbuf_size, 1);
591 /* We're going to free() this later on with g_free() instead of
592 xmlFree(), so the two "byte" types had better be the same
593 size. */
594 g_assert(sizeof(xmlChar) == sizeof(gchar));
595 *new_size = (gsize)xmlbuf_size;
596 result = (gchar*)xmlbuf;
597 }
598
599 xmlFreeDoc(doc);
600 xmlCleanupParser();
601 return result;
602 }
603
604
605 static gboolean gdk_pixbuf_stop_load(gpointer data, GError **error) {
606 SvgTinyContext* context = (SvgTinyContext*)data;
607 GdkPixbuf* pixbuf = NULL;
608 GError* sub_error = NULL;
609
610 g_assert(context != NULL);
611 if (context->svg_data == NULL || context->svg_data_size == 0) {
612 /* Is it possible to begin/stop with no increments in between?
613 * I sure don't know. Let's play it safe. */
614 return FALSE;
615 }
616
617 /* If we're inside of gtk-encode-symbolic-svg right now, we need to
618 process the insane librsvg-specific XInclude directive it hands
619 us before proceeding. */
620 gsize newsize;
621 gchar* newdata = process_gtk_symbolic_svg_xinclude(context->svg_data,
622 context->svg_data_size,
623 &newsize);
624 if (newdata != NULL) {
625 g_free(context->svg_data);
626 context->svg_data = newdata;
627 context->svg_data_size = newsize;
628 }
629
630 /* OK, we've got an SVG with no XIncludes now. */
631 pixbuf = gdk_pixbuf_from_svg_buffer(context->svg_data,
632 context->svg_data_size,
633 &sub_error);
634
635 if (pixbuf != NULL) {
636 emit_prepared(context, pixbuf);
637 emit_updated(context, pixbuf);
638 g_object_unref(pixbuf);
639 }
640 else {
641 g_propagate_error(error, sub_error);
642 return FALSE;
643 }
644 g_free(context->svg_data);
645 g_free(context);
646
647 return TRUE;
648 }
649
650
651 G_MODULE_EXPORT void fill_vtable(GdkPixbufModule* module);
652 void fill_vtable(GdkPixbufModule* module) {
653 module->begin_load = gdk_pixbuf_begin_load;
654 module->load_increment = gdk_pixbuf_load_increment;
655 module->stop_load = gdk_pixbuf_stop_load;
656 }
657
658 G_MODULE_EXPORT void fill_info(GdkPixbufFormat *info);
659 void fill_info(GdkPixbufFormat* info) {
660 /* Borrowed from librsvg-2.40.21 */
661 static const GdkPixbufModulePattern signature[] = {
662 { " <svg", "* ", 100 },
663 { " <!DOCTYPE svg", "* ", 100 },
664 { NULL, NULL, 0 }
665 };
666
667 /* I'm not sure if we should support gzipped svg here? */
668 static const gchar *mime_types[] = {
669 "image/svg+xml",
670 "image/svg",
671 "image/svg-xml",
672 "image/vnd.adobe.svg+xml",
673 "text/xml-svg",
674 "image/svg+xml-compressed",
675 NULL
676 };
677
678 static const gchar *extensions[] = {
679 "svg",
680 "svgz",
681 "svg.gz",
682 NULL
683 };
684
685 info->name = "svg";
686 info->signature = (GdkPixbufModulePattern*)signature;
687 info->description = "Scalable Vector Graphics";
688 info->mime_types = (gchar**)mime_types;
689 info->extensions = (gchar**)extensions;
690 info->flags = GDK_PIXBUF_FORMAT_SCALABLE;
691 info->license = "AGPL3";
692 }
693
694
695 /**
696 * @brief Entry point of the svg2png test program.
697 */
698 int main(int argc, char** argv) {
699 char* svgpath;
700 char* pngpath;
701 GError* err = NULL;
702 GdkPixbuf* pb;
703
704 /* Parse arguments, and maybe print usage */
705 if (argc < 3) {
706 g_printf("Usage: %s INPUT OUTPUT\n", argv[0]);
707 g_printf("Convert an SVG file (INPUT) to a PNG file (OUTPUT)\n");
708 return 2;
709 }
710
711 svgpath = argv[1];
712 pngpath = argv[2];
713
714 pb = gdk_pixbuf_new_from_file(svgpath, &err);
715 if (!pb) {
716 g_fprintf(stderr,
717 "Error %d in gdk_pixbuf_new_from_file: %s\n",
718 err->code,
719 err->message);
720 g_error_free(err);
721 return 1;
722 }
723
724 gdk_pixbuf_save(pb, pngpath, "png", NULL, NULL);
725 g_object_unref(pb);
726 return 0;
727 }