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