silence warnings for UNUSED variables without changeing the funtion interfaces -...
[rrdtool.git] / src / rrd_gfx.c
1 /****************************************************************************
2  * RRDtool 1.2.4  Copyright by Tobi Oetiker, 1997-2005
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 #include FT_GLYPH_H
19
20 #include "rrd_gfx.h"
21 #include "rrd_afm.h"
22 #include "unused.h"
23
24 /* lines are better drawn on the pixle than between pixles */
25 #define LINEOFFSET 0.5
26
27 #define USE_PDF_FAKE_ALPHA 1
28 #define USE_EPS_FAKE_ALPHA 1
29
30 typedef struct gfx_char_s *gfx_char;
31 struct gfx_char_s {
32   FT_UInt     index;    /* glyph index */
33   FT_Vector   pos;      /* location from baseline in 26.6 */
34   FT_Glyph    image;    /* glyph bitmap */
35 };
36
37 typedef struct gfx_string_s *gfx_string;
38 struct gfx_string_s {
39   unsigned int    width;
40   unsigned int    height;
41   size_t          count;  /* number of characters */
42   gfx_char        glyphs;
43   size_t          num_glyphs;
44   FT_BBox         bbox;
45   FT_Matrix       transform;
46 };
47
48 /* compute string bbox */
49 static void compute_string_bbox(gfx_string string);
50
51 /* create a freetype glyph string */
52 gfx_string gfx_string_create ( gfx_canvas_t *canvas, FT_Face face,
53                                const char *text, int rotation, double tabwidth, double size);
54
55 /* create a freetype glyph string */
56 static void gfx_string_destroy ( gfx_string string );
57
58 static
59 gfx_node_t *gfx_new_node( gfx_canvas_t *canvas,enum gfx_en type){
60   gfx_node_t *node = art_new(gfx_node_t,1);
61   if (node == NULL) return NULL;
62   node->type = type;
63   node->color = 0x0;        /* color of element  0xRRGGBBAA  alpha 0xff is solid*/
64   node->size =0.0;         /* font size, line width */
65   node->path = NULL;        /* path */
66   node->points = 0;
67   node->points_max =0;
68   node->closed_path = 0;
69   node->filename = NULL;             /* font or image filename */
70   node->text = NULL;
71   node->x = 0.0;
72   node->y = 0.0;          /* position */
73   node->angle = 0;  
74   node->halign = GFX_H_NULL; /* text alignement */
75   node->valign = GFX_V_NULL; /* text alignement */
76   node->tabwidth = 0.0; 
77   node->next = NULL; 
78   if (canvas->lastnode != NULL){
79       canvas->lastnode->next = node;
80   }
81   if (canvas->firstnode == NULL){
82       canvas->firstnode = node;
83   }  
84   canvas->lastnode = node;
85   return node;
86 }
87
88 gfx_canvas_t *gfx_new_canvas (void) {
89     gfx_canvas_t *canvas = art_new(gfx_canvas_t,1);
90     canvas->firstnode = NULL;
91     canvas->lastnode = NULL;
92     canvas->imgformat = IF_PNG; /* we default to PNG output */
93     canvas->interlaced = 0;
94     canvas->zoom = 1.0;
95     canvas->font_aa_threshold = -1.0;
96     canvas->aa_type = AA_NORMAL;
97     return canvas;
98 }
99
100 /* create a new line */
101 gfx_node_t  *gfx_new_line(gfx_canvas_t *canvas, 
102                            double X0, double Y0, 
103                            double X1, double Y1,
104                            double width, gfx_color_t color){
105   return gfx_new_dashed_line(canvas, X0, Y0, X1, Y1, width, color, 0, 0);
106 }
107
108 gfx_node_t  *gfx_new_dashed_line(gfx_canvas_t *canvas, 
109                            double X0, double Y0, 
110                            double X1, double Y1,
111                            double width, gfx_color_t color,
112                            double dash_on, double dash_off){
113
114   gfx_node_t *node;
115   ArtVpath *vec;
116   node = gfx_new_node(canvas,GFX_LINE);
117   if (node == NULL) return NULL;
118   vec = art_new(ArtVpath, 3);
119   if (vec == NULL) return NULL;
120   vec[0].code = ART_MOVETO_OPEN; vec[0].x=X0+LINEOFFSET; vec[0].y=Y0+LINEOFFSET;
121   vec[1].code = ART_LINETO; vec[1].x=X1+LINEOFFSET; vec[1].y=Y1+LINEOFFSET;
122   vec[2].code = ART_END; vec[2].x=0;vec[2].y=0;
123   
124   node->points = 3;
125   node->points_max = 3;
126   node->color = color;
127   node->size  = width;
128   node->dash_on = dash_on;
129   node->dash_off = dash_off;
130   node->path  = vec;
131   return node;
132 }
133
134 /* create a new area */
135 gfx_node_t   *gfx_new_area   (gfx_canvas_t *canvas, 
136                               double X0, double Y0,
137                               double X1, double Y1,
138                               double X2, double Y2,
139                               gfx_color_t color) {
140
141   gfx_node_t *node;
142   ArtVpath *vec;
143   node = gfx_new_node(canvas,GFX_AREA);
144   if (node == NULL) return NULL;
145   vec = art_new(ArtVpath, 5);
146   if (vec == NULL) return NULL;
147   vec[0].code = ART_MOVETO; vec[0].x=X0; vec[0].y=Y0;
148   vec[1].code = ART_LINETO; vec[1].x=X1; vec[1].y=Y1;
149   vec[2].code = ART_LINETO; vec[2].x=X2; vec[2].y=Y2;
150   vec[3].code = ART_LINETO; vec[3].x=X0; vec[3].y=Y0;
151   vec[4].code = ART_END; vec[4].x=0; vec[4].y=0;
152   
153   node->points = 5;
154   node->points_max = 5;
155   node->color = color;
156   node->path  = vec;
157
158   return node;
159 }
160
161 /* add a point to a line or to an area */
162 int           gfx_add_point  (gfx_node_t *node, 
163                               double x, double y){
164   if (node == NULL) return 1;
165   if (node->type == GFX_AREA) {
166     double X0 = node->path[0].x;
167     double Y0 = node->path[0].y;
168     node->points -= 2;
169     art_vpath_add_point (&(node->path),
170                          &(node->points),
171                          &(node->points_max),
172                          ART_LINETO,
173                          x,y);
174     art_vpath_add_point (&(node->path),
175                          &(node->points),
176                          &(node->points_max),
177                          ART_LINETO,
178                          X0,Y0);
179     art_vpath_add_point (&(node->path),
180                          &(node->points),
181                          &(node->points_max),
182                          ART_END,
183                          0,0);
184   } else if (node->type == GFX_LINE) {
185     node->points -= 1;
186     art_vpath_add_point (&(node->path),
187                          &(node->points),
188                          &(node->points_max),
189                          ART_LINETO,
190                          x+LINEOFFSET,y+LINEOFFSET);
191     art_vpath_add_point (&(node->path),
192                          &(node->points),
193                          &(node->points_max),
194                          ART_END,
195                          0,0);
196     
197   } else {
198     /* can only add point to areas and lines */
199     return 1;
200   }
201   return 0;
202 }
203
204 void           gfx_close_path  (gfx_node_t *node) {
205     node->closed_path = 1;
206     if (node->path[0].code == ART_MOVETO_OPEN)
207         node->path[0].code = ART_MOVETO;
208 }
209
210 /* create a text node */
211 gfx_node_t   *gfx_new_text   (gfx_canvas_t *canvas,  
212                               double x, double y, gfx_color_t color,
213                               char* font, double size,                        
214                               double tabwidth, double angle,
215                               enum gfx_h_align_en h_align,
216                               enum gfx_v_align_en v_align,
217                               char* text){
218    gfx_node_t *node = gfx_new_node(canvas,GFX_TEXT);
219    
220    node->text = strdup(text);
221    node->size = size;
222    node->filename = strdup(font);
223    node->x = x;
224    node->y = y;
225    node->angle = angle;   
226    node->color = color;
227    node->tabwidth = tabwidth;
228    node->halign = h_align;
229    node->valign = v_align;
230 #if 0
231   /* debugging: show text anchor
232      green is along x-axis, red is downward y-axis */
233    if (1) {
234      double a = 2 * M_PI * -node->angle / 360.0;
235      double cos_a = cos(a);
236      double sin_a = sin(a);
237      double len = 3;
238      gfx_new_line(canvas,
239          x, y,
240          x + len * cos_a, y - len * sin_a,
241          0.2, 0x00FF0000);
242      gfx_new_line(canvas,
243          x, y,
244          x + len * sin_a, y + len * cos_a,
245          0.2, 0xFF000000);
246    }
247 #endif
248    return node;
249 }
250
251 int           gfx_render(gfx_canvas_t *canvas, 
252                               art_u32 width, art_u32 height, 
253                               gfx_color_t background, FILE *fp){
254   switch (canvas->imgformat) {
255   case IF_PNG: 
256     return gfx_render_png (canvas, width, height, background, fp);
257   case IF_SVG: 
258     return gfx_render_svg (canvas, width, height, background, fp);
259   case IF_EPS:
260     return gfx_render_eps (canvas, width, height, background, fp);
261   case IF_PDF:
262     return gfx_render_pdf (canvas, width, height, background, fp);
263   default:
264     return -1;
265   }
266 }
267
268 static void gfx_string_destroy ( gfx_string string ) {
269   unsigned int n;
270   if (string->glyphs) {
271     for (n=0; n<string->num_glyphs; ++n)
272       FT_Done_Glyph (string->glyphs[n].image);
273     free (string->glyphs);
274   }
275   free (string);
276 }
277
278
279 double gfx_get_text_width ( gfx_canvas_t *canvas,
280                             double start, char* font, double size,
281                             double tabwidth, char* text, int rotation){
282   switch (canvas->imgformat) {
283   case IF_PNG: 
284     return gfx_get_text_width_libart (canvas, start, font, size, tabwidth, text, rotation);
285   case IF_SVG: /* fall through */ 
286   case IF_EPS:
287   case IF_PDF:
288     return afm_get_text_width(start, font, size, tabwidth, text);
289   default:
290     return size * strlen(text);
291   }
292 }
293
294 double gfx_get_text_width_libart (
295                             gfx_canvas_t *canvas, double UNUSED(start), char* font, double size,
296                             double tabwidth, char* text, int rotation ){
297
298   int           error;
299   double        text_width=0;
300   FT_Face       face;
301   FT_Library    library=NULL;  
302   gfx_string    string;
303
304   FT_Init_FreeType( &library );
305   error = FT_New_Face( library, font, 0, &face );
306   if ( error ) return -1;
307   error = FT_Set_Char_Size(face,  size*64,size*64,  100,100);
308   if ( error ) return -1;
309
310   string = gfx_string_create( canvas, face, text, rotation, tabwidth, size );
311   text_width = string->width;
312   gfx_string_destroy(string);
313   FT_Done_FreeType(library);
314   return text_width/64;
315 }
316
317 static void gfx_libart_close_path(gfx_node_t *node, ArtVpath **vec)
318 {
319     /* libart must have end==start for closed paths,
320        even if using ART_MOVETO and not ART_MOVETO_OPEN
321        so add extra point which is the same as the starting point */
322     int points_max = node->points; /* scaled array has exact size */
323     int points = node->points - 1;
324     art_vpath_add_point (vec, &points, &points_max, ART_LINETO,
325             (**vec).x, (**vec).y);
326     art_vpath_add_point (vec, &points, &points_max, ART_END, 0, 0);
327 }
328
329
330 /* find bbox of a string */
331 static void compute_string_bbox(gfx_string string) {
332     unsigned int n;
333     FT_BBox bbox;
334
335     bbox.xMin = bbox.yMin = 32000;
336     bbox.xMax = bbox.yMax = -32000;
337     for ( n = 0; n < string->num_glyphs; n++ ) {
338       FT_BBox glyph_bbox;
339       FT_Glyph_Get_CBox( string->glyphs[n].image, ft_glyph_bbox_gridfit,
340        &glyph_bbox );
341       if (glyph_bbox.xMin < bbox.xMin) {
342          bbox.xMin = glyph_bbox.xMin;
343       }
344       if (glyph_bbox.yMin < bbox.yMin) {
345         bbox.yMin = glyph_bbox.yMin;
346       }
347       if (glyph_bbox.xMax > bbox.xMax) {
348          bbox.xMax = glyph_bbox.xMax;
349       }
350       if (glyph_bbox.yMax > bbox.yMax) {
351          bbox.yMax = glyph_bbox.yMax;
352       }
353     }
354     if ( bbox.xMin > bbox.xMax ) { 
355       bbox.xMin = 0;
356       bbox.yMin = 0;
357       bbox.xMax = 0;
358       bbox.yMax = 0;
359     }
360     string->bbox.xMin = bbox.xMin;
361     string->bbox.xMax = bbox.xMax;
362     string->bbox.yMin = bbox.yMin;
363     string->bbox.yMax = bbox.yMax;
364
365
366 /* create a free type glyph string */
367 gfx_string gfx_string_create(gfx_canvas_t *canvas, FT_Face face,const char *text,
368         int rotation, double tabwidth, double size )
369 {
370
371   FT_GlyphSlot  slot = face->glyph;  /* a small shortcut */
372   FT_Bool       use_kerning;
373   FT_UInt       previous;
374   FT_Vector     ft_pen;
375
376   gfx_string    string;
377   gfx_char      glyph;          /* current glyph in table */
378   unsigned int  n;
379   int           error;
380   int        gottab = 0;    
381   ft_pen.x = 0;   /* start at (0,0) !! */
382   ft_pen.y = 0;
383
384   string = (gfx_string) malloc (sizeof(struct gfx_string_s));
385   string->width = 0;
386   string->height = 0;
387   string->count = strlen (text);
388   string->glyphs = (gfx_char) calloc (string->count,sizeof(struct gfx_char_s));
389   string->num_glyphs = 0;
390   string->transform.xx = (FT_Fixed)( cos(M_PI*(rotation)/180.0)*0x10000);
391   string->transform.xy = (FT_Fixed)(-sin(M_PI*(rotation)/180.0)*0x10000);
392   string->transform.yx = (FT_Fixed)( sin(M_PI*(rotation)/180.0)*0x10000);
393   string->transform.yy = (FT_Fixed)( cos(M_PI*(rotation)/180.0)*0x10000);
394
395   use_kerning = FT_HAS_KERNING(face);
396   previous    = 0;
397   glyph = string->glyphs;
398   for (n=0; n<string->count;glyph++) {
399     FT_Vector   vec;
400     /* handle the tabs ...
401        have a witespace glyph inserted, but set its width such that the distance
402     of the new right edge is x times tabwidth from 0,0 where x is an integer. */    
403     unsigned char letter = text[n];
404           
405     gottab = 0;
406     if (letter == '\\' && n+1 < string->count && text[n+1] == 't'){
407             /* we have a tab here so skip the backslash and
408                set t to ' ' so that we get a white space */
409             gottab = 1;
410             n++;
411             letter  = ' ';            
412     }            
413     if (letter == '\t'){
414         letter = ' ';
415         gottab = 1 ;
416     }            
417     /* initialize each struct gfx_char_s */
418     glyph->index = 0;
419     glyph->pos.x = 0;
420     glyph->pos.y = 0;
421     glyph->image = NULL;
422
423     glyph->index = FT_Get_Char_Index( face, letter );
424
425     /* compute glyph origin */
426     if ( use_kerning && previous && glyph->index ) {
427       FT_Vector kerning;
428       FT_Get_Kerning (face, previous, glyph->index,
429           ft_kerning_default, &kerning);
430       ft_pen.x += kerning.x;
431       ft_pen.y += kerning.y;
432     }
433
434     /* load the glyph image (in its native format) */
435     /* for now, we take a monochrome glyph bitmap */
436     error = FT_Load_Glyph (face, glyph->index, size > canvas->font_aa_threshold ?
437                             canvas->aa_type == AA_NORMAL ? FT_LOAD_TARGET_NORMAL :
438                             canvas->aa_type == AA_LIGHT ? FT_LOAD_TARGET_LIGHT :
439                             FT_LOAD_TARGET_MONO : FT_LOAD_TARGET_MONO);
440     if (error) {
441       fprintf (stderr, "couldn't load glyph:  %c\n", letter);
442       continue;
443     }
444     error = FT_Get_Glyph (slot, &glyph->image);
445     if (error) {
446       fprintf (stderr, "couldn't get glyph from slot:  %c\n", letter);
447       continue;
448     }
449     /* if we are in tabbing mode, we replace the tab with a space and shift the position
450        of the space so that its left edge is where the tab was supposed to land us */
451     if (gottab){
452        /* we are in gridfitting mode so the calculations happen in 1/64 pixles */
453         ft_pen.x = tabwidth*64.0 * (float)(1 + (long)(ft_pen.x / (tabwidth * 64.0))) - slot->advance.x;
454     }
455     /* store current pen position */
456     glyph->pos.x = ft_pen.x;
457     glyph->pos.y = ft_pen.y;
458
459
460     ft_pen.x   += slot->advance.x;    
461     ft_pen.y   += slot->advance.y;
462
463     /* rotate glyph */
464     vec = glyph->pos;
465     FT_Vector_Transform (&vec, &string->transform);
466     error = FT_Glyph_Transform (glyph->image, &string->transform, &vec);
467     if (error) {
468       fprintf (stderr, "couldn't transform glyph\n");
469       continue;
470     }
471
472     /* convert to a bitmap - destroy native image */
473     error = FT_Glyph_To_Bitmap (&glyph->image, size > canvas->font_aa_threshold ?
474                             canvas->aa_type == AA_NORMAL ? FT_RENDER_MODE_NORMAL :
475                             canvas->aa_type == AA_LIGHT ? FT_RENDER_MODE_LIGHT :
476                             FT_RENDER_MODE_MONO : FT_RENDER_MODE_MONO, 0, 1);
477     if (error) {
478       fprintf (stderr, "couldn't convert glyph to bitmap\n");
479       continue;
480     }
481
482     /* increment number of glyphs */
483     previous = glyph->index;
484     string->num_glyphs++;
485     n++;
486     
487   }
488 /*  printf ("number of glyphs = %d\n", string->num_glyphs);*/
489   compute_string_bbox( string );
490   /* the last character was a tab */  
491   /* if (gottab) { */
492       string->width = ft_pen.x;
493   /* } else {
494       string->width = string->bbox.xMax - string->bbox.xMin;
495   } */
496   string->height = string->bbox.yMax - string->bbox.yMin;
497
498   return string;
499 }
500
501
502 static int gfx_save_png (art_u8 *buffer, FILE *fp,
503                      long width, long height, long bytes_per_pixel);
504 /* render grafics into png image */
505
506 int           gfx_render_png (gfx_canvas_t *canvas, 
507                               art_u32 width, art_u32 height, 
508                               gfx_color_t background, FILE *fp){
509     
510     
511     FT_Library    library;
512     gfx_node_t *node = canvas->firstnode;    
513     /*
514     art_u8 red = background >> 24, green = (background >> 16) & 0xff;
515     art_u8 blue = (background >> 8) & 0xff, alpha = ( background & 0xff );
516     */
517     unsigned long pys_width = width * canvas->zoom;
518     unsigned long pys_height = height * canvas->zoom;
519     const int bytes_per_pixel = 4;
520     unsigned long rowstride = pys_width*bytes_per_pixel; /* bytes per pixel */
521     
522     /* fill that buffer with out background color */
523     gfx_color_t *buffp = art_new (gfx_color_t, pys_width*pys_height);
524     art_u8 *buffer = (art_u8 *)buffp;
525     unsigned long i;
526     for (i=0;i<pys_width*pys_height;
527          i++){
528         *(buffp++)=background;
529     }
530     FT_Init_FreeType( &library );
531     while(node){
532         switch (node->type) {
533         case GFX_LINE:
534         case GFX_AREA: {   
535             ArtVpath *vec;
536             double dst[6];     
537             ArtSVP *svp;
538             art_affine_scale(dst,canvas->zoom,canvas->zoom);
539             vec = art_vpath_affine_transform(node->path,dst);
540             if (node->closed_path)
541                 gfx_libart_close_path(node, &vec);
542             /* gfx_round_scaled_coordinates(vec); */
543             /* pvec = art_vpath_perturb(vec);
544                art_free(vec); */
545             if(node->type == GFX_LINE){
546                 svp = art_svp_vpath_stroke ( vec, ART_PATH_STROKE_JOIN_ROUND,
547                                              ART_PATH_STROKE_CAP_ROUND,
548                                              node->size*canvas->zoom,4,0.25);
549             } else {
550                 svp  = art_svp_from_vpath ( vec );
551                 /* this takes time and is unnecessary since we make
552                    sure elsewhere that the areas are going clock-whise */
553                 /*  svpt = art_svp_uncross( svp );
554                     art_svp_free(svp);
555                     svp  = art_svp_rewind_uncrossed(svpt,ART_WIND_RULE_NONZERO); 
556                     art_svp_free(svpt);
557                  */
558             }
559             art_free(vec);
560             /* this is from gnome since libart does not have this yet */
561             gnome_print_art_rgba_svp_alpha (svp ,0,0, pys_width, pys_height,
562                                 node->color, buffer, rowstride, NULL);
563             art_svp_free(svp);
564             break;
565         }
566         case GFX_TEXT: {
567             unsigned int  n;
568             int  error;
569             art_u8 fcolor[4],falpha;
570             FT_Face       face;
571             gfx_char      glyph;
572             gfx_string    string;
573             FT_Vector     vec;  /* 26.6 */
574
575             float pen_x = 0.0 , pen_y = 0.0;
576             /* double x,y; */
577             long   ix,iy;
578             
579             fcolor[0] = node->color >> 24;
580             fcolor[1] = (node->color >> 16) & 0xff;
581             fcolor[2] = (node->color >> 8) & 0xff;
582             falpha = node->color & 0xff;
583             error = FT_New_Face( library,
584                                  (char *)node->filename,
585                                  0,
586                                  &face );
587             if ( error ) {
588                 rrd_set_error("failed to load %s",node->filename);
589                 break;
590             }
591             error = FT_Set_Char_Size(face,   /* handle to face object            */
592                                      (long)(node->size*64),
593                                      (long)(node->size*64),
594                                      (long)(100*canvas->zoom),
595                                      (long)(100*canvas->zoom));
596             if ( error ) break;
597             pen_x = node->x * canvas->zoom;
598             pen_y = node->y * canvas->zoom;
599
600             string = gfx_string_create (canvas, face, node->text, node->angle, node->tabwidth, node->size);
601             switch(node->halign){
602             case GFX_H_RIGHT:  vec.x = -string->bbox.xMax;
603                                break;          
604             case GFX_H_CENTER: vec.x = abs(string->bbox.xMax) >= abs(string->bbox.xMin) ?
605                                        -string->bbox.xMax/2:-string->bbox.xMin/2;
606                                break;          
607             case GFX_H_LEFT:   vec.x = -string->bbox.xMin;
608                                break;
609             case GFX_H_NULL:   vec.x = 0;
610                                break;          
611             }
612
613             switch(node->valign){
614             case GFX_V_TOP:    vec.y = string->bbox.yMax;
615                                break;
616             case GFX_V_CENTER: vec.y = abs(string->bbox.yMax) >= abs(string->bbox.yMin) ?
617                                        string->bbox.yMax/2:string->bbox.yMin/2;
618                                break;
619             case GFX_V_BOTTOM: vec.y = 0;
620                                break;
621             case GFX_V_NULL:   vec.y = 0;
622                                break;
623             }
624             pen_x += vec.x/64;
625             pen_y += vec.y/64;
626             glyph = string->glyphs;
627             for(n=0; n<string->num_glyphs; ++n, ++glyph) {
628                 int gr;
629                 FT_Glyph        image;
630                 FT_BitmapGlyph  bit;
631                 /* long buf_x,comp_n; */
632                 /* make copy to transform */
633                 if (! glyph->image) {
634                   fprintf (stderr, "no image\n");
635                   continue;
636                 }
637                 error = FT_Glyph_Copy (glyph->image, &image);
638                 if (error) {
639                   fprintf (stderr, "couldn't copy image\n");
640                   continue;
641                 }
642
643                 /* transform it */
644                 vec = glyph->pos;
645                 FT_Vector_Transform (&vec, &string->transform);
646
647                 bit = (FT_BitmapGlyph) image;
648                 gr = bit->bitmap.num_grays -1;
649 /* 
650                 buf_x = (pen_x + 0.5) + (double)bit->left;
651                 comp_n = buf_x + bit->bitmap.width > pys_width ? pys_width - buf_x : bit->bitmap.width;
652                 if (buf_x < 0 || buf_x >= (long)pys_width) continue;
653                 buf_x *=  bytes_per_pixel ;
654                 for (iy=0; iy < bit->bitmap.rows; iy++){                    
655                     long buf_y = iy+(pen_y+0.5)-(double)bit->top;
656                     if (buf_y < 0 || buf_y >= (long)pys_height) continue;
657                     buf_y *= rowstride;
658                     for (ix=0;ix < bit->bitmap.width;ix++){             
659                         *(letter + (ix*bytes_per_pixel+3)) = *(bit->bitmap.buffer + iy * bit->bitmap.width + ix);
660                     }
661                     art_rgba_rgba_composite(buffer + buf_y + buf_x ,letter,comp_n);
662                  }
663                  art_free(letter);
664 */
665                 switch ( bit->bitmap.pixel_mode ) {
666                     case FT_PIXEL_MODE_GRAY:
667                         for (iy=0; iy < bit->bitmap.rows; iy++){
668                             long buf_y = iy+(pen_y+0.5)-bit->top;
669                             if (buf_y < 0 || buf_y >= (long)pys_height) continue;
670                             buf_y *= rowstride;
671                             for (ix=0;ix < bit->bitmap.width;ix++){
672                                 long buf_x = ix + (pen_x + 0.5) + (double)bit->left ;
673                                 art_u8 font_alpha;
674
675                                 if (buf_x < 0 || buf_x >= (long)pys_width) continue;
676                                 buf_x *=  bytes_per_pixel ;
677                                 font_alpha =  *(bit->bitmap.buffer + iy * bit->bitmap.pitch + ix);
678                     if (font_alpha > 0){
679                                     fcolor[3] =  (art_u8)((double)font_alpha / gr * falpha);
680                         art_rgba_rgba_composite(buffer + buf_y + buf_x ,fcolor,1);
681                                 }
682                             }
683                         }
684                         break;
685
686                     case FT_PIXEL_MODE_MONO:
687                         for (iy=0; iy < bit->bitmap.rows; iy++){
688                             long buf_y = iy+(pen_y+0.5)-bit->top;
689                             if (buf_y < 0 || buf_y >= (long)pys_height) continue;
690                             buf_y *= rowstride;
691                             for (ix=0;ix < bit->bitmap.width;ix++){
692                                 long buf_x = ix + (pen_x + 0.5) + (double)bit->left ;
693
694                                 if (buf_x < 0 || buf_x >= (long)pys_width) continue;
695                                 buf_x *=  bytes_per_pixel ;
696                                 if ( (fcolor[3] = falpha * ((*(bit->bitmap.buffer + iy * bit->bitmap.pitch + ix/8) >> (7 - (ix % 8))) & 1)) > 0 )
697                                     art_rgba_rgba_composite(buffer + buf_y + buf_x ,fcolor,1);
698                             }
699                         }
700                         break;
701
702                         default:
703                             rrd_set_error("unknown freetype pixel mode: %d", bit->bitmap.pixel_mode);
704                             break;
705                 }
706
707 /*
708                 for (iy=0; iy < bit->bitmap.rows; iy++){                    
709                     long buf_y = iy+(pen_y+0.5)-bit->top;
710                     if (buf_y < 0 || buf_y >= (long)pys_height) continue;
711                     buf_y *= rowstride;
712                     for (ix=0;ix < bit->bitmap.width;ix++){
713                         long buf_x = ix + (pen_x + 0.5) + (double)bit->left ;
714                         art_u8 font_alpha;
715                         
716                         if (buf_x < 0 || buf_x >= (long)pys_width) continue;
717                         buf_x *=  bytes_per_pixel ;
718                         font_alpha =  *(bit->bitmap.buffer + iy * bit->bitmap.width + ix);
719                         font_alpha =  (art_u8)((double)font_alpha / gr * falpha);
720                         for (iz = 0; iz < 3; iz++){
721                             art_u8 *orig = buffer + buf_y + buf_x + iz;
722                             *orig =  (art_u8)((double)*orig / gr * ( gr - font_alpha) +
723                                               (double)fcolor[iz] / gr * (font_alpha));
724                         }
725                     }
726                 }
727 */
728                 FT_Done_Glyph (image);
729             }
730             gfx_string_destroy(string);
731         }
732         }
733         node = node->next;
734     }  
735     gfx_save_png(buffer,fp , pys_width,pys_height,bytes_per_pixel);
736     art_free(buffer);
737     FT_Done_FreeType( library );
738     return 0;    
739 }
740
741 /* free memory used by nodes this will also remove memory required for
742    associated paths and svcs ... but not for text strings */
743 int
744 gfx_destroy    (gfx_canvas_t *canvas){  
745   gfx_node_t *next,*node = canvas->firstnode;
746   while(node){
747     next = node->next;
748     art_free(node->path);
749     free(node->text);
750     free(node->filename);
751     art_free(node);
752     node = next;
753   }
754   art_free(canvas);
755   return 0;
756 }
757  
758 static int gfx_save_png (art_u8 *buffer, FILE *fp,  long width, long height, long bytes_per_pixel){
759   png_structp png_ptr = NULL;
760   png_infop   info_ptr = NULL;
761   int i;
762   png_bytep *row_pointers;
763   int rowstride = width * bytes_per_pixel;
764   png_text text[2];
765   
766   if (fp == NULL)
767     return (1);
768
769   png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING,NULL,NULL,NULL);
770   if (png_ptr == NULL)
771    {
772       return (1);
773    }
774    row_pointers = (png_bytepp)png_malloc(png_ptr,
775                                      height*sizeof(png_bytep));
776
777   info_ptr = png_create_info_struct(png_ptr);
778
779   if (info_ptr == NULL)
780     {
781       png_free(png_ptr,row_pointers);
782       png_destroy_write_struct(&png_ptr,  (png_infopp)NULL);
783       return (1);
784     }
785
786   if (setjmp(png_jmpbuf(png_ptr)))
787     {
788       /* If we get here, we had a problem writing the file */
789       png_destroy_write_struct(&png_ptr, &info_ptr);
790       return (1);
791     }
792
793   png_init_io(png_ptr, fp);
794   png_set_IHDR (png_ptr, info_ptr,width, height,
795                 8, PNG_COLOR_TYPE_RGB_ALPHA,
796                 PNG_INTERLACE_NONE,
797                 PNG_COMPRESSION_TYPE_DEFAULT,
798                 PNG_FILTER_TYPE_DEFAULT);
799
800   text[0].key = "Software";
801   text[0].text = "RRDtool, Tobias Oetiker <tobi@oetike.ch>, http://tobi.oetiker.ch";
802   text[0].compression = PNG_TEXT_COMPRESSION_NONE;
803   png_set_text (png_ptr, info_ptr, text, 1);
804
805   /* lets make this fast while ending up with some increass in image size */
806   png_set_filter(png_ptr,0,PNG_FILTER_NONE);
807   /* png_set_filter(png_ptr,0,PNG_FILTER_SUB); */
808   png_set_compression_level(png_ptr,1);
809   /* png_set_compression_strategy(png_ptr,Z_HUFFMAN_ONLY); */
810   /* 
811   png_set_filter(png_ptr,PNG_FILTER_TYPE_BASE,PNG_FILTER_SUB);
812   png_set_compression_strategy(png_ptr,Z_HUFFMAN_ONLY);
813   png_set_compression_level(png_ptr,Z_BEST_SPEED); */
814   
815   /* Write header data */
816   png_write_info (png_ptr, info_ptr);
817   for (i = 0; i < height; i++)
818     row_pointers[i] = (png_bytep) (buffer + i*rowstride);
819   
820   png_write_image(png_ptr, row_pointers);
821   png_write_end(png_ptr, info_ptr);
822   png_free(png_ptr,row_pointers);
823   png_destroy_write_struct(&png_ptr, &info_ptr);
824   return 1;
825 }
826
827  
828 /* ----- COMMON ROUTINES for pdf, svg and eps */
829 #define min3(a, b, c) (a < b ? (a < c ? a : c) : (b < c ? b : c))
830 #define max3(a, b, c) (a > b ? (a > c ? a : c) : (b > c ? b : c))
831
832 #define PDF_CALC_DEBUG 0
833
834 typedef struct pdf_point
835 {
836         double x, y;
837 } pdf_point;
838
839 typedef struct
840 {
841         double ascender, descender, baselineY;
842         pdf_point sizep, minp, maxp;
843         double x, y, tdx, tdy;
844         double r, cos_r, sin_r;
845         double ma, mb, mc, md, mx, my; /* pdf coord matrix */
846         double tmx, tmy; /* last 2 coords of text coord matrix */
847 #if PDF_CALC_DEBUG
848         int debug;
849 #endif
850 } pdf_coords;
851
852 #if PDF_CALC_DEBUG
853 static void pdf_dump_calc(gfx_node_t *node, pdf_coords *g)
854 {
855         fprintf(stderr, "PDF CALC =============================\n");
856         fprintf(stderr, "   '%s' at %f pt\n", node->text, node->size);
857         fprintf(stderr, "   align h = %s, v = %s,  sizep = %f, %f\n",
858                 (node->halign == GFX_H_RIGHT ? "r" :
859                         (node->halign == GFX_H_CENTER ? "c" :
860                                 (node->halign == GFX_H_LEFT ? "l" : "N"))),
861                 (node->valign == GFX_V_TOP ? "t" :
862                         (node->valign == GFX_V_CENTER ? "c" :
863                                 (node->valign == GFX_V_BOTTOM ? "b" : "N"))),
864                         g->sizep.x, g->sizep.y);
865         fprintf(stderr, "   r = %f = %f, cos = %f, sin = %f\n",
866                         g->r, node->angle, g->cos_r, g->sin_r);
867         fprintf(stderr, "   ascender = %f, descender = %f, baselineY = %f\n",
868                 g->ascender, g->descender, g->baselineY);
869         fprintf(stderr, "   sizep: %f, %f\n", g->sizep.x, g->sizep.y);
870         fprintf(stderr, "   minp: %f, %f     maxp = %f, %f\n", 
871                         g->minp.x, g->minp.y, g->maxp.x, g->maxp.y);
872         fprintf(stderr, "   x = %f, y = %f\n", g->x, g->y);
873         fprintf(stderr, "   tdx = %f, tdy = %f\n", g->tdx, g->tdy);
874         fprintf(stderr, "   GM = %f, %f, %f, %f, %f, %f\n",
875                         g->ma, g->mb, g->mc, g->md, g->mx, g->my);
876         fprintf(stderr, "   TM = %f, %f, %f, %f, %f, %f\n",
877                         g->ma, g->mb, g->mc, g->md, g->tmx, g->tmy);
878 }
879 #endif
880  
881 #if PDF_CALC_DEBUG
882 #define PDF_DD(x) if (g->debug) x;
883 #else
884 #define PDF_DD(x)
885 #endif
886
887 static void pdf_rotate(pdf_coords *g, pdf_point *p)
888 {
889     double x2 = g->cos_r * p->x - g->sin_r * p->y;
890     double y2 = g->sin_r * p->x + g->cos_r * p->y;
891         PDF_DD( fprintf(stderr, "  rotate(%f, %f) -> %f, %f\n", p->x, p->y, x2, y2))
892     p->x = x2;
893         p->y = y2;
894 }
895
896
897 static void pdf_calc(int page_height, gfx_node_t *node, pdf_coords *g)
898 {
899         pdf_point a, b, c;
900 #if PDF_CALC_DEBUG
901         /* g->debug = !!strstr(node->text, "RevProxy-1") || !!strstr(node->text, "08:00"); */
902         g->debug = !!strstr(node->text, "sekunder") || !!strstr(node->text, "Web");
903 #endif
904         g->x = node->x;
905         g->y = page_height - node->y;
906         if (node->angle) {
907                 g->r = 2 * M_PI * node->angle / 360.0;
908                 g->cos_r = cos(g->r);
909                 g->sin_r = sin(g->r);
910         } else {
911                 g->r = 0;
912                 g->cos_r = 1;
913                 g->sin_r = 0;
914         }
915         g->ascender = afm_get_ascender(node->filename, node->size);
916         g->descender = afm_get_descender(node->filename, node->size);
917         g->sizep.x = afm_get_text_width(0, node->filename, node->size, node->tabwidth, node->text);
918         /* seems like libart ignores the descender when doing vertial-align = bottom,
919            so we do that too, to get labels v-aligning properly */
920         g->sizep.y = -g->ascender; /* + afm_get_descender(font->ps_font, node->size); */
921         g->baselineY = -g->ascender - g->sizep.y / 2;
922         a.x = g->sizep.x; a.y = g->sizep.y;
923         b.x = g->sizep.x; b.y = 0;
924         c.x = 0; c.y = g->sizep.y;
925         if (node->angle) {
926                 pdf_rotate(g, &a);
927                 pdf_rotate(g, &b);
928                 pdf_rotate(g, &c);
929         }
930         g->minp.x = min3(a.x, b.x, c.x);
931         g->minp.y = min3(a.y, b.y, c.y);
932         g->maxp.x = max3(a.x, b.x, c.x);
933         g->maxp.y = max3(a.y, b.y, c.y);
934   /* The alignment parameters in node->valign and node->halign
935      specifies the alignment in the non-rotated coordinate system
936      (very unlike pdf/postscript), which complicates matters.
937   */
938         switch (node->halign) {
939         case GFX_H_RIGHT:  g->tdx = -g->maxp.x; break;
940         case GFX_H_CENTER: g->tdx = -(g->maxp.x + g->minp.x) / 2; break;
941         case GFX_H_LEFT:   g->tdx = -g->minp.x; break;
942         case GFX_H_NULL:   g->tdx = 0; break;
943         }
944         switch(node->valign){
945         case GFX_V_TOP:    g->tdy = -g->maxp.y; break;
946         case GFX_V_CENTER: g->tdy = -(g->maxp.y + g->minp.y) / 2; break;
947         case GFX_V_BOTTOM: g->tdy = -g->minp.y; break;
948         case GFX_V_NULL:   g->tdy = 0; break;          
949         }
950         g->ma = g->cos_r;
951         g->mb = g->sin_r;
952         g->mc = -g->sin_r;
953         g->md = g->cos_r;
954         g->mx = g->x + g->tdx;
955         g->my = g->y + g->tdy;
956         g->tmx = g->mx - g->ascender * g->mc;
957         g->tmy = g->my - g->ascender * g->md;
958         PDF_DD(pdf_dump_calc(node, g))
959 }
960
961 /* ------- SVG -------
962    SVG reference:
963    http://www.w3.org/TR/SVG/
964 */
965 static int svg_indent = 0;
966 static int svg_single_line = 0;
967 static const char *svg_default_font = "-dummy-";
968 typedef struct svg_dash
969 {
970   int dash_enable;
971   double dash_adjust, dash_len, dash_offset;
972   double adjusted_on, adjusted_off;
973 } svg_dash;
974
975
976 static void svg_print_indent(FILE *fp)
977 {
978   int i;
979    for (i = svg_indent - svg_single_line; i > 0; i--) {
980      putc(' ', fp);
981      putc(' ', fp);
982    }
983 }
984  
985 static void svg_start_tag(FILE *fp, const char *name)
986 {
987    svg_print_indent(fp);
988    putc('<', fp);
989    fputs(name, fp);
990    svg_indent++;
991 }
992  
993 static void svg_close_tag_single_line(FILE *fp)
994 {
995    svg_single_line++;
996    putc('>', fp);
997 }
998  
999 static void svg_close_tag(FILE *fp)
1000 {
1001    putc('>', fp);
1002    if (!svg_single_line)
1003      putc('\n', fp);
1004 }
1005  
1006 static void svg_end_tag(FILE *fp, const char *name)
1007 {
1008    /* name is NULL if closing empty-node tag */
1009    svg_indent--;
1010    if (svg_single_line)
1011      svg_single_line--;
1012    else if (name)
1013      svg_print_indent(fp);
1014    if (name != NULL) {
1015      fputs("</", fp);
1016      fputs(name, fp);
1017    } else {
1018      putc('/', fp);
1019    }
1020    svg_close_tag(fp);
1021 }
1022  
1023 static void svg_close_tag_empty_node(FILE *fp)
1024 {
1025    svg_end_tag(fp, NULL);
1026 }
1027  
1028 static void svg_write_text(FILE *fp, const char *text)
1029 {
1030    const unsigned char *p, *start, *last;
1031    unsigned int ch;
1032    p = (const unsigned char*)text;
1033    if (!p)
1034      return;
1035    /* trim leading spaces */
1036    while (*p == ' ')
1037      p++;
1038    start = p;
1039    /* trim trailing spaces */
1040    last = p - 1;
1041    while ((ch = *p) != 0) {
1042      if (ch != ' ')
1043        last = p;
1044      p++;
1045   }
1046   /* encode trimmed text */
1047   p = start;
1048   while (p <= last) {
1049     ch = *p++;
1050     ch = afm_host2unicode(ch); /* unsafe macro */
1051     switch (ch) {
1052     case '&': fputs("&amp;", fp); break;
1053     case '<': fputs("&lt;", fp); break;
1054     case '>': fputs("&gt;", fp); break;
1055     case '"': fputs("&quot;", fp); break;
1056     default:
1057       if (ch >= 127)
1058         fprintf(fp, "&#%d;", ch);
1059       else
1060         putc(ch, fp);
1061      }
1062    }
1063 }
1064  
1065 static void svg_format_number(char *buf, int bufsize, double d)
1066 {
1067    /* omit decimals if integer to reduce filesize */
1068    char *p;
1069    snprintf(buf, bufsize, "%.2f", d);
1070    p = buf; /* doesn't trust snprintf return value */
1071    while (*p)
1072      p++;
1073    while (--p > buf) {
1074      char ch = *p;
1075      if (ch == '0') {
1076        *p = '\0'; /* zap trailing zeros */
1077        continue;
1078      }
1079      if (ch == '.')
1080        *p = '\0'; /* zap trailing dot */
1081      break;
1082    }
1083 }
1084  
1085 static void svg_write_number(FILE *fp, double d)
1086 {
1087    char buf[60];
1088    svg_format_number(buf, sizeof(buf), d);
1089    fputs(buf, fp);
1090 }
1091
1092 static int svg_color_is_black(int c)
1093 {
1094   /* gfx_color_t is RRGGBBAA */
1095   return c == 0x000000FF;
1096 }
1097  
1098 static void svg_write_color(FILE *fp, gfx_color_t c, const char *attr)
1099 {
1100   /* gfx_color_t is RRGGBBAA, svg can use #RRGGBB and #RGB like html */
1101   gfx_color_t rrggbb = (int)((c >> 8) & 0xFFFFFF);
1102   gfx_color_t opacity = c & 0xFF;
1103   fprintf(fp, " %s=\"", attr);
1104   if ((rrggbb & 0x0F0F0F) == ((rrggbb >> 4) & 0x0F0F0F)) {
1105      /* css2 short form, #rgb is #rrggbb, not #r0g0b0 */
1106     fprintf(fp, "#%03lX",
1107           ( ((rrggbb >> 8) & 0xF00)
1108           | ((rrggbb >> 4) & 0x0F0)
1109           | ( rrggbb       & 0x00F)));
1110    } else {
1111     fprintf(fp, "#%06lX", rrggbb);
1112    }
1113   fputs("\"", fp);
1114   if (opacity != 0xFF) {
1115     fprintf(fp, " opacity=\"");
1116     svg_write_number(fp, opacity / 255.0);
1117     fputs("\"", fp);
1118  }
1119 }
1120  
1121 static void svg_get_dash(gfx_node_t *node, svg_dash *d)
1122 {
1123   double offset;
1124   int mult;
1125   if (node->dash_on <= 0 || node->dash_off <= 0) {
1126     d->dash_enable = 0;
1127     return;
1128   }
1129   d->dash_enable = 1;
1130   d->dash_len = node->dash_on + node->dash_off;
1131   /* dash on/off adjustment due to round caps */
1132   d->dash_adjust = 0.8 * node->size;
1133   d->adjusted_on = node->dash_on - d->dash_adjust;
1134   if (d->adjusted_on < 0.01)
1135       d->adjusted_on = 0.01;
1136   d->adjusted_off = d->dash_len - d->adjusted_on;
1137   /* dash offset calc */
1138   if (node->path[0].x == node->path[1].x) /* only good for horz/vert lines */
1139     offset = node->path[0].y;
1140   else
1141     offset = node->path[0].x;
1142   mult = (int)fabs(offset / d->dash_len);
1143   d->dash_offset = offset - mult * d->dash_len;
1144   if (node->path[0].x < node->path[1].x || node->path[0].y < node->path[1].y)
1145     d->dash_offset = d->dash_len - d->dash_offset;
1146 }
1147
1148 static int svg_dash_equal(svg_dash *a, svg_dash *b)
1149 {
1150   if (a->dash_enable != b->dash_enable)
1151     return 0;
1152   if (a->adjusted_on != b->adjusted_on)
1153     return 0;
1154   if (a->adjusted_off != b->adjusted_off)
1155     return 0;
1156   /* rest of properties will be the same when on+off are */
1157   return 1;
1158 }
1159
1160 static void svg_common_path_attributes(FILE *fp, gfx_node_t *node)
1161 {
1162   svg_dash dash_info;
1163   svg_get_dash(node, &dash_info);
1164   fputs(" stroke-width=\"", fp);
1165   svg_write_number(fp, node->size);
1166   fputs("\"", fp);
1167   svg_write_color(fp, node->color, "stroke");
1168   fputs(" fill=\"none\"", fp);
1169   if (dash_info.dash_enable) {
1170     if (dash_info.dash_offset != 0) {
1171       fputs(" stroke-dashoffset=\"", fp);
1172       svg_write_number(fp, dash_info.dash_offset);
1173       fputs("\"", fp);
1174     }
1175     fputs(" stroke-dasharray=\"", fp);
1176     svg_write_number(fp, dash_info.adjusted_on);
1177     fputs(",", fp);
1178     svg_write_number(fp, dash_info.adjusted_off);
1179     fputs("\"", fp);
1180   }
1181 }
1182
1183 static int svg_is_int_step(double a, double b)
1184 {
1185    double diff = fabs(a - b);
1186    return floor(diff) == diff;
1187 }
1188  
1189 static int svg_path_straight_segment(FILE *fp,
1190      double lastA, double currentA, double currentB,
1191      gfx_node_t *node,
1192      int segment_idx, int isx, char absChar, char relChar)
1193 {
1194    if (!svg_is_int_step(lastA, currentA)) {
1195      putc(absChar, fp);
1196      svg_write_number(fp, currentA);
1197      return 0;
1198    }
1199    if (segment_idx < node->points - 1) {
1200      ArtVpath *vec = node->path + segment_idx + 1;
1201      if (vec->code == ART_LINETO) {
1202        double nextA = (isx ? vec->x : vec->y) - LINEOFFSET;
1203        double nextB = (isx ? vec->y : vec->x) - LINEOFFSET;
1204        if (nextB == currentB
1205            && ((currentA >= lastA) == (nextA >= currentA))
1206            && svg_is_int_step(currentA, nextA)) {
1207          return 1; /* skip to next as it is a straight line  */
1208        }
1209      }
1210    }
1211    putc(relChar, fp);
1212    svg_write_number(fp, currentA - lastA);
1213    return 0;
1214 }
1215  
1216 static void svg_path(FILE *fp, gfx_node_t *node, int multi)
1217 {
1218    int i;
1219    double lastX = 0, lastY = 0;
1220    /* for straight lines <path..> tags take less space than
1221       <line..> tags because of the efficient packing
1222       in the 'd' attribute */
1223    svg_start_tag(fp, "path");
1224   if (!multi)
1225     svg_common_path_attributes(fp, node);
1226    fputs(" d=\"", fp);
1227    /* specification of the 'd' attribute: */
1228    /* http://www.w3.org/TR/SVG/paths.html#PathDataGeneralInformation */
1229    for (i = 0; i < node->points; i++) {
1230      ArtVpath *vec = node->path + i;
1231      double x = vec->x - LINEOFFSET;
1232      double y = vec->y - LINEOFFSET;
1233      switch (vec->code) {
1234      case ART_MOVETO_OPEN: /* fall-through */
1235      case ART_MOVETO:
1236        putc('M', fp);
1237        svg_write_number(fp, x);
1238        putc(',', fp);
1239        svg_write_number(fp, y);
1240        break;
1241      case ART_LINETO:
1242        /* try optimize filesize by using minimal lineto commands */
1243        /* without introducing rounding errors. */
1244        if (x == lastX) {
1245          if (svg_path_straight_segment(fp, lastY, y, x, node, i, 0, 'V', 'v'))
1246            continue;
1247        } else if (y == lastY) {
1248          if (svg_path_straight_segment(fp, lastX, x, y, node, i, 1, 'H', 'h'))
1249            continue;
1250        } else {
1251          putc('L', fp);
1252          svg_write_number(fp, x);
1253          putc(',', fp);
1254          svg_write_number(fp, y);
1255        }
1256        break;
1257      case ART_CURVETO: break; /* unsupported */
1258      case ART_END: break; /* nop */
1259      }
1260      lastX = x;
1261      lastY = y;
1262    }
1263   if (node->closed_path)
1264     fputs(" Z", fp);
1265    fputs("\"", fp);
1266    svg_close_tag_empty_node(fp);
1267 }
1268  
1269 static void svg_multi_path(FILE *fp, gfx_node_t **nodeR)
1270 {
1271    /* optimize for multiple paths with the same color, penwidth, etc. */
1272    int num = 1;
1273    gfx_node_t *node = *nodeR;
1274    gfx_node_t *next = node->next;
1275    while (next) {
1276      if (next->type != node->type
1277          || next->size != node->size
1278         || next->color != node->color
1279         || next->dash_on != node->dash_on
1280         || next->dash_off != node->dash_off)
1281        break;
1282      next = next->next;
1283      num++;
1284    }
1285    if (num == 1) {
1286      svg_path(fp, node, 0);
1287      return;
1288    }
1289    svg_start_tag(fp, "g");
1290   svg_common_path_attributes(fp, node);
1291    svg_close_tag(fp);
1292    while (num && node) {
1293      svg_path(fp, node, 1);
1294      if (!--num)
1295        break;
1296      node = node->next;
1297      *nodeR = node;
1298    }
1299    svg_end_tag(fp, "g");
1300 }
1301  
1302 static void svg_area(FILE *fp, gfx_node_t *node)
1303 {
1304    int i;
1305    double startX = 0, startY = 0;
1306    svg_start_tag(fp, "polygon");
1307   fputs(" ", fp);
1308   svg_write_color(fp, node->color, "fill");
1309   fputs(" points=\"", fp);
1310    for (i = 0; i < node->points; i++) {
1311      ArtVpath *vec = node->path + i;
1312      double x = vec->x - LINEOFFSET;
1313      double y = vec->y - LINEOFFSET;
1314      switch (vec->code) {
1315        case ART_MOVETO_OPEN: /* fall-through */
1316        case ART_MOVETO:
1317          svg_write_number(fp, x);
1318          putc(',', fp);
1319          svg_write_number(fp, y);
1320          startX = x;
1321          startY = y;
1322          break;
1323        case ART_LINETO:
1324          if (i == node->points - 2
1325                         && node->path[i + 1].code == ART_END
1326              && fabs(x - startX) < 0.001 && fabs(y - startY) < 0.001) {
1327            break; /* poly area always closed, no need for last point */
1328          }
1329          putc(' ', fp);
1330          svg_write_number(fp, x);
1331          putc(',', fp);
1332          svg_write_number(fp, y);
1333          break;
1334        case ART_CURVETO: break; /* unsupported */
1335        case ART_END: break; /* nop */
1336      }
1337    }
1338    fputs("\"", fp);
1339    svg_close_tag_empty_node(fp);
1340 }
1341  
1342 static void svg_text(FILE *fp, gfx_node_t *node)
1343 {
1344    pdf_coords g;
1345    const char *fontname;
1346    /* as svg has 0,0 in top-left corner (like most screens) instead of
1347           bottom-left corner like pdf and eps, we have to fake the coords
1348           using offset and inverse sin(r) value */
1349    int page_height = 1000;
1350    pdf_calc(page_height, node, &g);
1351    if (node->angle != 0) {
1352      svg_start_tag(fp, "g");
1353          /* can't use svg_write_number as 2 decimals is far from enough to avoid
1354                 skewed text */
1355      fprintf(fp, " transform=\"matrix(%f,%f,%f,%f,%f,%f)\"",
1356                          g.ma, -g.mb, -g.mc, g.md, g.tmx, page_height - g.tmy);
1357      svg_close_tag(fp);
1358    }
1359    svg_start_tag(fp, "text");
1360    if (!node->angle) {
1361      fputs(" x=\"", fp);
1362      svg_write_number(fp, g.tmx);
1363      fputs("\" y=\"", fp);
1364      svg_write_number(fp, page_height - g.tmy);
1365      fputs("\"", fp);
1366    }
1367    fontname = afm_get_font_name(node->filename);
1368    if (strcmp(fontname, svg_default_font))
1369      fprintf(fp, " font-family=\"%s\"", fontname);
1370    fputs(" font-size=\"", fp);
1371    svg_write_number(fp, node->size);
1372    fputs("\"", fp);
1373   if (!svg_color_is_black(node->color))
1374     svg_write_color(fp, node->color, "fill");
1375    svg_close_tag_single_line(fp);
1376    /* support for node->tabwidth missing */
1377    svg_write_text(fp, node->text);
1378    svg_end_tag(fp, "text");
1379    if (node->angle != 0)
1380      svg_end_tag(fp, "g");
1381 }
1382  
1383 int       gfx_render_svg (gfx_canvas_t *canvas,
1384                  art_u32 width, art_u32 height,
1385                  gfx_color_t background, FILE *fp){
1386    gfx_node_t *node = canvas->firstnode;
1387    /* Find the first font used, and assume it is the mostly used
1388           one. It reduces the number of font-familty attributes. */
1389    while (node) {
1390            if (node->type == GFX_TEXT && node->filename) {
1391                    svg_default_font = afm_get_font_name(node->filename);
1392                    break;
1393            }
1394            node = node->next;
1395    }
1396    fputs(
1397 "<?xml version=\"1.0\" standalone=\"no\"?>\n"
1398 "<!DOCTYPE svg PUBLIC \"-//W3C//DTD SVG 1.0//EN\"\n"
1399 "   \"http://www.w3.org/TR/2001/REC-SVG-20010904/DTD/svg10.dtd\">\n"
1400 "<!--\n"
1401 "   SVG file created by\n"
1402 "        RRDtool 1.2.4 Tobias Oetiker, http://tobi.oetiker.ch\n"
1403 "\n"
1404 "   The width/height attributes in the outhermost svg node\n"
1405 "   are just default sizes for the browser which is used\n"
1406 "   if the svg file is openened directly without being\n"
1407 "   embedded in an html file.\n"
1408 "   The viewBox is the local coord system for rrdtool.\n"
1409 "-->\n", fp);
1410    svg_start_tag(fp, "svg");
1411    fputs(" width=\"", fp);
1412   svg_write_number(fp, width * canvas->zoom);
1413    fputs("\" height=\"", fp);
1414   svg_write_number(fp, height * canvas->zoom);
1415    fputs("\" x=\"0\" y=\"0\" viewBox=\"", fp);
1416    svg_write_number(fp, -LINEOFFSET);
1417    fputs(" ", fp);
1418    svg_write_number(fp, -LINEOFFSET);
1419    fputs(" ", fp);
1420    svg_write_number(fp, width - LINEOFFSET);
1421    fputs(" ", fp);
1422    svg_write_number(fp, height - LINEOFFSET);
1423    fputs("\" preserveAspectRatio=\"xMidYMid\"", fp);
1424   fprintf(fp, " font-family=\"%s\"", svg_default_font); /* default font */
1425   fputs(" stroke-linecap=\"round\" stroke-linejoin=\"round\"", fp);
1426    svg_close_tag(fp);
1427    svg_start_tag(fp, "rect");
1428    fprintf(fp, " x=\"0\" y=\"0\" width=\"%d\" height=\"%d\"", width, height);
1429   svg_write_color(fp, background, "fill");
1430    svg_close_tag_empty_node(fp);
1431    node = canvas->firstnode;
1432    while (node) {
1433      switch (node->type) {
1434      case GFX_LINE:
1435        svg_multi_path(fp, &node);
1436        break;
1437      case GFX_AREA:
1438        svg_area(fp, node);
1439        break;
1440      case GFX_TEXT:
1441        svg_text(fp, node);
1442      }
1443      node = node->next;
1444    }
1445    svg_end_tag(fp, "svg");
1446    return 0;
1447 }
1448
1449 /* ------- EPS -------
1450    EPS and Postscript references:
1451    http://partners.adobe.com/asn/developer/technotes/postscript.html
1452 */
1453
1454 typedef struct eps_font
1455 {
1456   const char *ps_font;
1457   int id;
1458   struct eps_font *next;
1459 } eps_font;
1460
1461 typedef struct eps_state
1462 {
1463   FILE *fp;
1464   gfx_canvas_t *canvas;
1465   art_u32 page_width, page_height;
1466   eps_font *font_list;
1467   /*--*/
1468   gfx_color_t color;
1469   const char *font;
1470   double font_size;
1471   double line_width;
1472   int linecap, linejoin;
1473   int has_dash;
1474 } eps_state;
1475
1476 static void eps_set_color(eps_state *state, gfx_color_t color)
1477 {
1478 #if USE_EPS_FAKE_ALPHA
1479    double a1, a2;
1480 #endif
1481    /* gfx_color_t is RRGGBBAA */
1482   if (state->color == color)
1483     return;
1484 #if USE_EPS_FAKE_ALPHA
1485   a1 = (color & 255) / 255.0;
1486   a2 = 255 * (1 - a1);
1487 #define eps_color_calc(x) (int)( ((x) & 255) * a1 + a2)
1488 #else
1489 #define eps_color_calc(x) (int)( (x) & 255)
1490 #endif
1491    /* gfx_color_t is RRGGBBAA */
1492   if (state->color == color)
1493     return;
1494   fprintf(state->fp, "%d %d %d Rgb\n",
1495       eps_color_calc(color >> 24),
1496       eps_color_calc(color >> 16),
1497       eps_color_calc(color >>  8));
1498   state->color = color;
1499 }
1500
1501 static int eps_add_font(eps_state *state, gfx_node_t *node)
1502 {
1503   /* The fonts list could be postponed to the end using
1504      (atend), but let's be nice and have them in the header. */
1505   const char *ps_font = afm_get_font_postscript_name(node->filename);
1506   eps_font *ef;
1507   for (ef = state->font_list; ef; ef = ef->next) {
1508     if (!strcmp(ps_font, ef->ps_font))
1509       return 0;
1510   }
1511   ef = malloc(sizeof(eps_font));
1512   if (ef == NULL) {
1513     rrd_set_error("malloc for eps_font");
1514     return -1;
1515   }
1516   ef->next = state->font_list;
1517   ef->ps_font = ps_font;
1518   state->font_list = ef;
1519   return 0;
1520 }
1521
1522 static void eps_list_fonts(eps_state *state, const char *dscName)
1523 {
1524   eps_font *ef;
1525   int lineLen = strlen(dscName);
1526   if (!state->font_list)
1527     return;
1528   fputs(dscName, state->fp);
1529   for (ef = state->font_list; ef; ef = ef->next) {
1530     int nameLen = strlen(ef->ps_font);
1531     if (lineLen + nameLen > 100 && lineLen) {
1532       fputs("\n", state->fp);
1533       fputs("%%- \n", state->fp);
1534       lineLen = 5;
1535     } else {
1536       fputs(" ", state->fp);
1537       lineLen++;
1538     }
1539     fputs(ef->ps_font, state->fp);
1540     lineLen += nameLen;
1541   }
1542   fputs("\n", state->fp);
1543 }
1544
1545 static void eps_define_fonts(eps_state *state)
1546 {
1547   eps_font *ef;
1548   if (!state->font_list)
1549     return;
1550   for (ef = state->font_list; ef; ef = ef->next) {
1551     /* PostScript¨ LANGUAGE REFERENCE third edition
1552        page 349 */
1553     fprintf(state->fp,
1554         "%%\n"
1555         "/%s findfont dup length dict begin\n"
1556         "{ 1 index /FID ne {def} {pop pop} ifelse } forall\n"
1557         "/Encoding ISOLatin1Encoding def\n"
1558         "currentdict end\n"
1559         "/%s-ISOLatin1 exch definefont pop\n"
1560         "/SetFont-%s { /%s-ISOLatin1 findfont exch scalefont setfont } bd\n",
1561         ef->ps_font, ef->ps_font, ef->ps_font, ef->ps_font);
1562   }
1563 }
1564
1565 static int eps_prologue(eps_state *state)
1566 {
1567   gfx_node_t *node;
1568   fputs(
1569     "%!PS-Adobe-3.0 EPSF-3.0\n"
1570     "%%Creator: RRDtool 1.2.4 Tobias Oetiker, http://tobi.oetiker.ch\n"
1571     /* can't like weird chars here */
1572     "%%Title: (RRDtool output)\n"
1573     "%%DocumentData: Clean7Bit\n"
1574     "", state->fp);
1575   fprintf(state->fp, "%%%%BoundingBox: 0 0 %d %d\n",
1576     state->page_width, state->page_height);
1577   for (node = state->canvas->firstnode; node; node = node->next) {
1578     if (node->type == GFX_TEXT && eps_add_font(state, node) == -1)
1579       return -1;
1580   }
1581   eps_list_fonts(state, "%%DocumentFonts:");
1582   eps_list_fonts(state, "%%DocumentNeededFonts:");
1583   fputs(
1584       "%%EndComments\n"
1585       "%%BeginProlog\n"
1586       "%%EndProlog\n" /* must have, or BoundingBox is ignored */
1587       "/bd { bind def } bind def\n"
1588       "", state->fp);
1589   fprintf(state->fp, "/X { %.2f add } bd\n", LINEOFFSET);
1590   fputs(
1591       "/X2 {X exch X exch} bd\n"
1592       "/M {X2 moveto} bd\n"
1593       "/L {X2 lineto} bd\n"
1594       "/m {moveto} bd\n"
1595       "/l {lineto} bd\n"
1596       "/S {stroke} bd\n"
1597       "/CP {closepath} bd\n"
1598       "/WS {setlinewidth stroke} bd\n"
1599       "/F {fill} bd\n"
1600       "/T1 {gsave} bd\n"
1601       "/T2 {concat 0 0 moveto show grestore} bd\n"
1602       "/T   {moveto show} bd\n"
1603       "/Rgb { 255.0 div 3 1 roll\n"
1604       "       255.0 div 3 1 roll \n"
1605       "       255.0 div 3 1 roll setrgbcolor } bd\n"
1606       "", state->fp);
1607   eps_define_fonts(state);
1608   return 0;
1609 }
1610
1611 static void eps_clear_dash(eps_state *state)
1612 {
1613   if (!state->has_dash)
1614     return;
1615   state->has_dash = 0;
1616   fputs("[1 0] 0 setdash\n", state->fp);
1617 }
1618
1619 static void eps_write_linearea(eps_state *state, gfx_node_t *node)
1620 {
1621   int i;
1622   FILE *fp = state->fp;
1623   int useOffset = 0;
1624   int clearDashIfAny = 1;
1625   eps_set_color(state, node->color);
1626   if (node->type == GFX_LINE) {
1627     svg_dash dash_info;
1628     if (state->linecap != 1) {
1629       fputs("1 setlinecap\n", fp);
1630       state->linecap = 1;
1631     }
1632     if (state->linejoin != 1) {
1633       fputs("1 setlinejoin\n", fp);
1634       state->linejoin = 1;
1635     }
1636     svg_get_dash(node, &dash_info);
1637     if (dash_info.dash_enable) {
1638       clearDashIfAny = 0;
1639       state->has_dash = 1;
1640       fputs("[", fp);
1641       svg_write_number(fp, dash_info.adjusted_on);
1642       fputs(" ", fp);
1643       svg_write_number(fp, dash_info.adjusted_off);
1644       fputs("] ", fp);
1645       svg_write_number(fp, dash_info.dash_offset);
1646       fputs(" setdash\n", fp);
1647     }
1648   }
1649   if (clearDashIfAny)
1650     eps_clear_dash(state);
1651   for (i = 0; i < node->points; i++) {
1652     ArtVpath *vec = node->path + i;
1653     double x = vec->x;
1654     double y = state->page_height - vec->y;
1655     if (vec->code == ART_MOVETO_OPEN || vec->code == ART_MOVETO)
1656       useOffset = (fabs(x - floor(x) - 0.5) < 0.01 && fabs(y - floor(y) - 0.5) < 0.01);
1657     if (useOffset) {
1658       x -= LINEOFFSET;
1659       y -= LINEOFFSET;
1660     }
1661     switch (vec->code) {
1662     case ART_MOVETO_OPEN: /* fall-through */
1663     case ART_MOVETO:
1664       svg_write_number(fp, x);
1665       fputc(' ', fp);
1666       svg_write_number(fp, y);
1667       fputc(' ', fp);
1668       fputs(useOffset ? "M\n" : "m\n", fp);
1669       break;
1670     case ART_LINETO:
1671       svg_write_number(fp, x);
1672       fputc(' ', fp);
1673       svg_write_number(fp, y);
1674       fputc(' ', fp);
1675       fputs(useOffset ? "L\n" : "l\n", fp);
1676       break;
1677     case ART_CURVETO: break; /* unsupported */
1678     case ART_END: break; /* nop */
1679     }
1680   }
1681   if (node->type == GFX_LINE) {
1682     if (node->closed_path)
1683       fputs("CP ", fp);
1684     if (node->size != state->line_width) {
1685       state->line_width = node->size;
1686       svg_write_number(fp, state->line_width);
1687       fputs(" WS\n", fp);
1688     } else {
1689       fputs("S\n", fp);
1690     }
1691    } else {
1692     fputs("F\n", fp);
1693    }
1694 }
1695
1696 static void eps_write_text(eps_state *state, gfx_node_t *node)
1697 {
1698   FILE *fp = state->fp;
1699   const unsigned char *p;
1700   const char *ps_font = afm_get_font_postscript_name(node->filename);
1701   int lineLen = 0;
1702   pdf_coords g;
1703   pdf_calc(state->page_height, node, &g);
1704   eps_set_color(state, node->color);
1705   if (strcmp(ps_font, state->font) || node->size != state->font_size) {
1706     state->font = ps_font;
1707     state->font_size = node->size;
1708     svg_write_number(fp, state->font_size);
1709     fprintf(fp, " SetFont-%s\n", state->font);
1710   }
1711   if (node->angle)
1712           fputs("T1 ", fp);
1713   fputs("(", fp);
1714   lineLen = 20;
1715   for (p = (const unsigned char*)node->text; *p; p++) {
1716     if (lineLen > 70) {
1717       fputs("\\\n", fp); /* backslash and \n */
1718       lineLen = 0;
1719     }
1720     switch (*p) {
1721       case '(':
1722       case ')':
1723       case '\\':
1724       case '\n':
1725       case '\r':
1726       case '\t':
1727         fputc('\\', fp);
1728         lineLen++;
1729         /* fall-through */
1730       default:
1731         if (*p >= 126)
1732           fprintf(fp, "\\%03o", *p);
1733         else
1734           fputc(*p, fp);
1735         lineLen++;
1736     }
1737   }
1738   if (node->angle) {
1739          /* can't use svg_write_number as 2 decimals is far from enough to avoid
1740                 skewed text */
1741           fprintf(fp, ") [%f %f %f %f %f %f] T2\n",
1742                           g.ma, g.mb, g.mc, g.md, g.tmx, g.tmy);
1743   } else {
1744           fputs(") ", fp);
1745           svg_write_number(fp, g.tmx);
1746           fputs(" ", fp);
1747           svg_write_number(fp, g.tmy);
1748           fputs(" T\n", fp);
1749   }
1750 }
1751
1752 static int eps_write_content(eps_state *state)
1753 {
1754   gfx_node_t *node;
1755   fputs("%\n", state->fp);
1756   for (node = state->canvas->firstnode; node; node = node->next) {
1757     switch (node->type) {
1758     case GFX_LINE:
1759     case GFX_AREA:
1760       eps_write_linearea(state, node);
1761       break;
1762     case GFX_TEXT:
1763       eps_write_text(state, node);
1764       break;
1765     }
1766   }
1767   return 0;
1768 }
1769
1770 int       gfx_render_eps (gfx_canvas_t *canvas,
1771                  art_u32 width, art_u32 height,
1772                  gfx_color_t background, FILE *fp){
1773   struct eps_state state;
1774   state.fp = fp;
1775   state.canvas = canvas;
1776   state.page_width = width;
1777   state.page_height = height;
1778   state.font = "no-default-font";
1779   state.font_size = -1;
1780   state.color = 0; /* black */
1781   state.font_list = NULL;
1782   state.linecap = -1;
1783   state.linejoin = -1;
1784   state.has_dash = 0;
1785   if (eps_prologue(&state) == -1)
1786     return -1;
1787   eps_set_color(&state, background);
1788   fprintf(fp, "0 0 M 0 %d L %d %d L %d 0 L fill\n",
1789       height, width, height, width);
1790   if (eps_write_content(&state) == -1)
1791     return 0;
1792   fputs("showpage\n", fp);
1793   fputs("%%EOF\n", fp);
1794   while (state.font_list) {
1795     eps_font *next = state.font_list->next;
1796     free(state.font_list);
1797     state.font_list = next;
1798   }
1799   return 0;
1800 }
1801
1802 /* ------- PDF -------
1803    PDF references page:
1804    http://partners.adobe.com/public/developer/pdf/index_reference.html
1805 */
1806
1807 typedef struct pdf_buffer
1808 {
1809   int id, is_obj, is_dict, is_stream, pdf_file_pos;
1810   char *data;
1811   int alloc_size, current_size;
1812   struct pdf_buffer *previous_buffer, *next_buffer;
1813   struct pdf_state *state;
1814 } pdf_buffer;
1815
1816 typedef struct pdf_font
1817 {
1818   const char *ps_font;
1819   pdf_buffer obj;
1820   struct pdf_font *next;
1821 } pdf_font;
1822
1823 typedef struct pdf_state
1824 {
1825   FILE *fp;
1826   gfx_canvas_t *canvas;
1827   art_u32 page_width, page_height;
1828   pdf_font *font_list;
1829   pdf_buffer *first_buffer, *last_buffer;
1830   int pdf_file_pos;
1831   int has_failed;
1832   /*--*/
1833   gfx_color_t stroke_color, fill_color;
1834   int font_id;
1835   double font_size;
1836   double line_width;
1837   svg_dash dash;
1838   int linecap, linejoin;
1839   int last_obj_id;
1840   /*--*/
1841   pdf_buffer pdf_header;
1842   pdf_buffer info_obj, catalog_obj, pages_obj, page1_obj;
1843   pdf_buffer fontsdict_obj;
1844   pdf_buffer graph_stream;
1845 } pdf_state;
1846
1847 static void pdf_init_buffer(pdf_state *state, pdf_buffer *buf)
1848 {
1849   int initial_size = 32;
1850   buf->state = state;
1851   buf->id = -42;
1852   buf->alloc_size = 0;
1853   buf->current_size = 0;
1854   buf->data = (char*)malloc(initial_size);
1855   buf->is_obj = 0;
1856   buf->previous_buffer = NULL;
1857   buf->next_buffer = NULL;
1858   if (buf->data == NULL) {
1859     rrd_set_error("malloc for pdf_buffer data");
1860     state->has_failed = 1;
1861     return;
1862   }
1863   buf->alloc_size = initial_size;
1864   if (state->last_buffer)
1865     state->last_buffer->next_buffer = buf;
1866   if (state->first_buffer == NULL)
1867     state->first_buffer = buf;
1868   buf->previous_buffer = state->last_buffer;
1869   state->last_buffer = buf;
1870 }
1871
1872 static void pdf_put(pdf_buffer *buf, const char *text, int len)
1873 {
1874   if (len <= 0)
1875     return;
1876   if (buf->alloc_size < buf->current_size + len) {
1877     int new_size = buf->alloc_size;
1878     char *new_buf;
1879     while (new_size < buf->current_size + len)
1880       new_size *= 4;
1881     new_buf = (char*)malloc(new_size);
1882     if (new_buf == NULL) {
1883       rrd_set_error("re-malloc for pdf_buffer data");
1884       buf->state->has_failed = 1;
1885       return;
1886     }
1887     memcpy(new_buf, buf->data, buf->current_size);
1888     free(buf->data);
1889     buf->data = new_buf;
1890     buf->alloc_size = new_size;
1891   }
1892   memcpy(buf->data + buf->current_size, text, len);
1893   buf->current_size += len;
1894 }
1895
1896 static void pdf_puts(pdf_buffer *buf, const char *text)
1897 {
1898   pdf_put(buf, text, strlen(text));
1899 }
1900
1901 static void pdf_indent(pdf_buffer *buf)
1902 {
1903   pdf_puts(buf, "\t");
1904 }
1905
1906 static void pdf_putsi(pdf_buffer *buf, const char *text)
1907 {
1908   pdf_indent(buf);
1909   pdf_puts(buf, text);
1910 }
1911
1912 static void pdf_putint(pdf_buffer *buf, int i)
1913 {
1914   char tmp[20];
1915   sprintf(tmp, "%d", i);
1916   pdf_puts(buf, tmp);
1917 }
1918
1919 static void pdf_putnumber(pdf_buffer *buf, double d)
1920 {
1921   char tmp[50];
1922   svg_format_number(tmp, sizeof(tmp), d);
1923   pdf_puts(buf, tmp);
1924 }
1925
1926 static void pdf_put_string_contents(pdf_buffer *buf, const char *text)
1927 {
1928     const char *p = text;
1929     while (1) {
1930         char ch = *p;
1931         switch (ch) {
1932             case 0: return;
1933             case '(':
1934             case ')':
1935             case '\\':
1936             case '\n':
1937             case '\r':
1938             case '\t':
1939                 pdf_puts(buf, "\\");
1940                 pdf_put(buf, (char)ch, 1);
1941                 break;
1942             default:
1943                 if (ch >= 126 || ch < 32) {
1944                     char tmp[10];
1945                     snprintf(tmp, sizeof(tmp), "\\%03o", ch);
1946                     pdf_puts(buf, tmp);
1947                 } else {
1948                     pdf_put(buf, p, 1);
1949                 }
1950         }
1951         p++;
1952     }
1953 }
1954
1955 static void pdf_init_object(pdf_state *state, pdf_buffer *buf)
1956 {
1957   pdf_init_buffer(state, buf);
1958   buf->id = ++state->last_obj_id;
1959   buf->is_obj = 1;
1960   buf->is_stream = 0;
1961 }
1962
1963 static void pdf_init_dict(pdf_state *state, pdf_buffer *buf)
1964 {
1965   pdf_init_object(state, buf);
1966   buf->is_dict = 1;
1967 }
1968
1969 static void pdf_set_color(pdf_buffer *buf, gfx_color_t color,
1970         gfx_color_t *current_color, const char *op)
1971 {
1972 #if USE_PDF_FAKE_ALPHA
1973    double a1, a2;
1974 #endif
1975    /* gfx_color_t is RRGGBBAA */
1976   if (*current_color == color)
1977     return;
1978 #if USE_PDF_FAKE_ALPHA
1979   a1 = (color & 255) / 255.0;
1980   a2 = 1 - a1;
1981 #define pdf_color_calc(x) ( ((x)  & 255) / 255.0 * a1 + a2)
1982 #else
1983 #define pdf_color_calc(x) ( ((x)  & 255) / 255.0)
1984 #endif
1985   pdf_putnumber(buf, pdf_color_calc(color >> 24));
1986   pdf_puts(buf, " ");
1987   pdf_putnumber(buf, pdf_color_calc(color >> 16));
1988   pdf_puts(buf, " ");
1989   pdf_putnumber(buf, pdf_color_calc(color >>  8));
1990   pdf_puts(buf, " ");
1991   pdf_puts(buf, op);
1992   pdf_puts(buf, "\n");
1993   *current_color = color;
1994 }
1995
1996 static void pdf_set_stroke_color(pdf_buffer *buf, gfx_color_t color)
1997 {
1998     pdf_set_color(buf, color, &buf->state->stroke_color, "RG");
1999 }
2000
2001 static void pdf_set_fill_color(pdf_buffer *buf, gfx_color_t color)
2002 {
2003     pdf_set_color(buf, color, &buf->state->fill_color, "rg");
2004 }
2005
2006 static pdf_font *pdf_find_font(pdf_state *state, gfx_node_t *node)
2007 {
2008   const char *ps_font = afm_get_font_postscript_name(node->filename);
2009   pdf_font *ef;
2010   for (ef = state->font_list; ef; ef = ef->next) {
2011     if (!strcmp(ps_font, ef->ps_font))
2012       return ef;
2013   }
2014   return NULL;
2015 }
2016
2017 static void pdf_add_font(pdf_state *state, gfx_node_t *node)
2018 {
2019   pdf_font *ef = pdf_find_font(state, node);
2020   if (ef)
2021     return;
2022   ef = malloc(sizeof(pdf_font));
2023   if (ef == NULL) {
2024     rrd_set_error("malloc for pdf_font");
2025     state->has_failed = 1;
2026     return;
2027   }
2028   pdf_init_dict(state, &ef->obj);
2029   ef->next = state->font_list;
2030   ef->ps_font = afm_get_font_postscript_name(node->filename);
2031   state->font_list = ef;
2032   /* fonts dict */
2033   pdf_putsi(&state->fontsdict_obj, "/F");
2034   pdf_putint(&state->fontsdict_obj, ef->obj.id);
2035   pdf_puts(&state->fontsdict_obj, " ");
2036   pdf_putint(&state->fontsdict_obj, ef->obj.id);
2037   pdf_puts(&state->fontsdict_obj, " 0 R\n");
2038   /* fonts def */
2039   pdf_putsi(&ef->obj, "/Type /Font\n");
2040   pdf_putsi(&ef->obj, "/Subtype /Type1\n");
2041   pdf_putsi(&ef->obj, "/Name /F");
2042   pdf_putint(&ef->obj, ef->obj.id);
2043   pdf_puts(&ef->obj, "\n");
2044   pdf_putsi(&ef->obj, "/BaseFont /");
2045   pdf_puts(&ef->obj, ef->ps_font);
2046   pdf_puts(&ef->obj, "\n");
2047   pdf_putsi(&ef->obj, "/Encoding /WinAnsiEncoding\n");
2048   /*  'Cp1252' (this is latin 1 extended with 27 characters;
2049       the encoding is also known as 'winansi')
2050       http://www.lowagie.com/iText/tutorial/ch09.html */
2051 }
2052
2053 static void pdf_create_fonts(pdf_state *state)
2054 {
2055   gfx_node_t *node;
2056   for (node = state->canvas->firstnode; node; node = node->next) {
2057     if (node->type == GFX_TEXT)
2058       pdf_add_font(state, node);
2059   }
2060 }
2061
2062 static void pdf_write_linearea(pdf_state *state, gfx_node_t *node)
2063 {
2064   int i;
2065   pdf_buffer *s = &state->graph_stream;
2066   if (node->type == GFX_LINE) {
2067     svg_dash dash_info;
2068     svg_get_dash(node, &dash_info);
2069     if (!svg_dash_equal(&dash_info, &state->dash)) {
2070       state->dash = dash_info;
2071       if (dash_info.dash_enable) {
2072         pdf_puts(s, "[");
2073         pdf_putnumber(s, dash_info.adjusted_on);
2074         pdf_puts(s, " ");
2075         pdf_putnumber(s, dash_info.adjusted_off);
2076         pdf_puts(s, "] ");
2077         pdf_putnumber(s, dash_info.dash_offset);
2078         pdf_puts(s, " d\n");
2079       } else {
2080         pdf_puts(s, "[] 0 d\n");
2081       }
2082     }
2083     pdf_set_stroke_color(s, node->color);
2084     if (state->linecap != 1) {
2085       pdf_puts(s, "1 j\n");
2086       state->linecap = 1;
2087     }
2088     if (state->linejoin != 1) {
2089       pdf_puts(s, "1 J\n");
2090       state->linejoin = 1;
2091     }
2092     if (node->size != state->line_width) {
2093       state->line_width = node->size;
2094       pdf_putnumber(s, state->line_width);
2095       pdf_puts(s, " w\n");
2096     }
2097   } else {
2098     pdf_set_fill_color(s, node->color);
2099   }
2100   for (i = 0; i < node->points; i++) {
2101     ArtVpath *vec = node->path + i;
2102     double x = vec->x;
2103     double y = state->page_height - vec->y;
2104     if (node->type == GFX_AREA) {
2105       x += LINEOFFSET; /* adjust for libart handling of areas */
2106       y -= LINEOFFSET;
2107     }
2108     switch (vec->code) {
2109     case ART_MOVETO_OPEN: /* fall-through */
2110     case ART_MOVETO:
2111       pdf_putnumber(s, x);
2112       pdf_puts(s, " ");
2113       pdf_putnumber(s, y);
2114       pdf_puts(s, " m\n");
2115       break;
2116     case ART_LINETO:
2117       pdf_putnumber(s, x);
2118       pdf_puts(s, " ");
2119       pdf_putnumber(s, y);
2120       pdf_puts(s, " l\n");
2121       break;
2122     case ART_CURVETO: break; /* unsupported */
2123     case ART_END: break; /* nop */
2124     }
2125   }
2126   if (node->type == GFX_LINE) {
2127     pdf_puts(s, node->closed_path ? "s\n" : "S\n");
2128    } else {
2129     pdf_puts(s, "f\n");
2130    }
2131 }
2132
2133
2134 static void pdf_write_matrix(pdf_state *state, gfx_node_t *node, pdf_coords *g, int useTM)
2135 {
2136         char tmp[150];
2137         pdf_buffer *s = &state->graph_stream;
2138         if (node->angle == 0) {
2139                 pdf_puts(s, "1 0 0 1 ");
2140                 pdf_putnumber(s, useTM ? g->tmx : g->mx);
2141                 pdf_puts(s, " ");
2142                 pdf_putnumber(s, useTM ? g->tmy : g->my);
2143         } else {
2144                  /* can't use svg_write_number as 2 decimals is far from enough to avoid
2145                         skewed text */
2146                 sprintf(tmp, "%f %f %f %f %f %f",
2147                                 g->ma, g->mb, g->mc, g->md, 
2148                                 useTM ? g->tmx : g->mx,
2149                                 useTM ? g->tmy : g->my);
2150                 pdf_puts(s, tmp);
2151         }
2152 }
2153
2154 static void pdf_write_text(pdf_state *state, gfx_node_t *node, 
2155     int last_was_text, int next_is_text)
2156 {
2157   pdf_coords g;
2158   pdf_buffer *s = &state->graph_stream;
2159   pdf_font *font = pdf_find_font(state, node);
2160   if (font == NULL) {
2161     rrd_set_error("font disappeared");
2162     state->has_failed = 1;
2163     return;
2164   }
2165   pdf_calc(state->page_height, node, &g);
2166 #if PDF_CALC_DEBUG
2167   pdf_puts(s, "q % debug green box\n");
2168   pdf_write_matrix(state, node, &g, 0);
2169   pdf_puts(s, " cm\n");
2170   pdf_set_fill_color(s, 0x90FF9000);
2171   pdf_puts(s, "0 0.4 0 rg\n");
2172   pdf_puts(s, "0 0 ");
2173   pdf_putnumber(s, g.sizep.x);
2174   pdf_puts(s, " ");
2175   pdf_putnumber(s, g.sizep.y);
2176   pdf_puts(s, " re\n");
2177   pdf_puts(s, "f\n");
2178   pdf_puts(s, "Q\n");
2179 #endif
2180   pdf_set_fill_color(s, node->color);
2181   if (PDF_CALC_DEBUG || !last_was_text)
2182     pdf_puts(s, "BT\n");
2183   if (state->font_id != font->obj.id || node->size != state->font_size) {
2184     state->font_id = font->obj.id;
2185     state->font_size = node->size;
2186     pdf_puts(s, "/F");
2187     pdf_putint(s, font->obj.id);
2188     pdf_puts(s, " ");
2189     pdf_putnumber(s, node->size);
2190     pdf_puts(s, " Tf\n");
2191   }
2192   pdf_write_matrix(state, node, &g, 1);
2193   pdf_puts(s, " Tm\n");
2194   pdf_puts(s, "(");
2195   pdf_put_string_contents(s, node->text);
2196   pdf_puts(s, ") Tj\n");
2197   if (PDF_CALC_DEBUG || !next_is_text)
2198     pdf_puts(s, "ET\n");
2199 }
2200  
2201 static void pdf_write_content(pdf_state *state)
2202 {
2203   gfx_node_t *node;
2204   int last_was_text = 0, next_is_text;
2205   for (node = state->canvas->firstnode; node; node = node->next) {
2206     switch (node->type) {
2207     case GFX_LINE:
2208     case GFX_AREA:
2209       pdf_write_linearea(state, node);
2210       break;
2211     case GFX_TEXT:
2212       next_is_text = node->next && node->next->type == GFX_TEXT;
2213       pdf_write_text(state, node, last_was_text, next_is_text);
2214       break;
2215     }
2216     last_was_text = node->type == GFX_TEXT;
2217   }
2218 }
2219
2220 static void pdf_init_document(pdf_state *state)
2221 {
2222   pdf_init_buffer(state, &state->pdf_header);
2223   pdf_init_dict(state, &state->catalog_obj);
2224   pdf_init_dict(state, &state->info_obj);
2225   pdf_init_dict(state, &state->pages_obj);
2226   pdf_init_dict(state, &state->page1_obj);
2227   pdf_init_dict(state, &state->fontsdict_obj);
2228   pdf_create_fonts(state);
2229   if (state->has_failed)
2230     return;
2231   /* make stream last object in file */
2232   pdf_init_object(state, &state->graph_stream);
2233   state->graph_stream.is_stream = 1;
2234 }
2235
2236 static void pdf_setup_document(pdf_state *state)
2237 {
2238   const char *creator = "RRDtool 1.2.4 Tobias Oetiker, http://tobi.oetiker.ch";
2239   /* all objects created by now, so init code can reference them */
2240   /* HEADER */
2241   pdf_puts(&state->pdf_header, "%PDF-1.3\n");
2242   /* following 8 bit comment is recommended by Adobe for
2243      indicating binary file to file transfer applications */
2244   pdf_puts(&state->pdf_header, "%\xE2\xE3\xCF\xD3\n");
2245   /* INFO */
2246   pdf_putsi(&state->info_obj, "/Creator (");
2247   pdf_put_string_contents(&state->info_obj, creator);
2248   pdf_puts(&state->info_obj, ")\n");
2249   /* CATALOG */
2250   pdf_putsi(&state->catalog_obj, "/Type /Catalog\n");
2251   pdf_putsi(&state->catalog_obj, "/Pages ");
2252   pdf_putint(&state->catalog_obj, state->pages_obj.id);
2253   pdf_puts(&state->catalog_obj, " 0 R\n");
2254   /* PAGES */
2255   pdf_putsi(&state->pages_obj, "/Type /Pages\n");
2256   pdf_putsi(&state->pages_obj, "/Kids [");
2257   pdf_putint(&state->pages_obj, state->page1_obj.id);
2258   pdf_puts(&state->pages_obj, " 0 R]\n");
2259   pdf_putsi(&state->pages_obj, "/Count 1\n");
2260   /* PAGE 1 */
2261   pdf_putsi(&state->page1_obj, "/Type /Page\n");
2262   pdf_putsi(&state->page1_obj, "/Parent ");
2263   pdf_putint(&state->page1_obj, state->pages_obj.id);
2264   pdf_puts(&state->page1_obj, " 0 R\n");
2265   pdf_putsi(&state->page1_obj, "/MediaBox [0 0 ");
2266   pdf_putint(&state->page1_obj, state->page_width);
2267   pdf_puts(&state->page1_obj, " ");
2268   pdf_putint(&state->page1_obj, state->page_height);
2269   pdf_puts(&state->page1_obj, "]\n");
2270   pdf_putsi(&state->page1_obj, "/Contents ");
2271   pdf_putint(&state->page1_obj, state->graph_stream.id);
2272   pdf_puts(&state->page1_obj, " 0 R\n");
2273   pdf_putsi(&state->page1_obj, "/Resources << /Font ");
2274   pdf_putint(&state->page1_obj, state->fontsdict_obj.id);
2275   pdf_puts(&state->page1_obj, " 0 R >>\n");
2276 }
2277
2278 static void pdf_write_string_to_file(pdf_state *state, const char *text)
2279 {
2280     fputs(text, state->fp);
2281     state->pdf_file_pos += strlen(text);
2282 }
2283
2284 static void pdf_write_buf_to_file(pdf_state *state, pdf_buffer *buf)
2285 {
2286   char tmp[40];
2287   buf->pdf_file_pos = state->pdf_file_pos;
2288   if (buf->is_obj) {
2289     snprintf(tmp, sizeof(tmp), "%d 0 obj\n", buf->id);
2290     pdf_write_string_to_file(state, tmp);
2291   }
2292   if (buf->is_dict)
2293     pdf_write_string_to_file(state, "<<\n");
2294   if (buf->is_stream) {
2295     snprintf(tmp, sizeof(tmp), "<< /Length %d >>\n", buf->current_size);
2296     pdf_write_string_to_file(state, tmp);
2297     pdf_write_string_to_file(state, "stream\n");
2298   }
2299   fwrite(buf->data, 1, buf->current_size, state->fp);
2300   state->pdf_file_pos += buf->current_size;
2301   if (buf->is_stream)
2302     pdf_write_string_to_file(state, "endstream\n");
2303   if (buf->is_dict)
2304     pdf_write_string_to_file(state, ">>\n");
2305   if (buf->is_obj)
2306     pdf_write_string_to_file(state, "endobj\n");
2307 }
2308
2309 static void pdf_write_to_file(pdf_state *state)
2310 {
2311   pdf_buffer *buf = state->first_buffer;
2312   int xref_pos;
2313   state->pdf_file_pos = 0;
2314   pdf_write_buf_to_file(state, &state->pdf_header);
2315   while (buf) {
2316     if (buf->is_obj)
2317       pdf_write_buf_to_file(state, buf);
2318     buf = buf->next_buffer;
2319   }
2320   xref_pos = state->pdf_file_pos;
2321   fprintf(state->fp, "xref\n");
2322   fprintf(state->fp, "%d %d\n", 0, state->last_obj_id + 1);
2323   /* TOC lines must be exactly 20 bytes including \n */
2324   fprintf(state->fp, "%010d %05d f\x20\n", 0, 65535);
2325   for (buf = state->first_buffer; buf; buf = buf->next_buffer) {
2326     if (buf->is_obj)
2327       fprintf(state->fp, "%010d %05d n\x20\n", buf->pdf_file_pos, 0);
2328   }
2329   fprintf(state->fp, "trailer\n");
2330   fprintf(state->fp, "<<\n");
2331   fprintf(state->fp, "\t/Size %d\n", state->last_obj_id + 1);
2332   fprintf(state->fp, "\t/Root %d 0 R\n", state->catalog_obj.id);
2333   fprintf(state->fp, "\t/Info %d 0 R\n", state->info_obj.id);
2334   fprintf(state->fp, ">>\n");
2335   fprintf(state->fp, "startxref\n");
2336   fprintf(state->fp, "%d\n", xref_pos);
2337   fputs("%%EOF\n", state->fp);
2338 }
2339
2340 static void pdf_free_resources(pdf_state *state)
2341 {
2342   pdf_buffer *buf = state->first_buffer;
2343   while (buf) {
2344     free(buf->data);
2345     buf->data = NULL;
2346     buf->alloc_size = buf->current_size = 0;
2347     buf = buf->next_buffer;
2348   }
2349   while (state->font_list) {
2350     pdf_font *next = state->font_list->next;
2351     free(state->font_list);
2352     state->font_list = next;
2353   }
2354 }
2355
2356 int       gfx_render_pdf (gfx_canvas_t *canvas,
2357                  art_u32 width, art_u32 height,
2358                  gfx_color_t UNUSED(background), FILE *fp){
2359   struct pdf_state state;
2360   memset(&state, 0, sizeof(pdf_state));
2361   state.fp = fp;
2362   state.canvas = canvas;
2363   state.page_width = width;
2364   state.page_height = height;
2365   state.font_id = -1;
2366   state.font_size = -1;
2367   state.font_list = NULL;
2368   state.linecap = -1;
2369   state.linejoin = -1;
2370   pdf_init_document(&state);
2371   /*
2372   pdf_set_color(&state, background);
2373   fprintf(fp, "0 0 M 0 %d L %d %d L %d 0 L fill\n",
2374       height, width, height, width);
2375   */
2376   if (!state.has_failed)
2377     pdf_write_content(&state);
2378   if (!state.has_failed)
2379     pdf_setup_document(&state);
2380   if (!state.has_failed)
2381     pdf_write_to_file(&state);
2382   pdf_free_resources(&state);
2383   return state.has_failed ? -1 : 0;
2384 }
2385