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