#include /* memcpy, memset */ #include #include #include /* includes glib.h */ #include #include /* * The width and height of the viewport that we'll render the SVG * into. The final "picture" may not actually be this size; based on * the height, width, viewBox, and preserveAspectRatio attributes in * the SVG itself, libsvgtiny may scale, stretch, offset, etc. the * paths to make them fit nicely into the viewport. */ #define VIEWPORT_WIDTH 512 #define VIEWPORT_HEIGHT 512 /* The start of an XInclude that was inserted by * gtk-encode-symbolic-svg */ #define XI_SIGNATURE "path_length; ) { switch ((int) path->path[j]) { case svgtiny_PATH_MOVE: cairo_move_to(cr, path->path[j + 1], path->path[j + 2]); j += 3; break; case svgtiny_PATH_CLOSE: cairo_close_path(cr); j += 1; break; case svgtiny_PATH_LINE: cairo_line_to(cr, path->path[j + 1], path->path[j + 2]); j += 3; break; case svgtiny_PATH_BEZIER: cairo_curve_to(cr, path->path[j + 1], path->path[j + 2], path->path[j + 3], path->path[j + 4], path->path[j + 5], path->path[j + 6]); j += 7; } } if (path->fill != svgtiny_TRANSPARENT) { cairo_set_source_rgba(cr, svgtiny_RED(path->fill) / 255.0, svgtiny_GREEN(path->fill) / 255.0, svgtiny_BLUE(path->fill) / 255.0, 1); cairo_fill_preserve(cr); } if (path->stroke != svgtiny_TRANSPARENT) { cairo_set_source_rgba(cr, svgtiny_RED(path->stroke) / 255.0, svgtiny_GREEN(path->stroke) / 255.0, svgtiny_BLUE(path->stroke) / 255.0, 1); cairo_set_line_width(cr, path->stroke_width); cairo_stroke_preserve(cr); } } /** * @brief Parse a buffer of SVG data into a diagram_t structure. * * @param buffer * The buffer containing the SVG document. * * @param bytecount * The number of bytes in @c buffer. * * @return If successful, a pointer to a @c diagram_t structure is * returned; if not, @c NULL is returned. You are expected to @c * svgtiny_free the result if it is valid. */ static diagram_t* svgtiny_diagram_from_buffer(char* buffer, size_t bytecount, int width, int height, GError** error) { diagram_t* diagram; svgtiny_code code; diagram = svgtiny_create(); if (!diagram) { g_set_error_literal(error, G_FILE_ERROR, G_FILE_ERROR_NOMEM, "out of memory in svgtiny_create()"); return NULL; } code = svgtiny_parse(diagram, buffer, bytecount, "", width, height); switch(code) { case svgtiny_OK: /* The one success case. */ return diagram; case svgtiny_OUT_OF_MEMORY: g_set_error_literal(error, G_FILE_ERROR, G_FILE_ERROR_NOMEM, "out of memory in svgtiny_parse()"); break; case svgtiny_LIBDOM_ERROR: g_set_error_literal(error, GDK_PIXBUF_ERROR, GDK_PIXBUF_ERROR_CORRUPT_IMAGE, "invalid XML DOM in svgtiny_parse()"); break; case svgtiny_NOT_SVG: g_set_error_literal(error, GDK_PIXBUF_ERROR, GDK_PIXBUF_ERROR_CORRUPT_IMAGE, "missing element in svgtiny_parse()"); break; case svgtiny_SVG_ERROR: g_set_error(error, GDK_PIXBUF_ERROR, GDK_PIXBUF_ERROR_CORRUPT_IMAGE, "SVG format error in svgtiny_parse() on line %i: %s", diagram->error_line, diagram->error_message); break; } /* All other cases above are failure */ return NULL; } /** * @brief Create a cairo context from a libsvgtiny diagram. * * @param diagram * A pointer to a valid libsvgtiny diagram. * * @return If successful, a pointer to a @c cairo_t context structure * is returned; if not, @c NULL is returned. You are expected to @c * cairo_destroy the result if it is valid. */ static cairo_t* cairo_context_from_diagram(diagram_t* diagram) { cairo_t* cr; cairo_surface_t* surface; cairo_status_t crs; unsigned int i; surface = cairo_image_surface_create(CAIRO_FORMAT_ARGB32, diagram->width, diagram->height); crs = cairo_surface_status(surface); if (crs != CAIRO_STATUS_SUCCESS) { g_fprintf(stderr, "cairo_image_surface_create failed: %s\n", cairo_status_to_string(crs)); cairo_surface_destroy(surface); return NULL; } cr = cairo_create(surface); crs = cairo_status(cr); /* Immediately destroy the surface which is now accessible as cr->target */ cairo_surface_destroy(surface); if (crs != CAIRO_STATUS_SUCCESS) { g_fprintf(stderr, "cairo_create failed: %s\n", cairo_status_to_string(crs)); cairo_destroy(cr); return NULL; } cairo_set_source_rgba(cr, 0, 0, 0, 0); cairo_paint(cr); /* Loop through the shapes in the diagram... */ for (i = 0; i != diagram->shape_count; i++) { /* If this shape is a path, just render it. */ if (diagram->shape[i].path) { render_path(cr, &diagram->shape[i]); } /* If this shape is text... */ if (diagram->shape[i].text) { /* Figure out what color to use from the R/G/B components of the shape's stroke. */ cairo_set_source_rgba(cr, svgtiny_RED(diagram->shape[i].stroke) / 255.0, svgtiny_GREEN(diagram->shape[i].stroke) / 255.0, svgtiny_BLUE(diagram->shape[i].stroke) / 255.0, 1); /* Then move to the actual position of the text within the shape... */ cairo_move_to(cr, diagram->shape[i].text_x, diagram->shape[i].text_y); /* and draw it. */ cairo_show_text(cr, diagram->shape[i].text); } } /* Check the status again just for good measure? */ crs = cairo_status(cr); if (crs != CAIRO_STATUS_SUCCESS) { g_fprintf(stderr, "cairo error: %s\n", cairo_status_to_string(crs)); cairo_destroy(cr); return NULL; } return cr; } /** * @brief Create a GdkPixbuf from a buffer of SVG data. * * @param buffer * The buffer containing the SVG document. * * @param bytecount * The number of bytes in @c buffer. * * @param error * The address of a @c GError pointer that we use to return errors. * * @return If successful, a valid pointer to a @c GdkPixbuf is * returned; if not, @c NULL is returned and @c error is populated. */ static GdkPixbuf* gdk_pixbuf_from_svg_buffer(char* buffer, size_t bytecount, GError** error) { diagram_t* diagram; cairo_t* cr = 0; GdkPixbuf* pb; GError* sub_error = NULL; diagram = svgtiny_diagram_from_buffer(buffer, bytecount, VIEWPORT_WIDTH, VIEWPORT_HEIGHT, &sub_error); if (!diagram) { g_propagate_error(error, sub_error); return NULL; } cr = cairo_context_from_diagram(diagram); if (!cr) { svgtiny_free(diagram); g_set_error_literal(error, GDK_PIXBUF_ERROR, GDK_PIXBUF_ERROR_CORRUPT_IMAGE, "could not create Cairo surface from SVG diagram"); return NULL; } /* I've gone back and forth on this about five times: we use the * diagram width and height, and not the viewport width and height. * This can ultimately render an image that's larger than the * viewport size, but I think GDK will resize the final pixbuf * anyway. More importantly, rendering small icons at a larger * (viewport) size seems to make the whole thing go ape-shit. * So for now I'm back in the diagram camp. */ pb = gdk_pixbuf_get_from_surface(cairo_get_target(cr), 0, 0, diagram->width, diagram->height); if (!pb) { g_set_error_literal(error, GDK_PIXBUF_ERROR, GDK_PIXBUF_ERROR_FAILED, "failed to obtain a GdkPixbuf from Cairo surface"); } return pb; } static gpointer gdk_pixbuf_begin_load(GdkPixbufModuleSizeFunc size_func, GdkPixbufModulePreparedFunc prep_func, GdkPixbufModuleUpdatedFunc updated_func, gpointer user_data, GError **error) { SvgTinyContext* context = g_new(SvgTinyContext, 1); context->size_func = size_func; context->prepared_func = prep_func; context->updated_func = updated_func; context->user_data = user_data; context->svg_data = NULL; context->svg_data_size = 0; return context; } static gboolean gdk_pixbuf_load_increment(gpointer data, const guchar* buf, guint buf_size, GError** error) { SvgTinyContext* context = (SvgTinyContext*)data; /* YOLO, what is error checking? */ context->svg_data = g_realloc(context->svg_data, context->svg_data_size + buf_size); memcpy(context->svg_data + context->svg_data_size, buf, buf_size); context->svg_data_size += buf_size; return TRUE; } static void emit_updated(SvgTinyContext* context, GdkPixbuf* pixbuf) { if (context->updated_func != NULL) { (*context->updated_func)(pixbuf, 0, 0, gdk_pixbuf_get_width(pixbuf), gdk_pixbuf_get_height(pixbuf), context->user_data); } } static void emit_prepared(SvgTinyContext* context, GdkPixbuf* pixbuf) { if (context->prepared_func != NULL) { (*context->prepared_func)(pixbuf, NULL, context->user_data); } } /** * @brief Process certain elements in an SVG buffer. * * GTK is very cute. Its gtk-encode-symbolic-svg tool wraps your SVG * in its own boilerplate, but then rather than including your SVG * data verbatim, it includes it via a sketchy XInclude that looks * like, * * * * Librsvg knows how to parse that, but libxml2 doesn't (the latter * can handle an XInclude, just not a base64-encoded data reference). * Fortunately, you can read the source to gtk-encode-symbolic-svg, * and just see what the format of that line will be. Here we're going * to parse out the base64 data, decode it, strip out its opening * and tags, and then replace the original * element with the result. Life is a little easier because the * closing tag always immediately follows the XInclude; we can * chop the whole thing off, decode the base64 stuff, and then paste * the result back on the end with its own closing tag intact. * * @param buffer * A buffer containing SVG file data. * * @param buf_size * The size of @c buffer (which may not be NULL-terminated). * * @param new_size * A pointer to the size of the new buffer, valid only if the * return value is non-NULL. * * @return A pointer to a buffer where the has been * processed. If no replacements were made, the result will be @c * NULL; otherwise, you are expected to @c free it when you are done. */ static char* process_gtk_symbolic_svg_xinclude(const char* buffer, size_t buf_size, size_t* new_size) { char* xi_start; char* xi; char* xi_stop; xi_start = g_strstr_len(buffer, buf_size, XI_SIGNATURE); if (xi_start == NULL) { return NULL; } xi = xi_start + strlen(XI_SIGNATURE); xi_stop = g_strstr_len(xi, (buffer + buf_size) - xi, "\""); if(xi_stop == NULL) { /* We found the start of an XInclude, but not the end of its base64-encoded data? Play it safe and do nothing. */ return NULL; } /* g_base64_decode needs a NULL-terminated string, so let's make "xi" into one */ *xi_stop = 0; gsize decoded_size; /* All files are ASCII, right? In GTK's gdkpixbufutils.c, our base64 * data is encoded from a binary file stream, i.e. bytes, without * any regard for what the text inside represents. Elsewhere we are * pretending that gchar is a reasonable data type to use for the * contents of an SVG file; here we are saying that again out loud. */ gchar* decoded = (gchar*)g_base64_decode(xi, &decoded_size); *xi_stop = '"'; /* We need another round of processing to strip the and * elements out of "decoded", but it's simpler to just overwrite * them with spaces before we proceed. We'll wind up with a document * that has a conspicuous chunk of whitespace in the middle of it, * but whatever. Note that we don't need to worry about the * element so much, because if one exists, it has to come before the * . As a result, we just need to strip everything up to the * leading tag. */ gchar* svg_open_start = g_strstr_len(decoded, decoded_size, ""); if (svg_open_end == NULL) { /* Uhhhhh */ g_free(decoded); return NULL; } memset(decoded, ' ', (1 + (svg_open_end - decoded))); } /* We're going to keep everything up to xi_start. If the svg_data, context->svg_data_size, &newsize); if (newdata != NULL) { g_free(context->svg_data); context->svg_data = newdata; context->svg_data_size = newsize; } /* OK, we've got an SVG with no XIncludes now. */ pixbuf = gdk_pixbuf_from_svg_buffer(context->svg_data, context->svg_data_size, &sub_error); if (pixbuf != NULL) { emit_prepared(context, pixbuf); emit_updated(context, pixbuf); g_object_unref(pixbuf); } else { g_propagate_error(error, sub_error); result = FALSE; } g_free(context->svg_data); g_free(context); return result; } G_MODULE_EXPORT void fill_vtable(GdkPixbufModule* module); void fill_vtable(GdkPixbufModule* module) { module->begin_load = gdk_pixbuf_begin_load; module->load_increment = gdk_pixbuf_load_increment; module->stop_load = gdk_pixbuf_stop_load; } G_MODULE_EXPORT void fill_info(GdkPixbufFormat *info); void fill_info(GdkPixbufFormat* info) { /* Borrowed from librsvg-2.40.21 */ static const GdkPixbufModulePattern signature[] = { { " name = "svg"; info->signature = (GdkPixbufModulePattern*)signature; info->description = "Scalable Vector Graphics"; info->mime_types = (gchar**)mime_types; info->extensions = (gchar**)extensions; info->flags = GDK_PIXBUF_FORMAT_SCALABLE; info->license = "AGPL3"; } int main(int argc, char** argv) { char* svgpath; char* pngpath; GError* err = NULL; GdkPixbuf* pb; /* Parse arguments, and maybe print usage */ if (argc < 3) { g_printf("Usage: %s INPUT OUTPUT\n", argv[0]); g_printf("Convert an SVG file (INPUT) to a PNG file (OUTPUT)\n"); return 2; } svgpath = argv[1]; pngpath = argv[2]; pb = gdk_pixbuf_new_from_file(svgpath, &err); if (!pb) { g_fprintf(stderr, "Error %d in gdk_pixbuf_new_from_file: %s\n", err->code, err->message); g_error_free(err); return 1; } gdk_pixbuf_save(pb, pngpath, "png", NULL, NULL); g_object_unref(pb); return 0; }