]> gitweb.michael.orlitzky.com - libsvgtiny-pixbuf.git/blob - io-svg.c
d0c2a1b7b654d5c818440b6a4dd41b43f03f9ee2
[libsvgtiny-pixbuf.git] / io-svg.c
1 #include <string.h> /* memcpy, memset */
2
3 #include <cairo.h>
4 #include <gdk/gdk.h>
5 #include <gdk-pixbuf/gdk-pixbuf.h> /* includes glib.h */
6 #include <glib/gprintf.h>
7 #include <svgtiny.h>
8
9 /*
10 * The width and height of the viewport that we'll render the SVG
11 * into. The final "picture" may not actually be this size; based on
12 * the height, width, viewBox, and preserveAspectRatio attributes in
13 * the SVG itself, libsvgtiny may scale, stretch, offset, etc. the
14 * paths to make them fit nicely into the viewport.
15 */
16 #define VIEWPORT_WIDTH 512
17 #define VIEWPORT_HEIGHT 512
18
19 /* The start of an XInclude that was inserted by
20 * gtk-encode-symbolic-svg */
21 #define XI_SIGNATURE "<xi:include href=\"data:text/xml;base64,"
22
23
24 /* Convenient typedefs for libsvgtiny */
25 typedef struct svgtiny_diagram diagram_t;
26 typedef struct svgtiny_shape shape_t;
27
28
29 typedef struct {
30 GdkPixbufModuleUpdatedFunc updated_func;
31 GdkPixbufModulePreparedFunc prepared_func;
32 GdkPixbufModuleSizeFunc size_func;
33 gpointer user_data;
34
35 /* The SVG "file" that we're building in memory. */
36 char* svg_data;
37
38 /* How far into svg_data are we? This should always point to the
39 next empty byte. If (for example) svg_data_size is 2, then
40 svg_data[0] and svg_data[1] are used, but svg_data[2] is free. */
41 size_t svg_data_size;
42
43 } SvgTinyContext;
44
45
46 /**
47 * @brief Render an svgtiny path using cairo.
48 *
49 * @param cr
50 * A pointer to a valid cairo context.
51 *
52 * @param path
53 * A pointer to an svgtiny shape that will be rendered on the
54 * cairo context's target surface.
55 */
56 static void render_path(cairo_t* cr, shape_t* path) {
57 unsigned int j;
58
59 cairo_new_path(cr);
60 for (j = 0; j != path->path_length; ) {
61 switch ((int) path->path[j]) {
62 case svgtiny_PATH_MOVE:
63 cairo_move_to(cr,
64 path->path[j + 1],
65 path->path[j + 2]);
66 j += 3;
67 break;
68 case svgtiny_PATH_CLOSE:
69 cairo_close_path(cr);
70 j += 1;
71 break;
72 case svgtiny_PATH_LINE:
73 cairo_line_to(cr,
74 path->path[j + 1],
75 path->path[j + 2]);
76 j += 3;
77 break;
78 case svgtiny_PATH_BEZIER:
79 cairo_curve_to(cr,
80 path->path[j + 1],
81 path->path[j + 2],
82 path->path[j + 3],
83 path->path[j + 4],
84 path->path[j + 5],
85 path->path[j + 6]);
86 j += 7;
87 }
88 }
89 if (path->fill != svgtiny_TRANSPARENT) {
90 cairo_set_source_rgba(cr,
91 svgtiny_RED(path->fill) / 255.0,
92 svgtiny_GREEN(path->fill) / 255.0,
93 svgtiny_BLUE(path->fill) / 255.0,
94 1);
95 cairo_fill_preserve(cr);
96 }
97 if (path->stroke != svgtiny_TRANSPARENT) {
98 cairo_set_source_rgba(cr,
99 svgtiny_RED(path->stroke) / 255.0,
100 svgtiny_GREEN(path->stroke) / 255.0,
101 svgtiny_BLUE(path->stroke) / 255.0,
102 1);
103 cairo_set_line_width(cr, path->stroke_width);
104 cairo_stroke_preserve(cr);
105 }
106 }
107
108 /**
109 * @brief Parse a buffer of SVG data into a diagram_t structure.
110 *
111 * @param buffer
112 * The buffer containing the SVG document.
113 *
114 * @param bytecount
115 * The number of bytes in @c buffer.
116 *
117 * @return If successful, a pointer to a @c diagram_t structure is
118 * returned; if not, @c NULL is returned. You are expected to @c
119 * svgtiny_free the result if it is valid.
120 */
121 static diagram_t* svgtiny_diagram_from_buffer(char* buffer,
122 size_t bytecount,
123 int width,
124 int height,
125 GError** error) {
126 diagram_t* diagram;
127 svgtiny_code code;
128
129 diagram = svgtiny_create();
130 if (!diagram) {
131 g_set_error_literal(error,
132 G_FILE_ERROR,
133 G_FILE_ERROR_NOMEM,
134 "out of memory in svgtiny_create()");
135 return NULL;
136 }
137
138 code = svgtiny_parse(diagram, buffer, bytecount, "", width, height);
139
140 switch(code) {
141 case svgtiny_OK:
142 /* The one success case. */
143 return diagram;
144 case svgtiny_OUT_OF_MEMORY:
145 g_set_error_literal(error,
146 G_FILE_ERROR,
147 G_FILE_ERROR_NOMEM,
148 "out of memory in svgtiny_parse()");
149 break;
150 case svgtiny_LIBDOM_ERROR:
151 g_set_error_literal(error,
152 GDK_PIXBUF_ERROR,
153 GDK_PIXBUF_ERROR_CORRUPT_IMAGE,
154 "invalid XML DOM in svgtiny_parse()");
155 break;
156 case svgtiny_NOT_SVG:
157 g_set_error_literal(error,
158 GDK_PIXBUF_ERROR,
159 GDK_PIXBUF_ERROR_CORRUPT_IMAGE,
160 "missing <svg> element in svgtiny_parse()");
161 break;
162 case svgtiny_SVG_ERROR:
163 g_set_error(error,
164 GDK_PIXBUF_ERROR,
165 GDK_PIXBUF_ERROR_CORRUPT_IMAGE,
166 "SVG format error in svgtiny_parse() on line %i: %s",
167 diagram->error_line,
168 diagram->error_message);
169 break;
170 }
171
172 /* All other cases above are failure */
173 return NULL;
174 }
175
176 /**
177 * @brief Create a cairo context from a libsvgtiny diagram.
178 *
179 * @param diagram
180 * A pointer to a valid libsvgtiny diagram.
181 *
182 * @return If successful, a pointer to a @c cairo_t context structure
183 * is returned; if not, @c NULL is returned. You are expected to @c
184 * cairo_destroy the result if it is valid.
185 */
186 static cairo_t* cairo_context_from_diagram(diagram_t* diagram) {
187 cairo_t* cr;
188 cairo_surface_t* surface;
189 cairo_status_t crs;
190 unsigned int i;
191
192 surface = cairo_image_surface_create(CAIRO_FORMAT_ARGB32,
193 diagram->width,
194 diagram->height);
195
196 crs = cairo_surface_status(surface);
197 if (crs != CAIRO_STATUS_SUCCESS) {
198 g_fprintf(stderr,
199 "cairo_image_surface_create failed: %s\n",
200 cairo_status_to_string(crs));
201 cairo_surface_destroy(surface);
202 return NULL;
203 }
204
205 cr = cairo_create(surface);
206 crs = cairo_status(cr);
207
208 /* Immediately destroy the surface which is now accessible as
209 cr->target */
210 cairo_surface_destroy(surface);
211
212 if (crs != CAIRO_STATUS_SUCCESS) {
213 g_fprintf(stderr,
214 "cairo_create failed: %s\n",
215 cairo_status_to_string(crs));
216 cairo_destroy(cr);
217 return NULL;
218 }
219
220 cairo_set_source_rgba(cr, 0, 0, 0, 0);
221 cairo_paint(cr);
222
223 /* Loop through the shapes in the diagram... */
224 for (i = 0; i != diagram->shape_count; i++) {
225
226 /* If this shape is a path, just render it. */
227 if (diagram->shape[i].path) {
228 render_path(cr, &diagram->shape[i]);
229 }
230
231 /* If this shape is text... */
232 if (diagram->shape[i].text) {
233 /* Figure out what color to use from the R/G/B components of the
234 shape's stroke. */
235 cairo_set_source_rgba(cr,
236 svgtiny_RED(diagram->shape[i].stroke) / 255.0,
237 svgtiny_GREEN(diagram->shape[i].stroke) / 255.0,
238 svgtiny_BLUE(diagram->shape[i].stroke) / 255.0,
239 1);
240 /* Then move to the actual position of the text within the
241 shape... */
242 cairo_move_to(cr,
243 diagram->shape[i].text_x,
244 diagram->shape[i].text_y);
245
246 /* and draw it. */
247 cairo_show_text(cr, diagram->shape[i].text);
248 }
249 }
250
251
252 /* Check the status again just for good measure? */
253 crs = cairo_status(cr);
254 if (crs != CAIRO_STATUS_SUCCESS) {
255 g_fprintf(stderr,
256 "cairo error: %s\n",
257 cairo_status_to_string(crs));
258 cairo_destroy(cr);
259 return NULL;
260 }
261
262 return cr;
263 }
264
265 /**
266 * @brief Create a GdkPixbuf from a buffer of SVG data.
267 *
268 * @param buffer
269 * The buffer containing the SVG document.
270 *
271 * @param bytecount
272 * The number of bytes in @c buffer.
273 *
274 * @param error
275 * The address of a @c GError pointer that we use to return errors.
276 *
277 * @return If successful, a valid pointer to a @c GdkPixbuf is
278 * returned; if not, @c NULL is returned and @c error is populated.
279 */
280 static GdkPixbuf* gdk_pixbuf_from_svg_buffer(char* buffer,
281 size_t bytecount,
282 GError** error) {
283 diagram_t* diagram;
284 cairo_t* cr = 0;
285 GdkPixbuf* pb;
286 GError* sub_error = NULL;
287
288 diagram = svgtiny_diagram_from_buffer(buffer,
289 bytecount,
290 VIEWPORT_WIDTH,
291 VIEWPORT_HEIGHT,
292 &sub_error);
293 if (!diagram) {
294 g_propagate_error(error, sub_error);
295 return NULL;
296 }
297
298 cr = cairo_context_from_diagram(diagram);
299 if (!cr) {
300 svgtiny_free(diagram);
301 g_set_error_literal(error,
302 GDK_PIXBUF_ERROR,
303 GDK_PIXBUF_ERROR_CORRUPT_IMAGE,
304 "could not create Cairo surface from SVG diagram");
305 return NULL;
306 }
307
308
309 /* I've gone back and forth on this about five times: we use the
310 * diagram width and height, and not the viewport width and height.
311 * This can ultimately render an image that's larger than the
312 * viewport size, but I think GDK will resize the final pixbuf
313 * anyway. More importantly, rendering small icons at a larger
314 * (viewport) size seems to make the whole thing go ape-shit.
315 * So for now I'm back in the diagram camp.
316 */
317 pb = gdk_pixbuf_get_from_surface(cairo_get_target(cr),
318 0,
319 0,
320 diagram->width,
321 diagram->height);
322
323
324 if (!pb) {
325 g_set_error_literal(error,
326 GDK_PIXBUF_ERROR,
327 GDK_PIXBUF_ERROR_FAILED,
328 "failed to obtain a GdkPixbuf from Cairo surface");
329 }
330
331 return pb;
332 }
333
334
335 static gpointer gdk_pixbuf_begin_load(GdkPixbufModuleSizeFunc size_func,
336 GdkPixbufModulePreparedFunc prep_func,
337 GdkPixbufModuleUpdatedFunc updated_func,
338 gpointer user_data,
339 GError **error) {
340
341 SvgTinyContext* context = g_new(SvgTinyContext, 1);
342
343 context->size_func = size_func;
344 context->prepared_func = prep_func;
345 context->updated_func = updated_func;
346 context->user_data = user_data;
347
348 context->svg_data = NULL;
349 context->svg_data_size = 0;
350
351 return context;
352 }
353
354 static gboolean gdk_pixbuf_load_increment(gpointer data,
355 const guchar* buf,
356 guint buf_size,
357 GError** error) {
358 SvgTinyContext* context = (SvgTinyContext*)data;
359
360 /* YOLO, what is error checking? */
361 context->svg_data = g_realloc(context->svg_data,
362 context->svg_data_size + buf_size);
363 memcpy(context->svg_data + context->svg_data_size, buf, buf_size);
364 context->svg_data_size += buf_size;
365
366 return TRUE;
367 }
368
369 static void emit_updated(SvgTinyContext* context, GdkPixbuf* pixbuf) {
370 if (context->updated_func != NULL) {
371 (*context->updated_func)(pixbuf,
372 0,
373 0,
374 gdk_pixbuf_get_width(pixbuf),
375 gdk_pixbuf_get_height(pixbuf),
376 context->user_data);
377 }
378 }
379
380 static void emit_prepared(SvgTinyContext* context, GdkPixbuf* pixbuf) {
381 if (context->prepared_func != NULL) {
382 (*context->prepared_func)(pixbuf, NULL, context->user_data);
383 }
384 }
385
386
387 /**
388 * @brief Process certain <xi:include> elements in an SVG buffer.
389 *
390 * GTK is very cute. Its gtk-encode-symbolic-svg tool wraps your SVG
391 * in its own boilerplate, but then rather than including your SVG
392 * data verbatim, it includes it via a sketchy XInclude that looks
393 * like,
394 *
395 * <xi:include href="data:text/xml;base64,PD94bWwgd..."/>
396 *
397 * Librsvg knows how to parse that, but libxml2 doesn't (the latter
398 * can handle an XInclude, just not a base64-encoded data reference).
399 * Fortunately, you can read the source to gtk-encode-symbolic-svg,
400 * and just see what the format of that line will be. Here we're going
401 * to parse out the base64 data, decode it, strip out its opening
402 * <xml> and <svg> tags, and then replace the original <xi:include>
403 * element with the result. Life is a little easier because the
404 * closing </svg> tag always immediately follows the XInclude; we can
405 * chop the whole thing off, decode the base64 stuff, and then paste
406 * the result back on the end with its own closing </svg> tag intact.
407 *
408 * @param buffer
409 * A buffer containing SVG file data.
410 *
411 * @param buf_size
412 * The size of @c buffer (which may not be NULL-terminated).
413 *
414 * @param new_size
415 * A pointer to the size of the new buffer, valid only if the
416 * return value is non-NULL.
417 *
418 * @return A pointer to a buffer where the <xi:include> has been
419 * processed. If no replacements were made, the result will be @c
420 * NULL; otherwise, you are expected to @c free it when you are done.
421 */
422 static char* process_gtk_symbolic_svg_xinclude(const char* buffer,
423 size_t buf_size,
424 size_t* new_size) {
425 char* xi_start;
426 char* xi;
427 char* xi_stop;
428
429 xi_start = g_strstr_len(buffer, buf_size, XI_SIGNATURE);
430 if (xi_start == NULL) {
431 return NULL;
432 }
433
434 xi = xi_start + strlen(XI_SIGNATURE);
435 xi_stop = g_strstr_len(xi, (buffer + buf_size) - xi, "\"");
436 if(xi_stop == NULL) {
437 /* We found the start of an XInclude, but not the end of its
438 base64-encoded data? Play it safe and do nothing. */
439 return NULL;
440 }
441
442 /* g_base64_decode needs a NULL-terminated string, so let's make
443 "xi" into one */
444 *xi_stop = 0;
445 gsize decoded_size;
446
447 /* All files are ASCII, right? In GTK's gdkpixbufutils.c, our base64
448 * data is encoded from a binary file stream, i.e. bytes, without
449 * any regard for what the text inside represents. Elsewhere we are
450 * pretending that gchar is a reasonable data type to use for the
451 * contents of an SVG file; here we are saying that again out loud.
452 */
453 gchar* decoded = (gchar*)g_base64_decode(xi, &decoded_size);
454 *xi_stop = '"';
455
456 /* We need another round of processing to strip the <xml> and <svg>
457 * elements out of "decoded", but it's simpler to just overwrite
458 * them with spaces before we proceed. We'll wind up with a document
459 * that has a conspicuous chunk of whitespace in the middle of it,
460 * but whatever. Note that we don't need to worry about the <xml>
461 * element so much, because if one exists, it has to come before the
462 * <svg>. As a result, we just need to strip everything up to the
463 * leading <svg> tag. */
464 gchar* svg_open_start = g_strstr_len(decoded, decoded_size, "<svg ");
465 if (svg_open_start == NULL) {
466 /* Uhhhhh */
467 g_free(decoded);
468 return NULL;
469 }
470 else {
471 gchar* svg_open_end = g_strstr_len(svg_open_start, decoded_size, ">");
472 if (svg_open_end == NULL) {
473 /* Uhhhhh */
474 g_free(decoded);
475 return NULL;
476 }
477 memset(decoded, ' ', (1 + (svg_open_end - decoded)));
478 }
479
480 /* We're going to keep everything up to xi_start. If the <xi:include
481 * started at, say, position three, then this would compute a size
482 * of three. Which is correct: we want to retain buffer[0],
483 * buffer[1], and buffer[2]. */
484 size_t keep_size = xi_start - buffer;
485 *new_size = keep_size + decoded_size;
486
487 char* result = g_malloc(*new_size);
488 memcpy(result, buffer, keep_size);
489 memcpy(result+keep_size, decoded, decoded_size);
490 g_free(decoded);
491 return result;
492 }
493
494
495 static gboolean gdk_pixbuf_stop_load(gpointer data, GError **error) {
496 SvgTinyContext* context = (SvgTinyContext*)data;
497 GdkPixbuf* pixbuf = NULL;
498 gboolean result = TRUE;
499 GError* sub_error = NULL;
500
501
502 /* If we're inside of gtk-encode-symbolic-svg right now, we need to
503 process the insane librsvg-specific XInclude directive it hands
504 us before proceeding. */
505 size_t newsize;
506 char* newdata = process_gtk_symbolic_svg_xinclude(context->svg_data,
507 context->svg_data_size,
508 &newsize);
509 if (newdata != NULL) {
510 g_free(context->svg_data);
511 context->svg_data = newdata;
512 context->svg_data_size = newsize;
513 }
514
515 /* OK, we've got an SVG with no XIncludes now. */
516 pixbuf = gdk_pixbuf_from_svg_buffer(context->svg_data,
517 context->svg_data_size,
518 &sub_error);
519
520 if (pixbuf != NULL) {
521 emit_prepared(context, pixbuf);
522 emit_updated(context, pixbuf);
523 g_object_unref(pixbuf);
524 }
525 else {
526 g_propagate_error(error, sub_error);
527 result = FALSE;
528 }
529 g_free(context->svg_data);
530 g_free(context);
531
532 return result;
533 }
534
535
536 G_MODULE_EXPORT void fill_vtable(GdkPixbufModule* module);
537 void fill_vtable(GdkPixbufModule* module) {
538 module->begin_load = gdk_pixbuf_begin_load;
539 module->load_increment = gdk_pixbuf_load_increment;
540 module->stop_load = gdk_pixbuf_stop_load;
541 }
542
543 G_MODULE_EXPORT void fill_info(GdkPixbufFormat *info);
544 void fill_info(GdkPixbufFormat* info) {
545 /* Borrowed from librsvg-2.40.21 */
546 static const GdkPixbufModulePattern signature[] = {
547 { " <svg", "* ", 100 },
548 { " <!DOCTYPE svg", "* ", 100 },
549 { NULL, NULL, 0 }
550 };
551
552 /* I'm not sure if we should support gzipped svg here? */
553 static const gchar *mime_types[] = {
554 "image/svg+xml",
555 "image/svg",
556 "image/svg-xml",
557 "image/vnd.adobe.svg+xml",
558 "text/xml-svg",
559 "image/svg+xml-compressed",
560 NULL
561 };
562
563 static const gchar *extensions[] = {
564 "svg",
565 "svgz",
566 "svg.gz",
567 NULL
568 };
569
570 info->name = "svg";
571 info->signature = (GdkPixbufModulePattern*)signature;
572 info->description = "Scalable Vector Graphics";
573 info->mime_types = (gchar**)mime_types;
574 info->extensions = (gchar**)extensions;
575 info->flags = GDK_PIXBUF_FORMAT_SCALABLE;
576 info->license = "AGPL3";
577 }
578
579
580 int main(int argc, char** argv) {
581 char* svgpath;
582 char* pngpath;
583 GError* err = NULL;
584 GdkPixbuf* pb;
585
586 /* Parse arguments, and maybe print usage */
587 if (argc < 3) {
588 g_printf("Usage: %s INPUT OUTPUT\n", argv[0]);
589 g_printf("Convert an SVG file (INPUT) to a PNG file (OUTPUT)\n");
590 return 2;
591 }
592
593 svgpath = argv[1];
594 pngpath = argv[2];
595
596 pb = gdk_pixbuf_new_from_file(svgpath, &err);
597 if (!pb) {
598 g_fprintf(stderr,
599 "Error %d in gdk_pixbuf_new_from_file: %s\n",
600 err->code,
601 err->message);
602 g_error_free(err);
603 return 1;
604 }
605
606 gdk_pixbuf_save(pb, pngpath, "png", NULL, NULL);
607 g_object_unref(pb);
608 return 0;
609 }