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);
138 /* There's a thread-safety issue in libwapcaplet that can cause
139 * svgtiny_parse() to crash if you load lots of SVGs at once:
141 * https://bugs.netsurf-browser.org/mantis/view.php?id=2857
143 * Putting a lock around svgtiny_parse() is a pretty simple solution
144 * and looks like it does the trick.
147 g_mutex_lock(&mutex
);
148 code
= svgtiny_parse(diagram
,
153 g_mutex_unlock (&mutex
);
157 /* The one success case. */
159 case svgtiny_OUT_OF_MEMORY
:
160 g_set_error_literal(error
,
163 "out of memory in svgtiny_parse()");
165 case svgtiny_LIBDOM_ERROR
:
166 g_set_error_literal(error
,
168 GDK_PIXBUF_ERROR_CORRUPT_IMAGE
,
169 "invalid XML DOM in svgtiny_parse()");
171 case svgtiny_NOT_SVG
:
172 g_set_error_literal(error
,
174 GDK_PIXBUF_ERROR_CORRUPT_IMAGE
,
175 "missing <svg> element in svgtiny_parse()");
177 case svgtiny_SVG_ERROR
:
180 GDK_PIXBUF_ERROR_CORRUPT_IMAGE
,
181 "SVG format error in svgtiny_parse() on line %i: %s",
183 diagram
->error_message
);
187 /* All other cases above are failure */
192 * @brief Create a cairo context from a libsvgtiny diagram.
195 * A pointer to a valid libsvgtiny diagram.
197 * @return If successful, a pointer to a @c cairo_t context structure
198 * is returned; if not, @c NULL is returned. You are expected to @c
199 * cairo_destroy the result if it is valid.
201 static cairo_t
* cairo_context_from_diagram(const diagram_t
* diagram
) {
203 cairo_surface_t
* surface
;
207 surface
= cairo_image_surface_create(CAIRO_FORMAT_ARGB32
,
211 crs
= cairo_surface_status(surface
);
212 if (crs
!= CAIRO_STATUS_SUCCESS
) {
214 "cairo_image_surface_create failed: %s\n",
215 cairo_status_to_string(crs
));
216 cairo_surface_destroy(surface
);
220 cr
= cairo_create(surface
);
221 crs
= cairo_status(cr
);
223 /* Immediately destroy the surface which is now accessible as
225 cairo_surface_destroy(surface
);
227 if (crs
!= CAIRO_STATUS_SUCCESS
) {
229 "cairo_create failed: %s\n",
230 cairo_status_to_string(crs
));
235 cairo_set_source_rgba(cr
, 0, 0, 0, 0);
238 /* Loop through the shapes in the diagram... */
239 for (i
= 0; i
!= diagram
->shape_count
; i
++) {
241 /* If this shape is a path, just render it. */
242 if (diagram
->shape
[i
].path
) {
243 render_path(cr
, &diagram
->shape
[i
]);
246 /* If this shape is text... */
247 if (diagram
->shape
[i
].text
) {
248 /* Figure out what color to use from the R/G/B components of the
250 cairo_set_source_rgba(cr
,
251 svgtiny_RED(diagram
->shape
[i
].stroke
) / 255.0,
252 svgtiny_GREEN(diagram
->shape
[i
].stroke
) / 255.0,
253 svgtiny_BLUE(diagram
->shape
[i
].stroke
) / 255.0,
255 /* Then move to the actual position of the text within the
258 diagram
->shape
[i
].text_x
,
259 diagram
->shape
[i
].text_y
);
262 cairo_show_text(cr
, diagram
->shape
[i
].text
);
267 /* Check the status again just for good measure? */
268 crs
= cairo_status(cr
);
269 if (crs
!= CAIRO_STATUS_SUCCESS
) {
272 cairo_status_to_string(crs
));
281 * @brief Create a GdkPixbuf from a buffer of SVG data.
284 * The buffer containing the SVG document.
287 * The number of bytes in @c buffer.
290 * The address of a @c GError pointer that we use to return errors.
292 * @return If successful, a valid pointer to a @c GdkPixbuf is
293 * returned; if not, @c NULL is returned and @c error is populated.
295 static GdkPixbuf
* gdk_pixbuf_from_svg_buffer(const gchar
* buffer
,
301 GError
* sub_error
= NULL
;
303 diagram
= svgtiny_diagram_from_buffer(buffer
,
309 g_propagate_error(error
, sub_error
);
313 cr
= cairo_context_from_diagram(diagram
);
315 svgtiny_free(diagram
);
316 g_set_error_literal(error
,
318 GDK_PIXBUF_ERROR_CORRUPT_IMAGE
,
319 "could not create Cairo surface from SVG diagram");
324 /* I've gone back and forth on this about five times: we use the
325 * diagram width and height, and not the viewport width and height.
326 * This can ultimately render an image that's larger than the
327 * viewport size, but I think GDK will resize the final pixbuf
328 * anyway. More importantly, rendering small icons at a larger
329 * (viewport) size seems to make the whole thing go ape-shit.
330 * So for now I'm back in the diagram camp.
332 pb
= gdk_pixbuf_get_from_surface(cairo_get_target(cr
),
340 g_set_error_literal(error
,
342 GDK_PIXBUF_ERROR_FAILED
,
343 "failed to obtain a GdkPixbuf from Cairo surface");
350 static gpointer
gdk_pixbuf_begin_load(GdkPixbufModuleSizeFunc size_func
,
351 GdkPixbufModulePreparedFunc prep_func
,
352 GdkPixbufModuleUpdatedFunc updated_func
,
356 SvgTinyContext
* context
= g_new(SvgTinyContext
, 1);
358 context
->size_func
= size_func
;
359 context
->prepared_func
= prep_func
;
360 context
->updated_func
= updated_func
;
361 context
->user_data
= user_data
;
363 context
->svg_data
= NULL
;
364 context
->svg_data_size
= 0;
369 static gboolean
gdk_pixbuf_load_increment(gpointer data
,
373 SvgTinyContext
* context
= (SvgTinyContext
*)data
;
379 context
->svg_data
= g_realloc(context
->svg_data
,
380 context
->svg_data_size
+ buf_size
);
381 memcpy(context
->svg_data
+ context
->svg_data_size
, buf
, buf_size
);
382 context
->svg_data_size
+= buf_size
;
387 static void emit_updated(SvgTinyContext
* context
, GdkPixbuf
* pixbuf
) {
388 if (context
->updated_func
!= NULL
) {
389 (*context
->updated_func
)(pixbuf
,
392 gdk_pixbuf_get_width(pixbuf
),
393 gdk_pixbuf_get_height(pixbuf
),
398 static void emit_prepared(SvgTinyContext
* context
, GdkPixbuf
* pixbuf
) {
399 if (context
->prepared_func
!= NULL
) {
400 (*context
->prepared_func
)(pixbuf
, NULL
, context
->user_data
);
407 * @brief Replace one GTK <xi:include> element by its data.
410 * A pointer to an <xi:include> element node.
412 * @return TRUE if we replaced the node, and FALSE otherwise.
415 static gboolean
process_one_xinclude(xmlNode
* node
) {
418 href
= xmlGetProp(node
, BAD_CAST
"href");
420 /* We only process XIncludes with base64 data hrefs */
424 if (xmlStrncmp(href
, BAD_CAST
"data:text/xml;base64,", 21)) {
425 /* We only process XIncludes with base64 data hrefs */
429 xmlChar
* hrefdata
= href
+21;
431 /* Verify that hrefdata is base64-encoded (and that it's safe to
432 cast to a signed gchar pointer). I'm assuming that everyone is
433 using the RFC 4648 encoding? */
434 for (unsigned int i
=0; i
< xmlStrlen(hrefdata
); i
++) {
435 if (hrefdata
[i
] > 'z') {
438 if (hrefdata
[i
] < '0' && hrefdata
[i
] != '+' && hrefdata
[i
] != '/') {
443 /* WARNING: the xmlChar and guchar types here are compatible, but
444 the decoded data is not necessarily NULL-terminated, while all of
445 the libxml2 functions that operate on a xmlChar pointer assume
448 xmlChar
* decoded
= g_base64_decode((const gchar
*)hrefdata
, &decoded_size
);
450 /* This cast is safe because signed and unsigned chars are the same size,
451 and xmlReadMemory is going to treat the data as binary anyway. */
452 xmlDoc
* xinc_doc
= xmlReadMemory((const char*)decoded
,
459 if (xinc_doc
== NULL
) {
463 xmlNode
* xinc_root
= xmlDocGetRootElement(xinc_doc
);
464 if (xinc_root
== NULL
|| xmlStrcmp(xinc_root
->name
, BAD_CAST
"svg")) {
468 /* Replace the original xinclude "node" with the children of this
469 "svg" node. Do the order of the nodes in an SVG matter? I don't
470 know, but we go to a little bit of extra trouble here to ensure
471 that we put the replacement in the right place, i.e. after its
472 previous sibling (if there is one). */
474 xmlNode
* p
= xmlPreviousElementSibling(node
);
477 /* If there is no previous sibling element, do one AddChild()
478 first. Then we're back to the case of a previous sibling. */
480 cur_node
= xmlFirstElementChild(xinc_root
);
484 cur_node
= xmlFirstElementChild(xinc_root
);
486 /* Without the xmlCopyNode, I get segfaults, and I don't care to
488 p
= xmlAddChild(p
, xmlCopyNode(cur_node
,1));
489 xmlReconciliateNs(p
->doc
, p
);
491 cur_node
= xmlNextElementSibling(cur_node
);
495 g_assert(p
!= NULL
); /* xmlAddChild didn't fail */
501 p
= xmlAddNextSibling(p
, xmlCopyNode(cur_node
,1));
502 xmlReconciliateNs(p
->doc
, p
);
503 cur_node
= xmlNextElementSibling(cur_node
);
506 xmlFreeDoc(xinc_doc
);
512 * @brief Replace all GTK <xi:include> elements in a tree by their data.
515 * A node pointer, to the root of the tree.
517 * @return TRUE if we replaced any <xi:include> element nodes, and
521 static gboolean
process_child_xincludes(xmlNode
* a_node
) {
522 gboolean result
= FALSE
;
523 xmlNode
* cur_node
= a_node
;
526 g_assert(cur_node
== NULL
|| cur_node
->type
== XML_ELEMENT_NODE
);
529 if (!xmlStrcmp(cur_node
->name
, BAD_CAST
"include")) {
530 /* process_one_xinclude() clobbers this node, so we need
531 to get its successor before calling that function. */
532 next_node
= xmlNextElementSibling(cur_node
);
533 if (process_one_xinclude(cur_node
)) {
536 cur_node
= next_node
;
540 if (process_child_xincludes(xmlFirstElementChild(cur_node
))) {
543 cur_node
= xmlNextElementSibling(cur_node
);
551 * @brief Process GTK <xi:include> elements in an SVG buffer.
553 * GTK is very cute. Its gtk-encode-symbolic-svg tool wraps your SVG
554 * in its own boilerplate, but then rather than including your SVG
555 * data verbatim, it includes it via a sketchy XInclude that looks
558 * <xi:include href="data:text/xml;base64,PD94bWwgd..."/>
560 * Librsvg knows how to parse that, but libxml2 doesn't (the latter
561 * can handle an XInclude, just not a base64-encoded data reference).
562 * Fortunately, you can read the source to gtk-encode-symbolic-svg,
563 * and just see what the format of that line will be. Here we're going
564 * to parse out the base64 data, decode it, strip out its opening
565 * <xml> and <svg> tags, and then replace the original <xi:include>
566 * element with the result.
569 * A buffer containing SVG file data.
572 * The size of @c buffer (which may not be NULL-terminated).
575 * A pointer to the size of the new buffer, valid only if the
576 * return value is non-NULL.
578 * @return A pointer to a buffer where the <xi:include> has been
579 * processed. If no replacements were made, the result will be @c
580 * NULL; otherwise, you are expected to @c free it when you are done.
582 static gchar
* process_gtk_symbolic_svg_xinclude(const gchar
* buffer
,
586 xmlDoc
* doc
= xmlReadMemory(buffer
,buf_size
,"symbolic.xml",NULL
,0);
591 xmlNode
* root_element
= xmlDocGetRootElement(doc
);
592 if (root_element
== NULL
) {
596 gchar
* result
= NULL
;
597 if (process_child_xincludes(root_element
)) {
598 /* If we actually replaced something, we need to return the new
599 document in a buffer. */
602 xmlDocDumpFormatMemory(doc
, &xmlbuf
, &xmlbuf_size
, 1);
603 /* We're going to free() this later on with g_free() instead of
604 xmlFree(), so the two "byte" types had better be the same
606 g_assert(sizeof(xmlChar
) == sizeof(gchar
));
607 *new_size
= (gsize
)xmlbuf_size
;
608 result
= (gchar
*)xmlbuf
;
617 static gboolean
gdk_pixbuf_stop_load(gpointer data
, GError
**error
) {
618 SvgTinyContext
* context
= (SvgTinyContext
*)data
;
619 GdkPixbuf
* pixbuf
= NULL
;
620 GError
* sub_error
= NULL
;
622 g_assert(context
!= NULL
);
623 if (context
->svg_data
== NULL
|| context
->svg_data_size
== 0) {
624 /* Is it possible to begin/stop with no increments in between?
625 * I sure don't know. Let's play it safe. */
629 /* If we're inside of gtk-encode-symbolic-svg right now, we need to
630 process the insane librsvg-specific XInclude directive it hands
631 us before proceeding. */
633 gchar
* newdata
= process_gtk_symbolic_svg_xinclude(context
->svg_data
,
634 context
->svg_data_size
,
636 if (newdata
!= NULL
) {
637 g_free(context
->svg_data
);
638 context
->svg_data
= newdata
;
639 context
->svg_data_size
= newsize
;
642 /* OK, we've got an SVG with no XIncludes now. */
643 pixbuf
= gdk_pixbuf_from_svg_buffer(context
->svg_data
,
644 context
->svg_data_size
,
647 if (pixbuf
!= NULL
) {
648 emit_prepared(context
, pixbuf
);
649 emit_updated(context
, pixbuf
);
650 g_object_unref(pixbuf
);
653 g_propagate_error(error
, sub_error
);
656 g_free(context
->svg_data
);
663 G_MODULE_EXPORT
void fill_vtable(GdkPixbufModule
* module);
664 void fill_vtable(GdkPixbufModule
* module) {
665 module->begin_load
= gdk_pixbuf_begin_load
;
666 module->load_increment
= gdk_pixbuf_load_increment
;
667 module->stop_load
= gdk_pixbuf_stop_load
;
670 G_MODULE_EXPORT
void fill_info(GdkPixbufFormat
*info
);
671 void fill_info(GdkPixbufFormat
* info
) {
672 /* Borrowed from librsvg-2.40.21 */
673 static const GdkPixbufModulePattern signature
[] = {
674 { " <svg", "* ", 100 },
675 { " <!DOCTYPE svg", "* ", 100 },
679 /* I'm not sure if we should support gzipped svg here? */
680 static const gchar
*mime_types
[] = {
684 "image/vnd.adobe.svg+xml",
686 "image/svg+xml-compressed",
690 static const gchar
*extensions
[] = {
698 info
->signature
= (GdkPixbufModulePattern
*)signature
;
699 info
->description
= "Scalable Vector Graphics";
700 info
->mime_types
= (gchar
**)mime_types
;
701 info
->extensions
= (gchar
**)extensions
;
702 info
->flags
= GDK_PIXBUF_FORMAT_SCALABLE
;
703 info
->license
= "AGPL3";
708 * @brief Entry point of the svg2png test program.
710 int main(int argc
, char** argv
) {
716 /* Parse arguments, and maybe print usage */
718 g_printf("Usage: %s INPUT OUTPUT\n", argv
[0]);
719 g_printf("Convert an SVG file (INPUT) to a PNG file (OUTPUT)\n");
726 pb
= gdk_pixbuf_new_from_file(svgpath
, &err
);
729 "Error %d in gdk_pixbuf_new_from_file: %s\n",
736 gdk_pixbuf_save(pb
, pngpath
, "png", NULL
, NULL
);