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