]> gitweb.michael.orlitzky.com - libsvgtiny-pixbuf.git/blob - io-svg.c
c08fa7dfbd51998607752edbfdea31b424b488c7
[libsvgtiny-pixbuf.git] / io-svg.c
1 #include <stdio.h> /* fprintf, printf */
2 #include <string.h> /* memcpy, memset, strstr */
3
4 #include <cairo.h>
5 #include <gdk/gdk.h>
6 #include <gdk-pixbuf/gdk-pixbuf.h> /* includes glib.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 if (code != svgtiny_OK) {
141 switch (code) {
142 case svgtiny_OUT_OF_MEMORY:
143 g_set_error_literal(error,
144 G_FILE_ERROR,
145 G_FILE_ERROR_NOMEM,
146 "out of memory in svgtiny_parse()");
147 break;
148 case svgtiny_LIBDOM_ERROR:
149 g_set_error_literal(error,
150 GDK_PIXBUF_ERROR,
151 GDK_PIXBUF_ERROR_CORRUPT_IMAGE,
152 "invalid XML DOM in svgtiny_parse()");
153 break;
154 case svgtiny_NOT_SVG:
155 g_set_error_literal(error,
156 GDK_PIXBUF_ERROR,
157 GDK_PIXBUF_ERROR_CORRUPT_IMAGE,
158 "missing <svg> element in svgtiny_parse()");
159 break;
160 case svgtiny_SVG_ERROR:
161 g_set_error(error,
162 GDK_PIXBUF_ERROR,
163 GDK_PIXBUF_ERROR_CORRUPT_IMAGE,
164 "SVG format error in svgtiny_parse() on line %i: %s",
165 diagram->error_line,
166 diagram->error_message);
167 break;
168 }
169 return NULL;
170 }
171
172 return diagram;
173 }
174
175 /**
176 * @brief Create a cairo context from a libsvgtiny diagram.
177 *
178 * @param diagram
179 * A pointer to a valid libsvgtiny diagram.
180 *
181 * @return If successful, a pointer to a @c cairo_t context structure
182 * is returned; if not, @c NULL is returned. You are expected to @c
183 * cairo_destroy the result if it is valid.
184 */
185 static cairo_t* cairo_context_from_diagram(diagram_t* diagram) {
186 cairo_t* cr;
187 cairo_surface_t* surface;
188 cairo_status_t crs;
189 unsigned int i;
190
191 surface = cairo_image_surface_create(CAIRO_FORMAT_ARGB32,
192 diagram->width,
193 diagram->height);
194
195 crs = cairo_surface_status(surface);
196 if (crs != CAIRO_STATUS_SUCCESS) {
197 fprintf(stderr,
198 "cairo_image_surface_create failed: %s\n",
199 cairo_status_to_string(crs));
200 cairo_surface_destroy(surface);
201 return NULL;
202 }
203
204 cr = cairo_create(surface);
205 crs = cairo_status(cr);
206
207 /* Immediately destroy the surface which is now accessible as
208 cr->target */
209 cairo_surface_destroy(surface);
210
211 if (crs != CAIRO_STATUS_SUCCESS) {
212 fprintf(stderr,
213 "cairo_create failed: %s\n",
214 cairo_status_to_string(crs));
215 cairo_destroy(cr);
216 return NULL;
217 }
218
219 cairo_set_source_rgba(cr, 0, 0, 0, 0);
220 cairo_paint(cr);
221
222 /* Loop through the shapes in the diagram... */
223 for (i = 0; i != diagram->shape_count; i++) {
224
225 /* If this shape is a path, just render it. */
226 if (diagram->shape[i].path) {
227 render_path(cr, &diagram->shape[i]);
228 }
229
230 /* If this shape is text... */
231 if (diagram->shape[i].text) {
232 /* Figure out what color to use from the R/G/B components of the
233 shape's stroke. */
234 cairo_set_source_rgba(cr,
235 svgtiny_RED(diagram->shape[i].stroke) / 255.0,
236 svgtiny_GREEN(diagram->shape[i].stroke) / 255.0,
237 svgtiny_BLUE(diagram->shape[i].stroke) / 255.0,
238 1);
239 /* Then move to the actual position of the text within the
240 shape... */
241 cairo_move_to(cr,
242 diagram->shape[i].text_x,
243 diagram->shape[i].text_y);
244
245 /* and draw it. */
246 cairo_show_text(cr, diagram->shape[i].text);
247 }
248 }
249
250
251 /* Check the status again just for good measure? */
252 crs = cairo_status(cr);
253 if (crs != CAIRO_STATUS_SUCCESS) {
254 fprintf(stderr,
255 "cairo error: %s\n",
256 cairo_status_to_string(crs));
257 cairo_destroy(cr);
258 return NULL;
259 }
260
261 return cr;
262 }
263
264 /**
265 * @brief Create a GdkPixbuf from a buffer of SVG data.
266 *
267 * @param buffer
268 * The buffer containing the SVG document.
269 *
270 * @param bytecount
271 * The number of bytes in @c buffer.
272 *
273 * @param error
274 * The address of a @c GError pointer that we use to return errors.
275 *
276 * @return If successful, a valid pointer to a @c GdkPixbuf is
277 * returned; if not, @c NULL is returned and @c error is populated.
278 */
279 static GdkPixbuf* gdk_pixbuf_from_svg_buffer(char* buffer,
280 size_t bytecount,
281 GError** error) {
282 diagram_t* diagram;
283 cairo_t* cr = 0;
284 GdkPixbuf* pb;
285 GError* sub_error = NULL;
286
287 diagram = svgtiny_diagram_from_buffer(buffer,
288 bytecount,
289 VIEWPORT_WIDTH,
290 VIEWPORT_HEIGHT,
291 &sub_error);
292 if (!diagram) {
293 g_propagate_error(error, sub_error);
294 return NULL;
295 }
296
297 cr = cairo_context_from_diagram(diagram);
298 if (!cr) {
299 svgtiny_free(diagram);
300 g_set_error_literal(error,
301 GDK_PIXBUF_ERROR,
302 GDK_PIXBUF_ERROR_CORRUPT_IMAGE,
303 "could not create Cairo surface from SVG diagram");
304 return NULL;
305 }
306
307
308 /* I've gone back and forth on this about five times: we use the
309 * diagram width and height, and not the viewport width and height.
310 * This can ultimately render an image that's larger than the
311 * viewport size, but I think GDK will resize the final pixbuf
312 * anyway. More importantly, rendering small icons at a larger
313 * (viewport) size seems to make the whole thing go ape-shit.
314 * So for now I'm back in the diagram camp.
315 */
316 pb = gdk_pixbuf_get_from_surface(cairo_get_target(cr),
317 0,
318 0,
319 diagram->width,
320 diagram->height);
321
322
323 if (!pb) {
324 g_set_error_literal(error,
325 GDK_PIXBUF_ERROR,
326 GDK_PIXBUF_ERROR_FAILED,
327 "failed to obtain a GdkPixbuf from Cairo surface");
328 }
329
330 return pb;
331 }
332
333
334 static gpointer gdk_pixbuf_begin_load(GdkPixbufModuleSizeFunc size_func,
335 GdkPixbufModulePreparedFunc prep_func,
336 GdkPixbufModuleUpdatedFunc updated_func,
337 gpointer user_data,
338 GError **error) {
339
340 SvgTinyContext* context = g_new(SvgTinyContext, 1);
341
342 context->size_func = size_func;
343 context->prepared_func = prep_func;
344 context->updated_func = updated_func;
345 context->user_data = user_data;
346
347 context->svg_data = NULL;
348 context->svg_data_size = 0;
349
350 return context;
351 }
352
353 static gboolean gdk_pixbuf_load_increment(gpointer data,
354 const guchar* buf,
355 guint buf_size,
356 GError** error) {
357 size_t increment = 0;
358 SvgTinyContext* context = (SvgTinyContext*)data;
359
360 /* YOLO, no 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 = strstr(buffer, XI_SIGNATURE);
430 if (xi_start == NULL) {
431 return NULL;
432 }
433
434 xi = xi_start + strlen(XI_SIGNATURE);
435 xi_stop = strstr(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 guchar* decoded = g_base64_decode(xi, &decoded_size);
447
448 /* We need another round of processing to strip the <xml> and <svg>
449 * elements out of "decoded", but it's simpler to just overwrite
450 * them with spaces before we proceed. We'll wind up with a document
451 * that has a conspicuous chunk of whitespace in the middle of it,
452 * but whatever. Note that we don't need to worry about the <xml>
453 * element so much, because if one exists, it has to come before the
454 * <svg>. As a result, we just need to strip everything up to the
455 * leading <svg> tag. */
456 guchar* svg_open_start = strstr(decoded, "<svg ");
457 guchar* svg_open_end = strstr(svg_open_start, ">");
458 memset(decoded, ' ', (1 + (svg_open_end - decoded)));
459
460 /* We're going to keep everything up to xi_start. If the <xi:include
461 * started at, say, position three, then this would compute a size
462 * of three. Which is correct: we want to retain buffer[0],
463 * buffer[1], and buffer[2]. */
464 size_t keep_size = xi_start - buffer;
465 *new_size = keep_size + decoded_size;
466
467 char* result = g_malloc(*new_size);
468 memcpy(result, buffer, keep_size);
469 memcpy(result+keep_size, decoded, decoded_size);
470 g_free(decoded);
471 return result;
472 }
473
474
475 static gboolean gdk_pixbuf_stop_load(gpointer data, GError **error) {
476 SvgTinyContext* context = (SvgTinyContext*)data;
477 GdkPixbuf* pixbuf = NULL;
478 gboolean result = TRUE;
479 GError* sub_error = NULL;
480
481
482 /* If we're inside of gtk-encode-symbolic-svg right now, we need to
483 process the insane librsvg-specific XInclude directive it hands
484 us before proceeding. */
485 size_t newsize;
486 char* newdata = process_gtk_symbolic_svg_xinclude(context->svg_data,
487 context->svg_data_size,
488 &newsize);
489 if (newdata != NULL) {
490 g_free(context->svg_data);
491 context->svg_data = newdata;
492 context->svg_data_size = newsize;
493 }
494
495 /* OK, we've got an SVG with no XIncludes now. */
496 pixbuf = gdk_pixbuf_from_svg_buffer(context->svg_data,
497 context->svg_data_size,
498 &sub_error);
499
500 if (pixbuf != NULL) {
501 emit_prepared(context, pixbuf);
502 emit_updated(context, pixbuf);
503 g_object_unref(pixbuf);
504 }
505 else {
506 g_propagate_error(error, sub_error);
507 result = FALSE;
508 }
509 g_free(context->svg_data);
510 g_free(context);
511
512 return result;
513 }
514
515
516 G_MODULE_EXPORT void fill_vtable(GdkPixbufModule* module);
517 void fill_vtable(GdkPixbufModule* module) {
518 module->begin_load = gdk_pixbuf_begin_load;
519 module->load_increment = gdk_pixbuf_load_increment;
520 module->stop_load = gdk_pixbuf_stop_load;
521 }
522
523 G_MODULE_EXPORT void fill_info(GdkPixbufFormat *info);
524 void fill_info(GdkPixbufFormat* info) {
525 /* Borrowed from librsvg-2.40.21 */
526 static const GdkPixbufModulePattern signature[] = {
527 { " <svg", "* ", 100 },
528 { " <!DOCTYPE svg", "* ", 100 },
529 { NULL, NULL, 0 }
530 };
531
532 /* I'm not sure if we should support gzipped svg here? */
533 static const gchar *mime_types[] = {
534 "image/svg+xml",
535 "image/svg",
536 "image/svg-xml",
537 "image/vnd.adobe.svg+xml",
538 "text/xml-svg",
539 "image/svg+xml-compressed",
540 NULL
541 };
542
543 static const gchar *extensions[] = {
544 "svg",
545 "svgz",
546 "svg.gz",
547 NULL
548 };
549
550 info->name = "svg";
551 info->signature = (GdkPixbufModulePattern*)signature;
552 info->description = "Scalable Vector Graphics";
553 info->mime_types = (gchar**)mime_types;
554 info->extensions = (gchar**)extensions;
555 info->flags = GDK_PIXBUF_FORMAT_SCALABLE;
556 info->license = "AGPL3";
557 }
558
559
560 int main(int argc, char** argv) {
561 char* svgpath;
562 char* pngpath;
563 FILE* fp;
564 GError* err = NULL;
565 GdkPixbuf* pb;
566
567 /* Parse arguments, and maybe print usage */
568 if (argc < 3) {
569 printf("Usage: %s INPUT OUTPUT\n", argv[0]);
570 printf("Convert an SVG file (INPUT) to a PNG file (OUTPUT)\n");
571 return 2;
572 }
573
574 svgpath = argv[1];
575 pngpath = argv[2];
576
577 pb = gdk_pixbuf_new_from_file(svgpath, &err);
578 if (!pb) {
579 fprintf(stderr,
580 "Error %d in gdk_pixbuf_new_from_file: %s\n",
581 err->code,
582 err->message);
583 g_error_free(err);
584 return 1;
585 }
586
587 gdk_pixbuf_save(pb, pngpath, "png", NULL, NULL);
588 g_object_unref(pb);
589 return 0;
590 }