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