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