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