make create much faster .. -- David M. Grimes <dgrimes@navisite.com>
[rrdtool.git] / src / rrd_gfx.c
1 /****************************************************************************
2  * RRDtool 1.1.x  Copyright Tobias Oetiker, 1997 - 2002
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   if (strcmp(node->filename, svg_default_font))
1120     fprintf(fp, " font-family=\"%s\"", node->filename);
1121    fputs("\" font-size=\"", fp);
1122    svg_write_number(fp, node->size);
1123    fputs("\"", fp);
1124   if (!svg_color_is_black(node->color))
1125     svg_write_color(fp, node->color, "fill");
1126    switch (node->halign) {
1127    case GFX_H_RIGHT:  fputs(" text-anchor=\"end\"", fp); break;
1128    case GFX_H_CENTER: fputs(" text-anchor=\"middle\"", fp); break;
1129    case GFX_H_LEFT: break;
1130    case GFX_H_NULL: break;
1131    }
1132    svg_close_tag_single_line(fp);
1133    /* support for node->tabwidth missing */
1134    svg_write_text(fp, node->text);
1135    svg_end_tag(fp, "text");
1136    if (node->angle != 0)
1137      svg_end_tag(fp, "g");
1138 }
1139  
1140 int       gfx_render_svg (gfx_canvas_t *canvas,
1141                  art_u32 width, art_u32 height,
1142                  gfx_color_t background, FILE *fp){
1143    gfx_node_t *node = canvas->firstnode;
1144    fputs(
1145 "<?xml version=\"1.0\" standalone=\"no\"?>\n"
1146 "<!DOCTYPE svg PUBLIC \"-//W3C//DTD SVG 1.0//EN\"\n"
1147 "   \"http://www.w3.org/TR/2001/REC-SVG-20010904/DTD/svg10.dtd\">\n"
1148 "<!--\n"
1149 "   SVG file created by RRDtool,\n"
1150 "   Tobias Oetiker <tobi@oetike.ch>, http://tobi.oetiker.ch\n"
1151 "\n"
1152 "   The width/height attributes in the outhermost svg node\n"
1153 "   are just default sizes for the browser which is used\n"
1154 "   if the svg file is openened directly without being\n"
1155 "   embedded in an html file.\n"
1156 "   The viewBox is the local coord system for rrdtool.\n"
1157 "-->\n", fp);
1158    svg_start_tag(fp, "svg");
1159    fputs(" width=\"", fp);
1160   svg_write_number(fp, width * canvas->zoom);
1161    fputs("\" height=\"", fp);
1162   svg_write_number(fp, height * canvas->zoom);
1163    fputs("\" x=\"0\" y=\"0\" viewBox=\"", fp);
1164    svg_write_number(fp, -LINEOFFSET);
1165    fputs(" ", fp);
1166    svg_write_number(fp, -LINEOFFSET);
1167    fputs(" ", fp);
1168    svg_write_number(fp, width - LINEOFFSET);
1169    fputs(" ", fp);
1170    svg_write_number(fp, height - LINEOFFSET);
1171    fputs("\" preserveAspectRatio=\"xMidYMid\"", fp);
1172   fprintf(fp, " font-family=\"%s\"", svg_default_font); /* default font */
1173   fputs(" stroke-linecap=\"round\" stroke-linejoin=\"round\"", fp);
1174    svg_close_tag(fp);
1175    svg_start_tag(fp, "rect");
1176    fprintf(fp, " x=\"0\" y=\"0\" width=\"%d\" height=\"%d\"", width, height);
1177   svg_write_color(fp, background, "fill");
1178    svg_close_tag_empty_node(fp);
1179    while (node) {
1180      switch (node->type) {
1181      case GFX_LINE:
1182        svg_multi_path(fp, &node);
1183        break;
1184      case GFX_AREA:
1185        svg_area(fp, node);
1186        break;
1187      case GFX_TEXT:
1188        svg_text(fp, node);
1189      }
1190      node = node->next;
1191    }
1192    svg_end_tag(fp, "svg");
1193    return 0;
1194 }
1195
1196 /* ------- EPS -------
1197    EPS and Postscript references:
1198    http://partners.adobe.com/asn/developer/technotes/postscript.html
1199 */
1200
1201 typedef struct eps_font
1202 {
1203   const char *ps_font;
1204   int id;
1205   struct eps_font *next;
1206 } eps_font;
1207
1208 typedef struct eps_state
1209 {
1210   FILE *fp;
1211   gfx_canvas_t *canvas;
1212   art_u32 page_width, page_height;
1213   eps_font *font_list;
1214   /*--*/
1215   gfx_color_t color;
1216   const char *font;
1217   double font_size;
1218   double line_width;
1219   int linecap, linejoin;
1220   int has_dash;
1221 } eps_state;
1222
1223 static void eps_set_color(eps_state *state, gfx_color_t color)
1224 {
1225    /* gfx_color_t is RRGGBBAA */
1226   if (state->color == color)
1227     return;
1228   fprintf(state->fp, "%d %d %d Rgb\n",
1229       (int)((color >> 24) & 255),
1230       (int)((color >> 16) & 255),
1231       (int)((color >>  8) & 255));
1232   state->color = color;
1233 }
1234
1235 static int eps_add_font(eps_state *state, gfx_node_t *node)
1236 {
1237   /* The fonts list could be postponed to the end using
1238      (atend), but let's be nice and have them in the header. */
1239   const char *ps_font = afm_get_font_postscript_name(node->filename);
1240   eps_font *ef;
1241   for (ef = state->font_list; ef; ef = ef->next) {
1242     if (!strcmp(ps_font, ef->ps_font))
1243       return 0;
1244   }
1245   ef = malloc(sizeof(eps_font));
1246   if (ef == NULL) {
1247     rrd_set_error("malloc for eps_font");
1248     return -1;
1249   }
1250   ef->next = state->font_list;
1251   ef->ps_font = ps_font;
1252   state->font_list = ef;
1253   return 0;
1254 }
1255
1256 static void eps_list_fonts(eps_state *state, const char *dscName)
1257 {
1258   eps_font *ef;
1259   int lineLen = strlen(dscName);
1260   if (!state->font_list)
1261     return;
1262   fputs(dscName, state->fp);
1263   for (ef = state->font_list; ef; ef = ef->next) {
1264     int nameLen = strlen(ef->ps_font);
1265     if (lineLen + nameLen > 100 && lineLen) {
1266       fputs("\n", state->fp);
1267       fputs("%%- \n", state->fp);
1268       lineLen = 5;
1269     } else {
1270       fputs(" ", state->fp);
1271       lineLen++;
1272     }
1273     fputs(ef->ps_font, state->fp);
1274     lineLen += nameLen;
1275   }
1276   fputs("\n", state->fp);
1277 }
1278
1279 static void eps_define_fonts(eps_state *state)
1280 {
1281   eps_font *ef;
1282   if (!state->font_list)
1283     return;
1284   for (ef = state->font_list; ef; ef = ef->next) {
1285     /* PostScript¨ LANGUAGE REFERENCE third edition
1286        page 349 */
1287     fprintf(state->fp,
1288         "%%\n"
1289         "/%s findfont dup length dict begin\n"
1290         "{ 1 index /FID ne {def} {pop pop} ifelse } forall\n"
1291         "/Encoding ISOLatin1Encoding def\n"
1292         "currentdict end\n"
1293         "/%s-ISOLatin1 exch definefont pop\n"
1294         "/SetFont-%s { /%s-ISOLatin1 findfont exch scalefont setfont } bd\n",
1295         ef->ps_font, ef->ps_font, ef->ps_font, ef->ps_font);
1296   }
1297 }
1298
1299 static int eps_prologue(eps_state *state)
1300 {
1301   gfx_node_t *node;
1302   fputs(
1303     "%!PS-Adobe-3.0 EPSF-3.0\n"
1304     "%%Creator: RRDtool 1.1.x, Tobias Oetiker, http://tobi.oetiker.ch\n"
1305     /* can't like weird chars here */
1306     "%%Title: (RRDTool output)\n"
1307     "%%DocumentData: Clean7Bit\n"
1308     "", state->fp);
1309   fprintf(state->fp, "%%%%BoundingBox: 0 0 %d %d\n",
1310     state->page_width, state->page_height);
1311   for (node = state->canvas->firstnode; node; node = node->next) {
1312     if (node->type == GFX_TEXT && eps_add_font(state, node) == -1)
1313       return -1;
1314   }
1315   eps_list_fonts(state, "%%DocumentFonts:");
1316   eps_list_fonts(state, "%%DocumentNeededFonts:");
1317   fputs(
1318       "%%EndComments\n"
1319       "%%BeginProlog\n"
1320       "%%EndProlog\n" /* must have, or BoundingBox is ignored */
1321       "/bd { bind def } bind def\n"
1322       "", state->fp);
1323   fprintf(state->fp, "/X { %.2f add } bd\n", LINEOFFSET);
1324   fputs(
1325       "/X2 {X exch X exch} bd\n"
1326       "/M {X2 moveto} bd\n"
1327       "/L {X2 lineto} bd\n"
1328       "/m {moveto} bd\n"
1329       "/l {lineto} bd\n"
1330       "/S {stroke} bd\n"
1331       "/CP {closepath} bd\n"
1332       "/WS {setlinewidth stroke} bd\n"
1333       "/F {fill} bd\n"
1334       "/TaL { } bd\n"
1335       "/TaC {dup stringwidth pop neg 2 div 0 rmoveto } bd\n"
1336       "/TaR {dup stringwidth pop neg 0 rmoveto } bd\n"
1337       "/TL {moveto TaL show} bd\n"
1338       "/TC {moveto TaC show} bd\n"
1339       "/TR {moveto TaR show} bd\n"
1340       "/Rgb { 255.0 div 3 1 roll\n"
1341       "       255.0 div 3 1 roll \n"
1342       "       255.0 div 3 1 roll setrgbcolor } bd\n"
1343       "", state->fp);
1344   eps_define_fonts(state);
1345   return 0;
1346 }
1347
1348 static void eps_clear_dash(eps_state *state)
1349 {
1350   if (!state->has_dash)
1351     return;
1352   state->has_dash = 0;
1353   fputs("[1 0] 0 setdash\n", state->fp);
1354 }
1355
1356 static void eps_write_linearea(eps_state *state, gfx_node_t *node)
1357 {
1358   int i;
1359   FILE *fp = state->fp;
1360   int useOffset = 0;
1361   int clearDashIfAny = 1;
1362   eps_set_color(state, node->color);
1363   if (node->type == GFX_LINE) {
1364     svg_dash dash_info;
1365     if (state->linecap != 1) {
1366       fputs("1 setlinecap\n", fp);
1367       state->linecap = 1;
1368     }
1369     if (state->linejoin != 1) {
1370       fputs("1 setlinejoin\n", fp);
1371       state->linejoin = 1;
1372     }
1373     svg_get_dash(node, &dash_info);
1374     if (dash_info.dash_enable) {
1375       clearDashIfAny = 0;
1376       state->has_dash = 1;
1377       fputs("[", fp);
1378       svg_write_number(fp, dash_info.adjusted_on);
1379       fputs(" ", fp);
1380       svg_write_number(fp, dash_info.adjusted_off);
1381       fputs("] ", fp);
1382       svg_write_number(fp, dash_info.dash_offset);
1383       fputs(" setdash\n", fp);
1384     }
1385   }
1386   if (clearDashIfAny)
1387     eps_clear_dash(state);
1388   for (i = 0; i < node->points; i++) {
1389     ArtVpath *vec = node->path + i;
1390     double x = vec->x;
1391     double y = state->page_height - vec->y;
1392     if (vec->code == ART_MOVETO_OPEN || vec->code == ART_MOVETO)
1393       useOffset = (fabs(x - floor(x) - 0.5) < 0.01 && fabs(y - floor(y) - 0.5) < 0.01);
1394     if (useOffset) {
1395       x -= LINEOFFSET;
1396       y -= LINEOFFSET;
1397     }
1398     switch (vec->code) {
1399     case ART_MOVETO_OPEN: /* fall-through */
1400     case ART_MOVETO:
1401       svg_write_number(fp, x);
1402       fputc(' ', fp);
1403       svg_write_number(fp, y);
1404       fputc(' ', fp);
1405       fputs(useOffset ? "M\n" : "m\n", fp);
1406       break;
1407     case ART_LINETO:
1408       svg_write_number(fp, x);
1409       fputc(' ', fp);
1410       svg_write_number(fp, y);
1411       fputc(' ', fp);
1412       fputs(useOffset ? "L\n" : "l\n", fp);
1413       break;
1414     case ART_CURVETO: break; /* unsupported */
1415     case ART_END: break; /* nop */
1416     }
1417   }
1418   if (node->type == GFX_LINE) {
1419     if (node->closed_path)
1420       fputs("CP ", fp);
1421     if (node->size != state->line_width) {
1422       state->line_width = node->size;
1423       svg_write_number(fp, state->line_width);
1424       fputs(" WS\n", fp);
1425     } else {
1426       fputs("S\n", fp);
1427     }
1428    } else {
1429     fputs("F\n", fp);
1430    }
1431 }
1432
1433 static void eps_write_text(eps_state *state, gfx_node_t *node)
1434 {
1435   FILE *fp = state->fp;
1436   const unsigned char *p;
1437   const char *ps_font = afm_get_font_postscript_name(node->filename);
1438   char align = 'L';
1439   double x = node->x;
1440   double y = state->page_height - node->y, ydelta = 0;
1441   int lineLen = 0;
1442   eps_set_color(state, node->color);
1443   if (strcmp(ps_font, state->font) || node->size != state->font_size) {
1444     state->font = ps_font;
1445     state->font_size = node->size;
1446     svg_write_number(fp, state->font_size);
1447     fprintf(fp, " SetFont-%s\n", state->font);
1448   }
1449   fputs("(", fp);
1450   lineLen = 20;
1451   for (p = (const unsigned char*)node->text; *p; p++) {
1452     if (lineLen > 70) {
1453       fputs("\\\n", fp); /* backslash and \n */
1454       lineLen = 0;
1455     }
1456     switch (*p) {
1457       case '(':
1458       case ')':
1459       case '\\':
1460       case '\n':
1461       case '\r':
1462       case '\t':
1463         fputc('\\', fp);
1464         lineLen++;
1465         /* fall-through */
1466       default:
1467         if (*p >= 126)
1468           fprintf(fp, "\\%03o", *p);
1469         else
1470           fputc(*p, fp);
1471         lineLen++;
1472     }
1473   }
1474   fputs(") ", fp);
1475   switch(node->valign){
1476   case GFX_V_TOP:    ydelta = -node->size; break;
1477   case GFX_V_CENTER: ydelta = -node->size / 3.0; break;          
1478   case GFX_V_BOTTOM: break;          
1479   case GFX_V_NULL: break;          
1480   }
1481   if (node->angle == 0)
1482     y += ydelta;
1483   switch (node->halign) {
1484   case GFX_H_RIGHT:  align = 'R'; break;
1485   case GFX_H_CENTER: align = 'C'; break;
1486   case GFX_H_LEFT: align= 'L'; break;
1487   case GFX_H_NULL: align= 'L'; break;
1488   }
1489   if (node->angle != 0) {
1490     fputs("\n", fp);
1491     fputs("  gsave ", fp);
1492     svg_write_number(fp, x);
1493     fputc(' ', fp);
1494     svg_write_number(fp, y);
1495     fputs(" translate ", fp);
1496     svg_write_number(fp, -node->angle);
1497     fputs(" rotate 0 ", fp);
1498     svg_write_number(fp, ydelta);
1499     fputs(" moveto ", fp);
1500     fprintf(fp, "Ta%c", align);
1501     fputs(" show grestore\n", fp);
1502   } else {
1503     svg_write_number(fp, x);
1504     fputc(' ', fp);
1505     svg_write_number(fp, y);
1506     fputs(" T", fp);
1507     fputc(align, fp);
1508     fputc('\n', fp);
1509   }
1510 }
1511
1512 static int eps_write_content(eps_state *state)
1513 {
1514   gfx_node_t *node;
1515   fputs("%\n", state->fp);
1516   for (node = state->canvas->firstnode; node; node = node->next) {
1517     switch (node->type) {
1518     case GFX_LINE:
1519     case GFX_AREA:
1520       eps_write_linearea(state, node);
1521       break;
1522     case GFX_TEXT:
1523       eps_write_text(state, node);
1524       break;
1525     }
1526   }
1527   return 0;
1528 }
1529
1530 int       gfx_render_eps (gfx_canvas_t *canvas,
1531                  art_u32 width, art_u32 height,
1532                  gfx_color_t background, FILE *fp){
1533   struct eps_state state;
1534   state.fp = fp;
1535   state.canvas = canvas;
1536   state.page_width = width;
1537   state.page_height = height;
1538   state.font = "no-default-font";
1539   state.font_size = -1;
1540   state.color = 0; /* black */
1541   state.font_list = NULL;
1542   state.linecap = -1;
1543   state.linejoin = -1;
1544   state.has_dash = 0;
1545   if (eps_prologue(&state) == -1)
1546     return -1;
1547   eps_set_color(&state, background);
1548   fprintf(fp, "0 0 M 0 %d L %d %d L %d 0 L fill\n",
1549       height, width, height, width);
1550   if (eps_write_content(&state) == -1)
1551     return 0;
1552   fputs("showpage\n", fp);
1553   fputs("%%EOF\n", fp);
1554   while (state.font_list) {
1555     eps_font *next = state.font_list->next;
1556     free(state.font_list);
1557     state.font_list = next;
1558   }
1559   return 0;
1560 }
1561
1562 /* ------- PDF -------
1563    PDF references page:
1564    http://partners.adobe.com/asn/developer/technotes/acrobatpdf.html
1565 */
1566
1567 typedef struct pdf_buffer
1568 {
1569   int id, is_obj, is_dict, is_stream, pdf_file_pos;
1570   char *data;
1571   int alloc_size, current_size;
1572   struct pdf_buffer *previous_buffer, *next_buffer;
1573   struct pdf_state *state;
1574 } pdf_buffer;
1575
1576 typedef struct pdf_font
1577 {
1578   const char *ps_font;
1579   pdf_buffer obj;
1580   struct pdf_font *next;
1581 } pdf_font;
1582
1583 typedef struct pdf_state
1584 {
1585   FILE *fp;
1586   gfx_canvas_t *canvas;
1587   art_u32 page_width, page_height;
1588   pdf_font *font_list;
1589   pdf_buffer *first_buffer, *last_buffer;
1590   int pdf_file_pos;
1591   int has_failed;
1592   /*--*/
1593   gfx_color_t stroke_color, fill_color;
1594   int font_id;
1595   double font_size;
1596   double line_width;
1597   svg_dash dash;
1598   int linecap, linejoin;
1599   int last_obj_id;
1600   /*--*/
1601   pdf_buffer pdf_header;
1602   pdf_buffer catalog_obj, pages_obj, page1_obj;
1603   pdf_buffer fontsdict_obj;
1604   pdf_buffer graph_stream;
1605 } pdf_state;
1606
1607 static void pdf_init_buffer(pdf_state *state, pdf_buffer *buf)
1608 {
1609   int initial_size = 32;
1610   buf->state = state;
1611   buf->id = -42;
1612   buf->alloc_size = 0;
1613   buf->current_size = 0;
1614   buf->data = (char*)malloc(initial_size);
1615   buf->is_obj = 0;
1616   buf->previous_buffer = NULL;
1617   buf->next_buffer = NULL;
1618   if (buf->data == NULL) {
1619     rrd_set_error("malloc for pdf_buffer data");
1620     state->has_failed = 1;
1621     return;
1622   }
1623   buf->alloc_size = initial_size;
1624   if (state->last_buffer)
1625     state->last_buffer->next_buffer = buf;
1626   if (state->first_buffer == NULL)
1627     state->first_buffer = buf;
1628   buf->previous_buffer = state->last_buffer;
1629   state->last_buffer = buf;
1630 }
1631
1632 static void pdf_put(pdf_buffer *buf, const char *text, int len)
1633 {
1634   if (len <= 0)
1635     return;
1636   if (buf->alloc_size < buf->current_size + len) {
1637     int new_size = buf->alloc_size;
1638     char *new_buf;
1639     while (new_size < buf->current_size + len)
1640       new_size *= 4;
1641     new_buf = (char*)malloc(new_size);
1642     if (new_buf == NULL) {
1643       rrd_set_error("re-malloc for pdf_buffer data");
1644       buf->state->has_failed = 1;
1645       return;
1646     }
1647     memcpy(new_buf, buf->data, buf->current_size);
1648     free(buf->data);
1649     buf->data = new_buf;
1650     buf->alloc_size = new_size;
1651   }
1652   memcpy(buf->data + buf->current_size, text, len);
1653   buf->current_size += len;
1654 }
1655
1656 static void pdf_puts(pdf_buffer *buf, const char *text)
1657 {
1658   pdf_put(buf, text, strlen(text));
1659 }
1660
1661 static void pdf_indent(pdf_buffer *buf)
1662 {
1663   pdf_puts(buf, "\t");
1664 }
1665
1666 static void pdf_putsi(pdf_buffer *buf, const char *text)
1667 {
1668   pdf_indent(buf);
1669   pdf_puts(buf, text);
1670 }
1671
1672 static void pdf_putint(pdf_buffer *buf, int i)
1673 {
1674   char tmp[20];
1675   sprintf(tmp, "%d", i);
1676   pdf_puts(buf, tmp);
1677 }
1678
1679 static void pdf_putnumber(pdf_buffer *buf, double d)
1680 {
1681   char tmp[50];
1682   svg_format_number(tmp, sizeof(tmp), d);
1683   pdf_puts(buf, tmp);
1684 }
1685
1686 static void pdf_init_object(pdf_state *state, pdf_buffer *buf)
1687 {
1688   pdf_init_buffer(state, buf);
1689   buf->id = ++state->last_obj_id;
1690   buf->is_obj = 1;
1691   buf->is_stream = 0;
1692 }
1693
1694 static void pdf_init_dict(pdf_state *state, pdf_buffer *buf)
1695 {
1696   pdf_init_object(state, buf);
1697   buf->is_dict = 1;
1698 }
1699
1700 static void pdf_set_color(pdf_buffer *buf, gfx_color_t color,
1701         gfx_color_t *current_color, const char *op)
1702 {
1703    /* gfx_color_t is RRGGBBAA */
1704   if (*current_color == color)
1705     return;
1706   pdf_putnumber(buf, ((color >> 24) & 255) / 255.0);
1707   pdf_puts(buf, " ");
1708   pdf_putnumber(buf, ((color >> 16) & 255) / 255.0);
1709   pdf_puts(buf, " ");
1710   pdf_putnumber(buf, ((color >>  8) & 255) / 255.0);
1711   pdf_puts(buf, " ");
1712   pdf_puts(buf, op);
1713   pdf_puts(buf, "\n");
1714   *current_color = color;
1715 }
1716
1717 static void pdf_set_stroke_color(pdf_buffer *buf, gfx_color_t color)
1718 {
1719     pdf_set_color(buf, color, &buf->state->stroke_color, "RG");
1720 }
1721
1722 static void pdf_set_fill_color(pdf_buffer *buf, gfx_color_t color)
1723 {
1724     pdf_set_color(buf, color, &buf->state->fill_color, "rg");
1725 }
1726
1727 static pdf_font *pdf_find_font(pdf_state *state, gfx_node_t *node)
1728 {
1729   const char *ps_font = afm_get_font_postscript_name(node->filename);
1730   pdf_font *ef;
1731   for (ef = state->font_list; ef; ef = ef->next) {
1732     if (!strcmp(ps_font, ef->ps_font))
1733       return ef;
1734   }
1735   return NULL;
1736 }
1737
1738 static void pdf_add_font(pdf_state *state, gfx_node_t *node)
1739 {
1740   pdf_font *ef = pdf_find_font(state, node);
1741   if (ef)
1742     return;
1743   ef = malloc(sizeof(pdf_font));
1744   if (ef == NULL) {
1745     rrd_set_error("malloc for pdf_font");
1746     state->has_failed = 1;
1747     return;
1748   }
1749   pdf_init_dict(state, &ef->obj);
1750   ef->next = state->font_list;
1751   ef->ps_font = afm_get_font_postscript_name(node->filename);
1752   state->font_list = ef;
1753   /* fonts dict */
1754   pdf_putsi(&state->fontsdict_obj, "/F");
1755   pdf_putint(&state->fontsdict_obj, ef->obj.id);
1756   pdf_puts(&state->fontsdict_obj, " ");
1757   pdf_putint(&state->fontsdict_obj, ef->obj.id);
1758   pdf_puts(&state->fontsdict_obj, " 0 R\n");
1759   /* fonts def */
1760   pdf_putsi(&ef->obj, "/Type /Font\n");
1761   pdf_putsi(&ef->obj, "/Subtype /Type1\n");
1762   pdf_putsi(&ef->obj, "/Name /F");
1763   pdf_putint(&ef->obj, ef->obj.id);
1764   pdf_puts(&ef->obj, "\n");
1765   pdf_putsi(&ef->obj, "/BaseFont /");
1766   pdf_puts(&ef->obj, ef->ps_font);
1767   pdf_puts(&ef->obj, "\n");
1768   pdf_putsi(&ef->obj, "/Encoding /WinAnsiEncoding\n");
1769   /*  'Cp1252' (this is latin 1 extended with 27 characters;
1770       the encoding is also known as 'winansi')
1771       http://www.lowagie.com/iText/tutorial/ch09.html */
1772 }
1773
1774 static void pdf_create_fonts(pdf_state *state)
1775 {
1776   gfx_node_t *node;
1777   for (node = state->canvas->firstnode; node; node = node->next) {
1778     if (node->type == GFX_TEXT)
1779       pdf_add_font(state, node);
1780   }
1781 }
1782
1783 static void pdf_write_linearea(pdf_state *state, gfx_node_t *node)
1784 {
1785   int i;
1786   pdf_buffer *s = &state->graph_stream;
1787   if (node->type == GFX_LINE) {
1788     svg_dash dash_info;
1789     svg_get_dash(node, &dash_info);
1790     if (!svg_dash_equal(&dash_info, &state->dash)) {
1791       state->dash = dash_info;
1792       if (dash_info.dash_enable) {
1793         pdf_puts(s, "[");
1794         pdf_putnumber(s, dash_info.adjusted_on);
1795         pdf_puts(s, " ");
1796         pdf_putnumber(s, dash_info.adjusted_off);
1797         pdf_puts(s, "] ");
1798         pdf_putnumber(s, dash_info.dash_offset);
1799         pdf_puts(s, " d\n");
1800       } else {
1801         pdf_puts(s, "[] 0 d\n");
1802       }
1803     }
1804     pdf_set_stroke_color(s, node->color);
1805     if (state->linecap != 1) {
1806       pdf_puts(s, "1 j\n");
1807       state->linecap = 1;
1808     }
1809     if (state->linejoin != 1) {
1810       pdf_puts(s, "1 J\n");
1811       state->linejoin = 1;
1812     }
1813     if (node->size != state->line_width) {
1814       state->line_width = node->size;
1815       pdf_putnumber(s, state->line_width);
1816       pdf_puts(s, " w\n");
1817     }
1818   } else {
1819     pdf_set_fill_color(s, node->color);
1820   }
1821   for (i = 0; i < node->points; i++) {
1822     ArtVpath *vec = node->path + i;
1823     double x = vec->x;
1824     double y = state->page_height - vec->y;
1825     if (node->type == GFX_AREA) {
1826       x += LINEOFFSET; /* adjust for libart handling of areas */
1827       y -= LINEOFFSET;
1828     }
1829     switch (vec->code) {
1830     case ART_MOVETO_OPEN: /* fall-through */
1831     case ART_MOVETO:
1832       pdf_putnumber(s, x);
1833       pdf_puts(s, " ");
1834       pdf_putnumber(s, y);
1835       pdf_puts(s, " m\n");
1836       break;
1837     case ART_LINETO:
1838       pdf_putnumber(s, x);
1839       pdf_puts(s, " ");
1840       pdf_putnumber(s, y);
1841       pdf_puts(s, " l\n");
1842       break;
1843     case ART_CURVETO: break; /* unsupported */
1844     case ART_END: break; /* nop */
1845     }
1846   }
1847   if (node->type == GFX_LINE) {
1848     pdf_puts(s, node->closed_path ? "s\n" : "S\n");
1849    } else {
1850     pdf_puts(s, "f\n");
1851    }
1852 }
1853
1854 static void pdf_write_text(pdf_state *state, gfx_node_t *node, 
1855     int last_was_text, int next_is_text)
1856 {
1857   char tmp[30];
1858   pdf_buffer *s = &state->graph_stream;
1859   const unsigned char *p;
1860   pdf_font *font = pdf_find_font(state, node);
1861   double x = node->x;
1862   double y = state->page_height - node->y;
1863   double dx = 0, dy = 0;
1864   double cos_a = 0, sin_a = 0;
1865   if (font == NULL) {
1866     rrd_set_error("font disappeared");
1867     state->has_failed = 1;
1868     return;
1869   }
1870   switch(node->valign){
1871   case GFX_V_TOP:    dy = -node->size; break;
1872   case GFX_V_CENTER: dy = -node->size / 3.0; break;          
1873   case GFX_V_BOTTOM: break;          
1874   case GFX_V_NULL: break;          
1875   }
1876   switch (node->halign) {
1877   case GFX_H_RIGHT:  dx = -afm_get_text_width(0, font->ps_font, 
1878                          node->size, node->tabwidth, node->text);
1879                      break;
1880   case GFX_H_CENTER: dx = -afm_get_text_width(0, font->ps_font, 
1881                          node->size, node->tabwidth, node->text) / 2;
1882                      break;
1883   case GFX_H_LEFT: break;
1884   case GFX_H_NULL: break;
1885   }
1886   pdf_set_fill_color(s, node->color);
1887   if (node->angle != 0) {
1888     double a = 2 * M_PI * -node->angle / 360.0;
1889     double new_x, new_y;
1890     cos_a = cos(a);
1891     sin_a = sin(a);
1892     new_x = cos_a * dx - sin_a * dy + x;
1893     new_y = sin_a * dx + cos_a * dy + y;
1894     x = new_x;
1895     y = new_y;
1896   } else {
1897     x += dx;
1898     y += dy;
1899   }
1900   if (!last_was_text)
1901     pdf_puts(s, "BT\n");
1902   if (state->font_id != font->obj.id || node->size != state->font_size) {
1903     state->font_id = font->obj.id;
1904     state->font_size = node->size;
1905     pdf_puts(s, "/F");
1906     pdf_putint(s, font->obj.id);
1907     pdf_puts(s, " ");
1908     pdf_putnumber(s, node->size);
1909     pdf_puts(s, " Tf\n");
1910   }
1911   if (node->angle == 0) {
1912     pdf_puts(s, "1 0 0 1 ");
1913   } else {
1914     pdf_putnumber(s, cos_a);
1915     pdf_puts(s, " ");
1916     pdf_putnumber(s, sin_a);
1917     pdf_puts(s, " ");
1918     pdf_putnumber(s, -sin_a);
1919     pdf_puts(s, " ");
1920     pdf_putnumber(s, cos_a);
1921     pdf_puts(s, " ");
1922   }
1923   pdf_putnumber(s, x);
1924   pdf_puts(s, " ");
1925   pdf_putnumber(s, y);
1926   pdf_puts(s, " Tm\n");
1927   pdf_puts(s, "(");
1928   for (p = (const unsigned char*)node->text; *p; p++) {
1929     switch (*p) {
1930       case '(':
1931       case ')':
1932       case '\\':
1933       case '\n':
1934       case '\r':
1935       case '\t':
1936         pdf_puts(s, "\\");
1937         /* fall-through */
1938       default:
1939         if (*p >= 126) {
1940           snprintf(tmp, sizeof(tmp), "\\%03o", *p);
1941           pdf_puts(s, tmp);
1942         } else {
1943           pdf_put(s, (const char*)p, 1);
1944         }
1945     }
1946   }
1947   pdf_puts(s, ") Tj\n");
1948   if (!next_is_text)
1949     pdf_puts(s, "ET\n");
1950 }
1951  
1952 static void pdf_write_content(pdf_state *state)
1953 {
1954   gfx_node_t *node;
1955   int last_was_text = 0, next_is_text;
1956   for (node = state->canvas->firstnode; node; node = node->next) {
1957     switch (node->type) {
1958     case GFX_LINE:
1959     case GFX_AREA:
1960       pdf_write_linearea(state, node);
1961       break;
1962     case GFX_TEXT:
1963       next_is_text = node->next && node->next->type == GFX_TEXT;
1964       pdf_write_text(state, node, last_was_text, next_is_text);
1965       break;
1966     }
1967     last_was_text = node->type == GFX_TEXT;
1968   }
1969 }
1970
1971 static void pdf_init_document(pdf_state *state)
1972 {
1973   pdf_init_buffer(state, &state->pdf_header);
1974   pdf_init_dict(state, &state->catalog_obj);
1975   pdf_init_dict(state, &state->pages_obj);
1976   pdf_init_dict(state, &state->page1_obj);
1977   pdf_init_dict(state, &state->fontsdict_obj);
1978   pdf_create_fonts(state);
1979   if (state->has_failed)
1980     return;
1981   /* make stream last object in file */
1982   pdf_init_object(state, &state->graph_stream);
1983   state->graph_stream.is_stream = 1;
1984 }
1985
1986 static void pdf_setup_document(pdf_state *state)
1987 {
1988   /* all objects created by now, so init code can reference them */
1989   /* HEADER */
1990   pdf_puts(&state->pdf_header, "%PDF-1.3\n");
1991   /* following 8 bit comment is recommended by Adobe for
1992      indicating binary file to file transfer applications */
1993   pdf_puts(&state->pdf_header, "%\xE2\xE3\xCF\xD3\n");
1994   /* CATALOG */
1995   pdf_putsi(&state->catalog_obj, "/Type /Catalog\n");
1996   pdf_putsi(&state->catalog_obj, "/Pages ");
1997   pdf_putint(&state->catalog_obj, state->pages_obj.id);
1998   pdf_puts(&state->catalog_obj, " 0 R\n");
1999   /* PAGES */
2000   pdf_putsi(&state->pages_obj, "/Type /Pages\n");
2001   pdf_putsi(&state->pages_obj, "/Kids [");
2002   pdf_putint(&state->pages_obj, state->page1_obj.id);
2003   pdf_puts(&state->pages_obj, " 0 R]\n");
2004   pdf_putsi(&state->pages_obj, "/Count 1\n");
2005   /* PAGE 1 */
2006   pdf_putsi(&state->page1_obj, "/Type /Page\n");
2007   pdf_putsi(&state->page1_obj, "/Parent ");
2008   pdf_putint(&state->page1_obj, state->pages_obj.id);
2009   pdf_puts(&state->page1_obj, " 0 R\n");
2010   pdf_putsi(&state->page1_obj, "/MediaBox [0 0 ");
2011   pdf_putint(&state->page1_obj, state->page_width);
2012   pdf_puts(&state->page1_obj, " ");
2013   pdf_putint(&state->page1_obj, state->page_height);
2014   pdf_puts(&state->page1_obj, "]\n");
2015   pdf_putsi(&state->page1_obj, "/Contents ");
2016   pdf_putint(&state->page1_obj, state->graph_stream.id);
2017   pdf_puts(&state->page1_obj, " 0 R\n");
2018   pdf_putsi(&state->page1_obj, "/Resources << /Font ");
2019   pdf_putint(&state->page1_obj, state->fontsdict_obj.id);
2020   pdf_puts(&state->page1_obj, " 0 R >>\n");
2021 }
2022
2023 static void pdf_write_string_to_file(pdf_state *state, const char *text)
2024 {
2025     fputs(text, state->fp);
2026     state->pdf_file_pos += strlen(text);
2027 }
2028
2029 static void pdf_write_buf_to_file(pdf_state *state, pdf_buffer *buf)
2030 {
2031   char tmp[40];
2032   buf->pdf_file_pos = state->pdf_file_pos;
2033   if (buf->is_obj) {
2034     snprintf(tmp, sizeof(tmp), "%d 0 obj\n", buf->id);
2035     pdf_write_string_to_file(state, tmp);
2036   }
2037   if (buf->is_dict)
2038     pdf_write_string_to_file(state, "<<\n");
2039   if (buf->is_stream) {
2040     snprintf(tmp, sizeof(tmp), "<< /Length %d >>\n", buf->current_size);
2041     pdf_write_string_to_file(state, tmp);
2042     pdf_write_string_to_file(state, "stream\n");
2043   }
2044   fwrite(buf->data, 1, buf->current_size, state->fp);
2045   state->pdf_file_pos += buf->current_size;
2046   if (buf->is_stream)
2047     pdf_write_string_to_file(state, "endstream\n");
2048   if (buf->is_dict)
2049     pdf_write_string_to_file(state, ">>\n");
2050   if (buf->is_obj)
2051     pdf_write_string_to_file(state, "endobj\n");
2052 }
2053
2054 static void pdf_write_to_file(pdf_state *state)
2055 {
2056   pdf_buffer *buf = state->first_buffer;
2057   int xref_pos;
2058   state->pdf_file_pos = 0;
2059   pdf_write_buf_to_file(state, &state->pdf_header);
2060   while (buf) {
2061     if (buf->is_obj)
2062       pdf_write_buf_to_file(state, buf);
2063     buf = buf->next_buffer;
2064   }
2065   xref_pos = state->pdf_file_pos;
2066   fprintf(state->fp, "xref\n");
2067   fprintf(state->fp, "%d %d\n", 0, state->last_obj_id + 1);
2068   /* TOC lines must be exactly 20 bytes including \n */
2069   fprintf(state->fp, "%010d %05d f\x20\n", 0, 65535);
2070   for (buf = state->first_buffer; buf; buf = buf->next_buffer) {
2071     if (buf->is_obj)
2072       fprintf(state->fp, "%010d %05d n\x20\n", buf->pdf_file_pos, 0);
2073   }
2074   fprintf(state->fp, "trailer\n");
2075   fprintf(state->fp, "<<\n");
2076   fprintf(state->fp, "\t/Size %d\n", state->last_obj_id + 1);
2077   fprintf(state->fp, "\t/Root %d 0 R\n", state->catalog_obj.id);
2078   fprintf(state->fp, ">>\n");
2079   fprintf(state->fp, "startxref\n");
2080   fprintf(state->fp, "%d\n", xref_pos);
2081   fputs("%%EOF\n", state->fp);
2082 }
2083
2084 static void pdf_free_resources(pdf_state *state)
2085 {
2086   pdf_buffer *buf = state->first_buffer;
2087   while (buf) {
2088     free(buf->data);
2089     buf->data = NULL;
2090     buf->alloc_size = buf->current_size = 0;
2091     buf = buf->next_buffer;
2092   }
2093   while (state->font_list) {
2094     pdf_font *next = state->font_list->next;
2095     free(state->font_list);
2096     state->font_list = next;
2097   }
2098 }
2099
2100 int       gfx_render_pdf (gfx_canvas_t *canvas,
2101                  art_u32 width, art_u32 height,
2102                  gfx_color_t background, FILE *fp){
2103   struct pdf_state state;
2104   memset(&state, 0, sizeof(pdf_state));
2105   state.fp = fp;
2106   state.canvas = canvas;
2107   state.page_width = width;
2108   state.page_height = height;
2109   state.font_id = -1;
2110   state.font_size = -1;
2111   state.font_list = NULL;
2112   state.linecap = -1;
2113   state.linejoin = -1;
2114   pdf_init_document(&state);
2115   /*
2116   pdf_set_color(&state, background);
2117   fprintf(fp, "0 0 M 0 %d L %d %d L %d 0 L fill\n",
2118       height, width, height, width);
2119   */
2120   if (!state.has_failed)
2121     pdf_write_content(&state);
2122   if (!state.has_failed)
2123     pdf_setup_document(&state);
2124   if (!state.has_failed)
2125     pdf_write_to_file(&state);
2126   pdf_free_resources(&state);
2127   return state.has_failed ? -1 : 0;
2128 }
2129