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