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