1 #include <string.h> /* memcpy, memset */
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>
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.
18 #define VIEWPORT_WIDTH 512
19 #define VIEWPORT_HEIGHT 512
21 /* Convenient typedefs for libsvgtiny */
22 typedef struct svgtiny_diagram diagram_t
;
23 typedef struct svgtiny_shape shape_t
;
27 GdkPixbufModuleUpdatedFunc updated_func
;
28 GdkPixbufModulePreparedFunc prepared_func
;
29 GdkPixbufModuleSizeFunc size_func
;
32 /* The SVG "file" that we're building in memory. */
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. */
44 * @brief Render an svgtiny path using cairo.
47 * A pointer to a valid cairo context.
50 * A pointer to an svgtiny shape that will be rendered on the
51 * cairo context's target surface.
53 static void render_path(cairo_t
* cr
, shape_t
* path
) {
57 for (j
= 0; j
!= path
->path_length
; ) {
58 switch ((int) path
->path
[j
]) {
59 case svgtiny_PATH_MOVE
:
65 case svgtiny_PATH_CLOSE
:
69 case svgtiny_PATH_LINE
:
75 case svgtiny_PATH_BEZIER
:
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,
92 cairo_fill_preserve(cr
);
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,
100 cairo_set_line_width(cr
, path
->stroke_width
);
101 cairo_stroke_preserve(cr
);
106 * @brief Parse a buffer of SVG data into a diagram_t structure.
109 * The buffer containing the SVG document.
112 * The number of bytes in @c buffer.
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.
118 static diagram_t
* svgtiny_diagram_from_buffer(const gchar
* buffer
,
126 diagram
= svgtiny_create();
128 g_set_error_literal(error
,
131 "out of memory in svgtiny_create()");
135 g_assert((int)width
>= 0);
136 g_assert((int)height
>= 0);
137 code
= svgtiny_parse(diagram
,
145 /* The one success case. */
147 case svgtiny_OUT_OF_MEMORY
:
148 g_set_error_literal(error
,
151 "out of memory in svgtiny_parse()");
153 case svgtiny_LIBDOM_ERROR
:
154 g_set_error_literal(error
,
156 GDK_PIXBUF_ERROR_CORRUPT_IMAGE
,
157 "invalid XML DOM in svgtiny_parse()");
159 case svgtiny_NOT_SVG
:
160 g_set_error_literal(error
,
162 GDK_PIXBUF_ERROR_CORRUPT_IMAGE
,
163 "missing <svg> element in svgtiny_parse()");
165 case svgtiny_SVG_ERROR
:
168 GDK_PIXBUF_ERROR_CORRUPT_IMAGE
,
169 "SVG format error in svgtiny_parse() on line %i: %s",
171 diagram
->error_message
);
175 /* All other cases above are failure */
180 * @brief Create a cairo context from a libsvgtiny diagram.
183 * A pointer to a valid libsvgtiny diagram.
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.
189 static cairo_t
* cairo_context_from_diagram(const diagram_t
* diagram
) {
191 cairo_surface_t
* surface
;
195 surface
= cairo_image_surface_create(CAIRO_FORMAT_ARGB32
,
199 crs
= cairo_surface_status(surface
);
200 if (crs
!= CAIRO_STATUS_SUCCESS
) {
202 "cairo_image_surface_create failed: %s\n",
203 cairo_status_to_string(crs
));
204 cairo_surface_destroy(surface
);
208 cr
= cairo_create(surface
);
209 crs
= cairo_status(cr
);
211 /* Immediately destroy the surface which is now accessible as
213 cairo_surface_destroy(surface
);
215 if (crs
!= CAIRO_STATUS_SUCCESS
) {
217 "cairo_create failed: %s\n",
218 cairo_status_to_string(crs
));
223 cairo_set_source_rgba(cr
, 0, 0, 0, 0);
226 /* Loop through the shapes in the diagram... */
227 for (i
= 0; i
!= diagram
->shape_count
; i
++) {
229 /* If this shape is a path, just render it. */
230 if (diagram
->shape
[i
].path
) {
231 render_path(cr
, &diagram
->shape
[i
]);
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
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,
243 /* Then move to the actual position of the text within the
246 diagram
->shape
[i
].text_x
,
247 diagram
->shape
[i
].text_y
);
250 cairo_show_text(cr
, diagram
->shape
[i
].text
);
255 /* Check the status again just for good measure? */
256 crs
= cairo_status(cr
);
257 if (crs
!= CAIRO_STATUS_SUCCESS
) {
260 cairo_status_to_string(crs
));
269 * @brief Create a GdkPixbuf from a buffer of SVG data.
272 * The buffer containing the SVG document.
275 * The number of bytes in @c buffer.
278 * The address of a @c GError pointer that we use to return errors.
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.
283 static GdkPixbuf
* gdk_pixbuf_from_svg_buffer(const gchar
* buffer
,
289 GError
* sub_error
= NULL
;
291 diagram
= svgtiny_diagram_from_buffer(buffer
,
297 g_propagate_error(error
, sub_error
);
301 cr
= cairo_context_from_diagram(diagram
);
303 svgtiny_free(diagram
);
304 g_set_error_literal(error
,
306 GDK_PIXBUF_ERROR_CORRUPT_IMAGE
,
307 "could not create Cairo surface from SVG diagram");
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.
320 pb
= gdk_pixbuf_get_from_surface(cairo_get_target(cr
),
328 g_set_error_literal(error
,
330 GDK_PIXBUF_ERROR_FAILED
,
331 "failed to obtain a GdkPixbuf from Cairo surface");
338 static gpointer
gdk_pixbuf_begin_load(GdkPixbufModuleSizeFunc size_func
,
339 GdkPixbufModulePreparedFunc prep_func
,
340 GdkPixbufModuleUpdatedFunc updated_func
,
344 SvgTinyContext
* context
= g_new(SvgTinyContext
, 1);
346 context
->size_func
= size_func
;
347 context
->prepared_func
= prep_func
;
348 context
->updated_func
= updated_func
;
349 context
->user_data
= user_data
;
351 context
->svg_data
= NULL
;
352 context
->svg_data_size
= 0;
357 static gboolean
gdk_pixbuf_load_increment(gpointer data
,
361 SvgTinyContext
* context
= (SvgTinyContext
*)data
;
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
;
375 static void emit_updated(SvgTinyContext
* context
, GdkPixbuf
* pixbuf
) {
376 if (context
->updated_func
!= NULL
) {
377 (*context
->updated_func
)(pixbuf
,
380 gdk_pixbuf_get_width(pixbuf
),
381 gdk_pixbuf_get_height(pixbuf
),
386 static void emit_prepared(SvgTinyContext
* context
, GdkPixbuf
* pixbuf
) {
387 if (context
->prepared_func
!= NULL
) {
388 (*context
->prepared_func
)(pixbuf
, NULL
, context
->user_data
);
395 * @brief Replace one GTK <xi:include> element by its data.
398 * A pointer to an <xi:include> element node.
400 * @return TRUE if we replaced the node, and FALSE otherwise.
403 static gboolean
process_one_xinclude(xmlNode
* node
) {
406 href
= xmlGetProp(node
, BAD_CAST
"href");
408 /* We only process XIncludes with base64 data hrefs */
412 if (xmlStrncmp(href
, BAD_CAST
"data:text/xml;base64,", 21)) {
413 /* We only process XIncludes with base64 data hrefs */
417 xmlChar
* hrefdata
= href
+21;
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') {
426 if (hrefdata
[i
] < '0' && hrefdata
[i
] != '+' && hrefdata
[i
] != '/') {
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
436 xmlChar
* decoded
= g_base64_decode((const gchar
*)hrefdata
, &decoded_size
);
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
,
447 if (xinc_doc
== NULL
) {
451 xmlNode
* xinc_root
= xmlDocGetRootElement(xinc_doc
);
452 if (xinc_root
== NULL
|| xmlStrcmp(xinc_root
->name
, BAD_CAST
"svg")) {
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). */
462 xmlNode
* p
= xmlPreviousElementSibling(node
);
465 /* If there is no previous sibling element, do one AddChild()
466 first. Then we're back to the case of a previous sibling. */
468 cur_node
= xmlFirstElementChild(xinc_root
);
472 cur_node
= xmlFirstElementChild(xinc_root
);
474 /* Without the xmlCopyNode, I get segfaults, and I don't care to
476 p
= xmlAddChild(p
, xmlCopyNode(cur_node
,1));
477 xmlReconciliateNs(p
->doc
, p
);
479 cur_node
= xmlNextElementSibling(cur_node
);
483 g_assert(p
!= NULL
); /* xmlAddChild didn't fail */
489 p
= xmlAddNextSibling(p
, xmlCopyNode(cur_node
,1));
490 xmlReconciliateNs(p
->doc
, p
);
491 cur_node
= xmlNextElementSibling(cur_node
);
494 xmlFreeDoc(xinc_doc
);
500 * @brief Replace all GTK <xi:include> elements in a tree by their data.
503 * A node pointer, to the root of the tree.
505 * @return TRUE if we replaced any <xi:include> element nodes, and
509 static gboolean
process_child_xincludes(xmlNode
* a_node
) {
510 gboolean result
= FALSE
;
511 xmlNode
* cur_node
= a_node
;
514 g_assert(cur_node
== NULL
|| cur_node
->type
== XML_ELEMENT_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
)) {
524 cur_node
= next_node
;
528 if (process_child_xincludes(xmlFirstElementChild(cur_node
))) {
531 cur_node
= xmlNextElementSibling(cur_node
);
539 * @brief Process GTK <xi:include> elements in an SVG buffer.
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
546 * <xi:include href="data:text/xml;base64,PD94bWwgd..."/>
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.
557 * A buffer containing SVG file data.
560 * The size of @c buffer (which may not be NULL-terminated).
563 * A pointer to the size of the new buffer, valid only if the
564 * return value is non-NULL.
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.
570 static gchar
* process_gtk_symbolic_svg_xinclude(const gchar
* buffer
,
574 xmlDoc
* doc
= xmlReadMemory(buffer
,buf_size
,"symbolic.xml",NULL
,0);
579 xmlNode
* root_element
= xmlDocGetRootElement(doc
);
580 if (root_element
== NULL
) {
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. */
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
594 g_assert(sizeof(xmlChar
) == sizeof(gchar
));
595 *new_size
= (gsize
)xmlbuf_size
;
596 result
= (gchar
*)xmlbuf
;
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
;
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. */
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. */
621 gchar
* newdata
= process_gtk_symbolic_svg_xinclude(context
->svg_data
,
622 context
->svg_data_size
,
624 if (newdata
!= NULL
) {
625 g_free(context
->svg_data
);
626 context
->svg_data
= newdata
;
627 context
->svg_data_size
= newsize
;
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
,
635 if (pixbuf
!= NULL
) {
636 emit_prepared(context
, pixbuf
);
637 emit_updated(context
, pixbuf
);
638 g_object_unref(pixbuf
);
641 g_propagate_error(error
, sub_error
);
644 g_free(context
->svg_data
);
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
;
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 },
667 /* I'm not sure if we should support gzipped svg here? */
668 static const gchar
*mime_types
[] = {
672 "image/vnd.adobe.svg+xml",
674 "image/svg+xml-compressed",
678 static const gchar
*extensions
[] = {
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";
696 * @brief Entry point of the svg2png test program.
698 int main(int argc
, char** argv
) {
704 /* Parse arguments, and maybe print usage */
706 g_printf("Usage: %s INPUT OUTPUT\n", argv
[0]);
707 g_printf("Convert an SVG file (INPUT) to a PNG file (OUTPUT)\n");
714 pb
= gdk_pixbuf_new_from_file(svgpath
, &err
);
717 "Error %d in gdk_pixbuf_new_from_file: %s\n",
724 gdk_pixbuf_save(pb
, pngpath
, "png", NULL
, NULL
);