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