EPS/SVG/PDF code ... more comments and better font finder including removal of hardc...
[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 = "-dummy-";
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    const char *fontname;
1345    /* as svg has 0,0 in top-left corner (like most screens) instead of
1346           bottom-left corner like pdf and eps, we have to fake the coords
1347           using offset and inverse sin(r) value */
1348    int page_height = 1000;
1349    pdf_calc(page_height, node, &g);
1350    if (node->angle != 0) {
1351      svg_start_tag(fp, "g");
1352          /* can't use svg_write_number as 2 decimals is far from enough to avoid
1353                 skewed text */
1354      fprintf(fp, " transform=\"matrix(%f,%f,%f,%f,%f,%f)\"",
1355                          g.ma, -g.mb, -g.mc, g.md, g.tmx, page_height - g.tmy);
1356      svg_close_tag(fp);
1357    }
1358    svg_start_tag(fp, "text");
1359    if (!node->angle) {
1360      fputs(" x=\"", fp);
1361      svg_write_number(fp, g.tmx);
1362      fputs("\" y=\"", fp);
1363      svg_write_number(fp, page_height - g.tmy);
1364      fputs("\"", fp);
1365    }
1366    fontname = afm_get_font_name(node->filename);
1367    if (strcmp(fontname, svg_default_font))
1368      fprintf(fp, " font-family=\"%s\"", fontname);
1369    fputs(" font-size=\"", fp);
1370    svg_write_number(fp, node->size);
1371    fputs("\"", fp);
1372   if (!svg_color_is_black(node->color))
1373     svg_write_color(fp, node->color, "fill");
1374    svg_close_tag_single_line(fp);
1375    /* support for node->tabwidth missing */
1376    svg_write_text(fp, node->text);
1377    svg_end_tag(fp, "text");
1378    if (node->angle != 0)
1379      svg_end_tag(fp, "g");
1380 }
1381  
1382 int       gfx_render_svg (gfx_canvas_t *canvas,
1383                  art_u32 width, art_u32 height,
1384                  gfx_color_t background, FILE *fp){
1385    gfx_node_t *node = canvas->firstnode;
1386    /* Find the first font used, and assume it is the mostly used
1387           one. It reduces the number of font-familty attributes. */
1388    while (node) {
1389            if (node->type == GFX_TEXT && node->filename) {
1390                    svg_default_font = afm_get_font_name(node->filename);
1391                    break;
1392            }
1393            node = node->next;
1394    }
1395    fputs(
1396 "<?xml version=\"1.0\" standalone=\"no\"?>\n"
1397 "<!DOCTYPE svg PUBLIC \"-//W3C//DTD SVG 1.0//EN\"\n"
1398 "   \"http://www.w3.org/TR/2001/REC-SVG-20010904/DTD/svg10.dtd\">\n"
1399 "<!--\n"
1400 "   SVG file created by\n"
1401 "        RRDtool 1.2.4 Tobias Oetiker, http://tobi.oetiker.ch\n"
1402 "\n"
1403 "   The width/height attributes in the outhermost svg node\n"
1404 "   are just default sizes for the browser which is used\n"
1405 "   if the svg file is openened directly without being\n"
1406 "   embedded in an html file.\n"
1407 "   The viewBox is the local coord system for rrdtool.\n"
1408 "-->\n", fp);
1409    svg_start_tag(fp, "svg");
1410    fputs(" width=\"", fp);
1411   svg_write_number(fp, width * canvas->zoom);
1412    fputs("\" height=\"", fp);
1413   svg_write_number(fp, height * canvas->zoom);
1414    fputs("\" x=\"0\" y=\"0\" viewBox=\"", fp);
1415    svg_write_number(fp, -LINEOFFSET);
1416    fputs(" ", fp);
1417    svg_write_number(fp, -LINEOFFSET);
1418    fputs(" ", fp);
1419    svg_write_number(fp, width - LINEOFFSET);
1420    fputs(" ", fp);
1421    svg_write_number(fp, height - LINEOFFSET);
1422    fputs("\" preserveAspectRatio=\"xMidYMid\"", fp);
1423   fprintf(fp, " font-family=\"%s\"", svg_default_font); /* default font */
1424   fputs(" stroke-linecap=\"round\" stroke-linejoin=\"round\"", fp);
1425    svg_close_tag(fp);
1426    svg_start_tag(fp, "rect");
1427    fprintf(fp, " x=\"0\" y=\"0\" width=\"%d\" height=\"%d\"", width, height);
1428   svg_write_color(fp, background, "fill");
1429    svg_close_tag_empty_node(fp);
1430    node = canvas->firstnode;
1431    while (node) {
1432      switch (node->type) {
1433      case GFX_LINE:
1434        svg_multi_path(fp, &node);
1435        break;
1436      case GFX_AREA:
1437        svg_area(fp, node);
1438        break;
1439      case GFX_TEXT:
1440        svg_text(fp, node);
1441      }
1442      node = node->next;
1443    }
1444    svg_end_tag(fp, "svg");
1445    return 0;
1446 }
1447
1448 /* ------- EPS -------
1449    EPS and Postscript references:
1450    http://partners.adobe.com/asn/developer/technotes/postscript.html
1451 */
1452
1453 typedef struct eps_font
1454 {
1455   const char *ps_font;
1456   int id;
1457   struct eps_font *next;
1458 } eps_font;
1459
1460 typedef struct eps_state
1461 {
1462   FILE *fp;
1463   gfx_canvas_t *canvas;
1464   art_u32 page_width, page_height;
1465   eps_font *font_list;
1466   /*--*/
1467   gfx_color_t color;
1468   const char *font;
1469   double font_size;
1470   double line_width;
1471   int linecap, linejoin;
1472   int has_dash;
1473 } eps_state;
1474
1475 static void eps_set_color(eps_state *state, gfx_color_t color)
1476 {
1477 #if USE_EPS_FAKE_ALPHA
1478    double a1, a2;
1479 #endif
1480    /* gfx_color_t is RRGGBBAA */
1481   if (state->color == color)
1482     return;
1483 #if USE_EPS_FAKE_ALPHA
1484   a1 = (color & 255) / 255.0;
1485   a2 = 255 * (1 - a1);
1486 #define eps_color_calc(x) (int)( ((x) & 255) * a1 + a2)
1487 #else
1488 #define eps_color_calc(x) (int)( (x) & 255)
1489 #endif
1490    /* gfx_color_t is RRGGBBAA */
1491   if (state->color == color)
1492     return;
1493   fprintf(state->fp, "%d %d %d Rgb\n",
1494       eps_color_calc(color >> 24),
1495       eps_color_calc(color >> 16),
1496       eps_color_calc(color >>  8));
1497   state->color = color;
1498 }
1499
1500 static int eps_add_font(eps_state *state, gfx_node_t *node)
1501 {
1502   /* The fonts list could be postponed to the end using
1503      (atend), but let's be nice and have them in the header. */
1504   const char *ps_font = afm_get_font_postscript_name(node->filename);
1505   eps_font *ef;
1506   for (ef = state->font_list; ef; ef = ef->next) {
1507     if (!strcmp(ps_font, ef->ps_font))
1508       return 0;
1509   }
1510   ef = malloc(sizeof(eps_font));
1511   if (ef == NULL) {
1512     rrd_set_error("malloc for eps_font");
1513     return -1;
1514   }
1515   ef->next = state->font_list;
1516   ef->ps_font = ps_font;
1517   state->font_list = ef;
1518   return 0;
1519 }
1520
1521 static void eps_list_fonts(eps_state *state, const char *dscName)
1522 {
1523   eps_font *ef;
1524   int lineLen = strlen(dscName);
1525   if (!state->font_list)
1526     return;
1527   fputs(dscName, state->fp);
1528   for (ef = state->font_list; ef; ef = ef->next) {
1529     int nameLen = strlen(ef->ps_font);
1530     if (lineLen + nameLen > 100 && lineLen) {
1531       fputs("\n", state->fp);
1532       fputs("%%- \n", state->fp);
1533       lineLen = 5;
1534     } else {
1535       fputs(" ", state->fp);
1536       lineLen++;
1537     }
1538     fputs(ef->ps_font, state->fp);
1539     lineLen += nameLen;
1540   }
1541   fputs("\n", state->fp);
1542 }
1543
1544 static void eps_define_fonts(eps_state *state)
1545 {
1546   eps_font *ef;
1547   if (!state->font_list)
1548     return;
1549   for (ef = state->font_list; ef; ef = ef->next) {
1550     /* PostScript¨ LANGUAGE REFERENCE third edition
1551        page 349 */
1552     fprintf(state->fp,
1553         "%%\n"
1554         "/%s findfont dup length dict begin\n"
1555         "{ 1 index /FID ne {def} {pop pop} ifelse } forall\n"
1556         "/Encoding ISOLatin1Encoding def\n"
1557         "currentdict end\n"
1558         "/%s-ISOLatin1 exch definefont pop\n"
1559         "/SetFont-%s { /%s-ISOLatin1 findfont exch scalefont setfont } bd\n",
1560         ef->ps_font, ef->ps_font, ef->ps_font, ef->ps_font);
1561   }
1562 }
1563
1564 static int eps_prologue(eps_state *state)
1565 {
1566   gfx_node_t *node;
1567   fputs(
1568     "%!PS-Adobe-3.0 EPSF-3.0\n"
1569     "%%Creator: RRDtool 1.2.4 Tobias Oetiker, http://tobi.oetiker.ch\n"
1570     /* can't like weird chars here */
1571     "%%Title: (RRDtool output)\n"
1572     "%%DocumentData: Clean7Bit\n"
1573     "", state->fp);
1574   fprintf(state->fp, "%%%%BoundingBox: 0 0 %d %d\n",
1575     state->page_width, state->page_height);
1576   for (node = state->canvas->firstnode; node; node = node->next) {
1577     if (node->type == GFX_TEXT && eps_add_font(state, node) == -1)
1578       return -1;
1579   }
1580   eps_list_fonts(state, "%%DocumentFonts:");
1581   eps_list_fonts(state, "%%DocumentNeededFonts:");
1582   fputs(
1583       "%%EndComments\n"
1584       "%%BeginProlog\n"
1585       "%%EndProlog\n" /* must have, or BoundingBox is ignored */
1586       "/bd { bind def } bind def\n"
1587       "", state->fp);
1588   fprintf(state->fp, "/X { %.2f add } bd\n", LINEOFFSET);
1589   fputs(
1590       "/X2 {X exch X exch} bd\n"
1591       "/M {X2 moveto} bd\n"
1592       "/L {X2 lineto} bd\n"
1593       "/m {moveto} bd\n"
1594       "/l {lineto} bd\n"
1595       "/S {stroke} bd\n"
1596       "/CP {closepath} bd\n"
1597       "/WS {setlinewidth stroke} bd\n"
1598       "/F {fill} bd\n"
1599       "/T1 {gsave} bd\n"
1600       "/T2 {concat 0 0 moveto show grestore} bd\n"
1601       "/T   {moveto show} bd\n"
1602       "/Rgb { 255.0 div 3 1 roll\n"
1603       "       255.0 div 3 1 roll \n"
1604       "       255.0 div 3 1 roll setrgbcolor } bd\n"
1605       "", state->fp);
1606   eps_define_fonts(state);
1607   return 0;
1608 }
1609
1610 static void eps_clear_dash(eps_state *state)
1611 {
1612   if (!state->has_dash)
1613     return;
1614   state->has_dash = 0;
1615   fputs("[1 0] 0 setdash\n", state->fp);
1616 }
1617
1618 static void eps_write_linearea(eps_state *state, gfx_node_t *node)
1619 {
1620   int i;
1621   FILE *fp = state->fp;
1622   int useOffset = 0;
1623   int clearDashIfAny = 1;
1624   eps_set_color(state, node->color);
1625   if (node->type == GFX_LINE) {
1626     svg_dash dash_info;
1627     if (state->linecap != 1) {
1628       fputs("1 setlinecap\n", fp);
1629       state->linecap = 1;
1630     }
1631     if (state->linejoin != 1) {
1632       fputs("1 setlinejoin\n", fp);
1633       state->linejoin = 1;
1634     }
1635     svg_get_dash(node, &dash_info);
1636     if (dash_info.dash_enable) {
1637       clearDashIfAny = 0;
1638       state->has_dash = 1;
1639       fputs("[", fp);
1640       svg_write_number(fp, dash_info.adjusted_on);
1641       fputs(" ", fp);
1642       svg_write_number(fp, dash_info.adjusted_off);
1643       fputs("] ", fp);
1644       svg_write_number(fp, dash_info.dash_offset);
1645       fputs(" setdash\n", fp);
1646     }
1647   }
1648   if (clearDashIfAny)
1649     eps_clear_dash(state);
1650   for (i = 0; i < node->points; i++) {
1651     ArtVpath *vec = node->path + i;
1652     double x = vec->x;
1653     double y = state->page_height - vec->y;
1654     if (vec->code == ART_MOVETO_OPEN || vec->code == ART_MOVETO)
1655       useOffset = (fabs(x - floor(x) - 0.5) < 0.01 && fabs(y - floor(y) - 0.5) < 0.01);
1656     if (useOffset) {
1657       x -= LINEOFFSET;
1658       y -= LINEOFFSET;
1659     }
1660     switch (vec->code) {
1661     case ART_MOVETO_OPEN: /* fall-through */
1662     case ART_MOVETO:
1663       svg_write_number(fp, x);
1664       fputc(' ', fp);
1665       svg_write_number(fp, y);
1666       fputc(' ', fp);
1667       fputs(useOffset ? "M\n" : "m\n", fp);
1668       break;
1669     case ART_LINETO:
1670       svg_write_number(fp, x);
1671       fputc(' ', fp);
1672       svg_write_number(fp, y);
1673       fputc(' ', fp);
1674       fputs(useOffset ? "L\n" : "l\n", fp);
1675       break;
1676     case ART_CURVETO: break; /* unsupported */
1677     case ART_END: break; /* nop */
1678     }
1679   }
1680   if (node->type == GFX_LINE) {
1681     if (node->closed_path)
1682       fputs("CP ", fp);
1683     if (node->size != state->line_width) {
1684       state->line_width = node->size;
1685       svg_write_number(fp, state->line_width);
1686       fputs(" WS\n", fp);
1687     } else {
1688       fputs("S\n", fp);
1689     }
1690    } else {
1691     fputs("F\n", fp);
1692    }
1693 }
1694
1695 static void eps_write_text(eps_state *state, gfx_node_t *node)
1696 {
1697   FILE *fp = state->fp;
1698   const unsigned char *p;
1699   const char *ps_font = afm_get_font_postscript_name(node->filename);
1700   int lineLen = 0;
1701   pdf_coords g;
1702   pdf_calc(state->page_height, node, &g);
1703   eps_set_color(state, node->color);
1704   if (strcmp(ps_font, state->font) || node->size != state->font_size) {
1705     state->font = ps_font;
1706     state->font_size = node->size;
1707     svg_write_number(fp, state->font_size);
1708     fprintf(fp, " SetFont-%s\n", state->font);
1709   }
1710   if (node->angle)
1711           fputs("T1 ", fp);
1712   fputs("(", fp);
1713   lineLen = 20;
1714   for (p = (const unsigned char*)node->text; *p; p++) {
1715     if (lineLen > 70) {
1716       fputs("\\\n", fp); /* backslash and \n */
1717       lineLen = 0;
1718     }
1719     switch (*p) {
1720       case '(':
1721       case ')':
1722       case '\\':
1723       case '\n':
1724       case '\r':
1725       case '\t':
1726         fputc('\\', fp);
1727         lineLen++;
1728         /* fall-through */
1729       default:
1730         if (*p >= 126)
1731           fprintf(fp, "\\%03o", *p);
1732         else
1733           fputc(*p, fp);
1734         lineLen++;
1735     }
1736   }
1737   if (node->angle) {
1738          /* can't use svg_write_number as 2 decimals is far from enough to avoid
1739                 skewed text */
1740           fprintf(fp, ") [%f %f %f %f %f %f] T2\n",
1741                           g.ma, g.mb, g.mc, g.md, g.tmx, g.tmy);
1742   } else {
1743           fputs(") ", fp);
1744           svg_write_number(fp, g.tmx);
1745           fputs(" ", fp);
1746           svg_write_number(fp, g.tmy);
1747           fputs(" T\n", fp);
1748   }
1749 }
1750
1751 static int eps_write_content(eps_state *state)
1752 {
1753   gfx_node_t *node;
1754   fputs("%\n", state->fp);
1755   for (node = state->canvas->firstnode; node; node = node->next) {
1756     switch (node->type) {
1757     case GFX_LINE:
1758     case GFX_AREA:
1759       eps_write_linearea(state, node);
1760       break;
1761     case GFX_TEXT:
1762       eps_write_text(state, node);
1763       break;
1764     }
1765   }
1766   return 0;
1767 }
1768
1769 int       gfx_render_eps (gfx_canvas_t *canvas,
1770                  art_u32 width, art_u32 height,
1771                  gfx_color_t background, FILE *fp){
1772   struct eps_state state;
1773   state.fp = fp;
1774   state.canvas = canvas;
1775   state.page_width = width;
1776   state.page_height = height;
1777   state.font = "no-default-font";
1778   state.font_size = -1;
1779   state.color = 0; /* black */
1780   state.font_list = NULL;
1781   state.linecap = -1;
1782   state.linejoin = -1;
1783   state.has_dash = 0;
1784   if (eps_prologue(&state) == -1)
1785     return -1;
1786   eps_set_color(&state, background);
1787   fprintf(fp, "0 0 M 0 %d L %d %d L %d 0 L fill\n",
1788       height, width, height, width);
1789   if (eps_write_content(&state) == -1)
1790     return 0;
1791   fputs("showpage\n", fp);
1792   fputs("%%EOF\n", fp);
1793   while (state.font_list) {
1794     eps_font *next = state.font_list->next;
1795     free(state.font_list);
1796     state.font_list = next;
1797   }
1798   return 0;
1799 }
1800
1801 /* ------- PDF -------
1802    PDF references page:
1803    http://partners.adobe.com/public/developer/pdf/index_reference.html
1804 */
1805
1806 typedef struct pdf_buffer
1807 {
1808   int id, is_obj, is_dict, is_stream, pdf_file_pos;
1809   char *data;
1810   int alloc_size, current_size;
1811   struct pdf_buffer *previous_buffer, *next_buffer;
1812   struct pdf_state *state;
1813 } pdf_buffer;
1814
1815 typedef struct pdf_font
1816 {
1817   const char *ps_font;
1818   pdf_buffer obj;
1819   struct pdf_font *next;
1820 } pdf_font;
1821
1822 typedef struct pdf_state
1823 {
1824   FILE *fp;
1825   gfx_canvas_t *canvas;
1826   art_u32 page_width, page_height;
1827   pdf_font *font_list;
1828   pdf_buffer *first_buffer, *last_buffer;
1829   int pdf_file_pos;
1830   int has_failed;
1831   /*--*/
1832   gfx_color_t stroke_color, fill_color;
1833   int font_id;
1834   double font_size;
1835   double line_width;
1836   svg_dash dash;
1837   int linecap, linejoin;
1838   int last_obj_id;
1839   /*--*/
1840   pdf_buffer pdf_header;
1841   pdf_buffer info_obj, catalog_obj, pages_obj, page1_obj;
1842   pdf_buffer fontsdict_obj;
1843   pdf_buffer graph_stream;
1844 } pdf_state;
1845
1846 static void pdf_init_buffer(pdf_state *state, pdf_buffer *buf)
1847 {
1848   int initial_size = 32;
1849   buf->state = state;
1850   buf->id = -42;
1851   buf->alloc_size = 0;
1852   buf->current_size = 0;
1853   buf->data = (char*)malloc(initial_size);
1854   buf->is_obj = 0;
1855   buf->previous_buffer = NULL;
1856   buf->next_buffer = NULL;
1857   if (buf->data == NULL) {
1858     rrd_set_error("malloc for pdf_buffer data");
1859     state->has_failed = 1;
1860     return;
1861   }
1862   buf->alloc_size = initial_size;
1863   if (state->last_buffer)
1864     state->last_buffer->next_buffer = buf;
1865   if (state->first_buffer == NULL)
1866     state->first_buffer = buf;
1867   buf->previous_buffer = state->last_buffer;
1868   state->last_buffer = buf;
1869 }
1870
1871 static void pdf_put(pdf_buffer *buf, const char *text, int len)
1872 {
1873   if (len <= 0)
1874     return;
1875   if (buf->alloc_size < buf->current_size + len) {
1876     int new_size = buf->alloc_size;
1877     char *new_buf;
1878     while (new_size < buf->current_size + len)
1879       new_size *= 4;
1880     new_buf = (char*)malloc(new_size);
1881     if (new_buf == NULL) {
1882       rrd_set_error("re-malloc for pdf_buffer data");
1883       buf->state->has_failed = 1;
1884       return;
1885     }
1886     memcpy(new_buf, buf->data, buf->current_size);
1887     free(buf->data);
1888     buf->data = new_buf;
1889     buf->alloc_size = new_size;
1890   }
1891   memcpy(buf->data + buf->current_size, text, len);
1892   buf->current_size += len;
1893 }
1894
1895 static void pdf_puts(pdf_buffer *buf, const char *text)
1896 {
1897   pdf_put(buf, text, strlen(text));
1898 }
1899
1900 static void pdf_indent(pdf_buffer *buf)
1901 {
1902   pdf_puts(buf, "\t");
1903 }
1904
1905 static void pdf_putsi(pdf_buffer *buf, const char *text)
1906 {
1907   pdf_indent(buf);
1908   pdf_puts(buf, text);
1909 }
1910
1911 static void pdf_putint(pdf_buffer *buf, int i)
1912 {
1913   char tmp[20];
1914   sprintf(tmp, "%d", i);
1915   pdf_puts(buf, tmp);
1916 }
1917
1918 static void pdf_putnumber(pdf_buffer *buf, double d)
1919 {
1920   char tmp[50];
1921   svg_format_number(tmp, sizeof(tmp), d);
1922   pdf_puts(buf, tmp);
1923 }
1924
1925 static void pdf_put_string_contents(pdf_buffer *buf, const char *text)
1926 {
1927     const char *p = text;
1928     while (1) {
1929         char ch = *p;
1930         switch (ch) {
1931             case 0: return;
1932             case '(':
1933             case ')':
1934             case '\\':
1935             case '\n':
1936             case '\r':
1937             case '\t':
1938                 pdf_puts(buf, "\\");
1939                 pdf_put(buf, (char)ch, 1);
1940                 break;
1941             default:
1942                 if (ch >= 126 || ch < 32) {
1943                     char tmp[10];
1944                     snprintf(tmp, sizeof(tmp), "\\%03o", ch);
1945                     pdf_puts(buf, tmp);
1946                 } else {
1947                     pdf_put(buf, p, 1);
1948                 }
1949         }
1950         p++;
1951     }
1952 }
1953
1954 static void pdf_init_object(pdf_state *state, pdf_buffer *buf)
1955 {
1956   pdf_init_buffer(state, buf);
1957   buf->id = ++state->last_obj_id;
1958   buf->is_obj = 1;
1959   buf->is_stream = 0;
1960 }
1961
1962 static void pdf_init_dict(pdf_state *state, pdf_buffer *buf)
1963 {
1964   pdf_init_object(state, buf);
1965   buf->is_dict = 1;
1966 }
1967
1968 static void pdf_set_color(pdf_buffer *buf, gfx_color_t color,
1969         gfx_color_t *current_color, const char *op)
1970 {
1971 #if USE_PDF_FAKE_ALPHA
1972    double a1, a2;
1973 #endif
1974    /* gfx_color_t is RRGGBBAA */
1975   if (*current_color == color)
1976     return;
1977 #if USE_PDF_FAKE_ALPHA
1978   a1 = (color & 255) / 255.0;
1979   a2 = 1 - a1;
1980 #define pdf_color_calc(x) ( ((x)  & 255) / 255.0 * a1 + a2)
1981 #else
1982 #define pdf_color_calc(x) ( ((x)  & 255) / 255.0)
1983 #endif
1984   pdf_putnumber(buf, pdf_color_calc(color >> 24));
1985   pdf_puts(buf, " ");
1986   pdf_putnumber(buf, pdf_color_calc(color >> 16));
1987   pdf_puts(buf, " ");
1988   pdf_putnumber(buf, pdf_color_calc(color >>  8));
1989   pdf_puts(buf, " ");
1990   pdf_puts(buf, op);
1991   pdf_puts(buf, "\n");
1992   *current_color = color;
1993 }
1994
1995 static void pdf_set_stroke_color(pdf_buffer *buf, gfx_color_t color)
1996 {
1997     pdf_set_color(buf, color, &buf->state->stroke_color, "RG");
1998 }
1999
2000 static void pdf_set_fill_color(pdf_buffer *buf, gfx_color_t color)
2001 {
2002     pdf_set_color(buf, color, &buf->state->fill_color, "rg");
2003 }
2004
2005 static pdf_font *pdf_find_font(pdf_state *state, gfx_node_t *node)
2006 {
2007   const char *ps_font = afm_get_font_postscript_name(node->filename);
2008   pdf_font *ef;
2009   for (ef = state->font_list; ef; ef = ef->next) {
2010     if (!strcmp(ps_font, ef->ps_font))
2011       return ef;
2012   }
2013   return NULL;
2014 }
2015
2016 static void pdf_add_font(pdf_state *state, gfx_node_t *node)
2017 {
2018   pdf_font *ef = pdf_find_font(state, node);
2019   if (ef)
2020     return;
2021   ef = malloc(sizeof(pdf_font));
2022   if (ef == NULL) {
2023     rrd_set_error("malloc for pdf_font");
2024     state->has_failed = 1;
2025     return;
2026   }
2027   pdf_init_dict(state, &ef->obj);
2028   ef->next = state->font_list;
2029   ef->ps_font = afm_get_font_postscript_name(node->filename);
2030   state->font_list = ef;
2031   /* fonts dict */
2032   pdf_putsi(&state->fontsdict_obj, "/F");
2033   pdf_putint(&state->fontsdict_obj, ef->obj.id);
2034   pdf_puts(&state->fontsdict_obj, " ");
2035   pdf_putint(&state->fontsdict_obj, ef->obj.id);
2036   pdf_puts(&state->fontsdict_obj, " 0 R\n");
2037   /* fonts def */
2038   pdf_putsi(&ef->obj, "/Type /Font\n");
2039   pdf_putsi(&ef->obj, "/Subtype /Type1\n");
2040   pdf_putsi(&ef->obj, "/Name /F");
2041   pdf_putint(&ef->obj, ef->obj.id);
2042   pdf_puts(&ef->obj, "\n");
2043   pdf_putsi(&ef->obj, "/BaseFont /");
2044   pdf_puts(&ef->obj, ef->ps_font);
2045   pdf_puts(&ef->obj, "\n");
2046   pdf_putsi(&ef->obj, "/Encoding /WinAnsiEncoding\n");
2047   /*  'Cp1252' (this is latin 1 extended with 27 characters;
2048       the encoding is also known as 'winansi')
2049       http://www.lowagie.com/iText/tutorial/ch09.html */
2050 }
2051
2052 static void pdf_create_fonts(pdf_state *state)
2053 {
2054   gfx_node_t *node;
2055   for (node = state->canvas->firstnode; node; node = node->next) {
2056     if (node->type == GFX_TEXT)
2057       pdf_add_font(state, node);
2058   }
2059 }
2060
2061 static void pdf_write_linearea(pdf_state *state, gfx_node_t *node)
2062 {
2063   int i;
2064   pdf_buffer *s = &state->graph_stream;
2065   if (node->type == GFX_LINE) {
2066     svg_dash dash_info;
2067     svg_get_dash(node, &dash_info);
2068     if (!svg_dash_equal(&dash_info, &state->dash)) {
2069       state->dash = dash_info;
2070       if (dash_info.dash_enable) {
2071         pdf_puts(s, "[");
2072         pdf_putnumber(s, dash_info.adjusted_on);
2073         pdf_puts(s, " ");
2074         pdf_putnumber(s, dash_info.adjusted_off);
2075         pdf_puts(s, "] ");
2076         pdf_putnumber(s, dash_info.dash_offset);
2077         pdf_puts(s, " d\n");
2078       } else {
2079         pdf_puts(s, "[] 0 d\n");
2080       }
2081     }
2082     pdf_set_stroke_color(s, node->color);
2083     if (state->linecap != 1) {
2084       pdf_puts(s, "1 j\n");
2085       state->linecap = 1;
2086     }
2087     if (state->linejoin != 1) {
2088       pdf_puts(s, "1 J\n");
2089       state->linejoin = 1;
2090     }
2091     if (node->size != state->line_width) {
2092       state->line_width = node->size;
2093       pdf_putnumber(s, state->line_width);
2094       pdf_puts(s, " w\n");
2095     }
2096   } else {
2097     pdf_set_fill_color(s, node->color);
2098   }
2099   for (i = 0; i < node->points; i++) {
2100     ArtVpath *vec = node->path + i;
2101     double x = vec->x;
2102     double y = state->page_height - vec->y;
2103     if (node->type == GFX_AREA) {
2104       x += LINEOFFSET; /* adjust for libart handling of areas */
2105       y -= LINEOFFSET;
2106     }
2107     switch (vec->code) {
2108     case ART_MOVETO_OPEN: /* fall-through */
2109     case ART_MOVETO:
2110       pdf_putnumber(s, x);
2111       pdf_puts(s, " ");
2112       pdf_putnumber(s, y);
2113       pdf_puts(s, " m\n");
2114       break;
2115     case ART_LINETO:
2116       pdf_putnumber(s, x);
2117       pdf_puts(s, " ");
2118       pdf_putnumber(s, y);
2119       pdf_puts(s, " l\n");
2120       break;
2121     case ART_CURVETO: break; /* unsupported */
2122     case ART_END: break; /* nop */
2123     }
2124   }
2125   if (node->type == GFX_LINE) {
2126     pdf_puts(s, node->closed_path ? "s\n" : "S\n");
2127    } else {
2128     pdf_puts(s, "f\n");
2129    }
2130 }
2131
2132
2133 static void pdf_write_matrix(pdf_state *state, gfx_node_t *node, pdf_coords *g, int useTM)
2134 {
2135         char tmp[150];
2136         pdf_buffer *s = &state->graph_stream;
2137         if (node->angle == 0) {
2138                 pdf_puts(s, "1 0 0 1 ");
2139                 pdf_putnumber(s, useTM ? g->tmx : g->mx);
2140                 pdf_puts(s, " ");
2141                 pdf_putnumber(s, useTM ? g->tmy : g->my);
2142         } else {
2143                  /* can't use svg_write_number as 2 decimals is far from enough to avoid
2144                         skewed text */
2145                 sprintf(tmp, "%f %f %f %f %f %f",
2146                                 g->ma, g->mb, g->mc, g->md, 
2147                                 useTM ? g->tmx : g->mx,
2148                                 useTM ? g->tmy : g->my);
2149                 pdf_puts(s, tmp);
2150         }
2151 }
2152
2153 static void pdf_write_text(pdf_state *state, gfx_node_t *node, 
2154     int last_was_text, int next_is_text)
2155 {
2156   pdf_coords g;
2157   pdf_buffer *s = &state->graph_stream;
2158   pdf_font *font = pdf_find_font(state, node);
2159   if (font == NULL) {
2160     rrd_set_error("font disappeared");
2161     state->has_failed = 1;
2162     return;
2163   }
2164   pdf_calc(state->page_height, node, &g);
2165 #if PDF_CALC_DEBUG
2166   pdf_puts(s, "q % debug green box\n");
2167   pdf_write_matrix(state, node, &g, 0);
2168   pdf_puts(s, " cm\n");
2169   pdf_set_fill_color(s, 0x90FF9000);
2170   pdf_puts(s, "0 0.4 0 rg\n");
2171   pdf_puts(s, "0 0 ");
2172   pdf_putnumber(s, g.sizep.x);
2173   pdf_puts(s, " ");
2174   pdf_putnumber(s, g.sizep.y);
2175   pdf_puts(s, " re\n");
2176   pdf_puts(s, "f\n");
2177   pdf_puts(s, "Q\n");
2178 #endif
2179   pdf_set_fill_color(s, node->color);
2180   if (PDF_CALC_DEBUG || !last_was_text)
2181     pdf_puts(s, "BT\n");
2182   if (state->font_id != font->obj.id || node->size != state->font_size) {
2183     state->font_id = font->obj.id;
2184     state->font_size = node->size;
2185     pdf_puts(s, "/F");
2186     pdf_putint(s, font->obj.id);
2187     pdf_puts(s, " ");
2188     pdf_putnumber(s, node->size);
2189     pdf_puts(s, " Tf\n");
2190   }
2191   pdf_write_matrix(state, node, &g, 1);
2192   pdf_puts(s, " Tm\n");
2193   pdf_puts(s, "(");
2194   pdf_put_string_contents(s, node->text);
2195   pdf_puts(s, ") Tj\n");
2196   if (PDF_CALC_DEBUG || !next_is_text)
2197     pdf_puts(s, "ET\n");
2198 }
2199  
2200 static void pdf_write_content(pdf_state *state)
2201 {
2202   gfx_node_t *node;
2203   int last_was_text = 0, next_is_text;
2204   for (node = state->canvas->firstnode; node; node = node->next) {
2205     switch (node->type) {
2206     case GFX_LINE:
2207     case GFX_AREA:
2208       pdf_write_linearea(state, node);
2209       break;
2210     case GFX_TEXT:
2211       next_is_text = node->next && node->next->type == GFX_TEXT;
2212       pdf_write_text(state, node, last_was_text, next_is_text);
2213       break;
2214     }
2215     last_was_text = node->type == GFX_TEXT;
2216   }
2217 }
2218
2219 static void pdf_init_document(pdf_state *state)
2220 {
2221   pdf_init_buffer(state, &state->pdf_header);
2222   pdf_init_dict(state, &state->catalog_obj);
2223   pdf_init_dict(state, &state->info_obj);
2224   pdf_init_dict(state, &state->pages_obj);
2225   pdf_init_dict(state, &state->page1_obj);
2226   pdf_init_dict(state, &state->fontsdict_obj);
2227   pdf_create_fonts(state);
2228   if (state->has_failed)
2229     return;
2230   /* make stream last object in file */
2231   pdf_init_object(state, &state->graph_stream);
2232   state->graph_stream.is_stream = 1;
2233 }
2234
2235 static void pdf_setup_document(pdf_state *state)
2236 {
2237   const char *creator = "RRDtool 1.2.4 Tobias Oetiker, http://tobi.oetiker.ch";
2238   /* all objects created by now, so init code can reference them */
2239   /* HEADER */
2240   pdf_puts(&state->pdf_header, "%PDF-1.3\n");
2241   /* following 8 bit comment is recommended by Adobe for
2242      indicating binary file to file transfer applications */
2243   pdf_puts(&state->pdf_header, "%\xE2\xE3\xCF\xD3\n");
2244   /* INFO */
2245   pdf_putsi(&state->info_obj, "/Creator (");
2246   pdf_put_string_contents(&state->info_obj, creator);
2247   pdf_puts(&state->info_obj, ")\n");
2248   /* CATALOG */
2249   pdf_putsi(&state->catalog_obj, "/Type /Catalog\n");
2250   pdf_putsi(&state->catalog_obj, "/Pages ");
2251   pdf_putint(&state->catalog_obj, state->pages_obj.id);
2252   pdf_puts(&state->catalog_obj, " 0 R\n");
2253   /* PAGES */
2254   pdf_putsi(&state->pages_obj, "/Type /Pages\n");
2255   pdf_putsi(&state->pages_obj, "/Kids [");
2256   pdf_putint(&state->pages_obj, state->page1_obj.id);
2257   pdf_puts(&state->pages_obj, " 0 R]\n");
2258   pdf_putsi(&state->pages_obj, "/Count 1\n");
2259   /* PAGE 1 */
2260   pdf_putsi(&state->page1_obj, "/Type /Page\n");
2261   pdf_putsi(&state->page1_obj, "/Parent ");
2262   pdf_putint(&state->page1_obj, state->pages_obj.id);
2263   pdf_puts(&state->page1_obj, " 0 R\n");
2264   pdf_putsi(&state->page1_obj, "/MediaBox [0 0 ");
2265   pdf_putint(&state->page1_obj, state->page_width);
2266   pdf_puts(&state->page1_obj, " ");
2267   pdf_putint(&state->page1_obj, state->page_height);
2268   pdf_puts(&state->page1_obj, "]\n");
2269   pdf_putsi(&state->page1_obj, "/Contents ");
2270   pdf_putint(&state->page1_obj, state->graph_stream.id);
2271   pdf_puts(&state->page1_obj, " 0 R\n");
2272   pdf_putsi(&state->page1_obj, "/Resources << /Font ");
2273   pdf_putint(&state->page1_obj, state->fontsdict_obj.id);
2274   pdf_puts(&state->page1_obj, " 0 R >>\n");
2275 }
2276
2277 static void pdf_write_string_to_file(pdf_state *state, const char *text)
2278 {
2279     fputs(text, state->fp);
2280     state->pdf_file_pos += strlen(text);
2281 }
2282
2283 static void pdf_write_buf_to_file(pdf_state *state, pdf_buffer *buf)
2284 {
2285   char tmp[40];
2286   buf->pdf_file_pos = state->pdf_file_pos;
2287   if (buf->is_obj) {
2288     snprintf(tmp, sizeof(tmp), "%d 0 obj\n", buf->id);
2289     pdf_write_string_to_file(state, tmp);
2290   }
2291   if (buf->is_dict)
2292     pdf_write_string_to_file(state, "<<\n");
2293   if (buf->is_stream) {
2294     snprintf(tmp, sizeof(tmp), "<< /Length %d >>\n", buf->current_size);
2295     pdf_write_string_to_file(state, tmp);
2296     pdf_write_string_to_file(state, "stream\n");
2297   }
2298   fwrite(buf->data, 1, buf->current_size, state->fp);
2299   state->pdf_file_pos += buf->current_size;
2300   if (buf->is_stream)
2301     pdf_write_string_to_file(state, "endstream\n");
2302   if (buf->is_dict)
2303     pdf_write_string_to_file(state, ">>\n");
2304   if (buf->is_obj)
2305     pdf_write_string_to_file(state, "endobj\n");
2306 }
2307
2308 static void pdf_write_to_file(pdf_state *state)
2309 {
2310   pdf_buffer *buf = state->first_buffer;
2311   int xref_pos;
2312   state->pdf_file_pos = 0;
2313   pdf_write_buf_to_file(state, &state->pdf_header);
2314   while (buf) {
2315     if (buf->is_obj)
2316       pdf_write_buf_to_file(state, buf);
2317     buf = buf->next_buffer;
2318   }
2319   xref_pos = state->pdf_file_pos;
2320   fprintf(state->fp, "xref\n");
2321   fprintf(state->fp, "%d %d\n", 0, state->last_obj_id + 1);
2322   /* TOC lines must be exactly 20 bytes including \n */
2323   fprintf(state->fp, "%010d %05d f\x20\n", 0, 65535);
2324   for (buf = state->first_buffer; buf; buf = buf->next_buffer) {
2325     if (buf->is_obj)
2326       fprintf(state->fp, "%010d %05d n\x20\n", buf->pdf_file_pos, 0);
2327   }
2328   fprintf(state->fp, "trailer\n");
2329   fprintf(state->fp, "<<\n");
2330   fprintf(state->fp, "\t/Size %d\n", state->last_obj_id + 1);
2331   fprintf(state->fp, "\t/Root %d 0 R\n", state->catalog_obj.id);
2332   fprintf(state->fp, "\t/Info %d 0 R\n", state->info_obj.id);
2333   fprintf(state->fp, ">>\n");
2334   fprintf(state->fp, "startxref\n");
2335   fprintf(state->fp, "%d\n", xref_pos);
2336   fputs("%%EOF\n", state->fp);
2337 }
2338
2339 static void pdf_free_resources(pdf_state *state)
2340 {
2341   pdf_buffer *buf = state->first_buffer;
2342   while (buf) {
2343     free(buf->data);
2344     buf->data = NULL;
2345     buf->alloc_size = buf->current_size = 0;
2346     buf = buf->next_buffer;
2347   }
2348   while (state->font_list) {
2349     pdf_font *next = state->font_list->next;
2350     free(state->font_list);
2351     state->font_list = next;
2352   }
2353 }
2354
2355 int       gfx_render_pdf (gfx_canvas_t *canvas,
2356                  art_u32 width, art_u32 height,
2357                  gfx_color_t background, FILE *fp){
2358   struct pdf_state state;
2359   memset(&state, 0, sizeof(pdf_state));
2360   state.fp = fp;
2361   state.canvas = canvas;
2362   state.page_width = width;
2363   state.page_height = height;
2364   state.font_id = -1;
2365   state.font_size = -1;
2366   state.font_list = NULL;
2367   state.linecap = -1;
2368   state.linejoin = -1;
2369   pdf_init_document(&state);
2370   /*
2371   pdf_set_color(&state, background);
2372   fprintf(fp, "0 0 M 0 %d L %d %d L %d 0 L fill\n",
2373       height, width, height, width);
2374   */
2375   if (!state.has_failed)
2376     pdf_write_content(&state);
2377   if (!state.has_failed)
2378     pdf_setup_document(&state);
2379   if (!state.has_failed)
2380     pdf_write_to_file(&state);
2381   pdf_free_resources(&state);
2382   return state.has_failed ? -1 : 0;
2383 }
2384