Updated/added MVSC++ 6.0 project files for compilation of
[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             }
388
389             switch(node->valign){
390             case GFX_V_TOP:    pen_y += text_height; break;
391             case GFX_V_CENTER: pen_y += text_height / 2.0; break;          
392             case GFX_V_BOTTOM: break;          
393             }
394
395             glyph_index=0;
396             for(text=(unsigned char *)node->text;*text;text++) {
397                 int gr;          
398                 previous = glyph_index;
399                 glyph_index = FT_Get_Char_Index( face, *text);
400                 
401                 if (use_kerning && previous && glyph_index){
402                     FT_Vector  delta;
403                     FT_Get_Kerning( face, previous, glyph_index,
404                                     0, &delta );
405                     pen_x += (double)delta.x / 64.0;
406                     
407                 }
408                 error = FT_Load_Glyph( face, glyph_index, FT_LOAD_RENDER );
409                 if ( error ) break;
410                 gr = slot->bitmap.num_grays -1;
411                 for (iy=0; iy < slot->bitmap.rows; iy++){
412                     long buf_y = iy+(pen_y+0.5)-slot->bitmap_top;
413                     if (buf_y < 0 || buf_y >= pys_height) continue;
414                     buf_y *= rowstride;
415                     for (ix=0;ix < slot->bitmap.width;ix++){
416                         long buf_x = ix + (pen_x + 0.5) + (double)slot->bitmap_left ;
417                         art_u8 font_alpha;
418                         
419                         if (buf_x < 0 || buf_x >= pys_width) continue;
420                         buf_x *=  bytes_per_pixel ;
421                         font_alpha =  *(slot->bitmap.buffer + iy * slot->bitmap.width + ix);
422                         font_alpha =  (art_u8)((double)font_alpha / gr * falpha);
423                         for (iz = 0; iz < 3; iz++){
424                             art_u8 *orig = buffer + buf_y + buf_x + iz;
425                             *orig =  (art_u8)((double)*orig / gr * ( gr - font_alpha) +
426                                               (double)fcolor[iz] / gr * (font_alpha));
427                         }
428                     }
429                 }
430                 pen_x += (double)slot->metrics.horiAdvance / 64.0;
431             }
432         }
433         }
434         node = node->next;
435     }  
436     gfx_save_png(buffer,fp , pys_width,pys_height,bytes_per_pixel);
437     art_free(buffer);
438     FT_Done_FreeType( library );
439     return 0;    
440 }
441
442 /* free memory used by nodes this will also remove memory required for
443    associated paths and svcs ... but not for text strings */
444 int
445 gfx_destroy    (gfx_canvas_t *canvas){  
446   gfx_node_t *next,*node = canvas->firstnode;
447   while(node){
448     next = node->next;
449     art_free(node->path);
450     art_free(node->svp);
451     free(node->text);
452     free(node->filename);
453     art_free(node);
454     node = next;
455   }
456   return 0;
457 }
458  
459 static int gfx_save_png (art_u8 *buffer, FILE *fp,  long width, long height, long bytes_per_pixel){
460   png_structp png_ptr = NULL;
461   png_infop   info_ptr = NULL;
462   int i;
463   png_bytep *row_pointers;
464   int rowstride = width * bytes_per_pixel;
465   png_text text[2];
466   
467   if (fp == NULL)
468     return (1);
469
470   png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING,NULL,NULL,NULL);
471   if (png_ptr == NULL)
472    {
473       return (1);
474    }
475    row_pointers = (png_bytepp)png_malloc(png_ptr,
476                                      height*sizeof(png_bytep));
477
478   info_ptr = png_create_info_struct(png_ptr);
479
480   if (info_ptr == NULL)
481     {
482       png_destroy_write_struct(&png_ptr,  (png_infopp)NULL);
483       return (1);
484     }
485
486   if (setjmp(png_jmpbuf(png_ptr)))
487     {
488       /* If we get here, we had a problem writing the file */
489       png_destroy_write_struct(&png_ptr, &info_ptr);
490       return (1);
491     }
492
493   png_init_io(png_ptr, fp);
494   png_set_IHDR (png_ptr, info_ptr,width, height,
495                 8, PNG_COLOR_TYPE_RGB,
496                 PNG_INTERLACE_NONE,
497                 PNG_COMPRESSION_TYPE_DEFAULT,
498                 PNG_FILTER_TYPE_DEFAULT);
499
500   text[0].key = "Software";
501   text[0].text = "RRDtool, Tobias Oetiker <tobi@oetike.ch>, http://tobi.oetiker.ch";
502   text[0].compression = PNG_TEXT_COMPRESSION_NONE;
503   png_set_text (png_ptr, info_ptr, text, 1);
504
505   /* Write header data */
506   png_write_info (png_ptr, info_ptr);
507
508   for (i = 0; i < height; i++)
509     row_pointers[i] = (png_bytep) (buffer + i*rowstride);
510
511   png_write_image(png_ptr, row_pointers);
512   png_write_end(png_ptr, info_ptr);
513   png_destroy_write_struct(&png_ptr, &info_ptr);
514   return 1;
515 }
516
517  
518 /* ------- SVG -------
519    SVG reference:
520    http://www.w3.org/TR/SVG/
521 */
522 static int svg_indent = 0;
523 static int svg_single_line = 0;
524 static const char *svg_default_font = "Helvetica";
525
526 static void svg_print_indent(FILE *fp)
527 {
528   int i;
529    for (i = svg_indent - svg_single_line; i > 0; i--) {
530      putc(' ', fp);
531      putc(' ', fp);
532    }
533 }
534  
535 static void svg_start_tag(FILE *fp, const char *name)
536 {
537    svg_print_indent(fp);
538    putc('<', fp);
539    fputs(name, fp);
540    svg_indent++;
541 }
542  
543 static void svg_close_tag_single_line(FILE *fp)
544 {
545    svg_single_line++;
546    putc('>', fp);
547 }
548  
549 static void svg_close_tag(FILE *fp)
550 {
551    putc('>', fp);
552    if (!svg_single_line)
553      putc('\n', fp);
554 }
555  
556 static void svg_end_tag(FILE *fp, const char *name)
557 {
558    /* name is NULL if closing empty-node tag */
559    svg_indent--;
560    if (svg_single_line)
561      svg_single_line--;
562    else if (name)
563      svg_print_indent(fp);
564    if (name != NULL) {
565      fputs("</", fp);
566      fputs(name, fp);
567    } else {
568      putc('/', fp);
569    }
570    svg_close_tag(fp);
571 }
572  
573 static void svg_close_tag_empty_node(FILE *fp)
574 {
575    svg_end_tag(fp, NULL);
576 }
577  
578 static void svg_write_text(FILE *fp, const char *p)
579 {
580    char ch;
581    const char *start, *last;
582    if (!p)
583      return;
584    /* trim leading spaces */
585    while (*p == ' ')
586      p++;
587    start = p;
588    /* trim trailing spaces */
589    last = p - 1;
590    while ((ch = *p) != 0) {
591      if (ch != ' ')
592        last = p;
593      p++;
594   }
595    /* encode trimmed text */
596    p = start;
597    while (p <= last) {
598      ch = *p++;
599      switch (ch) {
600        case '&': fputs("&amp;", fp); break;
601        case '<': fputs("&lt;", fp); break;
602        case '>': fputs("&gt;", fp); break;
603        case '"': fputs("&quot;", fp); break;
604        default: putc(ch, fp);
605      }
606    }
607 }
608  
609 static void svg_write_number(FILE *fp, double d)
610 {
611    /* omit decimals if integer to reduce filesize */
612    char buf[60], *p;
613    snprintf(buf, sizeof(buf), "%.2f", d);
614    p = buf; /* doesn't trust snprintf return value */
615    while (*p)
616      p++;
617    while (--p > buf) {
618      char ch = *p;
619      if (ch == '0') {
620        *p = '\0'; /* zap trailing zeros */
621        continue;
622      }
623      if (ch == '.')
624        *p = '\0'; /* zap trailing dot */
625      break;
626    }
627    fputs(buf, fp);
628 }
629  
630 static int svg_color_is_black(int c)
631 {
632   /* gfx_color_t is RRGGBBAA */
633   return c == 0x000000FF;
634 }
635  
636 static void svg_write_color(FILE *fp, gfx_color_t c, const char *attr)
637 {
638   /* gfx_color_t is RRGGBBAA, svg can use #RRGGBB and #RGB like html */
639   gfx_color_t rrggbb = (int)((c >> 8) & 0xFFFFFF);
640   gfx_color_t opacity = c & 0xFF;
641   fprintf(fp, " %s=\"", attr);
642   if ((rrggbb & 0x0F0F0F) == ((rrggbb >> 4) & 0x0F0F0F)) {
643      /* css2 short form, #rgb is #rrggbb, not #r0g0b0 */
644     fprintf(fp, "#%03lX",
645           ( ((rrggbb >> 8) & 0xF00)
646           | ((rrggbb >> 4) & 0x0F0)
647           | ( rrggbb       & 0x00F)));
648    } else {
649     fprintf(fp, "#%06lX", rrggbb);
650    }
651   fputs("\"", fp);
652   if (opacity != 0xFF) {
653     fprintf(fp, " stroke-opacity=\"");
654     svg_write_number(fp, opacity / 255.0);
655     fputs("\"", fp);
656  }
657 }
658  
659 static void svg_common_path_attributes(FILE *fp, gfx_node_t *node)
660 {
661   fputs(" stroke-width=\"", fp);
662   svg_write_number(fp, node->size);
663   fputs("\"", fp);
664   svg_write_color(fp, node->color, "stroke");
665   fputs(" fill=\"none\"", fp);
666   if (node->dash_on != 0 && node->dash_off != 0) {
667     fputs(" stroke-dasharray=\"", fp);
668     svg_write_number(fp, node->dash_on);
669     fputs(",", fp);
670     svg_write_number(fp, node->dash_off);
671     fputs("\"", fp);
672   }
673 }
674
675 static int svg_is_int_step(double a, double b)
676 {
677    double diff = fabs(a - b);
678    return floor(diff) == diff;
679 }
680  
681 static int svg_path_straight_segment(FILE *fp,
682      double lastA, double currentA, double currentB,
683      gfx_node_t *node,
684      int segment_idx, int isx, char absChar, char relChar)
685 {
686    if (!svg_is_int_step(lastA, currentA)) {
687      putc(absChar, fp);
688      svg_write_number(fp, currentA);
689      return 0;
690    }
691    if (segment_idx < node->points - 1) {
692      ArtVpath *vec = node->path + segment_idx + 1;
693      if (vec->code == ART_LINETO) {
694        double nextA = (isx ? vec->x : vec->y) - LINEOFFSET;
695        double nextB = (isx ? vec->y : vec->x) - LINEOFFSET;
696        if (nextB == currentB
697            && ((currentA >= lastA) == (nextA >= currentA))
698            && svg_is_int_step(currentA, nextA)) {
699          return 1; /* skip to next as it is a straight line  */
700        }
701      }
702    }
703    putc(relChar, fp);
704    svg_write_number(fp, currentA - lastA);
705    return 0;
706 }
707  
708 static void svg_path(FILE *fp, gfx_node_t *node, int multi)
709 {
710    int i;
711    double lastX = 0, lastY = 0;
712    /* for straight lines <path..> tags take less space than
713       <line..> tags because of the efficient packing
714       in the 'd' attribute */
715    svg_start_tag(fp, "path");
716   if (!multi)
717     svg_common_path_attributes(fp, node);
718    fputs(" d=\"", fp);
719    /* specification of the 'd' attribute: */
720    /* http://www.w3.org/TR/SVG/paths.html#PathDataGeneralInformation */
721    for (i = 0; i < node->points; i++) {
722      ArtVpath *vec = node->path + i;
723      double x = vec->x - LINEOFFSET;
724      double y = vec->y - LINEOFFSET;
725      switch (vec->code) {
726      case ART_MOVETO_OPEN: /* fall-through */
727      case ART_MOVETO:
728        putc('M', fp);
729        svg_write_number(fp, x);
730        putc(',', fp);
731        svg_write_number(fp, y);
732        break;
733      case ART_LINETO:
734        /* try optimize filesize by using minimal lineto commands */
735        /* without introducing rounding errors. */
736        if (x == lastX) {
737          if (svg_path_straight_segment(fp, lastY, y, x, node, i, 0, 'V', 'v'))
738            continue;
739        } else if (y == lastY) {
740          if (svg_path_straight_segment(fp, lastX, x, y, node, i, 1, 'H', 'h'))
741            continue;
742        } else {
743          putc('L', fp);
744          svg_write_number(fp, x);
745          putc(',', fp);
746          svg_write_number(fp, y);
747        }
748        break;
749      case ART_CURVETO: break; /* unsupported */
750      case ART_END: break; /* nop */
751      }
752      lastX = x;
753      lastY = y;
754    }
755   if (node->closed_path)
756     fputs(" Z", fp);
757    fputs("\"", fp);
758    svg_close_tag_empty_node(fp);
759 }
760  
761 static void svg_multi_path(FILE *fp, gfx_node_t **nodeR)
762 {
763    /* optimize for multiple paths with the same color, penwidth, etc. */
764    int num = 1;
765    gfx_node_t *node = *nodeR;
766    gfx_node_t *next = node->next;
767    while (next) {
768      if (next->type != node->type
769          || next->size != node->size
770         || next->color != node->color
771         || next->dash_on != node->dash_on
772         || next->dash_off != node->dash_off)
773        break;
774      next = next->next;
775      num++;
776    }
777    if (num == 1) {
778      svg_path(fp, node, 0);
779      return;
780    }
781    svg_start_tag(fp, "g");
782   svg_common_path_attributes(fp, node);
783    svg_close_tag(fp);
784    while (num && node) {
785      svg_path(fp, node, 1);
786      if (!--num)
787        break;
788      node = node->next;
789      *nodeR = node;
790    }
791    svg_end_tag(fp, "g");
792 }
793  
794 static void svg_area(FILE *fp, gfx_node_t *node)
795 {
796    int i;
797    double startX = 0, startY = 0;
798    svg_start_tag(fp, "polygon");
799   fputs(" ", fp);
800   svg_write_color(fp, node->color, "fill");
801   fputs(" points=\"", fp);
802    for (i = 0; i < node->points; i++) {
803      ArtVpath *vec = node->path + i;
804      double x = vec->x - LINEOFFSET;
805      double y = vec->y - LINEOFFSET;
806      switch (vec->code) {
807        case ART_MOVETO_OPEN: /* fall-through */
808        case ART_MOVETO:
809          svg_write_number(fp, x);
810          putc(',', fp);
811          svg_write_number(fp, y);
812          startX = x;
813          startY = y;
814          break;
815        case ART_LINETO:
816          if (i == node->points - 2
817                         && node->path[i + 1].code == ART_END
818              && fabs(x - startX) < 0.001 && fabs(y - startY) < 0.001) {
819            break; /* poly area always closed, no need for last point */
820          }
821          putc(' ', fp);
822          svg_write_number(fp, x);
823          putc(',', fp);
824          svg_write_number(fp, y);
825          break;
826        case ART_CURVETO: break; /* unsupported */
827        case ART_END: break; /* nop */
828      }
829    }
830    fputs("\"", fp);
831    svg_close_tag_empty_node(fp);
832 }
833  
834 static void svg_text(FILE *fp, gfx_node_t *node)
835 {
836    double x = node->x - LINEOFFSET;
837    double y = node->y - LINEOFFSET;
838    if (node->angle != 0) {
839      svg_start_tag(fp, "g");
840      fputs(" transform=\"translate(", fp);
841      svg_write_number(fp, x);
842      fputs(",", fp);
843      svg_write_number(fp, y);
844      fputs(") rotate(", fp);
845      svg_write_number(fp, node->angle);
846      fputs(")\"", fp);
847      x = y = 0;
848      svg_close_tag(fp);
849    }
850    switch (node->valign) {
851    case GFX_V_TOP:  y += node->size; break;
852    case GFX_V_CENTER: y += node->size / 2; break;
853    case GFX_V_BOTTOM: break;
854    case GFX_V_NULL: break;
855    }
856    svg_start_tag(fp, "text");
857    fputs(" x=\"", fp);
858    svg_write_number(fp, x);
859    fputs("\" y=\"", fp);
860    svg_write_number(fp, y);
861   if (strcmp(node->filename, svg_default_font))
862     fprintf(fp, " font-family=\"%s\"", node->filename);
863    fputs("\" font-size=\"", fp);
864    svg_write_number(fp, node->size);
865    fputs("\"", fp);
866   if (!svg_color_is_black(node->color))
867     svg_write_color(fp, node->color, "fill");
868    switch (node->halign) {
869    case GFX_H_RIGHT:  fputs(" text-anchor=\"end\"", fp); break;
870    case GFX_H_CENTER: fputs(" text-anchor=\"middle\"", fp); break;
871    case GFX_H_LEFT: break;
872    case GFX_H_NULL: break;
873    }
874    svg_close_tag_single_line(fp);
875    /* support for node->tabwidth missing */
876    svg_write_text(fp, node->text);
877    svg_end_tag(fp, "text");
878    if (node->angle != 0)
879      svg_end_tag(fp, "g");
880 }
881  
882 int       gfx_render_svg (gfx_canvas_t *canvas,
883                  art_u32 width, art_u32 height,
884                  gfx_color_t background, FILE *fp){
885    gfx_node_t *node = canvas->firstnode;
886    fputs(
887 "<?xml version=\"1.0\" standalone=\"no\"?>\n"
888 "<!DOCTYPE svg PUBLIC \"-//W3C//DTD SVG 1.0//EN\"\n"
889 "   \"http://www.w3.org/TR/2001/REC-SVG-20010904/DTD/svg10.dtd\">\n"
890 "<!--\n"
891 "   SVG file created by RRDtool,\n"
892 "   Tobias Oetiker <tobi@oetike.ch>, http://tobi.oetiker.ch\n"
893 "\n"
894 "   The width/height attributes in the outhermost svg node\n"
895 "   are just default sizes for the browser which is used\n"
896 "   if the svg file is openened directly without being\n"
897 "   embedded in an html file.\n"
898 "   The viewBox is the local coord system for rrdtool.\n"
899 "-->\n", fp);
900    svg_start_tag(fp, "svg");
901    fputs(" width=\"", fp);
902   svg_write_number(fp, width * canvas->zoom);
903    fputs("\" height=\"", fp);
904   svg_write_number(fp, height * canvas->zoom);
905    fputs("\" x=\"0\" y=\"0\" viewBox=\"", fp);
906    svg_write_number(fp, -LINEOFFSET);
907    fputs(" ", fp);
908    svg_write_number(fp, -LINEOFFSET);
909    fputs(" ", fp);
910    svg_write_number(fp, width - LINEOFFSET);
911    fputs(" ", fp);
912    svg_write_number(fp, height - LINEOFFSET);
913    fputs("\" preserveAspectRatio=\"xMidYMid\"", fp);
914   fprintf(fp, " font-family=\"%s\"", svg_default_font); /* default font */
915   fputs(" stroke-linecap=\"round\" stroke-linejoin=\"round\"", fp);
916    svg_close_tag(fp);
917    svg_start_tag(fp, "rect");
918    fprintf(fp, " x=\"0\" y=\"0\" width=\"%d\" height=\"%d\"", width, height);
919   svg_write_color(fp, background, "fill");
920    svg_close_tag_empty_node(fp);
921    while (node) {
922      switch (node->type) {
923      case GFX_LINE:
924        svg_multi_path(fp, &node);
925        break;
926      case GFX_AREA:
927        svg_area(fp, node);
928        break;
929      case GFX_TEXT:
930        svg_text(fp, node);
931      }
932      node = node->next;
933    }
934    svg_end_tag(fp, "svg");
935    return 0;
936 }