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