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