new options to tune how fontsmoothing works:
[rrdtool.git] / src / rrd_gfx.c
1 /****************************************************************************
2  * RRDtool 1.2.1  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     art_u8 *buffer = art_new (art_u8, rowstride*pys_height);
518     /* fill that buffer with out background color */
519     gfx_color_t *buffp;
520     long i;
521     for (i=0,buffp=(gfx_color_t *)buffer;
522          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,*pvec;
532             double dst[6];     
533             ArtSVP *svp,*svpt;
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 ( pvec, 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 ( pvec );
547                 svpt = art_svp_uncross( svp );
548                 art_svp_free(svp);
549                 svp  = art_svp_rewind_uncrossed(svpt,ART_WIND_RULE_NONZERO); 
550                 art_svp_free(svpt);
551             }
552             art_free(pvec);
553             /* this is from gnome since libart does not have this yet */
554             gnome_print_art_rgba_svp_alpha (svp ,0,0, pys_width, pys_height,
555                                 node->color, buffer, rowstride, NULL);
556             art_svp_free(svp);
557             break;
558         }
559         case GFX_TEXT: {
560             unsigned int  n;
561             int  error;
562             art_u8 fcolor[4],falpha;
563             FT_Face       face;
564             gfx_char      glyph;
565             gfx_string    string;
566             FT_Vector     vec;  /* 26.6 */
567
568             float pen_x = 0.0 , pen_y = 0.0;
569             /* double x,y; */
570             long   ix,iy;
571             
572             fcolor[0] = node->color >> 24;
573             fcolor[1] = (node->color >> 16) & 0xff;
574             fcolor[2] = (node->color >> 8) & 0xff;
575             falpha = node->color & 0xff;
576             error = FT_New_Face( library,
577                                  (char *)node->filename,
578                                  0,
579                                  &face );
580             if ( error ) {
581                 rrd_set_error("failed to load %s",node->filename);
582                 break;
583             }
584             error = FT_Set_Char_Size(face,   /* handle to face object            */
585                                      (long)(node->size*64),
586                                      (long)(node->size*64),
587                                      (long)(100*canvas->zoom),
588                                      (long)(100*canvas->zoom));
589             if ( error ) break;
590             pen_x = node->x * canvas->zoom;
591             pen_y = node->y * canvas->zoom;
592
593             string = gfx_string_create (canvas, face, node->text, node->angle, node->tabwidth, node->size);
594             switch(node->halign){
595             case GFX_H_RIGHT:  vec.x = -string->bbox.xMax;
596                                break;          
597             case GFX_H_CENTER: vec.x = abs(string->bbox.xMax) >= abs(string->bbox.xMin) ?
598                                        -string->bbox.xMax/2:-string->bbox.xMin/2;
599                                break;          
600             case GFX_H_LEFT:   vec.x = -string->bbox.xMin;
601                                break;
602             case GFX_H_NULL:   vec.x = 0;
603                                break;          
604             }
605
606             switch(node->valign){
607             case GFX_V_TOP:    vec.y = string->bbox.yMax;
608                                break;
609             case GFX_V_CENTER: vec.y = abs(string->bbox.yMax) >= abs(string->bbox.yMin) ?
610                                        string->bbox.yMax/2:string->bbox.yMin/2;
611                                break;
612             case GFX_V_BOTTOM: vec.y = 0;
613                                break;
614             case GFX_V_NULL:   vec.y = 0;
615                                break;
616             }
617             pen_x += vec.x/64;
618             pen_y += vec.y/64;
619             glyph = string->glyphs;
620             for(n=0; n<string->num_glyphs; ++n, ++glyph) {
621                 int gr;
622                 FT_Glyph        image;
623                 FT_BitmapGlyph  bit;
624                 /* long buf_x,comp_n; */
625                 /* make copy to transform */
626                 if (! glyph->image) {
627                   fprintf (stderr, "no image\n");
628                   continue;
629                 }
630                 error = FT_Glyph_Copy (glyph->image, &image);
631                 if (error) {
632                   fprintf (stderr, "couldn't copy image\n");
633                   continue;
634                 }
635
636                 /* transform it */
637                 vec = glyph->pos;
638                 FT_Vector_Transform (&vec, &string->transform);
639
640                 bit = (FT_BitmapGlyph) image;
641                 gr = bit->bitmap.num_grays -1;
642 /* 
643                 buf_x = (pen_x + 0.5) + (double)bit->left;
644                 comp_n = buf_x + bit->bitmap.width > pys_width ? pys_width - buf_x : bit->bitmap.width;
645                 if (buf_x < 0 || buf_x >= (long)pys_width) continue;
646                 buf_x *=  bytes_per_pixel ;
647                 for (iy=0; iy < bit->bitmap.rows; iy++){                    
648                     long buf_y = iy+(pen_y+0.5)-(double)bit->top;
649                     if (buf_y < 0 || buf_y >= (long)pys_height) continue;
650                     buf_y *= rowstride;
651                     for (ix=0;ix < bit->bitmap.width;ix++){             
652                         *(letter + (ix*bytes_per_pixel+3)) = *(bit->bitmap.buffer + iy * bit->bitmap.width + ix);
653                     }
654                     art_rgba_rgba_composite(buffer + buf_y + buf_x ,letter,comp_n);
655                  }
656                  art_free(letter);
657 */
658                 switch ( bit->bitmap.pixel_mode ) {
659                     case FT_PIXEL_MODE_GRAY:
660                         for (iy=0; iy < bit->bitmap.rows; iy++){
661                             long buf_y = iy+(pen_y+0.5)-bit->top;
662                             if (buf_y < 0 || buf_y >= (long)pys_height) continue;
663                             buf_y *= rowstride;
664                             for (ix=0;ix < bit->bitmap.width;ix++){
665                                 long buf_x = ix + (pen_x + 0.5) + (double)bit->left ;
666                                 art_u8 font_alpha;
667
668                                 if (buf_x < 0 || buf_x >= (long)pys_width) continue;
669                                 buf_x *=  bytes_per_pixel ;
670                                 font_alpha =  *(bit->bitmap.buffer + iy * bit->bitmap.pitch + ix);
671                     if (font_alpha > 0){
672                                     fcolor[3] =  (art_u8)((double)font_alpha / gr * falpha);
673                         art_rgba_rgba_composite(buffer + buf_y + buf_x ,fcolor,1);
674                                 }
675                             }
676                         }
677                         break;
678
679                     case FT_PIXEL_MODE_MONO:
680                         for (iy=0; iy < bit->bitmap.rows; iy++){
681                             long buf_y = iy+(pen_y+0.5)-bit->top;
682                             if (buf_y < 0 || buf_y >= (long)pys_height) continue;
683                             buf_y *= rowstride;
684                             for (ix=0;ix < bit->bitmap.width;ix++){
685                                 long buf_x = ix + (pen_x + 0.5) + (double)bit->left ;
686
687                                 if (buf_x < 0 || buf_x >= (long)pys_width) continue;
688                                 buf_x *=  bytes_per_pixel ;
689                                 if ( (fcolor[3] = falpha * ((*(bit->bitmap.buffer + iy * bit->bitmap.pitch + ix/8) >> (7 - (ix % 8))) & 1)) > 0 )
690                                     art_rgba_rgba_composite(buffer + buf_y + buf_x ,fcolor,1);
691                             }
692                         }
693                         break;
694
695                         default:
696                             rrd_set_error("unknown freetype pixel mode: %d", bit->bitmap.pixel_mode);
697                             break;
698                 }
699
700 /*
701                 for (iy=0; iy < bit->bitmap.rows; iy++){                    
702                     long buf_y = iy+(pen_y+0.5)-bit->top;
703                     if (buf_y < 0 || buf_y >= (long)pys_height) continue;
704                     buf_y *= rowstride;
705                     for (ix=0;ix < bit->bitmap.width;ix++){
706                         long buf_x = ix + (pen_x + 0.5) + (double)bit->left ;
707                         art_u8 font_alpha;
708                         
709                         if (buf_x < 0 || buf_x >= (long)pys_width) continue;
710                         buf_x *=  bytes_per_pixel ;
711                         font_alpha =  *(bit->bitmap.buffer + iy * bit->bitmap.width + ix);
712                         font_alpha =  (art_u8)((double)font_alpha / gr * falpha);
713                         for (iz = 0; iz < 3; iz++){
714                             art_u8 *orig = buffer + buf_y + buf_x + iz;
715                             *orig =  (art_u8)((double)*orig / gr * ( gr - font_alpha) +
716                                               (double)fcolor[iz] / gr * (font_alpha));
717                         }
718                     }
719                 }
720 */
721                 FT_Done_Glyph (image);
722             }
723             gfx_string_destroy(string);
724         }
725         }
726         node = node->next;
727     }  
728     gfx_save_png(buffer,fp , pys_width,pys_height,bytes_per_pixel);
729     art_free(buffer);
730     FT_Done_FreeType( library );
731     return 0;    
732 }
733
734 /* free memory used by nodes this will also remove memory required for
735    associated paths and svcs ... but not for text strings */
736 int
737 gfx_destroy    (gfx_canvas_t *canvas){  
738   gfx_node_t *next,*node = canvas->firstnode;
739   while(node){
740     next = node->next;
741     art_free(node->path);
742     free(node->text);
743     free(node->filename);
744     art_free(node);
745     node = next;
746   }
747   art_free(canvas);
748   return 0;
749 }
750  
751 static int gfx_save_png (art_u8 *buffer, FILE *fp,  long width, long height, long bytes_per_pixel){
752   png_structp png_ptr = NULL;
753   png_infop   info_ptr = NULL;
754   int i;
755   png_bytep *row_pointers;
756   int rowstride = width * bytes_per_pixel;
757   png_text text[2];
758   
759   if (fp == NULL)
760     return (1);
761
762   png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING,NULL,NULL,NULL);
763   if (png_ptr == NULL)
764    {
765       return (1);
766    }
767    row_pointers = (png_bytepp)png_malloc(png_ptr,
768                                      height*sizeof(png_bytep));
769
770   info_ptr = png_create_info_struct(png_ptr);
771
772   if (info_ptr == NULL)
773     {
774       png_free(png_ptr,row_pointers);
775       png_destroy_write_struct(&png_ptr,  (png_infopp)NULL);
776       return (1);
777     }
778
779   if (setjmp(png_jmpbuf(png_ptr)))
780     {
781       /* If we get here, we had a problem writing the file */
782       png_destroy_write_struct(&png_ptr, &info_ptr);
783       return (1);
784     }
785
786   png_init_io(png_ptr, fp);
787   png_set_IHDR (png_ptr, info_ptr,width, height,
788                 8, PNG_COLOR_TYPE_RGB_ALPHA,
789                 PNG_INTERLACE_NONE,
790                 PNG_COMPRESSION_TYPE_DEFAULT,
791                 PNG_FILTER_TYPE_DEFAULT);
792
793   text[0].key = "Software";
794   text[0].text = "RRDtool, Tobias Oetiker <tobi@oetike.ch>, http://tobi.oetiker.ch";
795   text[0].compression = PNG_TEXT_COMPRESSION_NONE;
796   png_set_text (png_ptr, info_ptr, text, 1);
797
798   /* lets make this fast */
799   /* png_set_filter(png_ptr,0,PNG_FILTER_NONE); */
800   png_set_compression_level(png_ptr,1);
801   /* png_set_compression_strategy(png_ptr,Z_HUFFMAN_ONLY); */
802   /* 
803   png_set_filter(png_ptr,PNG_FILTER_TYPE_BASE,PNG_FILTER_SUB);
804   png_set_compression_strategy(png_ptr,Z_HUFFMAN_ONLY);
805   png_set_compression_level(png_ptr,Z_BEST_SPEED); */
806   
807   /* Write header data */
808   png_write_info (png_ptr, info_ptr);
809   for (i = 0; i < height; i++)
810     row_pointers[i] = (png_bytep) (buffer + i*rowstride);
811   
812   png_write_image(png_ptr, row_pointers);
813   png_write_end(png_ptr, info_ptr);
814   png_free(png_ptr,row_pointers);
815   png_destroy_write_struct(&png_ptr, &info_ptr);
816   return 1;
817 }
818
819  
820 /* ------- SVG -------
821    SVG reference:
822    http://www.w3.org/TR/SVG/
823 */
824 static int svg_indent = 0;
825 static int svg_single_line = 0;
826 static const char *svg_default_font = "Helvetica";
827 typedef struct svg_dash
828 {
829   int dash_enable;
830   double dash_adjust, dash_len, dash_offset;
831   double adjusted_on, adjusted_off;
832 } svg_dash;
833
834
835 static void svg_print_indent(FILE *fp)
836 {
837   int i;
838    for (i = svg_indent - svg_single_line; i > 0; i--) {
839      putc(' ', fp);
840      putc(' ', fp);
841    }
842 }
843  
844 static void svg_start_tag(FILE *fp, const char *name)
845 {
846    svg_print_indent(fp);
847    putc('<', fp);
848    fputs(name, fp);
849    svg_indent++;
850 }
851  
852 static void svg_close_tag_single_line(FILE *fp)
853 {
854    svg_single_line++;
855    putc('>', fp);
856 }
857  
858 static void svg_close_tag(FILE *fp)
859 {
860    putc('>', fp);
861    if (!svg_single_line)
862      putc('\n', fp);
863 }
864  
865 static void svg_end_tag(FILE *fp, const char *name)
866 {
867    /* name is NULL if closing empty-node tag */
868    svg_indent--;
869    if (svg_single_line)
870      svg_single_line--;
871    else if (name)
872      svg_print_indent(fp);
873    if (name != NULL) {
874      fputs("</", fp);
875      fputs(name, fp);
876    } else {
877      putc('/', fp);
878    }
879    svg_close_tag(fp);
880 }
881  
882 static void svg_close_tag_empty_node(FILE *fp)
883 {
884    svg_end_tag(fp, NULL);
885 }
886  
887 static void svg_write_text(FILE *fp, const char *text)
888 {
889    const unsigned char *p, *start, *last;
890    unsigned int ch;
891    p = (const unsigned char*)text;
892    if (!p)
893      return;
894    /* trim leading spaces */
895    while (*p == ' ')
896      p++;
897    start = p;
898    /* trim trailing spaces */
899    last = p - 1;
900    while ((ch = *p) != 0) {
901      if (ch != ' ')
902        last = p;
903      p++;
904   }
905   /* encode trimmed text */
906   p = start;
907   while (p <= last) {
908     ch = *p++;
909     ch = afm_host2unicode(ch); /* unsafe macro */
910     switch (ch) {
911     case '&': fputs("&amp;", fp); break;
912     case '<': fputs("&lt;", fp); break;
913     case '>': fputs("&gt;", fp); break;
914     case '"': fputs("&quot;", fp); break;
915     default:
916       if (ch >= 127)
917         fprintf(fp, "&#%d;", ch);
918       else
919         putc(ch, fp);
920      }
921    }
922 }
923  
924 static void svg_format_number(char *buf, int bufsize, double d)
925 {
926    /* omit decimals if integer to reduce filesize */
927    char *p;
928    snprintf(buf, bufsize, "%.2f", d);
929    p = buf; /* doesn't trust snprintf return value */
930    while (*p)
931      p++;
932    while (--p > buf) {
933      char ch = *p;
934      if (ch == '0') {
935        *p = '\0'; /* zap trailing zeros */
936        continue;
937      }
938      if (ch == '.')
939        *p = '\0'; /* zap trailing dot */
940      break;
941    }
942 }
943  
944 static void svg_write_number(FILE *fp, double d)
945 {
946    char buf[60];
947    svg_format_number(buf, sizeof(buf), d);
948    fputs(buf, fp);
949 }
950
951 static int svg_color_is_black(int c)
952 {
953   /* gfx_color_t is RRGGBBAA */
954   return c == 0x000000FF;
955 }
956  
957 static void svg_write_color(FILE *fp, gfx_color_t c, const char *attr)
958 {
959   /* gfx_color_t is RRGGBBAA, svg can use #RRGGBB and #RGB like html */
960   gfx_color_t rrggbb = (int)((c >> 8) & 0xFFFFFF);
961   gfx_color_t opacity = c & 0xFF;
962   fprintf(fp, " %s=\"", attr);
963   if ((rrggbb & 0x0F0F0F) == ((rrggbb >> 4) & 0x0F0F0F)) {
964      /* css2 short form, #rgb is #rrggbb, not #r0g0b0 */
965     fprintf(fp, "#%03lX",
966           ( ((rrggbb >> 8) & 0xF00)
967           | ((rrggbb >> 4) & 0x0F0)
968           | ( rrggbb       & 0x00F)));
969    } else {
970     fprintf(fp, "#%06lX", rrggbb);
971    }
972   fputs("\"", fp);
973   if (opacity != 0xFF) {
974     fprintf(fp, " stroke-opacity=\"");
975     svg_write_number(fp, opacity / 255.0);
976     fputs("\"", fp);
977  }
978 }
979  
980 static void svg_get_dash(gfx_node_t *node, svg_dash *d)
981 {
982   double offset;
983   int mult;
984   if (node->dash_on <= 0 || node->dash_off <= 0) {
985     d->dash_enable = 0;
986     return;
987   }
988   d->dash_enable = 1;
989   d->dash_len = node->dash_on + node->dash_off;
990   /* dash on/off adjustment due to round caps */
991   d->dash_adjust = 0.8 * node->size;
992   d->adjusted_on = node->dash_on - d->dash_adjust;
993   if (d->adjusted_on < 0.01)
994       d->adjusted_on = 0.01;
995   d->adjusted_off = d->dash_len - d->adjusted_on;
996   /* dash offset calc */
997   if (node->path[0].x == node->path[1].x) /* only good for horz/vert lines */
998     offset = node->path[0].y;
999   else
1000     offset = node->path[0].x;
1001   mult = (int)fabs(offset / d->dash_len);
1002   d->dash_offset = offset - mult * d->dash_len;
1003   if (node->path[0].x < node->path[1].x || node->path[0].y < node->path[1].y)
1004     d->dash_offset = d->dash_len - d->dash_offset;
1005 }
1006
1007 static int svg_dash_equal(svg_dash *a, svg_dash *b)
1008 {
1009   if (a->dash_enable != b->dash_enable)
1010     return 0;
1011   if (a->adjusted_on != b->adjusted_on)
1012     return 0;
1013   if (a->adjusted_off != b->adjusted_off)
1014     return 0;
1015   /* rest of properties will be the same when on+off are */
1016   return 1;
1017 }
1018
1019 static void svg_common_path_attributes(FILE *fp, gfx_node_t *node)
1020 {
1021   svg_dash dash_info;
1022   svg_get_dash(node, &dash_info);
1023   fputs(" stroke-width=\"", fp);
1024   svg_write_number(fp, node->size);
1025   fputs("\"", fp);
1026   svg_write_color(fp, node->color, "stroke");
1027   fputs(" fill=\"none\"", fp);
1028   if (dash_info.dash_enable) {
1029     if (dash_info.dash_offset != 0) {
1030       fputs(" stroke-dashoffset=\"", fp);
1031       svg_write_number(fp, dash_info.dash_offset);
1032       fputs("\"", fp);
1033     }
1034     fputs(" stroke-dasharray=\"", fp);
1035     svg_write_number(fp, dash_info.adjusted_on);
1036     fputs(",", fp);
1037     svg_write_number(fp, dash_info.adjusted_off);
1038     fputs("\"", fp);
1039   }
1040 }
1041
1042 static int svg_is_int_step(double a, double b)
1043 {
1044    double diff = fabs(a - b);
1045    return floor(diff) == diff;
1046 }
1047  
1048 static int svg_path_straight_segment(FILE *fp,
1049      double lastA, double currentA, double currentB,
1050      gfx_node_t *node,
1051      int segment_idx, int isx, char absChar, char relChar)
1052 {
1053    if (!svg_is_int_step(lastA, currentA)) {
1054      putc(absChar, fp);
1055      svg_write_number(fp, currentA);
1056      return 0;
1057    }
1058    if (segment_idx < node->points - 1) {
1059      ArtVpath *vec = node->path + segment_idx + 1;
1060      if (vec->code == ART_LINETO) {
1061        double nextA = (isx ? vec->x : vec->y) - LINEOFFSET;
1062        double nextB = (isx ? vec->y : vec->x) - LINEOFFSET;
1063        if (nextB == currentB
1064            && ((currentA >= lastA) == (nextA >= currentA))
1065            && svg_is_int_step(currentA, nextA)) {
1066          return 1; /* skip to next as it is a straight line  */
1067        }
1068      }
1069    }
1070    putc(relChar, fp);
1071    svg_write_number(fp, currentA - lastA);
1072    return 0;
1073 }
1074  
1075 static void svg_path(FILE *fp, gfx_node_t *node, int multi)
1076 {
1077    int i;
1078    double lastX = 0, lastY = 0;
1079    /* for straight lines <path..> tags take less space than
1080       <line..> tags because of the efficient packing
1081       in the 'd' attribute */
1082    svg_start_tag(fp, "path");
1083   if (!multi)
1084     svg_common_path_attributes(fp, node);
1085    fputs(" d=\"", fp);
1086    /* specification of the 'd' attribute: */
1087    /* http://www.w3.org/TR/SVG/paths.html#PathDataGeneralInformation */
1088    for (i = 0; i < node->points; i++) {
1089      ArtVpath *vec = node->path + i;
1090      double x = vec->x - LINEOFFSET;
1091      double y = vec->y - LINEOFFSET;
1092      switch (vec->code) {
1093      case ART_MOVETO_OPEN: /* fall-through */
1094      case ART_MOVETO:
1095        putc('M', fp);
1096        svg_write_number(fp, x);
1097        putc(',', fp);
1098        svg_write_number(fp, y);
1099        break;
1100      case ART_LINETO:
1101        /* try optimize filesize by using minimal lineto commands */
1102        /* without introducing rounding errors. */
1103        if (x == lastX) {
1104          if (svg_path_straight_segment(fp, lastY, y, x, node, i, 0, 'V', 'v'))
1105            continue;
1106        } else if (y == lastY) {
1107          if (svg_path_straight_segment(fp, lastX, x, y, node, i, 1, 'H', 'h'))
1108            continue;
1109        } else {
1110          putc('L', fp);
1111          svg_write_number(fp, x);
1112          putc(',', fp);
1113          svg_write_number(fp, y);
1114        }
1115        break;
1116      case ART_CURVETO: break; /* unsupported */
1117      case ART_END: break; /* nop */
1118      }
1119      lastX = x;
1120      lastY = y;
1121    }
1122   if (node->closed_path)
1123     fputs(" Z", fp);
1124    fputs("\"", fp);
1125    svg_close_tag_empty_node(fp);
1126 }
1127  
1128 static void svg_multi_path(FILE *fp, gfx_node_t **nodeR)
1129 {
1130    /* optimize for multiple paths with the same color, penwidth, etc. */
1131    int num = 1;
1132    gfx_node_t *node = *nodeR;
1133    gfx_node_t *next = node->next;
1134    while (next) {
1135      if (next->type != node->type
1136          || next->size != node->size
1137         || next->color != node->color
1138         || next->dash_on != node->dash_on
1139         || next->dash_off != node->dash_off)
1140        break;
1141      next = next->next;
1142      num++;
1143    }
1144    if (num == 1) {
1145      svg_path(fp, node, 0);
1146      return;
1147    }
1148    svg_start_tag(fp, "g");
1149   svg_common_path_attributes(fp, node);
1150    svg_close_tag(fp);
1151    while (num && node) {
1152      svg_path(fp, node, 1);
1153      if (!--num)
1154        break;
1155      node = node->next;
1156      *nodeR = node;
1157    }
1158    svg_end_tag(fp, "g");
1159 }
1160  
1161 static void svg_area(FILE *fp, gfx_node_t *node)
1162 {
1163    int i;
1164    double startX = 0, startY = 0;
1165    svg_start_tag(fp, "polygon");
1166   fputs(" ", fp);
1167   svg_write_color(fp, node->color, "fill");
1168   fputs(" points=\"", fp);
1169    for (i = 0; i < node->points; i++) {
1170      ArtVpath *vec = node->path + i;
1171      double x = vec->x - LINEOFFSET;
1172      double y = vec->y - LINEOFFSET;
1173      switch (vec->code) {
1174        case ART_MOVETO_OPEN: /* fall-through */
1175        case ART_MOVETO:
1176          svg_write_number(fp, x);
1177          putc(',', fp);
1178          svg_write_number(fp, y);
1179          startX = x;
1180          startY = y;
1181          break;
1182        case ART_LINETO:
1183          if (i == node->points - 2
1184                         && node->path[i + 1].code == ART_END
1185              && fabs(x - startX) < 0.001 && fabs(y - startY) < 0.001) {
1186            break; /* poly area always closed, no need for last point */
1187          }
1188          putc(' ', fp);
1189          svg_write_number(fp, x);
1190          putc(',', fp);
1191          svg_write_number(fp, y);
1192          break;
1193        case ART_CURVETO: break; /* unsupported */
1194        case ART_END: break; /* nop */
1195      }
1196    }
1197    fputs("\"", fp);
1198    svg_close_tag_empty_node(fp);
1199 }
1200  
1201 static void svg_text(FILE *fp, gfx_node_t *node)
1202 {
1203    double x = node->x - LINEOFFSET;
1204    double y = node->y - LINEOFFSET;
1205    if (node->angle != 0) {
1206      svg_start_tag(fp, "g");
1207      fputs(" transform=\"translate(", fp);
1208      svg_write_number(fp, x);
1209      fputs(",", fp);
1210      svg_write_number(fp, y);
1211      fputs(") rotate(", fp);
1212      svg_write_number(fp, node->angle);
1213      fputs(")\"", fp);
1214      x = y = 0;
1215      svg_close_tag(fp);
1216    }
1217    switch (node->valign) {
1218    case GFX_V_TOP:  y += node->size; break;
1219    case GFX_V_CENTER: y += node->size / 3; break;
1220    case GFX_V_BOTTOM: break;
1221    case GFX_V_NULL: break;
1222    }
1223    svg_start_tag(fp, "text");
1224    fputs(" x=\"", fp);
1225    svg_write_number(fp, x);
1226    fputs("\" y=\"", fp);
1227    svg_write_number(fp, y);
1228
1229 /*  if (strcmp(node->filename, svg_default_font))
1230     fprintf(fp, " font-family=\"%s\"", node->filename);
1231     */
1232    fputs("\" font-family=\"Helvetica", fp);
1233    fputs("\" font-size=\"", fp);
1234    svg_write_number(fp, node->size);
1235    fputs("\"", fp);
1236   if (!svg_color_is_black(node->color))
1237     svg_write_color(fp, node->color, "fill");
1238    switch (node->halign) {
1239    case GFX_H_RIGHT:  fputs(" text-anchor=\"end\"", fp); break;
1240    case GFX_H_CENTER: fputs(" text-anchor=\"middle\"", fp); break;
1241    case GFX_H_LEFT: break;
1242    case GFX_H_NULL: break;
1243    }
1244    svg_close_tag_single_line(fp);
1245    /* support for node->tabwidth missing */
1246    svg_write_text(fp, node->text);
1247    svg_end_tag(fp, "text");
1248    if (node->angle != 0)
1249      svg_end_tag(fp, "g");
1250 }
1251  
1252 int       gfx_render_svg (gfx_canvas_t *canvas,
1253                  art_u32 width, art_u32 height,
1254                  gfx_color_t background, FILE *fp){
1255    gfx_node_t *node = canvas->firstnode;
1256    fputs(
1257 "<?xml version=\"1.0\" standalone=\"no\"?>\n"
1258 "<!DOCTYPE svg PUBLIC \"-//W3C//DTD SVG 1.0//EN\"\n"
1259 "   \"http://www.w3.org/TR/2001/REC-SVG-20010904/DTD/svg10.dtd\">\n"
1260 "<!--\n"
1261 "   SVG file created by RRDtool,\n"
1262 "   Tobias Oetiker <tobi@oetike.ch>, http://tobi.oetiker.ch\n"
1263 "\n"
1264 "   The width/height attributes in the outhermost svg node\n"
1265 "   are just default sizes for the browser which is used\n"
1266 "   if the svg file is openened directly without being\n"
1267 "   embedded in an html file.\n"
1268 "   The viewBox is the local coord system for rrdtool.\n"
1269 "-->\n", fp);
1270    svg_start_tag(fp, "svg");
1271    fputs(" width=\"", fp);
1272   svg_write_number(fp, width * canvas->zoom);
1273    fputs("\" height=\"", fp);
1274   svg_write_number(fp, height * canvas->zoom);
1275    fputs("\" x=\"0\" y=\"0\" viewBox=\"", fp);
1276    svg_write_number(fp, -LINEOFFSET);
1277    fputs(" ", fp);
1278    svg_write_number(fp, -LINEOFFSET);
1279    fputs(" ", fp);
1280    svg_write_number(fp, width - LINEOFFSET);
1281    fputs(" ", fp);
1282    svg_write_number(fp, height - LINEOFFSET);
1283    fputs("\" preserveAspectRatio=\"xMidYMid\"", fp);
1284   fprintf(fp, " font-family=\"%s\"", svg_default_font); /* default font */
1285   fputs(" stroke-linecap=\"round\" stroke-linejoin=\"round\"", fp);
1286    svg_close_tag(fp);
1287    svg_start_tag(fp, "rect");
1288    fprintf(fp, " x=\"0\" y=\"0\" width=\"%d\" height=\"%d\"", width, height);
1289   svg_write_color(fp, background, "fill");
1290    svg_close_tag_empty_node(fp);
1291    while (node) {
1292      switch (node->type) {
1293      case GFX_LINE:
1294        svg_multi_path(fp, &node);
1295        break;
1296      case GFX_AREA:
1297        svg_area(fp, node);
1298        break;
1299      case GFX_TEXT:
1300        svg_text(fp, node);
1301      }
1302      node = node->next;
1303    }
1304    svg_end_tag(fp, "svg");
1305    return 0;
1306 }
1307
1308 /* ------- EPS -------
1309    EPS and Postscript references:
1310    http://partners.adobe.com/asn/developer/technotes/postscript.html
1311 */
1312
1313 typedef struct eps_font
1314 {
1315   const char *ps_font;
1316   int id;
1317   struct eps_font *next;
1318 } eps_font;
1319
1320 typedef struct eps_state
1321 {
1322   FILE *fp;
1323   gfx_canvas_t *canvas;
1324   art_u32 page_width, page_height;
1325   eps_font *font_list;
1326   /*--*/
1327   gfx_color_t color;
1328   const char *font;
1329   double font_size;
1330   double line_width;
1331   int linecap, linejoin;
1332   int has_dash;
1333 } eps_state;
1334
1335 static void eps_set_color(eps_state *state, gfx_color_t color)
1336 {
1337    /* gfx_color_t is RRGGBBAA */
1338   if (state->color == color)
1339     return;
1340   fprintf(state->fp, "%d %d %d Rgb\n",
1341       (int)((color >> 24) & 255),
1342       (int)((color >> 16) & 255),
1343       (int)((color >>  8) & 255));
1344   state->color = color;
1345 }
1346
1347 static int eps_add_font(eps_state *state, gfx_node_t *node)
1348 {
1349   /* The fonts list could be postponed to the end using
1350      (atend), but let's be nice and have them in the header. */
1351   const char *ps_font = afm_get_font_postscript_name(node->filename);
1352   eps_font *ef;
1353   for (ef = state->font_list; ef; ef = ef->next) {
1354     if (!strcmp(ps_font, ef->ps_font))
1355       return 0;
1356   }
1357   ef = malloc(sizeof(eps_font));
1358   if (ef == NULL) {
1359     rrd_set_error("malloc for eps_font");
1360     return -1;
1361   }
1362   ef->next = state->font_list;
1363   ef->ps_font = ps_font;
1364   state->font_list = ef;
1365   return 0;
1366 }
1367
1368 static void eps_list_fonts(eps_state *state, const char *dscName)
1369 {
1370   eps_font *ef;
1371   int lineLen = strlen(dscName);
1372   if (!state->font_list)
1373     return;
1374   fputs(dscName, state->fp);
1375   for (ef = state->font_list; ef; ef = ef->next) {
1376     int nameLen = strlen(ef->ps_font);
1377     if (lineLen + nameLen > 100 && lineLen) {
1378       fputs("\n", state->fp);
1379       fputs("%%- \n", state->fp);
1380       lineLen = 5;
1381     } else {
1382       fputs(" ", state->fp);
1383       lineLen++;
1384     }
1385     fputs(ef->ps_font, state->fp);
1386     lineLen += nameLen;
1387   }
1388   fputs("\n", state->fp);
1389 }
1390
1391 static void eps_define_fonts(eps_state *state)
1392 {
1393   eps_font *ef;
1394   if (!state->font_list)
1395     return;
1396   for (ef = state->font_list; ef; ef = ef->next) {
1397     /* PostScript¨ LANGUAGE REFERENCE third edition
1398        page 349 */
1399     fprintf(state->fp,
1400         "%%\n"
1401         "/%s findfont dup length dict begin\n"
1402         "{ 1 index /FID ne {def} {pop pop} ifelse } forall\n"
1403         "/Encoding ISOLatin1Encoding def\n"
1404         "currentdict end\n"
1405         "/%s-ISOLatin1 exch definefont pop\n"
1406         "/SetFont-%s { /%s-ISOLatin1 findfont exch scalefont setfont } bd\n",
1407         ef->ps_font, ef->ps_font, ef->ps_font, ef->ps_font);
1408   }
1409 }
1410
1411 static int eps_prologue(eps_state *state)
1412 {
1413   gfx_node_t *node;
1414   fputs(
1415     "%!PS-Adobe-3.0 EPSF-3.0\n"
1416     "%%Creator: RRDtool 1.2.1 Tobias Oetiker, http://tobi.oetiker.ch\n"
1417     /* can't like weird chars here */
1418     "%%Title: (RRDtool output)\n"
1419     "%%DocumentData: Clean7Bit\n"
1420     "", state->fp);
1421   fprintf(state->fp, "%%%%BoundingBox: 0 0 %d %d\n",
1422     state->page_width, state->page_height);
1423   for (node = state->canvas->firstnode; node; node = node->next) {
1424     if (node->type == GFX_TEXT && eps_add_font(state, node) == -1)
1425       return -1;
1426   }
1427   eps_list_fonts(state, "%%DocumentFonts:");
1428   eps_list_fonts(state, "%%DocumentNeededFonts:");
1429   fputs(
1430       "%%EndComments\n"
1431       "%%BeginProlog\n"
1432       "%%EndProlog\n" /* must have, or BoundingBox is ignored */
1433       "/bd { bind def } bind def\n"
1434       "", state->fp);
1435   fprintf(state->fp, "/X { %.2f add } bd\n", LINEOFFSET);
1436   fputs(
1437       "/X2 {X exch X exch} bd\n"
1438       "/M {X2 moveto} bd\n"
1439       "/L {X2 lineto} bd\n"
1440       "/m {moveto} bd\n"
1441       "/l {lineto} bd\n"
1442       "/S {stroke} bd\n"
1443       "/CP {closepath} bd\n"
1444       "/WS {setlinewidth stroke} bd\n"
1445       "/F {fill} bd\n"
1446       "/TaL { } bd\n"
1447       "/TaC {dup stringwidth pop neg 2 div 0 rmoveto } bd\n"
1448       "/TaR {dup stringwidth pop neg 0 rmoveto } bd\n"
1449       "/TL {moveto TaL show} bd\n"
1450       "/TC {moveto TaC show} bd\n"
1451       "/TR {moveto TaR show} bd\n"
1452       "/Rgb { 255.0 div 3 1 roll\n"
1453       "       255.0 div 3 1 roll \n"
1454       "       255.0 div 3 1 roll setrgbcolor } bd\n"
1455       "", state->fp);
1456   eps_define_fonts(state);
1457   return 0;
1458 }
1459
1460 static void eps_clear_dash(eps_state *state)
1461 {
1462   if (!state->has_dash)
1463     return;
1464   state->has_dash = 0;
1465   fputs("[1 0] 0 setdash\n", state->fp);
1466 }
1467
1468 static void eps_write_linearea(eps_state *state, gfx_node_t *node)
1469 {
1470   int i;
1471   FILE *fp = state->fp;
1472   int useOffset = 0;
1473   int clearDashIfAny = 1;
1474   eps_set_color(state, node->color);
1475   if (node->type == GFX_LINE) {
1476     svg_dash dash_info;
1477     if (state->linecap != 1) {
1478       fputs("1 setlinecap\n", fp);
1479       state->linecap = 1;
1480     }
1481     if (state->linejoin != 1) {
1482       fputs("1 setlinejoin\n", fp);
1483       state->linejoin = 1;
1484     }
1485     svg_get_dash(node, &dash_info);
1486     if (dash_info.dash_enable) {
1487       clearDashIfAny = 0;
1488       state->has_dash = 1;
1489       fputs("[", fp);
1490       svg_write_number(fp, dash_info.adjusted_on);
1491       fputs(" ", fp);
1492       svg_write_number(fp, dash_info.adjusted_off);
1493       fputs("] ", fp);
1494       svg_write_number(fp, dash_info.dash_offset);
1495       fputs(" setdash\n", fp);
1496     }
1497   }
1498   if (clearDashIfAny)
1499     eps_clear_dash(state);
1500   for (i = 0; i < node->points; i++) {
1501     ArtVpath *vec = node->path + i;
1502     double x = vec->x;
1503     double y = state->page_height - vec->y;
1504     if (vec->code == ART_MOVETO_OPEN || vec->code == ART_MOVETO)
1505       useOffset = (fabs(x - floor(x) - 0.5) < 0.01 && fabs(y - floor(y) - 0.5) < 0.01);
1506     if (useOffset) {
1507       x -= LINEOFFSET;
1508       y -= LINEOFFSET;
1509     }
1510     switch (vec->code) {
1511     case ART_MOVETO_OPEN: /* fall-through */
1512     case ART_MOVETO:
1513       svg_write_number(fp, x);
1514       fputc(' ', fp);
1515       svg_write_number(fp, y);
1516       fputc(' ', fp);
1517       fputs(useOffset ? "M\n" : "m\n", fp);
1518       break;
1519     case ART_LINETO:
1520       svg_write_number(fp, x);
1521       fputc(' ', fp);
1522       svg_write_number(fp, y);
1523       fputc(' ', fp);
1524       fputs(useOffset ? "L\n" : "l\n", fp);
1525       break;
1526     case ART_CURVETO: break; /* unsupported */
1527     case ART_END: break; /* nop */
1528     }
1529   }
1530   if (node->type == GFX_LINE) {
1531     if (node->closed_path)
1532       fputs("CP ", fp);
1533     if (node->size != state->line_width) {
1534       state->line_width = node->size;
1535       svg_write_number(fp, state->line_width);
1536       fputs(" WS\n", fp);
1537     } else {
1538       fputs("S\n", fp);
1539     }
1540    } else {
1541     fputs("F\n", fp);
1542    }
1543 }
1544
1545 static void eps_write_text(eps_state *state, gfx_node_t *node)
1546 {
1547   FILE *fp = state->fp;
1548   const unsigned char *p;
1549   const char *ps_font = afm_get_font_postscript_name(node->filename);
1550   char align = 'L';
1551   double x = node->x;
1552   double y = state->page_height - node->y, ydelta = 0;
1553   int lineLen = 0;
1554   eps_set_color(state, node->color);
1555   if (strcmp(ps_font, state->font) || node->size != state->font_size) {
1556     state->font = ps_font;
1557     state->font_size = node->size;
1558     svg_write_number(fp, state->font_size);
1559     fprintf(fp, " SetFont-%s\n", state->font);
1560   }
1561   fputs("(", fp);
1562   lineLen = 20;
1563   for (p = (const unsigned char*)node->text; *p; p++) {
1564     if (lineLen > 70) {
1565       fputs("\\\n", fp); /* backslash and \n */
1566       lineLen = 0;
1567     }
1568     switch (*p) {
1569       case '(':
1570       case ')':
1571       case '\\':
1572       case '\n':
1573       case '\r':
1574       case '\t':
1575         fputc('\\', fp);
1576         lineLen++;
1577         /* fall-through */
1578       default:
1579         if (*p >= 126)
1580           fprintf(fp, "\\%03o", *p);
1581         else
1582           fputc(*p, fp);
1583         lineLen++;
1584     }
1585   }
1586   fputs(") ", fp);
1587   switch(node->valign){
1588   case GFX_V_TOP:    ydelta = -node->size; break;
1589   case GFX_V_CENTER: ydelta = -node->size / 3.0; break;          
1590   case GFX_V_BOTTOM: break;          
1591   case GFX_V_NULL: break;          
1592   }
1593   if (node->angle == 0)
1594     y += ydelta;
1595   switch (node->halign) {
1596   case GFX_H_RIGHT:  align = 'R'; break;
1597   case GFX_H_CENTER: align = 'C'; break;
1598   case GFX_H_LEFT: align= 'L'; break;
1599   case GFX_H_NULL: align= 'L'; break;
1600   }
1601   if (node->angle != 0) {
1602     fputs("\n", fp);
1603     fputs("  gsave ", fp);
1604     svg_write_number(fp, x);
1605     fputc(' ', fp);
1606     svg_write_number(fp, y);
1607     fputs(" translate ", fp);
1608     svg_write_number(fp, -node->angle);
1609     fputs(" rotate 0 ", fp);
1610     svg_write_number(fp, ydelta);
1611     fputs(" moveto ", fp);
1612     fprintf(fp, "Ta%c", align);
1613     fputs(" show grestore\n", fp);
1614   } else {
1615     svg_write_number(fp, x);
1616     fputc(' ', fp);
1617     svg_write_number(fp, y);
1618     fputs(" T", fp);
1619     fputc(align, fp);
1620     fputc('\n', fp);
1621   }
1622 }
1623
1624 static int eps_write_content(eps_state *state)
1625 {
1626   gfx_node_t *node;
1627   fputs("%\n", state->fp);
1628   for (node = state->canvas->firstnode; node; node = node->next) {
1629     switch (node->type) {
1630     case GFX_LINE:
1631     case GFX_AREA:
1632       eps_write_linearea(state, node);
1633       break;
1634     case GFX_TEXT:
1635       eps_write_text(state, node);
1636       break;
1637     }
1638   }
1639   return 0;
1640 }
1641
1642 int       gfx_render_eps (gfx_canvas_t *canvas,
1643                  art_u32 width, art_u32 height,
1644                  gfx_color_t background, FILE *fp){
1645   struct eps_state state;
1646   state.fp = fp;
1647   state.canvas = canvas;
1648   state.page_width = width;
1649   state.page_height = height;
1650   state.font = "no-default-font";
1651   state.font_size = -1;
1652   state.color = 0; /* black */
1653   state.font_list = NULL;
1654   state.linecap = -1;
1655   state.linejoin = -1;
1656   state.has_dash = 0;
1657   if (eps_prologue(&state) == -1)
1658     return -1;
1659   eps_set_color(&state, background);
1660   fprintf(fp, "0 0 M 0 %d L %d %d L %d 0 L fill\n",
1661       height, width, height, width);
1662   if (eps_write_content(&state) == -1)
1663     return 0;
1664   fputs("showpage\n", fp);
1665   fputs("%%EOF\n", fp);
1666   while (state.font_list) {
1667     eps_font *next = state.font_list->next;
1668     free(state.font_list);
1669     state.font_list = next;
1670   }
1671   return 0;
1672 }
1673
1674 /* ------- PDF -------
1675    PDF references page:
1676    http://partners.adobe.com/asn/developer/technotes/acrobatpdf.html
1677 */
1678
1679 typedef struct pdf_buffer
1680 {
1681   int id, is_obj, is_dict, is_stream, pdf_file_pos;
1682   char *data;
1683   int alloc_size, current_size;
1684   struct pdf_buffer *previous_buffer, *next_buffer;
1685   struct pdf_state *state;
1686 } pdf_buffer;
1687
1688 typedef struct pdf_font
1689 {
1690   const char *ps_font;
1691   pdf_buffer obj;
1692   struct pdf_font *next;
1693 } pdf_font;
1694
1695 typedef struct pdf_state
1696 {
1697   FILE *fp;
1698   gfx_canvas_t *canvas;
1699   art_u32 page_width, page_height;
1700   pdf_font *font_list;
1701   pdf_buffer *first_buffer, *last_buffer;
1702   int pdf_file_pos;
1703   int has_failed;
1704   /*--*/
1705   gfx_color_t stroke_color, fill_color;
1706   int font_id;
1707   double font_size;
1708   double line_width;
1709   svg_dash dash;
1710   int linecap, linejoin;
1711   int last_obj_id;
1712   /*--*/
1713   pdf_buffer pdf_header;
1714   pdf_buffer catalog_obj, pages_obj, page1_obj;
1715   pdf_buffer fontsdict_obj;
1716   pdf_buffer graph_stream;
1717 } pdf_state;
1718
1719 static void pdf_init_buffer(pdf_state *state, pdf_buffer *buf)
1720 {
1721   int initial_size = 32;
1722   buf->state = state;
1723   buf->id = -42;
1724   buf->alloc_size = 0;
1725   buf->current_size = 0;
1726   buf->data = (char*)malloc(initial_size);
1727   buf->is_obj = 0;
1728   buf->previous_buffer = NULL;
1729   buf->next_buffer = NULL;
1730   if (buf->data == NULL) {
1731     rrd_set_error("malloc for pdf_buffer data");
1732     state->has_failed = 1;
1733     return;
1734   }
1735   buf->alloc_size = initial_size;
1736   if (state->last_buffer)
1737     state->last_buffer->next_buffer = buf;
1738   if (state->first_buffer == NULL)
1739     state->first_buffer = buf;
1740   buf->previous_buffer = state->last_buffer;
1741   state->last_buffer = buf;
1742 }
1743
1744 static void pdf_put(pdf_buffer *buf, const char *text, int len)
1745 {
1746   if (len <= 0)
1747     return;
1748   if (buf->alloc_size < buf->current_size + len) {
1749     int new_size = buf->alloc_size;
1750     char *new_buf;
1751     while (new_size < buf->current_size + len)
1752       new_size *= 4;
1753     new_buf = (char*)malloc(new_size);
1754     if (new_buf == NULL) {
1755       rrd_set_error("re-malloc for pdf_buffer data");
1756       buf->state->has_failed = 1;
1757       return;
1758     }
1759     memcpy(new_buf, buf->data, buf->current_size);
1760     free(buf->data);
1761     buf->data = new_buf;
1762     buf->alloc_size = new_size;
1763   }
1764   memcpy(buf->data + buf->current_size, text, len);
1765   buf->current_size += len;
1766 }
1767
1768 static void pdf_puts(pdf_buffer *buf, const char *text)
1769 {
1770   pdf_put(buf, text, strlen(text));
1771 }
1772
1773 static void pdf_indent(pdf_buffer *buf)
1774 {
1775   pdf_puts(buf, "\t");
1776 }
1777
1778 static void pdf_putsi(pdf_buffer *buf, const char *text)
1779 {
1780   pdf_indent(buf);
1781   pdf_puts(buf, text);
1782 }
1783
1784 static void pdf_putint(pdf_buffer *buf, int i)
1785 {
1786   char tmp[20];
1787   sprintf(tmp, "%d", i);
1788   pdf_puts(buf, tmp);
1789 }
1790
1791 static void pdf_putnumber(pdf_buffer *buf, double d)
1792 {
1793   char tmp[50];
1794   svg_format_number(tmp, sizeof(tmp), d);
1795   pdf_puts(buf, tmp);
1796 }
1797
1798 static void pdf_init_object(pdf_state *state, pdf_buffer *buf)
1799 {
1800   pdf_init_buffer(state, buf);
1801   buf->id = ++state->last_obj_id;
1802   buf->is_obj = 1;
1803   buf->is_stream = 0;
1804 }
1805
1806 static void pdf_init_dict(pdf_state *state, pdf_buffer *buf)
1807 {
1808   pdf_init_object(state, buf);
1809   buf->is_dict = 1;
1810 }
1811
1812 static void pdf_set_color(pdf_buffer *buf, gfx_color_t color,
1813         gfx_color_t *current_color, const char *op)
1814 {
1815    /* gfx_color_t is RRGGBBAA */
1816   if (*current_color == color)
1817     return;
1818   pdf_putnumber(buf, ((color >> 24) & 255) / 255.0);
1819   pdf_puts(buf, " ");
1820   pdf_putnumber(buf, ((color >> 16) & 255) / 255.0);
1821   pdf_puts(buf, " ");
1822   pdf_putnumber(buf, ((color >>  8) & 255) / 255.0);
1823   pdf_puts(buf, " ");
1824   pdf_puts(buf, op);
1825   pdf_puts(buf, "\n");
1826   *current_color = color;
1827 }
1828
1829 static void pdf_set_stroke_color(pdf_buffer *buf, gfx_color_t color)
1830 {
1831     pdf_set_color(buf, color, &buf->state->stroke_color, "RG");
1832 }
1833
1834 static void pdf_set_fill_color(pdf_buffer *buf, gfx_color_t color)
1835 {
1836     pdf_set_color(buf, color, &buf->state->fill_color, "rg");
1837 }
1838
1839 static pdf_font *pdf_find_font(pdf_state *state, gfx_node_t *node)
1840 {
1841   const char *ps_font = afm_get_font_postscript_name(node->filename);
1842   pdf_font *ef;
1843   for (ef = state->font_list; ef; ef = ef->next) {
1844     if (!strcmp(ps_font, ef->ps_font))
1845       return ef;
1846   }
1847   return NULL;
1848 }
1849
1850 static void pdf_add_font(pdf_state *state, gfx_node_t *node)
1851 {
1852   pdf_font *ef = pdf_find_font(state, node);
1853   if (ef)
1854     return;
1855   ef = malloc(sizeof(pdf_font));
1856   if (ef == NULL) {
1857     rrd_set_error("malloc for pdf_font");
1858     state->has_failed = 1;
1859     return;
1860   }
1861   pdf_init_dict(state, &ef->obj);
1862   ef->next = state->font_list;
1863   ef->ps_font = afm_get_font_postscript_name(node->filename);
1864   state->font_list = ef;
1865   /* fonts dict */
1866   pdf_putsi(&state->fontsdict_obj, "/F");
1867   pdf_putint(&state->fontsdict_obj, ef->obj.id);
1868   pdf_puts(&state->fontsdict_obj, " ");
1869   pdf_putint(&state->fontsdict_obj, ef->obj.id);
1870   pdf_puts(&state->fontsdict_obj, " 0 R\n");
1871   /* fonts def */
1872   pdf_putsi(&ef->obj, "/Type /Font\n");
1873   pdf_putsi(&ef->obj, "/Subtype /Type1\n");
1874   pdf_putsi(&ef->obj, "/Name /F");
1875   pdf_putint(&ef->obj, ef->obj.id);
1876   pdf_puts(&ef->obj, "\n");
1877   pdf_putsi(&ef->obj, "/BaseFont /");
1878   pdf_puts(&ef->obj, ef->ps_font);
1879   pdf_puts(&ef->obj, "\n");
1880   pdf_putsi(&ef->obj, "/Encoding /WinAnsiEncoding\n");
1881   /*  'Cp1252' (this is latin 1 extended with 27 characters;
1882       the encoding is also known as 'winansi')
1883       http://www.lowagie.com/iText/tutorial/ch09.html */
1884 }
1885
1886 static void pdf_create_fonts(pdf_state *state)
1887 {
1888   gfx_node_t *node;
1889   for (node = state->canvas->firstnode; node; node = node->next) {
1890     if (node->type == GFX_TEXT)
1891       pdf_add_font(state, node);
1892   }
1893 }
1894
1895 static void pdf_write_linearea(pdf_state *state, gfx_node_t *node)
1896 {
1897   int i;
1898   pdf_buffer *s = &state->graph_stream;
1899   if (node->type == GFX_LINE) {
1900     svg_dash dash_info;
1901     svg_get_dash(node, &dash_info);
1902     if (!svg_dash_equal(&dash_info, &state->dash)) {
1903       state->dash = dash_info;
1904       if (dash_info.dash_enable) {
1905         pdf_puts(s, "[");
1906         pdf_putnumber(s, dash_info.adjusted_on);
1907         pdf_puts(s, " ");
1908         pdf_putnumber(s, dash_info.adjusted_off);
1909         pdf_puts(s, "] ");
1910         pdf_putnumber(s, dash_info.dash_offset);
1911         pdf_puts(s, " d\n");
1912       } else {
1913         pdf_puts(s, "[] 0 d\n");
1914       }
1915     }
1916     pdf_set_stroke_color(s, node->color);
1917     if (state->linecap != 1) {
1918       pdf_puts(s, "1 j\n");
1919       state->linecap = 1;
1920     }
1921     if (state->linejoin != 1) {
1922       pdf_puts(s, "1 J\n");
1923       state->linejoin = 1;
1924     }
1925     if (node->size != state->line_width) {
1926       state->line_width = node->size;
1927       pdf_putnumber(s, state->line_width);
1928       pdf_puts(s, " w\n");
1929     }
1930   } else {
1931     pdf_set_fill_color(s, node->color);
1932   }
1933   for (i = 0; i < node->points; i++) {
1934     ArtVpath *vec = node->path + i;
1935     double x = vec->x;
1936     double y = state->page_height - vec->y;
1937     if (node->type == GFX_AREA) {
1938       x += LINEOFFSET; /* adjust for libart handling of areas */
1939       y -= LINEOFFSET;
1940     }
1941     switch (vec->code) {
1942     case ART_MOVETO_OPEN: /* fall-through */
1943     case ART_MOVETO:
1944       pdf_putnumber(s, x);
1945       pdf_puts(s, " ");
1946       pdf_putnumber(s, y);
1947       pdf_puts(s, " m\n");
1948       break;
1949     case ART_LINETO:
1950       pdf_putnumber(s, x);
1951       pdf_puts(s, " ");
1952       pdf_putnumber(s, y);
1953       pdf_puts(s, " l\n");
1954       break;
1955     case ART_CURVETO: break; /* unsupported */
1956     case ART_END: break; /* nop */
1957     }
1958   }
1959   if (node->type == GFX_LINE) {
1960     pdf_puts(s, node->closed_path ? "s\n" : "S\n");
1961    } else {
1962     pdf_puts(s, "f\n");
1963    }
1964 }
1965
1966 static void pdf_write_text(pdf_state *state, gfx_node_t *node, 
1967     int last_was_text, int next_is_text)
1968 {
1969   char tmp[30];
1970   pdf_buffer *s = &state->graph_stream;
1971   const unsigned char *p;
1972   pdf_font *font = pdf_find_font(state, node);
1973   double x = node->x;
1974   double y = state->page_height - node->y;
1975   double dx = 0, dy = 0;
1976   double cos_a = 0, sin_a = 0;
1977   if (font == NULL) {
1978     rrd_set_error("font disappeared");
1979     state->has_failed = 1;
1980     return;
1981   }
1982   switch(node->valign){
1983   case GFX_V_TOP:    dy = -node->size; break;
1984   case GFX_V_CENTER: dy = -node->size / 3.0; break;          
1985   case GFX_V_BOTTOM: break;          
1986   case GFX_V_NULL: break;          
1987   }
1988   switch (node->halign) {
1989   case GFX_H_RIGHT:  dx = -afm_get_text_width(0, font->ps_font, 
1990                          node->size, node->tabwidth, node->text);
1991                      break;
1992   case GFX_H_CENTER: dx = -afm_get_text_width(0, font->ps_font, 
1993                          node->size, node->tabwidth, node->text) / 2;
1994                      break;
1995   case GFX_H_LEFT: break;
1996   case GFX_H_NULL: break;
1997   }
1998   pdf_set_fill_color(s, node->color);
1999   if (node->angle != 0) {
2000     double a = 2 * M_PI * -node->angle / 360.0;
2001     double new_x, new_y;
2002     cos_a = cos(a);
2003     sin_a = sin(a);
2004     new_x = cos_a * dx - sin_a * dy + x;
2005     new_y = sin_a * dx + cos_a * dy + y;
2006     x = new_x;
2007     y = new_y;
2008   } else {
2009     x += dx;
2010     y += dy;
2011   }
2012   if (!last_was_text)
2013     pdf_puts(s, "BT\n");
2014   if (state->font_id != font->obj.id || node->size != state->font_size) {
2015     state->font_id = font->obj.id;
2016     state->font_size = node->size;
2017     pdf_puts(s, "/F");
2018     pdf_putint(s, font->obj.id);
2019     pdf_puts(s, " ");
2020     pdf_putnumber(s, node->size);
2021     pdf_puts(s, " Tf\n");
2022   }
2023   if (node->angle == 0) {
2024     pdf_puts(s, "1 0 0 1 ");
2025   } else {
2026     pdf_putnumber(s, cos_a);
2027     pdf_puts(s, " ");
2028     pdf_putnumber(s, sin_a);
2029     pdf_puts(s, " ");
2030     pdf_putnumber(s, -sin_a);
2031     pdf_puts(s, " ");
2032     pdf_putnumber(s, cos_a);
2033     pdf_puts(s, " ");
2034   }
2035   pdf_putnumber(s, x);
2036   pdf_puts(s, " ");
2037   pdf_putnumber(s, y);
2038   pdf_puts(s, " Tm\n");
2039   pdf_puts(s, "(");
2040   for (p = (const unsigned char*)node->text; *p; p++) {
2041     switch (*p) {
2042       case '(':
2043       case ')':
2044       case '\\':
2045       case '\n':
2046       case '\r':
2047       case '\t':
2048         pdf_puts(s, "\\");
2049         /* fall-through */
2050       default:
2051         if (*p >= 126) {
2052           snprintf(tmp, sizeof(tmp), "\\%03o", *p);
2053           pdf_puts(s, tmp);
2054         } else {
2055           pdf_put(s, (const char*)p, 1);
2056         }
2057     }
2058   }
2059   pdf_puts(s, ") Tj\n");
2060   if (!next_is_text)
2061     pdf_puts(s, "ET\n");
2062 }
2063  
2064 static void pdf_write_content(pdf_state *state)
2065 {
2066   gfx_node_t *node;
2067   int last_was_text = 0, next_is_text;
2068   for (node = state->canvas->firstnode; node; node = node->next) {
2069     switch (node->type) {
2070     case GFX_LINE:
2071     case GFX_AREA:
2072       pdf_write_linearea(state, node);
2073       break;
2074     case GFX_TEXT:
2075       next_is_text = node->next && node->next->type == GFX_TEXT;
2076       pdf_write_text(state, node, last_was_text, next_is_text);
2077       break;
2078     }
2079     last_was_text = node->type == GFX_TEXT;
2080   }
2081 }
2082
2083 static void pdf_init_document(pdf_state *state)
2084 {
2085   pdf_init_buffer(state, &state->pdf_header);
2086   pdf_init_dict(state, &state->catalog_obj);
2087   pdf_init_dict(state, &state->pages_obj);
2088   pdf_init_dict(state, &state->page1_obj);
2089   pdf_init_dict(state, &state->fontsdict_obj);
2090   pdf_create_fonts(state);
2091   if (state->has_failed)
2092     return;
2093   /* make stream last object in file */
2094   pdf_init_object(state, &state->graph_stream);
2095   state->graph_stream.is_stream = 1;
2096 }
2097
2098 static void pdf_setup_document(pdf_state *state)
2099 {
2100   /* all objects created by now, so init code can reference them */
2101   /* HEADER */
2102   pdf_puts(&state->pdf_header, "%PDF-1.3\n");
2103   /* following 8 bit comment is recommended by Adobe for
2104      indicating binary file to file transfer applications */
2105   pdf_puts(&state->pdf_header, "%\xE2\xE3\xCF\xD3\n");
2106   /* CATALOG */
2107   pdf_putsi(&state->catalog_obj, "/Type /Catalog\n");
2108   pdf_putsi(&state->catalog_obj, "/Pages ");
2109   pdf_putint(&state->catalog_obj, state->pages_obj.id);
2110   pdf_puts(&state->catalog_obj, " 0 R\n");
2111   /* PAGES */
2112   pdf_putsi(&state->pages_obj, "/Type /Pages\n");
2113   pdf_putsi(&state->pages_obj, "/Kids [");
2114   pdf_putint(&state->pages_obj, state->page1_obj.id);
2115   pdf_puts(&state->pages_obj, " 0 R]\n");
2116   pdf_putsi(&state->pages_obj, "/Count 1\n");
2117   /* PAGE 1 */
2118   pdf_putsi(&state->page1_obj, "/Type /Page\n");
2119   pdf_putsi(&state->page1_obj, "/Parent ");
2120   pdf_putint(&state->page1_obj, state->pages_obj.id);
2121   pdf_puts(&state->page1_obj, " 0 R\n");
2122   pdf_putsi(&state->page1_obj, "/MediaBox [0 0 ");
2123   pdf_putint(&state->page1_obj, state->page_width);
2124   pdf_puts(&state->page1_obj, " ");
2125   pdf_putint(&state->page1_obj, state->page_height);
2126   pdf_puts(&state->page1_obj, "]\n");
2127   pdf_putsi(&state->page1_obj, "/Contents ");
2128   pdf_putint(&state->page1_obj, state->graph_stream.id);
2129   pdf_puts(&state->page1_obj, " 0 R\n");
2130   pdf_putsi(&state->page1_obj, "/Resources << /Font ");
2131   pdf_putint(&state->page1_obj, state->fontsdict_obj.id);
2132   pdf_puts(&state->page1_obj, " 0 R >>\n");
2133 }
2134
2135 static void pdf_write_string_to_file(pdf_state *state, const char *text)
2136 {
2137     fputs(text, state->fp);
2138     state->pdf_file_pos += strlen(text);
2139 }
2140
2141 static void pdf_write_buf_to_file(pdf_state *state, pdf_buffer *buf)
2142 {
2143   char tmp[40];
2144   buf->pdf_file_pos = state->pdf_file_pos;
2145   if (buf->is_obj) {
2146     snprintf(tmp, sizeof(tmp), "%d 0 obj\n", buf->id);
2147     pdf_write_string_to_file(state, tmp);
2148   }
2149   if (buf->is_dict)
2150     pdf_write_string_to_file(state, "<<\n");
2151   if (buf->is_stream) {
2152     snprintf(tmp, sizeof(tmp), "<< /Length %d >>\n", buf->current_size);
2153     pdf_write_string_to_file(state, tmp);
2154     pdf_write_string_to_file(state, "stream\n");
2155   }
2156   fwrite(buf->data, 1, buf->current_size, state->fp);
2157   state->pdf_file_pos += buf->current_size;
2158   if (buf->is_stream)
2159     pdf_write_string_to_file(state, "endstream\n");
2160   if (buf->is_dict)
2161     pdf_write_string_to_file(state, ">>\n");
2162   if (buf->is_obj)
2163     pdf_write_string_to_file(state, "endobj\n");
2164 }
2165
2166 static void pdf_write_to_file(pdf_state *state)
2167 {
2168   pdf_buffer *buf = state->first_buffer;
2169   int xref_pos;
2170   state->pdf_file_pos = 0;
2171   pdf_write_buf_to_file(state, &state->pdf_header);
2172   while (buf) {
2173     if (buf->is_obj)
2174       pdf_write_buf_to_file(state, buf);
2175     buf = buf->next_buffer;
2176   }
2177   xref_pos = state->pdf_file_pos;
2178   fprintf(state->fp, "xref\n");
2179   fprintf(state->fp, "%d %d\n", 0, state->last_obj_id + 1);
2180   /* TOC lines must be exactly 20 bytes including \n */
2181   fprintf(state->fp, "%010d %05d f\x20\n", 0, 65535);
2182   for (buf = state->first_buffer; buf; buf = buf->next_buffer) {
2183     if (buf->is_obj)
2184       fprintf(state->fp, "%010d %05d n\x20\n", buf->pdf_file_pos, 0);
2185   }
2186   fprintf(state->fp, "trailer\n");
2187   fprintf(state->fp, "<<\n");
2188   fprintf(state->fp, "\t/Size %d\n", state->last_obj_id + 1);
2189   fprintf(state->fp, "\t/Root %d 0 R\n", state->catalog_obj.id);
2190   fprintf(state->fp, ">>\n");
2191   fprintf(state->fp, "startxref\n");
2192   fprintf(state->fp, "%d\n", xref_pos);
2193   fputs("%%EOF\n", state->fp);
2194 }
2195
2196 static void pdf_free_resources(pdf_state *state)
2197 {
2198   pdf_buffer *buf = state->first_buffer;
2199   while (buf) {
2200     free(buf->data);
2201     buf->data = NULL;
2202     buf->alloc_size = buf->current_size = 0;
2203     buf = buf->next_buffer;
2204   }
2205   while (state->font_list) {
2206     pdf_font *next = state->font_list->next;
2207     free(state->font_list);
2208     state->font_list = next;
2209   }
2210 }
2211
2212 int       gfx_render_pdf (gfx_canvas_t *canvas,
2213                  art_u32 width, art_u32 height,
2214                  gfx_color_t background, FILE *fp){
2215   struct pdf_state state;
2216   memset(&state, 0, sizeof(pdf_state));
2217   state.fp = fp;
2218   state.canvas = canvas;
2219   state.page_width = width;
2220   state.page_height = height;
2221   state.font_id = -1;
2222   state.font_size = -1;
2223   state.font_list = NULL;
2224   state.linecap = -1;
2225   state.linejoin = -1;
2226   pdf_init_document(&state);
2227   /*
2228   pdf_set_color(&state, background);
2229   fprintf(fp, "0 0 M 0 %d L %d %d L %d 0 L fill\n",
2230       height, width, height, width);
2231   */
2232   if (!state.has_failed)
2233     pdf_write_content(&state);
2234   if (!state.has_failed)
2235     pdf_setup_document(&state);
2236   if (!state.has_failed)
2237     pdf_write_to_file(&state);
2238   pdf_free_resources(&state);
2239   return state.has_failed ? -1 : 0;
2240 }
2241