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