1 #include <string.h> /* memcpy, memset */
4 #include <gdk-pixbuf/gdk-pixbuf.h> /* includes glib.h */
5 #include <glib/gprintf.h>
6 #include <libxml/parser.h>
7 #include <libxml/tree.h>
10 /* This "header" includes extra code that we've copy/pasted from GDK */
11 #include "gdk_pixbuf_get_from_surface.h"
14 * The width and height of the viewport that we'll render the SVG
15 * into. The final "picture" may not actually be this size; based on
16 * the height, width, viewBox, and preserveAspectRatio attributes in
17 * the SVG itself, libsvgtiny may scale, stretch, offset, etc. the
18 * paths to make them fit nicely into the viewport.
20 #define VIEWPORT_WIDTH 512
21 #define VIEWPORT_HEIGHT 512
23 /* Convenient typedefs for libsvgtiny */
24 typedef struct svgtiny_diagram diagram_t
;
25 typedef struct svgtiny_shape shape_t
;
29 GdkPixbufModuleUpdatedFunc updated_func
;
30 GdkPixbufModulePreparedFunc prepared_func
;
31 GdkPixbufModuleSizeFunc size_func
;
34 /* The SVG "file" that we're building in memory. */
37 /* How far into svg_data are we? This should always point to the
38 next empty byte. If (for example) svg_data_size is 2, then
39 svg_data[0] and svg_data[1] are used, but svg_data[2] is free. */
46 * @brief Render an svgtiny path using cairo.
49 * A pointer to a valid cairo context.
52 * A pointer to an svgtiny shape that will be rendered on the
53 * cairo context's target surface.
55 static void render_path(cairo_t
* cr
, shape_t
* path
) {
59 for (j
= 0; j
!= path
->path_length
; ) {
60 switch ((int) path
->path
[j
]) {
61 case svgtiny_PATH_MOVE
:
67 case svgtiny_PATH_CLOSE
:
71 case svgtiny_PATH_LINE
:
77 case svgtiny_PATH_BEZIER
:
88 if (path
->fill
!= svgtiny_TRANSPARENT
) {
89 cairo_set_source_rgba(cr
,
90 svgtiny_RED(path
->fill
) / 255.0,
91 svgtiny_GREEN(path
->fill
) / 255.0,
92 svgtiny_BLUE(path
->fill
) / 255.0,
94 cairo_fill_preserve(cr
);
96 if (path
->stroke
!= svgtiny_TRANSPARENT
) {
97 cairo_set_source_rgba(cr
,
98 svgtiny_RED(path
->stroke
) / 255.0,
99 svgtiny_GREEN(path
->stroke
) / 255.0,
100 svgtiny_BLUE(path
->stroke
) / 255.0,
102 cairo_set_line_width(cr
, path
->stroke_width
);
103 cairo_stroke_preserve(cr
);
108 * @brief Parse a buffer of SVG data into a diagram_t structure.
111 * The buffer containing the SVG document.
114 * The number of bytes in @c buffer.
116 * @return If successful, a pointer to a @c diagram_t structure is
117 * returned; if not, @c NULL is returned. You are expected to @c
118 * svgtiny_free the result if it is valid.
120 static diagram_t
* svgtiny_diagram_from_buffer(const gchar
* buffer
,
128 diagram
= svgtiny_create();
130 g_set_error_literal(error
,
133 "out of memory in svgtiny_create()");
137 g_assert((int)width
>= 0);
138 g_assert((int)height
>= 0);
140 /* There's a thread-safety issue in libwapcaplet that can cause
141 * svgtiny_parse() to crash if you load lots of SVGs at once:
143 * https://bugs.netsurf-browser.org/mantis/view.php?id=2857
145 * Putting a lock around svgtiny_parse() is a pretty simple solution
146 * and looks like it does the trick.
149 g_mutex_lock(&mutex
);
150 code
= svgtiny_parse(diagram
,
155 g_mutex_unlock (&mutex
);
159 /* The one success case. */
161 case svgtiny_OUT_OF_MEMORY
:
162 g_set_error_literal(error
,
165 "out of memory in svgtiny_parse()");
167 case svgtiny_LIBDOM_ERROR
:
168 g_set_error_literal(error
,
170 GDK_PIXBUF_ERROR_CORRUPT_IMAGE
,
171 "invalid XML DOM in svgtiny_parse()");
173 case svgtiny_NOT_SVG
:
174 g_set_error_literal(error
,
176 GDK_PIXBUF_ERROR_CORRUPT_IMAGE
,
177 "missing <svg> element in svgtiny_parse()");
179 case svgtiny_SVG_ERROR
:
182 GDK_PIXBUF_ERROR_CORRUPT_IMAGE
,
183 "SVG format error in svgtiny_parse() on line %i: %s",
185 diagram
->error_message
);
189 /* All other cases above are failure */
194 * @brief Create a cairo context from a libsvgtiny diagram.
197 * A pointer to a valid libsvgtiny diagram.
199 * @return If successful, a pointer to a @c cairo_t context structure
200 * is returned; if not, @c NULL is returned. You are expected to @c
201 * cairo_destroy the result if it is valid.
203 static cairo_t
* cairo_context_from_diagram(const diagram_t
* diagram
) {
205 cairo_surface_t
* surface
;
209 surface
= cairo_image_surface_create(CAIRO_FORMAT_ARGB32
,
213 crs
= cairo_surface_status(surface
);
214 if (crs
!= CAIRO_STATUS_SUCCESS
) {
216 "cairo_image_surface_create failed: %s\n",
217 cairo_status_to_string(crs
));
218 cairo_surface_destroy(surface
);
222 cr
= cairo_create(surface
);
223 crs
= cairo_status(cr
);
225 /* Immediately destroy the surface which is now accessible as
227 cairo_surface_destroy(surface
);
229 if (crs
!= CAIRO_STATUS_SUCCESS
) {
231 "cairo_create failed: %s\n",
232 cairo_status_to_string(crs
));
237 cairo_set_source_rgba(cr
, 0, 0, 0, 0);
240 /* Loop through the shapes in the diagram... */
241 for (i
= 0; i
!= diagram
->shape_count
; i
++) {
243 /* If this shape is a path, just render it. */
244 if (diagram
->shape
[i
].path
) {
245 render_path(cr
, &diagram
->shape
[i
]);
248 /* If this shape is text... */
249 if (diagram
->shape
[i
].text
) {
250 /* Figure out what color to use from the R/G/B components of the
252 cairo_set_source_rgba(cr
,
253 svgtiny_RED(diagram
->shape
[i
].stroke
) / 255.0,
254 svgtiny_GREEN(diagram
->shape
[i
].stroke
) / 255.0,
255 svgtiny_BLUE(diagram
->shape
[i
].stroke
) / 255.0,
257 /* Then move to the actual position of the text within the
260 diagram
->shape
[i
].text_x
,
261 diagram
->shape
[i
].text_y
);
264 cairo_show_text(cr
, diagram
->shape
[i
].text
);
269 /* Check the status again just for good measure? */
270 crs
= cairo_status(cr
);
271 if (crs
!= CAIRO_STATUS_SUCCESS
) {
274 cairo_status_to_string(crs
));
283 * @brief Create a GdkPixbuf from a buffer of SVG data.
286 * The buffer containing the SVG document.
289 * The number of bytes in @c buffer.
292 * The address of a @c GError pointer that we use to return errors.
294 * @return If successful, a valid pointer to a @c GdkPixbuf is
295 * returned; if not, @c NULL is returned and @c error is populated.
297 static GdkPixbuf
* gdk_pixbuf_from_svg_buffer(const gchar
* buffer
,
303 GError
* sub_error
= NULL
;
305 diagram
= svgtiny_diagram_from_buffer(buffer
,
311 g_propagate_error(error
, sub_error
);
315 cr
= cairo_context_from_diagram(diagram
);
317 svgtiny_free(diagram
);
318 g_set_error_literal(error
,
320 GDK_PIXBUF_ERROR_CORRUPT_IMAGE
,
321 "could not create Cairo surface from SVG diagram");
326 /* I've gone back and forth on this about five times: we use the
327 * diagram width and height, and not the viewport width and height.
328 * This can ultimately render an image that's larger than the
329 * viewport size, but I think GDK will resize the final pixbuf
330 * anyway. More importantly, rendering small icons at a larger
331 * (viewport) size seems to make the whole thing go ape-shit.
332 * So for now I'm back in the diagram camp.
334 pb
= gdk_pixbuf_get_from_surface(cairo_get_target(cr
),
342 g_set_error_literal(error
,
344 GDK_PIXBUF_ERROR_FAILED
,
345 "failed to obtain a GdkPixbuf from Cairo surface");
352 static gpointer
gdk_pixbuf_begin_load(GdkPixbufModuleSizeFunc size_func
,
353 GdkPixbufModulePreparedFunc prep_func
,
354 GdkPixbufModuleUpdatedFunc updated_func
,
358 SvgTinyContext
* context
= g_new(SvgTinyContext
, 1);
360 context
->size_func
= size_func
;
361 context
->prepared_func
= prep_func
;
362 context
->updated_func
= updated_func
;
363 context
->user_data
= user_data
;
365 context
->svg_data
= NULL
;
366 context
->svg_data_size
= 0;
371 static gboolean
gdk_pixbuf_load_increment(gpointer data
,
375 SvgTinyContext
* context
= (SvgTinyContext
*)data
;
381 context
->svg_data
= g_realloc(context
->svg_data
,
382 context
->svg_data_size
+ buf_size
);
383 memcpy(context
->svg_data
+ context
->svg_data_size
, buf
, buf_size
);
384 context
->svg_data_size
+= buf_size
;
389 static void emit_updated(SvgTinyContext
* context
, GdkPixbuf
* pixbuf
) {
390 if (context
->updated_func
!= NULL
) {
391 (*context
->updated_func
)(pixbuf
,
394 gdk_pixbuf_get_width(pixbuf
),
395 gdk_pixbuf_get_height(pixbuf
),
400 static void emit_prepared(SvgTinyContext
* context
, GdkPixbuf
* pixbuf
) {
401 if (context
->prepared_func
!= NULL
) {
402 (*context
->prepared_func
)(pixbuf
, NULL
, context
->user_data
);
409 * @brief Replace one GTK <xi:include> element by its data.
412 * A pointer to an <xi:include> element node.
414 * @return TRUE if we replaced the node, and FALSE otherwise.
417 static gboolean
process_one_xinclude(xmlNode
* node
) {
420 href
= xmlGetProp(node
, BAD_CAST
"href");
422 /* We only process XIncludes with base64 data hrefs */
426 if (xmlStrncmp(href
, BAD_CAST
"data:text/xml;base64,", 21)) {
427 /* We only process XIncludes with base64 data hrefs */
431 xmlChar
* hrefdata
= href
+21;
433 /* Verify that hrefdata is base64-encoded (and that it's safe to
434 cast to a signed gchar pointer). I'm assuming that everyone is
435 using the RFC 4648 encoding? */
436 for (unsigned int i
=0; i
< xmlStrlen(hrefdata
); i
++) {
437 if (hrefdata
[i
] > 'z') {
440 if (hrefdata
[i
] < '0' && hrefdata
[i
] != '+' && hrefdata
[i
] != '/') {
445 /* WARNING: the xmlChar and guchar types here are compatible, but
446 the decoded data is not necessarily NULL-terminated, while all of
447 the libxml2 functions that operate on a xmlChar pointer assume
450 xmlChar
* decoded
= g_base64_decode((const gchar
*)hrefdata
, &decoded_size
);
452 /* This cast is safe because signed and unsigned chars are the same size,
453 and xmlReadMemory is going to treat the data as binary anyway. */
454 xmlDoc
* xinc_doc
= xmlReadMemory((const char*)decoded
,
461 if (xinc_doc
== NULL
) {
465 xmlNode
* xinc_root
= xmlDocGetRootElement(xinc_doc
);
466 if (xinc_root
== NULL
|| xmlStrcmp(xinc_root
->name
, BAD_CAST
"svg")) {
470 /* Replace the original xinclude "node" with the children of this
471 "svg" node. Do the order of the nodes in an SVG matter? I don't
472 know, but we go to a little bit of extra trouble here to ensure
473 that we put the replacement in the right place, i.e. after its
474 previous sibling (if there is one). */
476 xmlNode
* p
= xmlPreviousElementSibling(node
);
479 /* If there is no previous sibling element, do one AddChild()
480 first. Then we're back to the case of a previous sibling. */
482 cur_node
= xmlFirstElementChild(xinc_root
);
486 cur_node
= xmlFirstElementChild(xinc_root
);
488 /* Without the xmlCopyNode, I get segfaults, and I don't care to
490 p
= xmlAddChild(p
, xmlCopyNode(cur_node
,1));
491 xmlReconciliateNs(p
->doc
, p
);
493 cur_node
= xmlNextElementSibling(cur_node
);
497 g_assert(p
!= NULL
); /* xmlAddChild didn't fail */
503 p
= xmlAddNextSibling(p
, xmlCopyNode(cur_node
,1));
504 xmlReconciliateNs(p
->doc
, p
);
505 cur_node
= xmlNextElementSibling(cur_node
);
508 xmlFreeDoc(xinc_doc
);
514 * @brief Replace all GTK <xi:include> elements in a tree by their data.
517 * A node pointer, to the root of the tree.
519 * @return TRUE if we replaced any <xi:include> element nodes, and
523 static gboolean
process_child_xincludes(xmlNode
* a_node
) {
524 gboolean result
= FALSE
;
525 xmlNode
* cur_node
= a_node
;
528 g_assert(cur_node
== NULL
|| cur_node
->type
== XML_ELEMENT_NODE
);
531 if (!xmlStrcmp(cur_node
->name
, BAD_CAST
"include")) {
532 /* process_one_xinclude() clobbers this node, so we need
533 to get its successor before calling that function. */
534 next_node
= xmlNextElementSibling(cur_node
);
535 if (process_one_xinclude(cur_node
)) {
538 cur_node
= next_node
;
542 if (process_child_xincludes(xmlFirstElementChild(cur_node
))) {
545 cur_node
= xmlNextElementSibling(cur_node
);
553 * @brief Process GTK <xi:include> elements in an SVG buffer.
555 * GTK is very cute. Its gtk-encode-symbolic-svg tool wraps your SVG
556 * in its own boilerplate, but then rather than including your SVG
557 * data verbatim, it includes it via a sketchy XInclude that looks
560 * <xi:include href="data:text/xml;base64,PD94bWwgd..."/>
562 * Librsvg knows how to parse that, but libxml2 doesn't (the latter
563 * can handle an XInclude, just not a base64-encoded data reference).
564 * Fortunately, you can read the source to gtk-encode-symbolic-svg,
565 * and just see what the format of that line will be. Here we're going
566 * to parse out the base64 data, decode it, strip out its opening
567 * <xml> and <svg> tags, and then replace the original <xi:include>
568 * element with the result.
571 * A buffer containing SVG file data.
574 * The size of @c buffer (which may not be NULL-terminated).
577 * A pointer to the size of the new buffer, valid only if the
578 * return value is non-NULL.
580 * @return A pointer to a buffer where the <xi:include> has been
581 * processed. If no replacements were made, the result will be @c
582 * NULL; otherwise, you are expected to @c free it when you are done.
584 static gchar
* process_gtk_symbolic_svg_xinclude(const gchar
* buffer
,
588 xmlDoc
* doc
= xmlReadMemory(buffer
,buf_size
,"symbolic.xml",NULL
,0);
593 xmlNode
* root_element
= xmlDocGetRootElement(doc
);
594 if (root_element
== NULL
) {
598 gchar
* result
= NULL
;
599 if (process_child_xincludes(root_element
)) {
600 /* If we actually replaced something, we need to return the new
601 document in a buffer. */
604 xmlDocDumpFormatMemory(doc
, &xmlbuf
, &xmlbuf_size
, 1);
605 /* We're going to free() this later on with g_free() instead of
606 xmlFree(), so the two "byte" types had better be the same
608 g_assert(sizeof(xmlChar
) == sizeof(gchar
));
609 *new_size
= (gsize
)xmlbuf_size
;
610 result
= (gchar
*)xmlbuf
;
619 static gboolean
gdk_pixbuf_stop_load(gpointer data
, GError
**error
) {
620 SvgTinyContext
* context
= (SvgTinyContext
*)data
;
621 GdkPixbuf
* pixbuf
= NULL
;
622 GError
* sub_error
= NULL
;
624 g_assert(context
!= NULL
);
625 if (context
->svg_data
== NULL
|| context
->svg_data_size
== 0) {
626 /* Is it possible to begin/stop with no increments in between?
627 * I sure don't know. Let's play it safe. */
631 /* If we're inside of gtk-encode-symbolic-svg right now, we need to
632 process the insane librsvg-specific XInclude directive it hands
633 us before proceeding. */
635 gchar
* newdata
= process_gtk_symbolic_svg_xinclude(context
->svg_data
,
636 context
->svg_data_size
,
638 if (newdata
!= NULL
) {
639 g_free(context
->svg_data
);
640 context
->svg_data
= newdata
;
641 context
->svg_data_size
= newsize
;
644 /* OK, we've got an SVG with no XIncludes now. */
645 pixbuf
= gdk_pixbuf_from_svg_buffer(context
->svg_data
,
646 context
->svg_data_size
,
649 if (pixbuf
!= NULL
) {
650 emit_prepared(context
, pixbuf
);
651 emit_updated(context
, pixbuf
);
652 g_object_unref(pixbuf
);
655 g_propagate_error(error
, sub_error
);
658 g_free(context
->svg_data
);
665 G_MODULE_EXPORT
void fill_vtable(GdkPixbufModule
* module);
666 void fill_vtable(GdkPixbufModule
* module) {
667 module->begin_load
= gdk_pixbuf_begin_load
;
668 module->load_increment
= gdk_pixbuf_load_increment
;
669 module->stop_load
= gdk_pixbuf_stop_load
;
672 G_MODULE_EXPORT
void fill_info(GdkPixbufFormat
*info
);
673 void fill_info(GdkPixbufFormat
* info
) {
674 /* Borrowed from librsvg-2.40.21 */
675 static const GdkPixbufModulePattern signature
[] = {
676 { " <svg", "* ", 100 },
677 { " <!DOCTYPE svg", "* ", 100 },
681 /* I'm not sure if we should support gzipped svg here? */
682 static const gchar
*mime_types
[] = {
686 "image/vnd.adobe.svg+xml",
688 "image/svg+xml-compressed",
692 static const gchar
*extensions
[] = {
700 info
->signature
= (GdkPixbufModulePattern
*)signature
;
701 info
->description
= "Scalable Vector Graphics";
702 info
->mime_types
= (gchar
**)mime_types
;
703 info
->extensions
= (gchar
**)extensions
;
704 info
->flags
= GDK_PIXBUF_FORMAT_SCALABLE
;
705 info
->license
= "AGPL3";
710 * @brief Entry point of the svg2png test program.
712 int main(int argc
, char** argv
) {
718 /* Parse arguments, and maybe print usage */
720 g_printf("Usage: %s INPUT OUTPUT\n", argv
[0]);
721 g_printf("Convert an SVG file (INPUT) to a PNG file (OUTPUT)\n");
728 pb
= gdk_pixbuf_new_from_file(svgpath
, &err
);
731 "Error %d in gdk_pixbuf_new_from_file: %s\n",
738 gdk_pixbuf_save(pb
, pngpath
, "png", NULL
, NULL
);