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"
13 /* Declare the two functions that we export. Their names aren't
14 * mentioned in gdk-pixbuf-io.h, but they are required by the
15 * implementation, as you can confirm from the API docs or in
16 * gdk-pixbuf-io.c. The G_MODULE_EXPORT macro is defined in
18 G_MODULE_EXPORT
void fill_vtable(GdkPixbufModule
* module);
19 G_MODULE_EXPORT
void fill_info(GdkPixbufFormat
*info
);
22 /* The width and height of the viewport that we'll render the SVG
23 * into. The final "picture" may not actually be this size; based on
24 * the height, width, viewBox, and preserveAspectRatio attributes in
25 * the SVG itself, libsvgtiny may scale, stretch, offset, etc. the
26 * paths to make them fit nicely into the viewport. */
27 #define VIEWPORT_WIDTH 512
28 #define VIEWPORT_HEIGHT 512
30 /* Convenient typedefs for libsvgtiny */
31 typedef struct svgtiny_diagram diagram_t
;
32 typedef struct svgtiny_shape shape_t
;
35 /* Our main data structure. One of these is created when we start
36 * loading an SVG, and it persists while the SVG is being read. It
37 * contains a few boilerplate members, and the svg_data/svg_data_size
38 * fields that we use to keep track of the buffer where the SVG file
41 GdkPixbufModuleUpdatedFunc updated_func
;
42 GdkPixbufModulePreparedFunc prepared_func
;
45 /* The SVG "file" that we're building in memory. */
48 /* How far into svg_data are we? This should always point to the
49 next empty byte. If (for example) svg_data_size is 2, then
50 svg_data[0] and svg_data[1] are used, but svg_data[2] is free. */
57 * @brief Render an svgtiny path using cairo.
59 * This was lovingly borrowed from @c examples/svgtiny_display_x11.c
60 * in libsvgtiny itself, and modified to use a transparent background.
63 * A pointer to a valid cairo context.
66 * A pointer to an svgtiny shape that will be rendered on the
67 * cairo context's target surface.
69 static void render_path(cairo_t
* cr
, shape_t
* path
) {
73 for (j
= 0; j
!= path
->path_length
; ) {
74 switch ((int) path
->path
[j
]) {
75 case svgtiny_PATH_MOVE
:
81 case svgtiny_PATH_CLOSE
:
85 case svgtiny_PATH_LINE
:
91 case svgtiny_PATH_BEZIER
:
102 if (path
->fill
!= svgtiny_TRANSPARENT
) {
103 cairo_set_source_rgba(cr
,
104 svgtiny_RED(path
->fill
) / 255.0,
105 svgtiny_GREEN(path
->fill
) / 255.0,
106 svgtiny_BLUE(path
->fill
) / 255.0,
108 cairo_fill_preserve(cr
);
110 if (path
->stroke
!= svgtiny_TRANSPARENT
) {
111 cairo_set_source_rgba(cr
,
112 svgtiny_RED(path
->stroke
) / 255.0,
113 svgtiny_GREEN(path
->stroke
) / 255.0,
114 svgtiny_BLUE(path
->stroke
) / 255.0,
116 cairo_set_line_width(cr
, path
->stroke_width
);
117 cairo_stroke_preserve(cr
);
122 * @brief Parse a buffer of SVG data into a diagram_t structure.
125 * The buffer containing the SVG document.
128 * The number of bytes in @c buffer.
130 * @return If successful, a pointer to a @c diagram_t structure is
131 * returned; if not, @c NULL is returned. You are expected to @c
132 * svgtiny_free the result if it is valid.
134 static diagram_t
* svgtiny_diagram_from_buffer(const gchar
* buffer
,
142 diagram
= svgtiny_create();
144 g_set_error_literal(error
,
147 "out of memory in svgtiny_create()");
151 g_assert((int)width
>= 0);
152 g_assert((int)height
>= 0);
154 /* There's a thread-safety issue in libwapcaplet that can cause
155 * svgtiny_parse() to crash if you load lots of SVGs at once:
157 * https://bugs.netsurf-browser.org/mantis/view.php?id=2857
159 * Putting a lock around svgtiny_parse() is a pretty simple solution
160 * and looks like it does the trick.
163 g_mutex_lock(&mutex
);
164 code
= svgtiny_parse(diagram
,
169 g_mutex_unlock (&mutex
);
173 /* The one success case. */
175 case svgtiny_OUT_OF_MEMORY
:
176 g_set_error_literal(error
,
179 "out of memory in svgtiny_parse()");
181 case svgtiny_LIBDOM_ERROR
:
182 g_set_error_literal(error
,
184 GDK_PIXBUF_ERROR_CORRUPT_IMAGE
,
185 "invalid XML DOM in svgtiny_parse()");
187 case svgtiny_NOT_SVG
:
188 g_set_error_literal(error
,
190 GDK_PIXBUF_ERROR_CORRUPT_IMAGE
,
191 "missing <svg> element in svgtiny_parse()");
193 case svgtiny_SVG_ERROR
:
196 GDK_PIXBUF_ERROR_CORRUPT_IMAGE
,
197 "SVG format error in svgtiny_parse() on line %i: %s",
199 diagram
->error_message
);
203 /* All other cases above are failure */
208 * @brief Create a cairo context from a libsvgtiny diagram.
211 * A pointer to a valid libsvgtiny diagram.
213 * @return If successful, a pointer to a @c cairo_t context structure
214 * is returned; if not, @c NULL is returned. You are expected to @c
215 * cairo_destroy the result if it is valid.
217 static cairo_t
* cairo_context_from_diagram(const diagram_t
* diagram
) {
219 cairo_surface_t
* surface
;
223 surface
= cairo_image_surface_create(CAIRO_FORMAT_ARGB32
,
227 crs
= cairo_surface_status(surface
);
228 if (crs
!= CAIRO_STATUS_SUCCESS
) {
230 "cairo_image_surface_create failed: %s\n",
231 cairo_status_to_string(crs
));
232 cairo_surface_destroy(surface
);
236 cr
= cairo_create(surface
);
237 crs
= cairo_status(cr
);
239 /* Immediately destroy the surface which is now accessible as
241 cairo_surface_destroy(surface
);
243 if (crs
!= CAIRO_STATUS_SUCCESS
) {
245 "cairo_create failed: %s\n",
246 cairo_status_to_string(crs
));
251 cairo_set_source_rgba(cr
, 0, 0, 0, 0);
254 /* Loop through the shapes in the diagram... */
255 for (i
= 0; i
!= diagram
->shape_count
; i
++) {
257 /* If this shape is a path, just render it. */
258 if (diagram
->shape
[i
].path
) {
259 render_path(cr
, &diagram
->shape
[i
]);
262 /* If this shape is text... */
263 if (diagram
->shape
[i
].text
) {
264 /* Figure out what color to use from the R/G/B components of the
266 cairo_set_source_rgba(cr
,
267 svgtiny_RED(diagram
->shape
[i
].stroke
) / 255.0,
268 svgtiny_GREEN(diagram
->shape
[i
].stroke
) / 255.0,
269 svgtiny_BLUE(diagram
->shape
[i
].stroke
) / 255.0,
271 /* Then move to the actual position of the text within the
274 diagram
->shape
[i
].text_x
,
275 diagram
->shape
[i
].text_y
);
278 cairo_show_text(cr
, diagram
->shape
[i
].text
);
283 /* Check the status again just for good measure? */
284 crs
= cairo_status(cr
);
285 if (crs
!= CAIRO_STATUS_SUCCESS
) {
288 cairo_status_to_string(crs
));
297 * @brief Create a GdkPixbuf from a buffer of SVG data.
300 * The buffer containing the SVG document.
303 * The number of bytes in @c buffer.
306 * The address of a @c GError pointer that we use to return errors.
308 * @return If successful, a valid pointer to a @c GdkPixbuf is
309 * returned; if not, @c NULL is returned and @c error is populated.
311 static GdkPixbuf
* gdk_pixbuf_from_svg_buffer(const gchar
* buffer
,
317 GError
* sub_error
= NULL
;
319 diagram
= svgtiny_diagram_from_buffer(buffer
,
325 g_propagate_error(error
, sub_error
);
329 cr
= cairo_context_from_diagram(diagram
);
331 svgtiny_free(diagram
);
332 g_set_error_literal(error
,
334 GDK_PIXBUF_ERROR_CORRUPT_IMAGE
,
335 "could not create Cairo surface from SVG diagram");
340 /* I've gone back and forth on this about five times: we use the
341 * diagram width and height, and not the viewport width and height.
342 * This can ultimately render an image that's larger than the
343 * viewport size, but I think GDK will resize the final pixbuf
344 * anyway. More importantly, rendering small icons at a larger
345 * (viewport) size seems to make the whole thing go ape-shit.
346 * So for now I'm back in the diagram camp.
348 pb
= gdk_pixbuf_get_from_surface(cairo_get_target(cr
),
356 g_set_error_literal(error
,
358 GDK_PIXBUF_ERROR_FAILED
,
359 "failed to obtain a GdkPixbuf from Cairo surface");
367 * @brief Our implementation of GdkPixbufModuleBeginLoadFunc, as
368 * defined in gdk-pixbuf-io.h.
370 static gpointer
gdk_pixbuf_begin_load(GdkPixbufModuleSizeFunc size_func
,
371 GdkPixbufModulePreparedFunc prep_func
,
372 GdkPixbufModuleUpdatedFunc updated_func
,
376 SvgTinyContext
* context
= g_new(SvgTinyContext
, 1);
378 context
->prepared_func
= prep_func
;
379 context
->updated_func
= updated_func
;
380 context
->user_data
= user_data
;
382 context
->svg_data
= NULL
;
383 context
->svg_data_size
= 0;
390 * @brief Our implementation of GdkPixbufModuleIncrementLoadFunc, as
391 * defined in gdk-pixbuf-io.h.
393 static gboolean
gdk_pixbuf_load_increment(gpointer data
,
397 SvgTinyContext
* context
= (SvgTinyContext
*)data
;
403 context
->svg_data
= g_realloc(context
->svg_data
,
404 context
->svg_data_size
+ buf_size
);
405 memcpy(context
->svg_data
+ context
->svg_data_size
, buf
, buf_size
);
406 context
->svg_data_size
+= buf_size
;
412 * @brief Convenience function to execute the "updated" callback
413 * stored in our @c context.
415 static void emit_updated(SvgTinyContext
* context
, GdkPixbuf
* pixbuf
) {
416 if (context
->updated_func
!= NULL
) {
417 (*context
->updated_func
)(pixbuf
,
420 gdk_pixbuf_get_width(pixbuf
),
421 gdk_pixbuf_get_height(pixbuf
),
427 * @brief Convenience function to execute the "prepared" callback
428 * stored in our @c context.
430 static void emit_prepared(SvgTinyContext
* context
, GdkPixbuf
* pixbuf
) {
431 if (context
->prepared_func
!= NULL
) {
432 (*context
->prepared_func
)(pixbuf
, NULL
, context
->user_data
);
439 * @brief Replace one GTK <xi:include> element by its data.
442 * A pointer to an <xi:include> element node.
444 * @return TRUE if we replaced the node, and FALSE otherwise.
447 static gboolean
process_one_xinclude(xmlNode
* node
) {
450 href
= xmlGetProp(node
, BAD_CAST
"href");
452 /* We only process XIncludes with base64 data hrefs */
456 if (xmlStrncmp(href
, BAD_CAST
"data:text/xml;base64,", 21)) {
457 /* We only process XIncludes with base64 data hrefs */
461 xmlChar
* hrefdata
= href
+21;
463 /* Verify that hrefdata is base64-encoded (and that it's safe to
464 cast to a signed gchar pointer). I'm assuming that everyone is
465 using the RFC 4648 encoding? */
466 for (unsigned int i
=0; i
< xmlStrlen(hrefdata
); i
++) {
467 if (hrefdata
[i
] > 'z') {
470 if (hrefdata
[i
] < '0' && hrefdata
[i
] != '+' && hrefdata
[i
] != '/') {
475 /* WARNING: the xmlChar and guchar types here are compatible, but
476 the decoded data is not necessarily NULL-terminated, while all of
477 the libxml2 functions that operate on a xmlChar pointer assume
480 xmlChar
* decoded
= g_base64_decode((const gchar
*)hrefdata
, &decoded_size
);
482 /* This cast is safe because signed and unsigned chars are the same size,
483 and xmlReadMemory is going to treat the data as binary anyway. */
484 xmlDoc
* xinc_doc
= xmlReadMemory((const char*)decoded
,
491 if (xinc_doc
== NULL
) {
495 xmlNode
* xinc_root
= xmlDocGetRootElement(xinc_doc
);
496 if (xinc_root
== NULL
|| xmlStrcmp(xinc_root
->name
, BAD_CAST
"svg")) {
500 /* Replace the original xinclude "node" with the children of this
501 "svg" node. Do the order of the nodes in an SVG matter? I don't
502 know, but we go to a little bit of extra trouble here to ensure
503 that we put the replacement in the right place, i.e. after its
504 previous sibling (if there is one). */
506 xmlNode
* p
= xmlPreviousElementSibling(node
);
509 /* If there is no previous sibling element, do one AddChild()
510 first. Then we're back to the case of a previous sibling. */
512 cur_node
= xmlFirstElementChild(xinc_root
);
516 cur_node
= xmlFirstElementChild(xinc_root
);
518 /* Without the xmlCopyNode, I get segfaults, and I don't care to
520 p
= xmlAddChild(p
, xmlCopyNode(cur_node
,1));
521 xmlReconciliateNs(p
->doc
, p
);
523 cur_node
= xmlNextElementSibling(cur_node
);
527 g_assert(p
!= NULL
); /* xmlAddChild didn't fail */
533 p
= xmlAddNextSibling(p
, xmlCopyNode(cur_node
,1));
534 xmlReconciliateNs(p
->doc
, p
);
535 cur_node
= xmlNextElementSibling(cur_node
);
538 xmlFreeDoc(xinc_doc
);
544 * @brief Replace all GTK <xi:include> elements in a tree by their data.
547 * A node pointer, to the root of the tree.
549 * @return TRUE if we replaced any <xi:include> element nodes, and
553 static gboolean
process_child_xincludes(xmlNode
* a_node
) {
554 gboolean result
= FALSE
;
555 xmlNode
* cur_node
= a_node
;
558 g_assert(cur_node
== NULL
|| cur_node
->type
== XML_ELEMENT_NODE
);
561 if (!xmlStrcmp(cur_node
->name
, BAD_CAST
"include")) {
562 /* process_one_xinclude() clobbers this node, so we need
563 to get its successor before calling that function. */
564 next_node
= xmlNextElementSibling(cur_node
);
565 if (process_one_xinclude(cur_node
)) {
568 cur_node
= next_node
;
572 if (process_child_xincludes(xmlFirstElementChild(cur_node
))) {
575 cur_node
= xmlNextElementSibling(cur_node
);
583 * @brief Process GTK <xi:include> elements in an SVG buffer.
585 * GTK is very cute. Its gtk-encode-symbolic-svg tool wraps your SVG
586 * in its own boilerplate, but then rather than including your SVG
587 * data verbatim, it includes it via a sketchy XInclude that looks
590 * <xi:include href="data:text/xml;base64,PD94bWwgd..."/>
592 * Librsvg knows how to parse that, but libxml2 doesn't (the latter
593 * can handle an XInclude, just not a base64-encoded data reference).
594 * Fortunately, you can read the source to gtk-encode-symbolic-svg,
595 * and just see what the format of that line will be. Here we're going
596 * to parse out the base64 data, decode it, strip out its opening
597 * <xml> and <svg> tags, and then replace the original <xi:include>
598 * element with the result.
601 * A buffer containing SVG file data.
604 * The size of @c buffer (which may not be NULL-terminated).
607 * A pointer to the size of the new buffer, valid only if the
608 * return value is non-NULL.
610 * @return A pointer to a buffer where the <xi:include> has been
611 * processed. If no replacements were made, the result will be @c
612 * NULL; otherwise, you are expected to @c free it when you are done.
614 static gchar
* process_gtk_symbolic_svg_xinclude(const gchar
* buffer
,
618 xmlDoc
* doc
= xmlReadMemory(buffer
,buf_size
,"symbolic.xml",NULL
,0);
623 xmlNode
* root_element
= xmlDocGetRootElement(doc
);
624 if (root_element
== NULL
) {
628 gchar
* result
= NULL
;
629 if (process_child_xincludes(root_element
)) {
630 /* If we actually replaced something, we need to return the new
631 document in a buffer. */
634 xmlDocDumpFormatMemory(doc
, &xmlbuf
, &xmlbuf_size
, 1);
635 /* We're going to free() this later on with g_free() instead of
636 xmlFree(), so the two "byte" types had better be the same
638 g_assert(sizeof(xmlChar
) == sizeof(gchar
));
639 *new_size
= (gsize
)xmlbuf_size
;
640 result
= (gchar
*)xmlbuf
;
650 * @brief Our implementation of GdkPixbufModuleStopLoadFunc, as
651 * defined in gdk-pixbuf-io.h.
653 static gboolean
gdk_pixbuf_stop_load(gpointer data
, GError
**error
) {
654 SvgTinyContext
* context
= (SvgTinyContext
*)data
;
655 GdkPixbuf
* pixbuf
= NULL
;
656 GError
* sub_error
= NULL
;
658 g_assert(context
!= NULL
);
659 if (context
->svg_data
== NULL
|| context
->svg_data_size
== 0) {
660 /* Is it possible to begin/stop with no increments in between?
661 * I sure don't know. Let's play it safe. */
665 /* If we're inside of gtk-encode-symbolic-svg right now, we need to
666 process the insane librsvg-specific XInclude directive it hands
667 us before proceeding. */
669 gchar
* newdata
= process_gtk_symbolic_svg_xinclude(context
->svg_data
,
670 context
->svg_data_size
,
672 if (newdata
!= NULL
) {
673 g_free(context
->svg_data
);
674 context
->svg_data
= newdata
;
675 context
->svg_data_size
= newsize
;
678 /* OK, we've got an SVG with no XIncludes now. */
679 pixbuf
= gdk_pixbuf_from_svg_buffer(context
->svg_data
,
680 context
->svg_data_size
,
683 if (pixbuf
!= NULL
) {
684 emit_prepared(context
, pixbuf
);
685 emit_updated(context
, pixbuf
);
686 g_object_unref(pixbuf
);
689 g_propagate_error(error
, sub_error
);
692 g_free(context
->svg_data
);
700 * @brief Our implementation of GdkPixbufModuleFillVtableFunc, as
701 * defined in gdk-pixbuf-io.h.
703 void fill_vtable(GdkPixbufModule
* module) {
704 module->begin_load
= gdk_pixbuf_begin_load
;
705 module->load_increment
= gdk_pixbuf_load_increment
;
706 module->stop_load
= gdk_pixbuf_stop_load
;
710 * @brief Our implementation of GdkPixbufModuleFillInfoFunc, as
711 * defined in gdk-pixbuf-io.h.
713 void fill_info(GdkPixbufFormat
* info
) {
714 /* Borrowed from librsvg-2.40.21 */
715 static const GdkPixbufModulePattern signature
[] = {
716 { " <svg", "* ", 100 },
717 { " <!DOCTYPE svg", "* ", 100 },
721 /* I'm not sure if we should support gzipped svg here? */
722 static const gchar
*mime_types
[] = {
726 "image/vnd.adobe.svg+xml",
728 "image/svg+xml-compressed",
732 static const gchar
*extensions
[] = {
740 info
->signature
= (GdkPixbufModulePattern
*)signature
;
741 info
->description
= "Scalable Vector Graphics";
742 info
->mime_types
= (gchar
**)mime_types
;
743 info
->extensions
= (gchar
**)extensions
;
744 info
->flags
= GDK_PIXBUF_FORMAT_SCALABLE
;
745 info
->license
= "AGPL3";
750 * @brief Entry point of the svg2png test program.
752 int main(int argc
, char** argv
) {
758 /* Parse arguments, and maybe print usage */
760 g_printf("Usage: %s INPUT OUTPUT\n", argv
[0]);
761 g_printf("Convert an SVG file (INPUT) to a PNG file (OUTPUT)\n");
768 pb
= gdk_pixbuf_new_from_file(svgpath
, &err
);
771 "Error %d in gdk_pixbuf_new_from_file: %s\n",
778 gdk_pixbuf_save(pb
, pngpath
, "png", NULL
, NULL
);