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