Evenly-spaced y-axis gridlines.
[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 #include "rrd_afm.h"
21
22 /* lines are better drawn on the pixle than between pixles */
23 #define LINEOFFSET 0.5
24
25 static
26 gfx_node_t *gfx_new_node( gfx_canvas_t *canvas,enum gfx_en type){
27   gfx_node_t *node = art_new(gfx_node_t,1);
28   if (node == NULL) return NULL;
29   node->type = type;
30   node->color = 0x0;        /* color of element  0xRRGGBBAA  alpha 0xff is solid*/
31   node->size =0.0;         /* font size, line width */
32   node->path = NULL;        /* path */
33   node->points = 0;
34   node->points_max =0;
35   node->closed_path = 0;
36   node->svp = NULL;         /* svp */
37   node->filename = NULL;             /* font or image filename */
38   node->text = NULL;
39   node->x = 0.0;
40   node->y = 0.0;          /* position */
41   node->angle = 0;  
42   node->halign = GFX_H_NULL; /* text alignement */
43   node->valign = GFX_V_NULL; /* text alignement */
44   node->tabwidth = 0.0; 
45   node->next = NULL; 
46   if (canvas->lastnode != NULL){
47       canvas->lastnode->next = node;
48   }
49   if (canvas->firstnode == NULL){
50       canvas->firstnode = node;
51   }  
52   canvas->lastnode = node;
53   return node;
54 }
55
56 gfx_canvas_t *gfx_new_canvas (void) {
57     gfx_canvas_t *canvas = art_new(gfx_canvas_t,1);
58     canvas->firstnode = NULL;
59     canvas->lastnode = NULL;
60     canvas->imgformat = IF_PNG; /* we default to PNG output */
61     canvas->interlaced = 0;
62     canvas->zoom = 1.0;
63     return canvas;    
64 }
65
66 /* create a new line */
67 gfx_node_t  *gfx_new_line(gfx_canvas_t *canvas, 
68                            double X0, double Y0, 
69                            double X1, double Y1,
70                            double width, gfx_color_t color){
71   return gfx_new_dashed_line(canvas, X0, Y0, X1, Y1, width, color, 0, 0);
72 }
73
74 gfx_node_t  *gfx_new_dashed_line(gfx_canvas_t *canvas, 
75                            double X0, double Y0, 
76                            double X1, double Y1,
77                            double width, gfx_color_t color,
78                            double dash_on, double dash_off){
79
80   gfx_node_t *node;
81   ArtVpath *vec;
82   node = gfx_new_node(canvas,GFX_LINE);
83   if (node == NULL) return NULL;
84   vec = art_new(ArtVpath, 3);
85   if (vec == NULL) return NULL;
86   vec[0].code = ART_MOVETO_OPEN; vec[0].x=X0+LINEOFFSET; vec[0].y=Y0+LINEOFFSET;
87   vec[1].code = ART_LINETO; vec[1].x=X1+LINEOFFSET; vec[1].y=Y1+LINEOFFSET;
88   vec[2].code = ART_END;
89   
90   node->points = 3;
91   node->points_max = 3;
92   node->color = color;
93   node->size  = width;
94   node->dash_on = dash_on;
95   node->dash_off = dash_off;
96   node->path  = vec;
97   return node;
98 }
99
100 /* create a new area */
101 gfx_node_t   *gfx_new_area   (gfx_canvas_t *canvas, 
102                               double X0, double Y0,
103                               double X1, double Y1,
104                               double X2, double Y2,
105                               gfx_color_t color) {
106
107   gfx_node_t *node;
108   ArtVpath *vec;
109   node = gfx_new_node(canvas,GFX_AREA);
110   if (node == NULL) return NULL;
111   vec = art_new(ArtVpath, 5);
112   if (vec == NULL) return NULL;
113   vec[0].code = ART_MOVETO; vec[0].x=X0; vec[0].y=Y0;
114   vec[1].code = ART_LINETO; vec[1].x=X1; vec[1].y=Y1;
115   vec[2].code = ART_LINETO; vec[2].x=X2; vec[2].y=Y2;
116   vec[3].code = ART_LINETO; vec[3].x=X0; vec[3].y=Y0;
117   vec[4].code = ART_END;
118   
119   node->points = 5;
120   node->points_max = 5;
121   node->color = color;
122   node->path  = vec;
123
124   return node;
125 }
126
127 /* add a point to a line or to an area */
128 int           gfx_add_point  (gfx_node_t *node, 
129                               double x, double y){
130   if (node == NULL) return 1;
131   if (node->type == GFX_AREA) {
132     double X0 = node->path[0].x;
133     double Y0 = node->path[0].y;
134     node->points -= 2;
135     art_vpath_add_point (&(node->path),
136                          &(node->points),
137                          &(node->points_max),
138                          ART_LINETO,
139                          x,y);
140     art_vpath_add_point (&(node->path),
141                          &(node->points),
142                          &(node->points_max),
143                          ART_LINETO,
144                          X0,Y0);
145     art_vpath_add_point (&(node->path),
146                          &(node->points),
147                          &(node->points_max),
148                          ART_END,
149                          0,0);
150   } else if (node->type == GFX_LINE) {
151     node->points -= 1;
152     art_vpath_add_point (&(node->path),
153                          &(node->points),
154                          &(node->points_max),
155                          ART_LINETO,
156                          x+LINEOFFSET,y+LINEOFFSET);
157     art_vpath_add_point (&(node->path),
158                          &(node->points),
159                          &(node->points_max),
160                          ART_END,
161                          0,0);
162     
163   } else {
164     /* can only add point to areas and lines */
165     return 1;
166   }
167   return 0;
168 }
169
170 void           gfx_close_path  (gfx_node_t *node) {
171     node->closed_path = 1;
172     if (node->path[0].code == ART_MOVETO_OPEN)
173         node->path[0].code = ART_MOVETO;
174 }
175
176 /* create a text node */
177 gfx_node_t   *gfx_new_text   (gfx_canvas_t *canvas,  
178                               double x, double y, gfx_color_t color,
179                               char* font, double size,                        
180                               double tabwidth, double angle,
181                               enum gfx_h_align_en h_align,
182                               enum gfx_v_align_en v_align,
183                               char* text){
184    gfx_node_t *node = gfx_new_node(canvas,GFX_TEXT);
185    if (angle != 0.0){
186        /* currently we only support 0 and 270 */
187        angle = 270.0;
188    }
189    
190    node->text = strdup(text);
191    node->size = size;
192    node->filename = strdup(font);
193    node->x = x;
194    node->y = y;
195    node->angle = angle;   
196    node->color = color;
197    node->tabwidth = tabwidth;
198    node->halign = h_align;
199    node->valign = v_align;
200 #if 0
201   /* debugging: show text anchor */
202    gfx_new_line(canvas, x - 3, y + 0, x, y, 0.2, 0x00FF0000);
203    gfx_new_line(canvas, x - 0, y + 3, x, y, 0.2, 0x00FF0000);
204 #endif
205    return node;
206 }
207
208 int           gfx_render(gfx_canvas_t *canvas, 
209                               art_u32 width, art_u32 height, 
210                               gfx_color_t background, FILE *fp){
211   switch (canvas->imgformat) {
212   case IF_PNG: 
213     return gfx_render_png (canvas, width, height, background, fp);
214   case IF_SVG: 
215     return gfx_render_svg (canvas, width, height, background, fp);
216   case IF_EPS:
217     return gfx_render_eps (canvas, width, height, background, fp);
218   default:
219     return -1;
220   }
221 }
222
223 double gfx_get_text_width ( gfx_canvas_t *canvas,
224                             double start, char* font, double size,
225                             double tabwidth, char* text){
226   switch (canvas->imgformat) {
227   case IF_PNG: 
228     return gfx_get_text_width_libart (canvas, start, font, size, tabwidth, text);
229   case IF_SVG: /* fall through */ 
230   case IF_EPS:
231     return afm_get_text_width(start, font, size, tabwidth, text);
232   default:
233     return size * strlen(text);
234   }
235 }
236
237 double gfx_get_text_width_libart ( gfx_canvas_t *canvas,
238                             double start, char* font, double size,
239                             double tabwidth, char* text){
240
241   FT_GlyphSlot  slot;
242   FT_UInt       previous=0;
243   FT_UInt       glyph_index=0;
244   FT_Bool       use_kerning;
245   int           error;
246   FT_Face       face;
247   FT_Library    library=NULL;  
248   double        text_width=0;
249   FT_Init_FreeType( &library );
250   error = FT_New_Face( library, font, 0, &face );
251   if ( error ) return -1;
252   error = FT_Set_Char_Size(face,  size*64,size*64,  100,100);
253   if ( error ) return -1;
254
255   use_kerning = FT_HAS_KERNING(face);
256   slot = face->glyph;
257   for(;*text;text++) {  
258     previous = glyph_index;
259     glyph_index = FT_Get_Char_Index( face, *text);
260     
261     if (use_kerning && previous && glyph_index){
262       FT_Vector  delta;
263       FT_Get_Kerning( face, previous, glyph_index,
264                       0, &delta );
265       text_width += (double)delta.x / 64.0;
266       
267     }
268     error = FT_Load_Glyph( face, glyph_index, 0 );
269     if ( error ) {
270       FT_Done_FreeType(library);
271       return -1;
272     }
273     if (! previous) {
274       text_width -= (double)slot->metrics.horiBearingX / 64.0; /* add just char width */        
275     }
276     text_width += (double)slot->metrics.horiAdvance / 64.0;
277   }
278   text_width -= (double)slot->metrics.horiAdvance / 64.0; /* remove last step */
279   text_width += (double)slot->metrics.width / 64.0; /* add just char width */
280   text_width += (double)slot->metrics.horiBearingX / 64.0; /* add just char width */
281   FT_Done_FreeType(library);
282   return text_width;
283 }
284  
285 static void gfx_libart_close_path(gfx_canvas_t *canvas,
286         gfx_node_t *node, ArtVpath **vec)
287 {
288     /* libart must have end==start for closed paths,
289        even if using ART_MOVETO and not ART_MOVETO_OPEN
290        so add extra point which is the same as the starting point */
291     int points_max = node->points; /* scaled array has exact size */
292     int points = node->points - 1;
293     art_vpath_add_point (vec, &points, &points_max, ART_LINETO,
294             (**vec).x, (**vec).y);
295     art_vpath_add_point (vec, &points, &points_max, ART_END, 0, 0);
296 }
297
298 static void gfx_round_scaled_coordinates(gfx_canvas_t *canvas,
299         gfx_node_t *node, ArtVpath *vec)
300 {
301     while (vec->code != ART_END) {
302         vec->x = floor(vec->x - LINEOFFSET + 0.5) + LINEOFFSET;
303         vec->y = floor(vec->y - LINEOFFSET + 0.5) + LINEOFFSET;
304         vec++;
305     }
306 }
307
308 static int gfx_save_png (art_u8 *buffer, FILE *fp,
309                      long width, long height, long bytes_per_pixel);
310 /* render grafics into png image */
311 int           gfx_render_png (gfx_canvas_t *canvas, 
312                               art_u32 width, art_u32 height, 
313                               gfx_color_t background, FILE *fp){
314     
315     
316     FT_Library    library;
317     gfx_node_t *node = canvas->firstnode;    
318     art_u8 red = background >> 24, green = (background >> 16) & 0xff;
319     art_u8 blue = (background >> 8) & 0xff, alpha = ( background & 0xff );
320     unsigned long pys_width = width * canvas->zoom;
321     unsigned long pys_height = height * canvas->zoom;
322     const int bytes_per_pixel = 3;
323     unsigned long rowstride = pys_width*bytes_per_pixel; /* bytes per pixel */
324     art_u8 *buffer = art_new (art_u8, rowstride*pys_height);
325     art_rgb_run_alpha (buffer, red, green, blue, alpha, pys_width*pys_height);
326     FT_Init_FreeType( &library );
327     while(node){
328         switch (node->type) {
329         case GFX_LINE:
330         case GFX_AREA: {   
331             ArtVpath *vec;
332             double dst[6];     
333             ArtSVP *svp;
334             art_affine_scale(dst,canvas->zoom,canvas->zoom);
335             vec = art_vpath_affine_transform(node->path,dst);
336             if (node->closed_path)
337                 gfx_libart_close_path(canvas, node, &vec);
338             gfx_round_scaled_coordinates(canvas, node, vec);
339             if(node->type == GFX_LINE){
340                 svp = art_svp_vpath_stroke ( vec, ART_PATH_STROKE_JOIN_ROUND,
341                                              ART_PATH_STROKE_CAP_ROUND,
342                                              node->size*canvas->zoom,1,1);
343             } else {
344                 svp = art_svp_from_vpath ( vec );
345             }
346             art_free(vec);
347             art_rgb_svp_alpha (svp ,0,0, pys_width, pys_height,
348                                node->color, buffer, rowstride, NULL);
349             art_free(svp);
350             break;
351         }
352         case GFX_TEXT: {
353             int  error;
354             float text_width=0.0, text_height = 0.0;
355             unsigned char *text;
356             art_u8 fcolor[3],falpha;
357             FT_Face       face;
358             FT_GlyphSlot  slot;
359             FT_UInt       previous=0;
360             FT_UInt       glyph_index=0;
361             FT_Bool       use_kerning;
362
363             float pen_x = 0.0 , pen_y = 0.0;
364             /* double x,y; */
365             long   ix,iy,iz;
366             
367             fcolor[0] = node->color >> 24;
368             fcolor[1] = (node->color >> 16) & 0xff;
369             fcolor[2] = (node->color >> 8) & 0xff;
370             falpha = node->color & 0xff;
371             error = FT_New_Face( library,
372                                  (char *)node->filename,
373                                  0,
374                                  &face );
375             if ( error ) break;
376             use_kerning = FT_HAS_KERNING(face);
377
378             error = FT_Set_Char_Size(face,   /* handle to face object            */
379                                      (long)(node->size*64),
380                                      (long)(node->size*64),
381                                      (long)(100*canvas->zoom),
382                                      (long)(100*canvas->zoom));
383             if ( error ) break;
384             pen_x = node->x * canvas->zoom;
385             pen_y = node->y * canvas->zoom;
386             slot = face->glyph;
387
388             for(text=(unsigned char *)node->text;*text;text++) {        
389                 previous = glyph_index;
390                 glyph_index = FT_Get_Char_Index( face, *text);
391                 
392                 if (use_kerning && previous && glyph_index){
393                     FT_Vector  delta;
394                     FT_Get_Kerning( face, previous, glyph_index,
395                                     0, &delta );
396                     text_width += (double)delta.x / 64.0;
397                     
398                 }
399                 error = FT_Load_Glyph( face, glyph_index, 0 );
400                 if ( error ) break;
401                 if (previous == 0){
402                   pen_x -= (double)slot->metrics.horiBearingX / 64.0; /* adjust pos for first char */   
403                   text_width -= (double)slot->metrics.horiBearingX / 64.0; /* add just char width */    
404                 }
405                 if ( text_height < (double)slot->metrics.horiBearingY / 64.0 ) {
406                   text_height = (double)slot->metrics.horiBearingY / 64.0;
407                 }
408                 text_width += (double)slot->metrics.horiAdvance / 64.0;
409             }
410             text_width -= (double)slot->metrics.horiAdvance / 64.0; /* remove last step */
411             text_width += (double)slot->metrics.width / 64.0; /* add just char width */
412             text_width += (double)slot->metrics.horiBearingX / 64.0; /* add just char width */
413             
414             switch(node->halign){
415             case GFX_H_RIGHT:  pen_x -= text_width; break;
416             case GFX_H_CENTER: pen_x -= text_width / 2.0; break;          
417             case GFX_H_LEFT: break;          
418             case GFX_H_NULL: break;          
419             }
420
421             switch(node->valign){
422             case GFX_V_TOP:    pen_y += text_height; break;
423             case GFX_V_CENTER: pen_y += text_height / 2.0; break;          
424             case GFX_V_BOTTOM: break;          
425             case GFX_V_NULL: break;          
426             }
427
428             glyph_index=0;
429             for(text=(unsigned char *)node->text;*text;text++) {
430                 int gr;          
431                 previous = glyph_index;
432                 glyph_index = FT_Get_Char_Index( face, *text);
433                 
434                 if (use_kerning && previous && glyph_index){
435                     FT_Vector  delta;
436                     FT_Get_Kerning( face, previous, glyph_index,
437                                     0, &delta );
438                     pen_x += (double)delta.x / 64.0;
439                     
440                 }
441                 error = FT_Load_Glyph( face, glyph_index, FT_LOAD_RENDER );
442                 if ( error ) break;
443                 gr = slot->bitmap.num_grays -1;
444                 for (iy=0; iy < slot->bitmap.rows; iy++){
445                     long buf_y = iy+(pen_y+0.5)-slot->bitmap_top;
446                     if (buf_y < 0 || buf_y >= pys_height) continue;
447                     buf_y *= rowstride;
448                     for (ix=0;ix < slot->bitmap.width;ix++){
449                         long buf_x = ix + (pen_x + 0.5) + (double)slot->bitmap_left ;
450                         art_u8 font_alpha;
451                         
452                         if (buf_x < 0 || buf_x >= pys_width) continue;
453                         buf_x *=  bytes_per_pixel ;
454                         font_alpha =  *(slot->bitmap.buffer + iy * slot->bitmap.width + ix);
455                         font_alpha =  (art_u8)((double)font_alpha / gr * falpha);
456                         for (iz = 0; iz < 3; iz++){
457                             art_u8 *orig = buffer + buf_y + buf_x + iz;
458                             *orig =  (art_u8)((double)*orig / gr * ( gr - font_alpha) +
459                                               (double)fcolor[iz] / gr * (font_alpha));
460                         }
461                     }
462                 }
463                 pen_x += (double)slot->metrics.horiAdvance / 64.0;
464             }
465         }
466         }
467         node = node->next;
468     }  
469     gfx_save_png(buffer,fp , pys_width,pys_height,bytes_per_pixel);
470     art_free(buffer);
471     FT_Done_FreeType( library );
472     return 0;    
473 }
474
475 /* free memory used by nodes this will also remove memory required for
476    associated paths and svcs ... but not for text strings */
477 int
478 gfx_destroy    (gfx_canvas_t *canvas){  
479   gfx_node_t *next,*node = canvas->firstnode;
480   while(node){
481     next = node->next;
482     art_free(node->path);
483     art_free(node->svp);
484     free(node->text);
485     free(node->filename);
486     art_free(node);
487     node = next;
488   }
489   return 0;
490 }
491  
492 static int gfx_save_png (art_u8 *buffer, FILE *fp,  long width, long height, long bytes_per_pixel){
493   png_structp png_ptr = NULL;
494   png_infop   info_ptr = NULL;
495   int i;
496   png_bytep *row_pointers;
497   int rowstride = width * bytes_per_pixel;
498   png_text text[2];
499   
500   if (fp == NULL)
501     return (1);
502
503   png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING,NULL,NULL,NULL);
504   if (png_ptr == NULL)
505    {
506       return (1);
507    }
508    row_pointers = (png_bytepp)png_malloc(png_ptr,
509                                      height*sizeof(png_bytep));
510
511   info_ptr = png_create_info_struct(png_ptr);
512
513   if (info_ptr == NULL)
514     {
515       png_destroy_write_struct(&png_ptr,  (png_infopp)NULL);
516       return (1);
517     }
518
519   if (setjmp(png_jmpbuf(png_ptr)))
520     {
521       /* If we get here, we had a problem writing the file */
522       png_destroy_write_struct(&png_ptr, &info_ptr);
523       return (1);
524     }
525
526   png_init_io(png_ptr, fp);
527   png_set_IHDR (png_ptr, info_ptr,width, height,
528                 8, PNG_COLOR_TYPE_RGB,
529                 PNG_INTERLACE_NONE,
530                 PNG_COMPRESSION_TYPE_DEFAULT,
531                 PNG_FILTER_TYPE_DEFAULT);
532
533   text[0].key = "Software";
534   text[0].text = "RRDtool, Tobias Oetiker <tobi@oetike.ch>, http://tobi.oetiker.ch";
535   text[0].compression = PNG_TEXT_COMPRESSION_NONE;
536   png_set_text (png_ptr, info_ptr, text, 1);
537
538   /* Write header data */
539   png_write_info (png_ptr, info_ptr);
540
541   for (i = 0; i < height; i++)
542     row_pointers[i] = (png_bytep) (buffer + i*rowstride);
543
544   png_write_image(png_ptr, row_pointers);
545   png_write_end(png_ptr, info_ptr);
546   png_destroy_write_struct(&png_ptr, &info_ptr);
547   return 1;
548 }
549
550  
551 /* ------- SVG -------
552    SVG reference:
553    http://www.w3.org/TR/SVG/
554 */
555 static int svg_indent = 0;
556 static int svg_single_line = 0;
557 static const char *svg_default_font = "Helvetica";
558
559 static void svg_print_indent(FILE *fp)
560 {
561   int i;
562    for (i = svg_indent - svg_single_line; i > 0; i--) {
563      putc(' ', fp);
564      putc(' ', fp);
565    }
566 }
567  
568 static void svg_start_tag(FILE *fp, const char *name)
569 {
570    svg_print_indent(fp);
571    putc('<', fp);
572    fputs(name, fp);
573    svg_indent++;
574 }
575  
576 static void svg_close_tag_single_line(FILE *fp)
577 {
578    svg_single_line++;
579    putc('>', fp);
580 }
581  
582 static void svg_close_tag(FILE *fp)
583 {
584    putc('>', fp);
585    if (!svg_single_line)
586      putc('\n', fp);
587 }
588  
589 static void svg_end_tag(FILE *fp, const char *name)
590 {
591    /* name is NULL if closing empty-node tag */
592    svg_indent--;
593    if (svg_single_line)
594      svg_single_line--;
595    else if (name)
596      svg_print_indent(fp);
597    if (name != NULL) {
598      fputs("</", fp);
599      fputs(name, fp);
600    } else {
601      putc('/', fp);
602    }
603    svg_close_tag(fp);
604 }
605  
606 static void svg_close_tag_empty_node(FILE *fp)
607 {
608    svg_end_tag(fp, NULL);
609 }
610  
611 static void svg_write_text(FILE *fp, const char *text)
612 {
613    const unsigned char *p, *start, *last;
614    unsigned int ch;
615    p = (const unsigned char*)text;
616    if (!p)
617      return;
618    /* trim leading spaces */
619    while (*p == ' ')
620      p++;
621    start = p;
622    /* trim trailing spaces */
623    last = p - 1;
624    while ((ch = *p) != 0) {
625      if (ch != ' ')
626        last = p;
627      p++;
628   }
629   /* encode trimmed text */
630   p = start;
631   while (p <= last) {
632     ch = *p++;
633     ch = afm_host2unicode(ch); /* unsafe macro */
634     switch (ch) {
635     case '&': fputs("&amp;", fp); break;
636     case '<': fputs("&lt;", fp); break;
637     case '>': fputs("&gt;", fp); break;
638     case '"': fputs("&quot;", fp); break;
639     default:
640       if (ch >= 127)
641         fprintf(fp, "&#%d;", ch);
642       else
643         putc(ch, fp);
644      }
645    }
646 }
647  
648 static void svg_write_number(FILE *fp, double d)
649 {
650    /* omit decimals if integer to reduce filesize */
651    char buf[60], *p;
652    snprintf(buf, sizeof(buf), "%.2f", d);
653    p = buf; /* doesn't trust snprintf return value */
654    while (*p)
655      p++;
656    while (--p > buf) {
657      char ch = *p;
658      if (ch == '0') {
659        *p = '\0'; /* zap trailing zeros */
660        continue;
661      }
662      if (ch == '.')
663        *p = '\0'; /* zap trailing dot */
664      break;
665    }
666    fputs(buf, fp);
667 }
668  
669 static int svg_color_is_black(int c)
670 {
671   /* gfx_color_t is RRGGBBAA */
672   return c == 0x000000FF;
673 }
674  
675 static void svg_write_color(FILE *fp, gfx_color_t c, const char *attr)
676 {
677   /* gfx_color_t is RRGGBBAA, svg can use #RRGGBB and #RGB like html */
678   gfx_color_t rrggbb = (int)((c >> 8) & 0xFFFFFF);
679   gfx_color_t opacity = c & 0xFF;
680   fprintf(fp, " %s=\"", attr);
681   if ((rrggbb & 0x0F0F0F) == ((rrggbb >> 4) & 0x0F0F0F)) {
682      /* css2 short form, #rgb is #rrggbb, not #r0g0b0 */
683     fprintf(fp, "#%03lX",
684           ( ((rrggbb >> 8) & 0xF00)
685           | ((rrggbb >> 4) & 0x0F0)
686           | ( rrggbb       & 0x00F)));
687    } else {
688     fprintf(fp, "#%06lX", rrggbb);
689    }
690   fputs("\"", fp);
691   if (opacity != 0xFF) {
692     fprintf(fp, " stroke-opacity=\"");
693     svg_write_number(fp, opacity / 255.0);
694     fputs("\"", fp);
695  }
696 }
697  
698 static void svg_common_path_attributes(FILE *fp, gfx_node_t *node)
699 {
700   fputs(" stroke-width=\"", fp);
701   svg_write_number(fp, node->size);
702   fputs("\"", fp);
703   svg_write_color(fp, node->color, "stroke");
704   fputs(" fill=\"none\"", fp);
705   if (node->dash_on > 0 && node->dash_off > 0) {
706     fputs(" stroke-dasharray=\"", fp);
707     svg_write_number(fp, node->dash_on);
708     fputs(",", fp);
709     svg_write_number(fp, node->dash_off);
710     fputs("\"", fp);
711   }
712 }
713
714 static int svg_is_int_step(double a, double b)
715 {
716    double diff = fabs(a - b);
717    return floor(diff) == diff;
718 }
719  
720 static int svg_path_straight_segment(FILE *fp,
721      double lastA, double currentA, double currentB,
722      gfx_node_t *node,
723      int segment_idx, int isx, char absChar, char relChar)
724 {
725    if (!svg_is_int_step(lastA, currentA)) {
726      putc(absChar, fp);
727      svg_write_number(fp, currentA);
728      return 0;
729    }
730    if (segment_idx < node->points - 1) {
731      ArtVpath *vec = node->path + segment_idx + 1;
732      if (vec->code == ART_LINETO) {
733        double nextA = (isx ? vec->x : vec->y) - LINEOFFSET;
734        double nextB = (isx ? vec->y : vec->x) - LINEOFFSET;
735        if (nextB == currentB
736            && ((currentA >= lastA) == (nextA >= currentA))
737            && svg_is_int_step(currentA, nextA)) {
738          return 1; /* skip to next as it is a straight line  */
739        }
740      }
741    }
742    putc(relChar, fp);
743    svg_write_number(fp, currentA - lastA);
744    return 0;
745 }
746  
747 static void svg_path(FILE *fp, gfx_node_t *node, int multi)
748 {
749    int i;
750    double lastX = 0, lastY = 0;
751    /* for straight lines <path..> tags take less space than
752       <line..> tags because of the efficient packing
753       in the 'd' attribute */
754    svg_start_tag(fp, "path");
755   if (!multi)
756     svg_common_path_attributes(fp, node);
757    fputs(" d=\"", fp);
758    /* specification of the 'd' attribute: */
759    /* http://www.w3.org/TR/SVG/paths.html#PathDataGeneralInformation */
760    for (i = 0; i < node->points; i++) {
761      ArtVpath *vec = node->path + i;
762      double x = vec->x - LINEOFFSET;
763      double y = vec->y - LINEOFFSET;
764      switch (vec->code) {
765      case ART_MOVETO_OPEN: /* fall-through */
766      case ART_MOVETO:
767        putc('M', fp);
768        svg_write_number(fp, x);
769        putc(',', fp);
770        svg_write_number(fp, y);
771        break;
772      case ART_LINETO:
773        /* try optimize filesize by using minimal lineto commands */
774        /* without introducing rounding errors. */
775        if (x == lastX) {
776          if (svg_path_straight_segment(fp, lastY, y, x, node, i, 0, 'V', 'v'))
777            continue;
778        } else if (y == lastY) {
779          if (svg_path_straight_segment(fp, lastX, x, y, node, i, 1, 'H', 'h'))
780            continue;
781        } else {
782          putc('L', fp);
783          svg_write_number(fp, x);
784          putc(',', fp);
785          svg_write_number(fp, y);
786        }
787        break;
788      case ART_CURVETO: break; /* unsupported */
789      case ART_END: break; /* nop */
790      }
791      lastX = x;
792      lastY = y;
793    }
794   if (node->closed_path)
795     fputs(" Z", fp);
796    fputs("\"", fp);
797    svg_close_tag_empty_node(fp);
798 }
799  
800 static void svg_multi_path(FILE *fp, gfx_node_t **nodeR)
801 {
802    /* optimize for multiple paths with the same color, penwidth, etc. */
803    int num = 1;
804    gfx_node_t *node = *nodeR;
805    gfx_node_t *next = node->next;
806    while (next) {
807      if (next->type != node->type
808          || next->size != node->size
809         || next->color != node->color
810         || next->dash_on != node->dash_on
811         || next->dash_off != node->dash_off)
812        break;
813      next = next->next;
814      num++;
815    }
816    if (num == 1) {
817      svg_path(fp, node, 0);
818      return;
819    }
820    svg_start_tag(fp, "g");
821   svg_common_path_attributes(fp, node);
822    svg_close_tag(fp);
823    while (num && node) {
824      svg_path(fp, node, 1);
825      if (!--num)
826        break;
827      node = node->next;
828      *nodeR = node;
829    }
830    svg_end_tag(fp, "g");
831 }
832  
833 static void svg_area(FILE *fp, gfx_node_t *node)
834 {
835    int i;
836    double startX = 0, startY = 0;
837    svg_start_tag(fp, "polygon");
838   fputs(" ", fp);
839   svg_write_color(fp, node->color, "fill");
840   fputs(" points=\"", fp);
841    for (i = 0; i < node->points; i++) {
842      ArtVpath *vec = node->path + i;
843      double x = vec->x - LINEOFFSET;
844      double y = vec->y - LINEOFFSET;
845      switch (vec->code) {
846        case ART_MOVETO_OPEN: /* fall-through */
847        case ART_MOVETO:
848          svg_write_number(fp, x);
849          putc(',', fp);
850          svg_write_number(fp, y);
851          startX = x;
852          startY = y;
853          break;
854        case ART_LINETO:
855          if (i == node->points - 2
856                         && node->path[i + 1].code == ART_END
857              && fabs(x - startX) < 0.001 && fabs(y - startY) < 0.001) {
858            break; /* poly area always closed, no need for last point */
859          }
860          putc(' ', fp);
861          svg_write_number(fp, x);
862          putc(',', fp);
863          svg_write_number(fp, y);
864          break;
865        case ART_CURVETO: break; /* unsupported */
866        case ART_END: break; /* nop */
867      }
868    }
869    fputs("\"", fp);
870    svg_close_tag_empty_node(fp);
871 }
872  
873 static void svg_text(FILE *fp, gfx_node_t *node)
874 {
875    double x = node->x - LINEOFFSET;
876    double y = node->y - LINEOFFSET;
877    if (node->angle != 0) {
878      svg_start_tag(fp, "g");
879      fputs(" transform=\"translate(", fp);
880      svg_write_number(fp, x);
881      fputs(",", fp);
882      svg_write_number(fp, y);
883      fputs(") rotate(", fp);
884      svg_write_number(fp, node->angle);
885      fputs(")\"", fp);
886      x = y = 0;
887      svg_close_tag(fp);
888    }
889    switch (node->valign) {
890    case GFX_V_TOP:  y += node->size; break;
891    case GFX_V_CENTER: y += node->size / 2; break;
892    case GFX_V_BOTTOM: break;
893    case GFX_V_NULL: break;
894    }
895    svg_start_tag(fp, "text");
896    fputs(" x=\"", fp);
897    svg_write_number(fp, x);
898    fputs("\" y=\"", fp);
899    svg_write_number(fp, y);
900   if (strcmp(node->filename, svg_default_font))
901     fprintf(fp, " font-family=\"%s\"", node->filename);
902    fputs("\" font-size=\"", fp);
903    svg_write_number(fp, node->size);
904    fputs("\"", fp);
905   if (!svg_color_is_black(node->color))
906     svg_write_color(fp, node->color, "fill");
907    switch (node->halign) {
908    case GFX_H_RIGHT:  fputs(" text-anchor=\"end\"", fp); break;
909    case GFX_H_CENTER: fputs(" text-anchor=\"middle\"", fp); break;
910    case GFX_H_LEFT: break;
911    case GFX_H_NULL: break;
912    }
913    svg_close_tag_single_line(fp);
914    /* support for node->tabwidth missing */
915    svg_write_text(fp, node->text);
916    svg_end_tag(fp, "text");
917    if (node->angle != 0)
918      svg_end_tag(fp, "g");
919 }
920  
921 int       gfx_render_svg (gfx_canvas_t *canvas,
922                  art_u32 width, art_u32 height,
923                  gfx_color_t background, FILE *fp){
924    gfx_node_t *node = canvas->firstnode;
925    fputs(
926 "<?xml version=\"1.0\" standalone=\"no\"?>\n"
927 "<!DOCTYPE svg PUBLIC \"-//W3C//DTD SVG 1.0//EN\"\n"
928 "   \"http://www.w3.org/TR/2001/REC-SVG-20010904/DTD/svg10.dtd\">\n"
929 "<!--\n"
930 "   SVG file created by RRDtool,\n"
931 "   Tobias Oetiker <tobi@oetike.ch>, http://tobi.oetiker.ch\n"
932 "\n"
933 "   The width/height attributes in the outhermost svg node\n"
934 "   are just default sizes for the browser which is used\n"
935 "   if the svg file is openened directly without being\n"
936 "   embedded in an html file.\n"
937 "   The viewBox is the local coord system for rrdtool.\n"
938 "-->\n", fp);
939    svg_start_tag(fp, "svg");
940    fputs(" width=\"", fp);
941   svg_write_number(fp, width * canvas->zoom);
942    fputs("\" height=\"", fp);
943   svg_write_number(fp, height * canvas->zoom);
944    fputs("\" x=\"0\" y=\"0\" viewBox=\"", fp);
945    svg_write_number(fp, -LINEOFFSET);
946    fputs(" ", fp);
947    svg_write_number(fp, -LINEOFFSET);
948    fputs(" ", fp);
949    svg_write_number(fp, width - LINEOFFSET);
950    fputs(" ", fp);
951    svg_write_number(fp, height - LINEOFFSET);
952    fputs("\" preserveAspectRatio=\"xMidYMid\"", fp);
953   fprintf(fp, " font-family=\"%s\"", svg_default_font); /* default font */
954   fputs(" stroke-linecap=\"round\" stroke-linejoin=\"round\"", fp);
955    svg_close_tag(fp);
956    svg_start_tag(fp, "rect");
957    fprintf(fp, " x=\"0\" y=\"0\" width=\"%d\" height=\"%d\"", width, height);
958   svg_write_color(fp, background, "fill");
959    svg_close_tag_empty_node(fp);
960    while (node) {
961      switch (node->type) {
962      case GFX_LINE:
963        svg_multi_path(fp, &node);
964        break;
965      case GFX_AREA:
966        svg_area(fp, node);
967        break;
968      case GFX_TEXT:
969        svg_text(fp, node);
970      }
971      node = node->next;
972    }
973    svg_end_tag(fp, "svg");
974    return 0;
975 }
976
977 /* ------- EPS -------
978    EPS and Postscript references:
979    http://partners.adobe.com/asn/developer/technotes/postscript.html
980 */
981
982 typedef struct eps_font
983 {
984   const char *ps_font;
985   int id;
986   struct eps_font *next;
987 } eps_font;
988
989 typedef struct eps_state
990 {
991   FILE *fp;
992   gfx_canvas_t *canvas;
993   art_u32 page_width, page_height;
994   eps_font *font_list;
995   /*--*/
996   gfx_color_t color;
997   const char *font;
998   double font_size;
999   double line_width;
1000   int linecap, linejoin;
1001 } eps_state;
1002
1003 static void eps_set_color(eps_state *state, gfx_color_t color)
1004 {
1005    /* gfx_color_t is RRGGBBAA */
1006   if (state->color == color)
1007     return;
1008   fprintf(state->fp, "%d %d %d Rgb\n",
1009       (int)((color >> 24) & 255),
1010       (int)((color >> 16) & 255),
1011       (int)((color >>  8) & 255));
1012   state->color = color;
1013 }
1014
1015 static int eps_add_font(eps_state *state, gfx_node_t *node)
1016 {
1017   /* The fonts list could be postponed to the end using
1018      (atend), but let's be nice and have them in the header. */
1019   const char *ps_font = afm_get_font_postscript_name(node->filename);
1020   eps_font *ef;
1021   for (ef = state->font_list; ef; ef = ef->next) {
1022     if (!strcmp(ps_font, ef->ps_font))
1023       return 0;
1024   }
1025   ef = malloc(sizeof(eps_font));
1026   if (ef == NULL) {
1027     rrd_set_error("malloc for eps_font");
1028     return -1;
1029   }
1030   ef->next = state->font_list;
1031   ef->ps_font = ps_font;
1032   state->font_list = ef;
1033   return 0;
1034 }
1035
1036 static void eps_list_fonts(eps_state *state, const char *dscName)
1037 {
1038   eps_font *ef;
1039   int lineLen = strlen(dscName);
1040   if (!state->font_list)
1041     return;
1042   fputs(dscName, state->fp);
1043   for (ef = state->font_list; ef; ef = ef->next) {
1044     int nameLen = strlen(ef->ps_font);
1045     if (lineLen + nameLen > 100 && lineLen) {
1046       fputs("\n", state->fp);
1047       fputs("%%- \n", state->fp);
1048       lineLen = 5;
1049     } else {
1050       fputs(" ", state->fp);
1051       lineLen++;
1052     }
1053     fputs(ef->ps_font, state->fp);
1054     lineLen += nameLen;
1055   }
1056   fputs("\n", state->fp);
1057 }
1058
1059 static void eps_define_fonts(eps_state *state)
1060 {
1061   eps_font *ef;
1062   if (!state->font_list)
1063     return;
1064   for (ef = state->font_list; ef; ef = ef->next) {
1065     /* PostScript¨ LANGUAGE REFERENCE third edition
1066        page 349 */
1067     fprintf(state->fp,
1068         "%%\n"
1069         "/%s findfont dup length dict begin\n"
1070         "{ 1 index /FID ne {def} {pop pop} ifelse } forall\n"
1071         "/Encoding ISOLatin1Encoding def\n"
1072         "currentdict end\n"
1073         "/%s-ISOLatin1 exch definefont pop\n"
1074         "/SetFont-%s { /%s-ISOLatin1 findfont exch scalefont setfont } bd\n",
1075         ef->ps_font, ef->ps_font, ef->ps_font, ef->ps_font);
1076   }
1077 }
1078
1079 static int eps_prologue(eps_state *state)
1080 {
1081   gfx_node_t *node;
1082   fputs(
1083     "%!PS-Adobe-3.0 EPSF-3.0\n"
1084     "%%Creator: RRDtool 1.1.x, Tobias Oetiker, http://tobi.oetiker.ch\n"
1085     /* can't like weird chars here */
1086     "%%Title: (RRDTool output)\n"
1087     "%%DocumentData: Clean7Bit\n"
1088     "", state->fp);
1089   fprintf(state->fp, "%%%%BoundingBox: 0 0 %d %d\n",
1090     state->page_width, state->page_height);
1091   for (node = state->canvas->firstnode; node; node = node->next) {
1092     if (node->type == GFX_TEXT && eps_add_font(state, node) == -1)
1093       return -1;
1094   }
1095   eps_list_fonts(state, "%%DocumentFonts:");
1096   eps_list_fonts(state, "%%DocumentNeededFonts:");
1097   fputs(
1098       "%%EndComments\n"
1099       "%%BeginProlog\n"
1100       "%%EndProlog\n" /* must have, or BoundingBox is ignored */
1101       "/bd { bind def } bind def\n"
1102       "", state->fp);
1103   fprintf(state->fp, "/X { %.2f add } bd\n", LINEOFFSET);
1104   fputs(
1105       "/X2 {X exch X exch} bd\n"
1106       "/M {X2 moveto} bd\n"
1107       "/L {X2 lineto} bd\n"
1108       "/m {moveto} bd\n"
1109       "/l {lineto} bd\n"
1110       "/S {stroke} bd\n"
1111       "/CP {closepath} bd\n"
1112       "/WS {setlinewidth stroke} bd\n"
1113       "/F {fill} bd\n"
1114       "/TaL { } bd\n"
1115       "/TaC {dup stringwidth pop neg 2 div 0 rmoveto } bd\n"
1116       "/TaR {dup stringwidth pop neg 0 rmoveto } bd\n"
1117       "/TL {moveto TaL show} bd\n"
1118       "/TC {moveto TaC show} bd\n"
1119       "/TR {moveto TaR show} bd\n"
1120       "/Rgb { 255.0 div 3 1 roll\n"
1121       "       255.0 div 3 1 roll \n"
1122       "       255.0 div 3 1 roll setrgbcolor } bd\n"
1123       "", state->fp);
1124   eps_define_fonts(state);
1125   return 0;
1126 }
1127
1128 static void eps_write_linearea(eps_state *state, gfx_node_t *node)
1129 {
1130   int i;
1131   FILE *fp = state->fp;
1132   int useOffset = 0;
1133   eps_set_color(state, node->color);
1134   if (node->type == GFX_LINE) {
1135     if (state->linecap != 1) {
1136       fputs("1 setlinecap\n", fp);
1137       state->linecap = 1;
1138     }
1139     if (state->linejoin != 1) {
1140       fputs("1 setlinejoin\n", fp);
1141       state->linejoin = 1;
1142     }
1143   }
1144   for (i = 0; i < node->points; i++) {
1145     ArtVpath *vec = node->path + i;
1146     double x = vec->x;
1147     double y = state->page_height - vec->y;
1148     if (vec->code == ART_MOVETO_OPEN || vec->code == ART_MOVETO)
1149       useOffset = (fabs(x - floor(x) - 0.5) < 0.01 && fabs(y - floor(y) - 0.5) < 0.01);
1150     if (useOffset) {
1151       x -= LINEOFFSET;
1152       y -= LINEOFFSET;
1153     }
1154     switch (vec->code) {
1155     case ART_MOVETO_OPEN: /* fall-through */
1156     case ART_MOVETO:
1157       svg_write_number(fp, x);
1158       fputc(' ', fp);
1159       svg_write_number(fp, y);
1160       fputc(' ', fp);
1161       fputs(useOffset ? "M\n" : "m\n", fp);
1162       break;
1163     case ART_LINETO:
1164       svg_write_number(fp, x);
1165       fputc(' ', fp);
1166       svg_write_number(fp, y);
1167       fputc(' ', fp);
1168       fputs(useOffset ? "L\n" : "l\n", fp);
1169       break;
1170     case ART_CURVETO: break; /* unsupported */
1171     case ART_END: break; /* nop */
1172     }
1173   }
1174   if (node->type == GFX_LINE) {
1175     if (node->closed_path)
1176       fputs("CP ", fp);
1177     if (node->size != state->line_width) {
1178       state->line_width = node->size;
1179       svg_write_number(fp, state->line_width);
1180       fputs(" WS\n", fp);
1181     } else {
1182       fputs("S\n", fp);
1183     }
1184    } else {
1185     fputs("F\n", fp);
1186    }
1187 }
1188
1189 static void eps_write_text(eps_state *state, gfx_node_t *node)
1190 {
1191   FILE *fp = state->fp;
1192   const unsigned char *p;
1193   const char *ps_font = afm_get_font_postscript_name(node->filename);
1194   char align = 'L';
1195   double x = node->x;
1196   double y = state->page_height - node->y, ydelta = 0;
1197   int lineLen = 0;
1198   eps_set_color(state, node->color);
1199   if (strcmp(ps_font, state->font) || node->size != state->font_size) {
1200     state->font = ps_font;
1201     state->font_size = node->size;
1202     svg_write_number(fp, state->font_size);
1203     fprintf(fp, " SetFont-%s\n", state->font);
1204   }
1205   fputs("(", fp);
1206   lineLen = 20;
1207   for (p = (const unsigned char*)node->text; *p; p++) {
1208     if (lineLen > 70) {
1209       fputs("\\\n", fp); /* backslash and \n */
1210       lineLen = 0;
1211     }
1212     switch (*p) {
1213       case '(':
1214       case ')':
1215       case '\\':
1216       case '\n':
1217       case '\r':
1218       case '\t':
1219         fputc('\\', fp);
1220         lineLen++;
1221         /* fall-through */
1222       default:
1223         if (*p >= 126)
1224           fprintf(fp, "\\%03o", *p);
1225         else
1226           fputc(*p, fp);
1227         lineLen++;
1228     }
1229   }
1230   fputs(") ", fp);
1231   switch(node->valign){
1232   case GFX_V_TOP:    ydelta = -node->size; break;
1233   case GFX_V_CENTER: ydelta = -node->size / 3.0; break;          
1234   case GFX_V_BOTTOM: break;          
1235   case GFX_V_NULL: break;          
1236   }
1237   if (node->angle == 0)
1238     y += ydelta;
1239   switch (node->halign) {
1240   case GFX_H_RIGHT:  align = 'R'; break;
1241   case GFX_H_CENTER: align = 'C'; break;
1242   case GFX_H_LEFT: align= 'L'; break;
1243   case GFX_H_NULL: align= 'L'; break;
1244   }
1245   if (node->angle != 0) {
1246     fputs("\n", fp);
1247     fputs("  gsave ", fp);
1248     svg_write_number(fp, x);
1249     fputc(' ', fp);
1250     svg_write_number(fp, y);
1251     fputs(" translate ", fp);
1252     svg_write_number(fp, -node->angle);
1253     fputs(" rotate 0 ", fp);
1254     svg_write_number(fp, ydelta);
1255     fputs(" moveto ", fp);
1256     fprintf(fp, "Ta%c", align);
1257     fputs(" show grestore\n", fp);
1258   } else {
1259     svg_write_number(fp, x);
1260     fputc(' ', fp);
1261     svg_write_number(fp, y);
1262     fputs(" T", fp);
1263     fputc(align, fp);
1264     fputc('\n', fp);
1265   }
1266 }
1267
1268 static int eps_write_content(eps_state *state)
1269 {
1270   gfx_node_t *node;
1271   fputs("%\n", state->fp);
1272   for (node = state->canvas->firstnode; node; node = node->next) {
1273     switch (node->type) {
1274     case GFX_LINE:
1275     case GFX_AREA:
1276       eps_write_linearea(state, node);
1277       break;
1278     case GFX_TEXT:
1279       eps_write_text(state, node);
1280       break;
1281     }
1282   }
1283   return 0;
1284 }
1285
1286 int       gfx_render_eps (gfx_canvas_t *canvas,
1287                  art_u32 width, art_u32 height,
1288                  gfx_color_t background, FILE *fp){
1289   struct eps_state state;
1290   state.fp = fp;
1291   state.canvas = canvas;
1292   state.page_width = width;
1293   state.page_height = height;
1294   state.font = "no-default-font";
1295   state.font_size = -1;
1296   state.color = 0; /* black */
1297   state.font_list = NULL;
1298   state.linecap = -1;
1299   state.linejoin = -1;
1300   if (eps_prologue(&state) == -1)
1301     return -1;
1302   eps_set_color(&state, background);
1303   fprintf(fp, "0 0 M 0 %d L %d %d L %d 0 L fill\n",
1304       height, width, height, width);
1305   if (eps_write_content(&state) == -1)
1306     return 0;
1307   fputs("showpage\n", fp);
1308   fputs("%%EOF\n", fp);
1309   while (state.font_list) {
1310     eps_font *next = state.font_list->next;
1311     free(state.font_list);
1312     state.font_list = next;
1313   }
1314   return 0;
1315 }