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