Removed references to GIF
[rrdtool.git] / src / rrd_gfx.c
1 /****************************************************************************
2  * RRDtool 1.1.x  Copyright Tobias Oetiker, 1997 - 2002
3  ****************************************************************************
4  * rrd_gfx.c  graphics wrapper for rrdtool
5   **************************************************************************/
6
7 /* #define DEBUG */
8
9 #ifdef DEBUG
10 # define DPRINT(x)    (void)(printf x, printf("\n"))
11 #else
12 # define DPRINT(x)
13 #endif
14 #include "rrd_tool.h"
15 #include <png.h>
16 #include <ft2build.h>
17 #include FT_FREETYPE_H
18
19 #include "rrd_gfx.h"
20
21 /* lines are better drawn on the pixle than between pixles */
22 #define LINEOFFSET 0.5
23
24 static
25 gfx_node_t *gfx_new_node( gfx_canvas_t *canvas,enum gfx_en type){
26   gfx_node_t *node = art_new(gfx_node_t,1);
27   if (node == NULL) return NULL;
28   node->type = type;
29   node->color = 0x0;        /* color of element  0xRRGGBBAA  alpha 0xff is solid*/
30   node->size =0.0;         /* font size, line width */
31   node->path = NULL;        /* path */
32   node->points = 0;
33   node->points_max =0;
34   node->closed_path = 0;
35   node->svp = NULL;         /* svp */
36   node->filename = NULL;             /* font or image filename */
37   node->text = NULL;
38   node->x = 0.0;
39   node->y = 0.0;          /* position */
40   node->angle = 0;  
41   node->halign = GFX_H_NULL; /* text alignement */
42   node->valign = GFX_V_NULL; /* text alignement */
43   node->tabwidth = 0.0; 
44   node->next = NULL; 
45   if (canvas->lastnode != NULL){
46       canvas->lastnode->next = node;
47   }
48   if (canvas->firstnode == NULL){
49       canvas->firstnode = node;
50   }  
51   canvas->lastnode = node;
52   return node;
53 }
54
55 gfx_canvas_t *gfx_new_canvas (void) {
56     gfx_canvas_t *canvas = art_new(gfx_canvas_t,1);
57     canvas->firstnode = NULL;
58     canvas->lastnode = NULL;
59     canvas->imgformat = IF_PNG; /* we default to PNG output */
60     canvas->interlaced = 0;
61     canvas->zoom = 1.0;
62     return canvas;    
63 }
64
65 /* create a new line */
66 gfx_node_t  *gfx_new_line(gfx_canvas_t *canvas, 
67                            double X0, double Y0, 
68                            double X1, double Y1,
69                            double width, gfx_color_t color){
70   return gfx_new_dashed_line(canvas, X0, Y0, X1, Y1, width, color, 0, 0);
71 }
72
73 gfx_node_t  *gfx_new_dashed_line(gfx_canvas_t *canvas, 
74                            double X0, double Y0, 
75                            double X1, double Y1,
76                            double width, gfx_color_t color,
77                            double dash_on, double dash_off){
78
79   gfx_node_t *node;
80   ArtVpath *vec;
81   node = gfx_new_node(canvas,GFX_LINE);
82   if (node == NULL) return NULL;
83   vec = art_new(ArtVpath, 3);
84   if (vec == NULL) return NULL;
85   vec[0].code = ART_MOVETO_OPEN; vec[0].x=X0+LINEOFFSET; vec[0].y=Y0+LINEOFFSET;
86   vec[1].code = ART_LINETO; vec[1].x=X1+LINEOFFSET; vec[1].y=Y1+LINEOFFSET;
87   vec[2].code = ART_END;
88   
89   node->points = 3;
90   node->points_max = 3;
91   node->color = color;
92   node->size  = width;
93   node->dash_on = dash_on;
94   node->dash_off = dash_off;
95   node->path  = vec;
96   return node;
97 }
98
99 /* create a new area */
100 gfx_node_t   *gfx_new_area   (gfx_canvas_t *canvas, 
101                               double X0, double Y0,
102                               double X1, double Y1,
103                               double X2, double Y2,
104                               gfx_color_t color) {
105
106   gfx_node_t *node;
107   ArtVpath *vec;
108   node = gfx_new_node(canvas,GFX_AREA);
109   if (node == NULL) return NULL;
110   vec = art_new(ArtVpath, 5);
111   if (vec == NULL) return NULL;
112   vec[0].code = ART_MOVETO; vec[0].x=X0; vec[0].y=Y0;
113   vec[1].code = ART_LINETO; vec[1].x=X1; vec[1].y=Y1;
114   vec[2].code = ART_LINETO; vec[2].x=X2; vec[2].y=Y2;
115   vec[3].code = ART_LINETO; vec[3].x=X0; vec[3].y=Y0;
116   vec[4].code = ART_END;
117   
118   node->points = 5;
119   node->points_max = 5;
120   node->color = color;
121   node->path  = vec;
122
123   return node;
124 }
125
126 /* add a point to a line or to an area */
127 int           gfx_add_point  (gfx_node_t *node, 
128                               double x, double y){
129   if (node == NULL) return 1;
130   if (node->type == GFX_AREA) {
131     double X0 = node->path[0].x;
132     double Y0 = node->path[0].y;
133     node->points -= 2;
134     art_vpath_add_point (&(node->path),
135                          &(node->points),
136                          &(node->points_max),
137                          ART_LINETO,
138                          x,y);
139     art_vpath_add_point (&(node->path),
140                          &(node->points),
141                          &(node->points_max),
142                          ART_LINETO,
143                          X0,Y0);
144     art_vpath_add_point (&(node->path),
145                          &(node->points),
146                          &(node->points_max),
147                          ART_END,
148                          0,0);
149   } else if (node->type == GFX_LINE) {
150     node->points -= 1;
151     art_vpath_add_point (&(node->path),
152                          &(node->points),
153                          &(node->points_max),
154                          ART_LINETO,
155                          x+LINEOFFSET,y+LINEOFFSET);
156     art_vpath_add_point (&(node->path),
157                          &(node->points),
158                          &(node->points_max),
159                          ART_END,
160                          0,0);
161     
162   } else {
163     /* can only add point to areas and lines */
164     return 1;
165   }
166   return 0;
167 }
168
169 void           gfx_close_path  (gfx_node_t *node) {
170     node->closed_path = 1;
171 }
172
173 /* create a text node */
174 gfx_node_t   *gfx_new_text   (gfx_canvas_t *canvas,  
175                               double x, double y, gfx_color_t color,
176                               char* font, double size,                        
177                               double tabwidth, double angle,
178                               enum gfx_h_align_en h_align,
179                               enum gfx_v_align_en v_align,
180                               char* text){
181    gfx_node_t *node = gfx_new_node(canvas,GFX_TEXT);
182    if (angle != 0.0){
183        /* currently we only support 0 and 270 */
184        angle = 270.0;
185    }
186    
187    node->text = strdup(text);
188    node->size = size;
189    node->filename = strdup(font);
190    node->x = x;
191    node->y = y;
192    node->angle = angle;   
193    node->color = color;
194    node->tabwidth = tabwidth;
195    node->halign = h_align;
196    node->valign = v_align;
197    return node;
198 }
199
200 int           gfx_render(gfx_canvas_t *canvas, 
201                               art_u32 width, art_u32 height, 
202                               gfx_color_t background, FILE *fp){
203   switch (canvas->imgformat) {
204   case IF_PNG: 
205     return gfx_render_png (canvas, width, height, background, fp);
206   case IF_SVG: 
207     return gfx_render_svg (canvas, width, height, background, fp);
208   default:
209     return -1;
210   }
211 }
212
213 double gfx_get_text_width ( gfx_canvas_t *canvas,
214                             double start, char* font, double size,
215                             double tabwidth, char* text){
216   switch (canvas->imgformat) {
217   case IF_PNG: 
218     return gfx_get_text_width_libart (canvas, start, font, size, tabwidth, text);
219   default:
220     return size * strlen(text);
221   }
222 }
223
224 double gfx_get_text_width_libart ( gfx_canvas_t *canvas,
225                             double start, char* font, double size,
226                             double tabwidth, char* text){
227
228   FT_GlyphSlot  slot;
229   FT_UInt       previous=0;
230   FT_UInt       glyph_index=0;
231   FT_Bool       use_kerning;
232   int           error;
233   FT_Face       face;
234   FT_Library    library=NULL;  
235   double        text_width=0;
236   FT_Init_FreeType( &library );
237   error = FT_New_Face( library, font, 0, &face );
238   if ( error ) return -1;
239   error = FT_Set_Char_Size(face,  size*64,size*64,  100,100);
240   if ( error ) return -1;
241
242   use_kerning = FT_HAS_KERNING(face);
243   slot = face->glyph;
244   for(;*text;text++) {  
245     previous = glyph_index;
246     glyph_index = FT_Get_Char_Index( face, *text);
247     
248     if (use_kerning && previous && glyph_index){
249       FT_Vector  delta;
250       FT_Get_Kerning( face, previous, glyph_index,
251                       0, &delta );
252       text_width += (double)delta.x / 64.0;
253       
254     }
255     error = FT_Load_Glyph( face, glyph_index, 0 );
256     if ( error ) {
257       FT_Done_FreeType(library);
258       return -1;
259     }
260     if (! previous) {
261       text_width -= (double)slot->metrics.horiBearingX / 64.0; /* add just char width */        
262     }
263     text_width += (double)slot->metrics.horiAdvance / 64.0;
264   }
265   text_width -= (double)slot->metrics.horiAdvance / 64.0; /* remove last step */
266   text_width += (double)slot->metrics.width / 64.0; /* add just char width */
267   text_width += (double)slot->metrics.horiBearingX / 64.0; /* add just char width */
268   FT_Done_FreeType(library);
269   return text_width;
270 }
271  
272
273
274
275 static int gfx_save_png (art_u8 *buffer, FILE *fp,
276                      long width, long height, long bytes_per_pixel);
277 /* render grafics into png image */
278 int           gfx_render_png (gfx_canvas_t *canvas, 
279                               art_u32 width, art_u32 height, 
280                               gfx_color_t background, FILE *fp){
281     
282     
283     FT_Library    library;
284     gfx_node_t *node = canvas->firstnode;    
285     art_u8 red = background >> 24, green = (background >> 16) & 0xff;
286     art_u8 blue = (background >> 8) & 0xff, alpha = ( background & 0xff );
287     unsigned long pys_width = width * canvas->zoom;
288     unsigned long pys_height = height * canvas->zoom;
289     const int bytes_per_pixel = 3;
290     unsigned long rowstride = pys_width*bytes_per_pixel; /* bytes per pixel */
291     art_u8 *buffer = art_new (art_u8, rowstride*pys_height);
292     art_rgb_run_alpha (buffer, red, green, blue, alpha, pys_width*pys_height);
293     FT_Init_FreeType( &library );
294     while(node){
295         switch (node->type) {
296         case GFX_LINE:
297         case GFX_AREA: {   
298             ArtVpath *vec;
299             double dst[6];     
300             ArtSVP *svp;
301             if (node->closed_path) { 
302                 /* libart uses end==start for closed as indicator of closed path */
303                 gfx_add_point(node, node->path[0].x, node->path[0].y);
304                 node->closed_path = 0;
305             }
306             art_affine_scale(dst,canvas->zoom,canvas->zoom);
307             vec = art_vpath_affine_transform(node->path,dst);
308             if(node->type == GFX_LINE){
309                 svp = art_svp_vpath_stroke ( vec, ART_PATH_STROKE_JOIN_ROUND,
310                                              ART_PATH_STROKE_CAP_ROUND,
311                                              node->size*canvas->zoom,1,1);
312             } else {
313                 svp = art_svp_from_vpath ( vec );
314             }
315             art_free(vec);
316             art_rgb_svp_alpha (svp ,0,0, pys_width, pys_height,
317                                node->color, buffer, rowstride, NULL);
318             art_free(svp);
319             break;
320         }
321         case GFX_TEXT: {
322             int  error;
323             float text_width=0.0, text_height = 0.0;
324             unsigned char *text;
325             art_u8 fcolor[3],falpha;
326             FT_Face       face;
327             FT_GlyphSlot  slot;
328             FT_UInt       previous=0;
329             FT_UInt       glyph_index=0;
330             FT_Bool       use_kerning;
331
332             float pen_x = 0.0 , pen_y = 0.0;
333             /* double x,y; */
334             long   ix,iy,iz;
335             
336             fcolor[0] = node->color >> 24;
337             fcolor[1] = (node->color >> 16) & 0xff;
338             fcolor[2] = (node->color >> 8) & 0xff;
339             falpha = node->color & 0xff;
340             error = FT_New_Face( library,
341                                  (char *)node->filename,
342                                  0,
343                                  &face );
344             if ( error ) break;
345             use_kerning = FT_HAS_KERNING(face);
346
347             error = FT_Set_Char_Size(face,   /* handle to face object            */
348                                      (long)(node->size*64),
349                                      (long)(node->size*64),
350                                      (long)(100*canvas->zoom),
351                                      (long)(100*canvas->zoom));
352             if ( error ) break;
353             pen_x = node->x * canvas->zoom;
354             pen_y = node->y * canvas->zoom;
355             slot = face->glyph;
356
357             for(text=(unsigned char *)node->text;*text;text++) {        
358                 previous = glyph_index;
359                 glyph_index = FT_Get_Char_Index( face, *text);
360                 
361                 if (use_kerning && previous && glyph_index){
362                     FT_Vector  delta;
363                     FT_Get_Kerning( face, previous, glyph_index,
364                                     0, &delta );
365                     text_width += (double)delta.x / 64.0;
366                     
367                 }
368                 error = FT_Load_Glyph( face, glyph_index, 0 );
369                 if ( error ) break;
370                 if (previous == 0){
371                   pen_x -= (double)slot->metrics.horiBearingX / 64.0; /* adjust pos for first char */   
372                   text_width -= (double)slot->metrics.horiBearingX / 64.0; /* add just char width */    
373                 }
374                 if ( text_height < (double)slot->metrics.horiBearingY / 64.0 ) {
375                   text_height = (double)slot->metrics.horiBearingY / 64.0;
376                 }
377                 text_width += (double)slot->metrics.horiAdvance / 64.0;
378             }
379             text_width -= (double)slot->metrics.horiAdvance / 64.0; /* remove last step */
380             text_width += (double)slot->metrics.width / 64.0; /* add just char width */
381             text_width += (double)slot->metrics.horiBearingX / 64.0; /* add just char width */
382             
383             switch(node->halign){
384             case GFX_H_RIGHT:  pen_x -= text_width; break;
385             case GFX_H_CENTER: pen_x -= text_width / 2.0; break;          
386             case GFX_H_LEFT: break;          
387             case GFX_H_NULL: break;          
388             }
389
390             switch(node->valign){
391             case GFX_V_TOP:    pen_y += text_height; break;
392             case GFX_V_CENTER: pen_y += text_height / 2.0; break;          
393             case GFX_V_BOTTOM: break;          
394             case GFX_V_NULL: break;          
395             }
396
397             glyph_index=0;
398             for(text=(unsigned char *)node->text;*text;text++) {
399                 int gr;          
400                 previous = glyph_index;
401                 glyph_index = FT_Get_Char_Index( face, *text);
402                 
403                 if (use_kerning && previous && glyph_index){
404                     FT_Vector  delta;
405                     FT_Get_Kerning( face, previous, glyph_index,
406                                     0, &delta );
407                     pen_x += (double)delta.x / 64.0;
408                     
409                 }
410                 error = FT_Load_Glyph( face, glyph_index, FT_LOAD_RENDER );
411                 if ( error ) break;
412                 gr = slot->bitmap.num_grays -1;
413                 for (iy=0; iy < slot->bitmap.rows; iy++){
414                     long buf_y = iy+(pen_y+0.5)-slot->bitmap_top;
415                     if (buf_y < 0 || buf_y >= pys_height) continue;
416                     buf_y *= rowstride;
417                     for (ix=0;ix < slot->bitmap.width;ix++){
418                         long buf_x = ix + (pen_x + 0.5) + (double)slot->bitmap_left ;
419                         art_u8 font_alpha;
420                         
421                         if (buf_x < 0 || buf_x >= pys_width) continue;
422                         buf_x *=  bytes_per_pixel ;
423                         font_alpha =  *(slot->bitmap.buffer + iy * slot->bitmap.width + ix);
424                         font_alpha =  (art_u8)((double)font_alpha / gr * falpha);
425                         for (iz = 0; iz < 3; iz++){
426                             art_u8 *orig = buffer + buf_y + buf_x + iz;
427                             *orig =  (art_u8)((double)*orig / gr * ( gr - font_alpha) +
428                                               (double)fcolor[iz] / gr * (font_alpha));
429                         }
430                     }
431                 }
432                 pen_x += (double)slot->metrics.horiAdvance / 64.0;
433             }
434         }
435         }
436         node = node->next;
437     }  
438     gfx_save_png(buffer,fp , pys_width,pys_height,bytes_per_pixel);
439     art_free(buffer);
440     FT_Done_FreeType( library );
441     return 0;    
442 }
443
444 /* free memory used by nodes this will also remove memory required for
445    associated paths and svcs ... but not for text strings */
446 int
447 gfx_destroy    (gfx_canvas_t *canvas){  
448   gfx_node_t *next,*node = canvas->firstnode;
449   while(node){
450     next = node->next;
451     art_free(node->path);
452     art_free(node->svp);
453     free(node->text);
454     free(node->filename);
455     art_free(node);
456     node = next;
457   }
458   return 0;
459 }
460  
461 static int gfx_save_png (art_u8 *buffer, FILE *fp,  long width, long height, long bytes_per_pixel){
462   png_structp png_ptr = NULL;
463   png_infop   info_ptr = NULL;
464   int i;
465   png_bytep *row_pointers;
466   int rowstride = width * bytes_per_pixel;
467   png_text text[2];
468   
469   if (fp == NULL)
470     return (1);
471
472   png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING,NULL,NULL,NULL);
473   if (png_ptr == NULL)
474    {
475       return (1);
476    }
477    row_pointers = (png_bytepp)png_malloc(png_ptr,
478                                      height*sizeof(png_bytep));
479
480   info_ptr = png_create_info_struct(png_ptr);
481
482   if (info_ptr == NULL)
483     {
484       png_destroy_write_struct(&png_ptr,  (png_infopp)NULL);
485       return (1);
486     }
487
488   if (setjmp(png_jmpbuf(png_ptr)))
489     {
490       /* If we get here, we had a problem writing the file */
491       png_destroy_write_struct(&png_ptr, &info_ptr);
492       return (1);
493     }
494
495   png_init_io(png_ptr, fp);
496   png_set_IHDR (png_ptr, info_ptr,width, height,
497                 8, PNG_COLOR_TYPE_RGB,
498                 PNG_INTERLACE_NONE,
499                 PNG_COMPRESSION_TYPE_DEFAULT,
500                 PNG_FILTER_TYPE_DEFAULT);
501
502   text[0].key = "Software";
503   text[0].text = "RRDtool, Tobias Oetiker <tobi@oetike.ch>, http://tobi.oetiker.ch";
504   text[0].compression = PNG_TEXT_COMPRESSION_NONE;
505   png_set_text (png_ptr, info_ptr, text, 1);
506
507   /* Write header data */
508   png_write_info (png_ptr, info_ptr);
509
510   for (i = 0; i < height; i++)
511     row_pointers[i] = (png_bytep) (buffer + i*rowstride);
512
513   png_write_image(png_ptr, row_pointers);
514   png_write_end(png_ptr, info_ptr);
515   png_destroy_write_struct(&png_ptr, &info_ptr);
516   return 1;
517 }
518
519  
520 /* ------- SVG -------
521    SVG reference:
522    http://www.w3.org/TR/SVG/
523 */
524 static int svg_indent = 0;
525 static int svg_single_line = 0;
526 static const char *svg_default_font = "Helvetica";
527
528 static void svg_print_indent(FILE *fp)
529 {
530   int i;
531    for (i = svg_indent - svg_single_line; i > 0; i--) {
532      putc(' ', fp);
533      putc(' ', fp);
534    }
535 }
536  
537 static void svg_start_tag(FILE *fp, const char *name)
538 {
539    svg_print_indent(fp);
540    putc('<', fp);
541    fputs(name, fp);
542    svg_indent++;
543 }
544  
545 static void svg_close_tag_single_line(FILE *fp)
546 {
547    svg_single_line++;
548    putc('>', fp);
549 }
550  
551 static void svg_close_tag(FILE *fp)
552 {
553    putc('>', fp);
554    if (!svg_single_line)
555      putc('\n', fp);
556 }
557  
558 static void svg_end_tag(FILE *fp, const char *name)
559 {
560    /* name is NULL if closing empty-node tag */
561    svg_indent--;
562    if (svg_single_line)
563      svg_single_line--;
564    else if (name)
565      svg_print_indent(fp);
566    if (name != NULL) {
567      fputs("</", fp);
568      fputs(name, fp);
569    } else {
570      putc('/', fp);
571    }
572    svg_close_tag(fp);
573 }
574  
575 static void svg_close_tag_empty_node(FILE *fp)
576 {
577    svg_end_tag(fp, NULL);
578 }
579  
580 static void svg_write_text(FILE *fp, const char *p)
581 {
582    char ch;
583    const char *start, *last;
584    if (!p)
585      return;
586    /* trim leading spaces */
587    while (*p == ' ')
588      p++;
589    start = p;
590    /* trim trailing spaces */
591    last = p - 1;
592    while ((ch = *p) != 0) {
593      if (ch != ' ')
594        last = p;
595      p++;
596   }
597    /* encode trimmed text */
598    p = start;
599    while (p <= last) {
600      ch = *p++;
601      switch (ch) {
602        case '&': fputs("&amp;", fp); break;
603        case '<': fputs("&lt;", fp); break;
604        case '>': fputs("&gt;", fp); break;
605        case '"': fputs("&quot;", fp); break;
606        default: putc(ch, fp);
607      }
608    }
609 }
610  
611 static void svg_write_number(FILE *fp, double d)
612 {
613    /* omit decimals if integer to reduce filesize */
614    char buf[60], *p;
615    snprintf(buf, sizeof(buf), "%.2f", d);
616    p = buf; /* doesn't trust snprintf return value */
617    while (*p)
618      p++;
619    while (--p > buf) {
620      char ch = *p;
621      if (ch == '0') {
622        *p = '\0'; /* zap trailing zeros */
623        continue;
624      }
625      if (ch == '.')
626        *p = '\0'; /* zap trailing dot */
627      break;
628    }
629    fputs(buf, fp);
630 }
631  
632 static int svg_color_is_black(int c)
633 {
634   /* gfx_color_t is RRGGBBAA */
635   return c == 0x000000FF;
636 }
637  
638 static void svg_write_color(FILE *fp, gfx_color_t c, const char *attr)
639 {
640   /* gfx_color_t is RRGGBBAA, svg can use #RRGGBB and #RGB like html */
641   gfx_color_t rrggbb = (int)((c >> 8) & 0xFFFFFF);
642   gfx_color_t opacity = c & 0xFF;
643   fprintf(fp, " %s=\"", attr);
644   if ((rrggbb & 0x0F0F0F) == ((rrggbb >> 4) & 0x0F0F0F)) {
645      /* css2 short form, #rgb is #rrggbb, not #r0g0b0 */
646     fprintf(fp, "#%03lX",
647           ( ((rrggbb >> 8) & 0xF00)
648           | ((rrggbb >> 4) & 0x0F0)
649           | ( rrggbb       & 0x00F)));
650    } else {
651     fprintf(fp, "#%06lX", rrggbb);
652    }
653   fputs("\"", fp);
654   if (opacity != 0xFF) {
655     fprintf(fp, " stroke-opacity=\"");
656     svg_write_number(fp, opacity / 255.0);
657     fputs("\"", fp);
658  }
659 }
660  
661 static void svg_common_path_attributes(FILE *fp, gfx_node_t *node)
662 {
663   fputs(" stroke-width=\"", fp);
664   svg_write_number(fp, node->size);
665   fputs("\"", fp);
666   svg_write_color(fp, node->color, "stroke");
667   fputs(" fill=\"none\"", fp);
668   if (node->dash_on != 0 && node->dash_off != 0) {
669     fputs(" stroke-dasharray=\"", fp);
670     svg_write_number(fp, node->dash_on);
671     fputs(",", fp);
672     svg_write_number(fp, node->dash_off);
673     fputs("\"", fp);
674   }
675 }
676
677 static int svg_is_int_step(double a, double b)
678 {
679    double diff = fabs(a - b);
680    return floor(diff) == diff;
681 }
682  
683 static int svg_path_straight_segment(FILE *fp,
684      double lastA, double currentA, double currentB,
685      gfx_node_t *node,
686      int segment_idx, int isx, char absChar, char relChar)
687 {
688    if (!svg_is_int_step(lastA, currentA)) {
689      putc(absChar, fp);
690      svg_write_number(fp, currentA);
691      return 0;
692    }
693    if (segment_idx < node->points - 1) {
694      ArtVpath *vec = node->path + segment_idx + 1;
695      if (vec->code == ART_LINETO) {
696        double nextA = (isx ? vec->x : vec->y) - LINEOFFSET;
697        double nextB = (isx ? vec->y : vec->x) - LINEOFFSET;
698        if (nextB == currentB
699            && ((currentA >= lastA) == (nextA >= currentA))
700            && svg_is_int_step(currentA, nextA)) {
701          return 1; /* skip to next as it is a straight line  */
702        }
703      }
704    }
705    putc(relChar, fp);
706    svg_write_number(fp, currentA - lastA);
707    return 0;
708 }
709  
710 static void svg_path(FILE *fp, gfx_node_t *node, int multi)
711 {
712    int i;
713    double lastX = 0, lastY = 0;
714    /* for straight lines <path..> tags take less space than
715       <line..> tags because of the efficient packing
716       in the 'd' attribute */
717    svg_start_tag(fp, "path");
718   if (!multi)
719     svg_common_path_attributes(fp, node);
720    fputs(" d=\"", fp);
721    /* specification of the 'd' attribute: */
722    /* http://www.w3.org/TR/SVG/paths.html#PathDataGeneralInformation */
723    for (i = 0; i < node->points; i++) {
724      ArtVpath *vec = node->path + i;
725      double x = vec->x - LINEOFFSET;
726      double y = vec->y - LINEOFFSET;
727      switch (vec->code) {
728      case ART_MOVETO_OPEN: /* fall-through */
729      case ART_MOVETO:
730        putc('M', fp);
731        svg_write_number(fp, x);
732        putc(',', fp);
733        svg_write_number(fp, y);
734        break;
735      case ART_LINETO:
736        /* try optimize filesize by using minimal lineto commands */
737        /* without introducing rounding errors. */
738        if (x == lastX) {
739          if (svg_path_straight_segment(fp, lastY, y, x, node, i, 0, 'V', 'v'))
740            continue;
741        } else if (y == lastY) {
742          if (svg_path_straight_segment(fp, lastX, x, y, node, i, 1, 'H', 'h'))
743            continue;
744        } else {
745          putc('L', fp);
746          svg_write_number(fp, x);
747          putc(',', fp);
748          svg_write_number(fp, y);
749        }
750        break;
751      case ART_CURVETO: break; /* unsupported */
752      case ART_END: break; /* nop */
753      }
754      lastX = x;
755      lastY = y;
756    }
757   if (node->closed_path)
758     fputs(" Z", fp);
759    fputs("\"", fp);
760    svg_close_tag_empty_node(fp);
761 }
762  
763 static void svg_multi_path(FILE *fp, gfx_node_t **nodeR)
764 {
765    /* optimize for multiple paths with the same color, penwidth, etc. */
766    int num = 1;
767    gfx_node_t *node = *nodeR;
768    gfx_node_t *next = node->next;
769    while (next) {
770      if (next->type != node->type
771          || next->size != node->size
772         || next->color != node->color
773         || next->dash_on != node->dash_on
774         || next->dash_off != node->dash_off)
775        break;
776      next = next->next;
777      num++;
778    }
779    if (num == 1) {
780      svg_path(fp, node, 0);
781      return;
782    }
783    svg_start_tag(fp, "g");
784   svg_common_path_attributes(fp, node);
785    svg_close_tag(fp);
786    while (num && node) {
787      svg_path(fp, node, 1);
788      if (!--num)
789        break;
790      node = node->next;
791      *nodeR = node;
792    }
793    svg_end_tag(fp, "g");
794 }
795  
796 static void svg_area(FILE *fp, gfx_node_t *node)
797 {
798    int i;
799    double startX = 0, startY = 0;
800    svg_start_tag(fp, "polygon");
801   fputs(" ", fp);
802   svg_write_color(fp, node->color, "fill");
803   fputs(" points=\"", fp);
804    for (i = 0; i < node->points; i++) {
805      ArtVpath *vec = node->path + i;
806      double x = vec->x - LINEOFFSET;
807      double y = vec->y - LINEOFFSET;
808      switch (vec->code) {
809        case ART_MOVETO_OPEN: /* fall-through */
810        case ART_MOVETO:
811          svg_write_number(fp, x);
812          putc(',', fp);
813          svg_write_number(fp, y);
814          startX = x;
815          startY = y;
816          break;
817        case ART_LINETO:
818          if (i == node->points - 2
819                         && node->path[i + 1].code == ART_END
820              && fabs(x - startX) < 0.001 && fabs(y - startY) < 0.001) {
821            break; /* poly area always closed, no need for last point */
822          }
823          putc(' ', fp);
824          svg_write_number(fp, x);
825          putc(',', fp);
826          svg_write_number(fp, y);
827          break;
828        case ART_CURVETO: break; /* unsupported */
829        case ART_END: break; /* nop */
830      }
831    }
832    fputs("\"", fp);
833    svg_close_tag_empty_node(fp);
834 }
835  
836 static void svg_text(FILE *fp, gfx_node_t *node)
837 {
838    double x = node->x - LINEOFFSET;
839    double y = node->y - LINEOFFSET;
840    if (node->angle != 0) {
841      svg_start_tag(fp, "g");
842      fputs(" transform=\"translate(", fp);
843      svg_write_number(fp, x);
844      fputs(",", fp);
845      svg_write_number(fp, y);
846      fputs(") rotate(", fp);
847      svg_write_number(fp, node->angle);
848      fputs(")\"", fp);
849      x = y = 0;
850      svg_close_tag(fp);
851    }
852    switch (node->valign) {
853    case GFX_V_TOP:  y += node->size; break;
854    case GFX_V_CENTER: y += node->size / 2; break;
855    case GFX_V_BOTTOM: break;
856    case GFX_V_NULL: break;
857    }
858    svg_start_tag(fp, "text");
859    fputs(" x=\"", fp);
860    svg_write_number(fp, x);
861    fputs("\" y=\"", fp);
862    svg_write_number(fp, y);
863   if (strcmp(node->filename, svg_default_font))
864     fprintf(fp, " font-family=\"%s\"", node->filename);
865    fputs("\" font-size=\"", fp);
866    svg_write_number(fp, node->size);
867    fputs("\"", fp);
868   if (!svg_color_is_black(node->color))
869     svg_write_color(fp, node->color, "fill");
870    switch (node->halign) {
871    case GFX_H_RIGHT:  fputs(" text-anchor=\"end\"", fp); break;
872    case GFX_H_CENTER: fputs(" text-anchor=\"middle\"", fp); break;
873    case GFX_H_LEFT: break;
874    case GFX_H_NULL: break;
875    }
876    svg_close_tag_single_line(fp);
877    /* support for node->tabwidth missing */
878    svg_write_text(fp, node->text);
879    svg_end_tag(fp, "text");
880    if (node->angle != 0)
881      svg_end_tag(fp, "g");
882 }
883  
884 int       gfx_render_svg (gfx_canvas_t *canvas,
885                  art_u32 width, art_u32 height,
886                  gfx_color_t background, FILE *fp){
887    gfx_node_t *node = canvas->firstnode;
888    fputs(
889 "<?xml version=\"1.0\" standalone=\"no\"?>\n"
890 "<!DOCTYPE svg PUBLIC \"-//W3C//DTD SVG 1.0//EN\"\n"
891 "   \"http://www.w3.org/TR/2001/REC-SVG-20010904/DTD/svg10.dtd\">\n"
892 "<!--\n"
893 "   SVG file created by RRDtool,\n"
894 "   Tobias Oetiker <tobi@oetike.ch>, http://tobi.oetiker.ch\n"
895 "\n"
896 "   The width/height attributes in the outhermost svg node\n"
897 "   are just default sizes for the browser which is used\n"
898 "   if the svg file is openened directly without being\n"
899 "   embedded in an html file.\n"
900 "   The viewBox is the local coord system for rrdtool.\n"
901 "-->\n", fp);
902    svg_start_tag(fp, "svg");
903    fputs(" width=\"", fp);
904   svg_write_number(fp, width * canvas->zoom);
905    fputs("\" height=\"", fp);
906   svg_write_number(fp, height * canvas->zoom);
907    fputs("\" x=\"0\" y=\"0\" viewBox=\"", fp);
908    svg_write_number(fp, -LINEOFFSET);
909    fputs(" ", fp);
910    svg_write_number(fp, -LINEOFFSET);
911    fputs(" ", fp);
912    svg_write_number(fp, width - LINEOFFSET);
913    fputs(" ", fp);
914    svg_write_number(fp, height - LINEOFFSET);
915    fputs("\" preserveAspectRatio=\"xMidYMid\"", fp);
916   fprintf(fp, " font-family=\"%s\"", svg_default_font); /* default font */
917   fputs(" stroke-linecap=\"round\" stroke-linejoin=\"round\"", fp);
918    svg_close_tag(fp);
919    svg_start_tag(fp, "rect");
920    fprintf(fp, " x=\"0\" y=\"0\" width=\"%d\" height=\"%d\"", width, height);
921   svg_write_color(fp, background, "fill");
922    svg_close_tag_empty_node(fp);
923    while (node) {
924      switch (node->type) {
925      case GFX_LINE:
926        svg_multi_path(fp, &node);
927        break;
928      case GFX_AREA:
929        svg_area(fp, node);
930        break;
931      case GFX_TEXT:
932        svg_text(fp, node);
933      }
934      node = node->next;
935    }
936    svg_end_tag(fp, "svg");
937    return 0;
938 }