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