* allow configuration of the default tab width
[rrdtool.git] / src / rrd_gfx.c
1 /****************************************************************************
2  * RRDtool 1.2.x  Copyright Tobias 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   /* Write header data */
723   png_write_info (png_ptr, info_ptr);
724
725   for (i = 0; i < height; i++)
726     row_pointers[i] = (png_bytep) (buffer + i*rowstride);
727
728   png_write_image(png_ptr, row_pointers);
729   png_write_end(png_ptr, info_ptr);
730   png_destroy_write_struct(&png_ptr, &info_ptr);
731   return 1;
732 }
733
734  
735 /* ------- SVG -------
736    SVG reference:
737    http://www.w3.org/TR/SVG/
738 */
739 static int svg_indent = 0;
740 static int svg_single_line = 0;
741 static const char *svg_default_font = "Helvetica";
742 typedef struct svg_dash
743 {
744   int dash_enable;
745   double dash_adjust, dash_len, dash_offset;
746   double adjusted_on, adjusted_off;
747 } svg_dash;
748
749
750 static void svg_print_indent(FILE *fp)
751 {
752   int i;
753    for (i = svg_indent - svg_single_line; i > 0; i--) {
754      putc(' ', fp);
755      putc(' ', fp);
756    }
757 }
758  
759 static void svg_start_tag(FILE *fp, const char *name)
760 {
761    svg_print_indent(fp);
762    putc('<', fp);
763    fputs(name, fp);
764    svg_indent++;
765 }
766  
767 static void svg_close_tag_single_line(FILE *fp)
768 {
769    svg_single_line++;
770    putc('>', fp);
771 }
772  
773 static void svg_close_tag(FILE *fp)
774 {
775    putc('>', fp);
776    if (!svg_single_line)
777      putc('\n', fp);
778 }
779  
780 static void svg_end_tag(FILE *fp, const char *name)
781 {
782    /* name is NULL if closing empty-node tag */
783    svg_indent--;
784    if (svg_single_line)
785      svg_single_line--;
786    else if (name)
787      svg_print_indent(fp);
788    if (name != NULL) {
789      fputs("</", fp);
790      fputs(name, fp);
791    } else {
792      putc('/', fp);
793    }
794    svg_close_tag(fp);
795 }
796  
797 static void svg_close_tag_empty_node(FILE *fp)
798 {
799    svg_end_tag(fp, NULL);
800 }
801  
802 static void svg_write_text(FILE *fp, const char *text)
803 {
804    const unsigned char *p, *start, *last;
805    unsigned int ch;
806    p = (const unsigned char*)text;
807    if (!p)
808      return;
809    /* trim leading spaces */
810    while (*p == ' ')
811      p++;
812    start = p;
813    /* trim trailing spaces */
814    last = p - 1;
815    while ((ch = *p) != 0) {
816      if (ch != ' ')
817        last = p;
818      p++;
819   }
820   /* encode trimmed text */
821   p = start;
822   while (p <= last) {
823     ch = *p++;
824     ch = afm_host2unicode(ch); /* unsafe macro */
825     switch (ch) {
826     case '&': fputs("&amp;", fp); break;
827     case '<': fputs("&lt;", fp); break;
828     case '>': fputs("&gt;", fp); break;
829     case '"': fputs("&quot;", fp); break;
830     default:
831       if (ch >= 127)
832         fprintf(fp, "&#%d;", ch);
833       else
834         putc(ch, fp);
835      }
836    }
837 }
838  
839 static void svg_format_number(char *buf, int bufsize, double d)
840 {
841    /* omit decimals if integer to reduce filesize */
842    char *p;
843    snprintf(buf, bufsize, "%.2f", d);
844    p = buf; /* doesn't trust snprintf return value */
845    while (*p)
846      p++;
847    while (--p > buf) {
848      char ch = *p;
849      if (ch == '0') {
850        *p = '\0'; /* zap trailing zeros */
851        continue;
852      }
853      if (ch == '.')
854        *p = '\0'; /* zap trailing dot */
855      break;
856    }
857 }
858  
859 static void svg_write_number(FILE *fp, double d)
860 {
861    char buf[60];
862    svg_format_number(buf, sizeof(buf), d);
863    fputs(buf, fp);
864 }
865
866 static int svg_color_is_black(int c)
867 {
868   /* gfx_color_t is RRGGBBAA */
869   return c == 0x000000FF;
870 }
871  
872 static void svg_write_color(FILE *fp, gfx_color_t c, const char *attr)
873 {
874   /* gfx_color_t is RRGGBBAA, svg can use #RRGGBB and #RGB like html */
875   gfx_color_t rrggbb = (int)((c >> 8) & 0xFFFFFF);
876   gfx_color_t opacity = c & 0xFF;
877   fprintf(fp, " %s=\"", attr);
878   if ((rrggbb & 0x0F0F0F) == ((rrggbb >> 4) & 0x0F0F0F)) {
879      /* css2 short form, #rgb is #rrggbb, not #r0g0b0 */
880     fprintf(fp, "#%03lX",
881           ( ((rrggbb >> 8) & 0xF00)
882           | ((rrggbb >> 4) & 0x0F0)
883           | ( rrggbb       & 0x00F)));
884    } else {
885     fprintf(fp, "#%06lX", rrggbb);
886    }
887   fputs("\"", fp);
888   if (opacity != 0xFF) {
889     fprintf(fp, " stroke-opacity=\"");
890     svg_write_number(fp, opacity / 255.0);
891     fputs("\"", fp);
892  }
893 }
894  
895 static void svg_get_dash(gfx_node_t *node, svg_dash *d)
896 {
897   double offset;
898   int mult;
899   if (node->dash_on <= 0 || node->dash_off <= 0) {
900     d->dash_enable = 0;
901     return;
902   }
903   d->dash_enable = 1;
904   d->dash_len = node->dash_on + node->dash_off;
905   /* dash on/off adjustment due to round caps */
906   d->dash_adjust = 0.8 * node->size;
907   d->adjusted_on = node->dash_on - d->dash_adjust;
908   if (d->adjusted_on < 0.01)
909       d->adjusted_on = 0.01;
910   d->adjusted_off = d->dash_len - d->adjusted_on;
911   /* dash offset calc */
912   if (node->path[0].x == node->path[1].x) /* only good for horz/vert lines */
913     offset = node->path[0].y;
914   else
915     offset = node->path[0].x;
916   mult = (int)fabs(offset / d->dash_len);
917   d->dash_offset = offset - mult * d->dash_len;
918   if (node->path[0].x < node->path[1].x || node->path[0].y < node->path[1].y)
919     d->dash_offset = d->dash_len - d->dash_offset;
920 }
921
922 static int svg_dash_equal(svg_dash *a, svg_dash *b)
923 {
924   if (a->dash_enable != b->dash_enable)
925     return 0;
926   if (a->adjusted_on != b->adjusted_on)
927     return 0;
928   if (a->adjusted_off != b->adjusted_off)
929     return 0;
930   /* rest of properties will be the same when on+off are */
931   return 1;
932 }
933
934 static void svg_common_path_attributes(FILE *fp, gfx_node_t *node)
935 {
936   svg_dash dash_info;
937   svg_get_dash(node, &dash_info);
938   fputs(" stroke-width=\"", fp);
939   svg_write_number(fp, node->size);
940   fputs("\"", fp);
941   svg_write_color(fp, node->color, "stroke");
942   fputs(" fill=\"none\"", fp);
943   if (dash_info.dash_enable) {
944     if (dash_info.dash_offset != 0) {
945       fputs(" stroke-dashoffset=\"", fp);
946       svg_write_number(fp, dash_info.dash_offset);
947       fputs("\"", fp);
948     }
949     fputs(" stroke-dasharray=\"", fp);
950     svg_write_number(fp, dash_info.adjusted_on);
951     fputs(",", fp);
952     svg_write_number(fp, dash_info.adjusted_off);
953     fputs("\"", fp);
954   }
955 }
956
957 static int svg_is_int_step(double a, double b)
958 {
959    double diff = fabs(a - b);
960    return floor(diff) == diff;
961 }
962  
963 static int svg_path_straight_segment(FILE *fp,
964      double lastA, double currentA, double currentB,
965      gfx_node_t *node,
966      int segment_idx, int isx, char absChar, char relChar)
967 {
968    if (!svg_is_int_step(lastA, currentA)) {
969      putc(absChar, fp);
970      svg_write_number(fp, currentA);
971      return 0;
972    }
973    if (segment_idx < node->points - 1) {
974      ArtVpath *vec = node->path + segment_idx + 1;
975      if (vec->code == ART_LINETO) {
976        double nextA = (isx ? vec->x : vec->y) - LINEOFFSET;
977        double nextB = (isx ? vec->y : vec->x) - LINEOFFSET;
978        if (nextB == currentB
979            && ((currentA >= lastA) == (nextA >= currentA))
980            && svg_is_int_step(currentA, nextA)) {
981          return 1; /* skip to next as it is a straight line  */
982        }
983      }
984    }
985    putc(relChar, fp);
986    svg_write_number(fp, currentA - lastA);
987    return 0;
988 }
989  
990 static void svg_path(FILE *fp, gfx_node_t *node, int multi)
991 {
992    int i;
993    double lastX = 0, lastY = 0;
994    /* for straight lines <path..> tags take less space than
995       <line..> tags because of the efficient packing
996       in the 'd' attribute */
997    svg_start_tag(fp, "path");
998   if (!multi)
999     svg_common_path_attributes(fp, node);
1000    fputs(" d=\"", fp);
1001    /* specification of the 'd' attribute: */
1002    /* http://www.w3.org/TR/SVG/paths.html#PathDataGeneralInformation */
1003    for (i = 0; i < node->points; i++) {
1004      ArtVpath *vec = node->path + i;
1005      double x = vec->x - LINEOFFSET;
1006      double y = vec->y - LINEOFFSET;
1007      switch (vec->code) {
1008      case ART_MOVETO_OPEN: /* fall-through */
1009      case ART_MOVETO:
1010        putc('M', fp);
1011        svg_write_number(fp, x);
1012        putc(',', fp);
1013        svg_write_number(fp, y);
1014        break;
1015      case ART_LINETO:
1016        /* try optimize filesize by using minimal lineto commands */
1017        /* without introducing rounding errors. */
1018        if (x == lastX) {
1019          if (svg_path_straight_segment(fp, lastY, y, x, node, i, 0, 'V', 'v'))
1020            continue;
1021        } else if (y == lastY) {
1022          if (svg_path_straight_segment(fp, lastX, x, y, node, i, 1, 'H', 'h'))
1023            continue;
1024        } else {
1025          putc('L', fp);
1026          svg_write_number(fp, x);
1027          putc(',', fp);
1028          svg_write_number(fp, y);
1029        }
1030        break;
1031      case ART_CURVETO: break; /* unsupported */
1032      case ART_END: break; /* nop */
1033      }
1034      lastX = x;
1035      lastY = y;
1036    }
1037   if (node->closed_path)
1038     fputs(" Z", fp);
1039    fputs("\"", fp);
1040    svg_close_tag_empty_node(fp);
1041 }
1042  
1043 static void svg_multi_path(FILE *fp, gfx_node_t **nodeR)
1044 {
1045    /* optimize for multiple paths with the same color, penwidth, etc. */
1046    int num = 1;
1047    gfx_node_t *node = *nodeR;
1048    gfx_node_t *next = node->next;
1049    while (next) {
1050      if (next->type != node->type
1051          || next->size != node->size
1052         || next->color != node->color
1053         || next->dash_on != node->dash_on
1054         || next->dash_off != node->dash_off)
1055        break;
1056      next = next->next;
1057      num++;
1058    }
1059    if (num == 1) {
1060      svg_path(fp, node, 0);
1061      return;
1062    }
1063    svg_start_tag(fp, "g");
1064   svg_common_path_attributes(fp, node);
1065    svg_close_tag(fp);
1066    while (num && node) {
1067      svg_path(fp, node, 1);
1068      if (!--num)
1069        break;
1070      node = node->next;
1071      *nodeR = node;
1072    }
1073    svg_end_tag(fp, "g");
1074 }
1075  
1076 static void svg_area(FILE *fp, gfx_node_t *node)
1077 {
1078    int i;
1079    double startX = 0, startY = 0;
1080    svg_start_tag(fp, "polygon");
1081   fputs(" ", fp);
1082   svg_write_color(fp, node->color, "fill");
1083   fputs(" points=\"", fp);
1084    for (i = 0; i < node->points; i++) {
1085      ArtVpath *vec = node->path + i;
1086      double x = vec->x - LINEOFFSET;
1087      double y = vec->y - LINEOFFSET;
1088      switch (vec->code) {
1089        case ART_MOVETO_OPEN: /* fall-through */
1090        case ART_MOVETO:
1091          svg_write_number(fp, x);
1092          putc(',', fp);
1093          svg_write_number(fp, y);
1094          startX = x;
1095          startY = y;
1096          break;
1097        case ART_LINETO:
1098          if (i == node->points - 2
1099                         && node->path[i + 1].code == ART_END
1100              && fabs(x - startX) < 0.001 && fabs(y - startY) < 0.001) {
1101            break; /* poly area always closed, no need for last point */
1102          }
1103          putc(' ', fp);
1104          svg_write_number(fp, x);
1105          putc(',', fp);
1106          svg_write_number(fp, y);
1107          break;
1108        case ART_CURVETO: break; /* unsupported */
1109        case ART_END: break; /* nop */
1110      }
1111    }
1112    fputs("\"", fp);
1113    svg_close_tag_empty_node(fp);
1114 }
1115  
1116 static void svg_text(FILE *fp, gfx_node_t *node)
1117 {
1118    double x = node->x - LINEOFFSET;
1119    double y = node->y - LINEOFFSET;
1120    if (node->angle != 0) {
1121      svg_start_tag(fp, "g");
1122      fputs(" transform=\"translate(", fp);
1123      svg_write_number(fp, x);
1124      fputs(",", fp);
1125      svg_write_number(fp, y);
1126      fputs(") rotate(", fp);
1127      svg_write_number(fp, node->angle);
1128      fputs(")\"", fp);
1129      x = y = 0;
1130      svg_close_tag(fp);
1131    }
1132    switch (node->valign) {
1133    case GFX_V_TOP:  y += node->size; break;
1134    case GFX_V_CENTER: y += node->size / 3; break;
1135    case GFX_V_BOTTOM: break;
1136    case GFX_V_NULL: break;
1137    }
1138    svg_start_tag(fp, "text");
1139    fputs(" x=\"", fp);
1140    svg_write_number(fp, x);
1141    fputs("\" y=\"", fp);
1142    svg_write_number(fp, y);
1143
1144 /*  if (strcmp(node->filename, svg_default_font))
1145     fprintf(fp, " font-family=\"%s\"", node->filename);
1146     */
1147    fputs("\" font-family=\"Helvetica", fp);
1148    fputs("\" font-size=\"", fp);
1149    svg_write_number(fp, node->size);
1150    fputs("\"", fp);
1151   if (!svg_color_is_black(node->color))
1152     svg_write_color(fp, node->color, "fill");
1153    switch (node->halign) {
1154    case GFX_H_RIGHT:  fputs(" text-anchor=\"end\"", fp); break;
1155    case GFX_H_CENTER: fputs(" text-anchor=\"middle\"", fp); break;
1156    case GFX_H_LEFT: break;
1157    case GFX_H_NULL: break;
1158    }
1159    svg_close_tag_single_line(fp);
1160    /* support for node->tabwidth missing */
1161    svg_write_text(fp, node->text);
1162    svg_end_tag(fp, "text");
1163    if (node->angle != 0)
1164      svg_end_tag(fp, "g");
1165 }
1166  
1167 int       gfx_render_svg (gfx_canvas_t *canvas,
1168                  art_u32 width, art_u32 height,
1169                  gfx_color_t background, FILE *fp){
1170    gfx_node_t *node = canvas->firstnode;
1171    fputs(
1172 "<?xml version=\"1.0\" standalone=\"no\"?>\n"
1173 "<!DOCTYPE svg PUBLIC \"-//W3C//DTD SVG 1.0//EN\"\n"
1174 "   \"http://www.w3.org/TR/2001/REC-SVG-20010904/DTD/svg10.dtd\">\n"
1175 "<!--\n"
1176 "   SVG file created by RRDtool,\n"
1177 "   Tobias Oetiker <tobi@oetike.ch>, http://tobi.oetiker.ch\n"
1178 "\n"
1179 "   The width/height attributes in the outhermost svg node\n"
1180 "   are just default sizes for the browser which is used\n"
1181 "   if the svg file is openened directly without being\n"
1182 "   embedded in an html file.\n"
1183 "   The viewBox is the local coord system for rrdtool.\n"
1184 "-->\n", fp);
1185    svg_start_tag(fp, "svg");
1186    fputs(" width=\"", fp);
1187   svg_write_number(fp, width * canvas->zoom);
1188    fputs("\" height=\"", fp);
1189   svg_write_number(fp, height * canvas->zoom);
1190    fputs("\" x=\"0\" y=\"0\" viewBox=\"", fp);
1191    svg_write_number(fp, -LINEOFFSET);
1192    fputs(" ", fp);
1193    svg_write_number(fp, -LINEOFFSET);
1194    fputs(" ", fp);
1195    svg_write_number(fp, width - LINEOFFSET);
1196    fputs(" ", fp);
1197    svg_write_number(fp, height - LINEOFFSET);
1198    fputs("\" preserveAspectRatio=\"xMidYMid\"", fp);
1199   fprintf(fp, " font-family=\"%s\"", svg_default_font); /* default font */
1200   fputs(" stroke-linecap=\"round\" stroke-linejoin=\"round\"", fp);
1201    svg_close_tag(fp);
1202    svg_start_tag(fp, "rect");
1203    fprintf(fp, " x=\"0\" y=\"0\" width=\"%d\" height=\"%d\"", width, height);
1204   svg_write_color(fp, background, "fill");
1205    svg_close_tag_empty_node(fp);
1206    while (node) {
1207      switch (node->type) {
1208      case GFX_LINE:
1209        svg_multi_path(fp, &node);
1210        break;
1211      case GFX_AREA:
1212        svg_area(fp, node);
1213        break;
1214      case GFX_TEXT:
1215        svg_text(fp, node);
1216      }
1217      node = node->next;
1218    }
1219    svg_end_tag(fp, "svg");
1220    return 0;
1221 }
1222
1223 /* ------- EPS -------
1224    EPS and Postscript references:
1225    http://partners.adobe.com/asn/developer/technotes/postscript.html
1226 */
1227
1228 typedef struct eps_font
1229 {
1230   const char *ps_font;
1231   int id;
1232   struct eps_font *next;
1233 } eps_font;
1234
1235 typedef struct eps_state
1236 {
1237   FILE *fp;
1238   gfx_canvas_t *canvas;
1239   art_u32 page_width, page_height;
1240   eps_font *font_list;
1241   /*--*/
1242   gfx_color_t color;
1243   const char *font;
1244   double font_size;
1245   double line_width;
1246   int linecap, linejoin;
1247   int has_dash;
1248 } eps_state;
1249
1250 static void eps_set_color(eps_state *state, gfx_color_t color)
1251 {
1252    /* gfx_color_t is RRGGBBAA */
1253   if (state->color == color)
1254     return;
1255   fprintf(state->fp, "%d %d %d Rgb\n",
1256       (int)((color >> 24) & 255),
1257       (int)((color >> 16) & 255),
1258       (int)((color >>  8) & 255));
1259   state->color = color;
1260 }
1261
1262 static int eps_add_font(eps_state *state, gfx_node_t *node)
1263 {
1264   /* The fonts list could be postponed to the end using
1265      (atend), but let's be nice and have them in the header. */
1266   const char *ps_font = afm_get_font_postscript_name(node->filename);
1267   eps_font *ef;
1268   for (ef = state->font_list; ef; ef = ef->next) {
1269     if (!strcmp(ps_font, ef->ps_font))
1270       return 0;
1271   }
1272   ef = malloc(sizeof(eps_font));
1273   if (ef == NULL) {
1274     rrd_set_error("malloc for eps_font");
1275     return -1;
1276   }
1277   ef->next = state->font_list;
1278   ef->ps_font = ps_font;
1279   state->font_list = ef;
1280   return 0;
1281 }
1282
1283 static void eps_list_fonts(eps_state *state, const char *dscName)
1284 {
1285   eps_font *ef;
1286   int lineLen = strlen(dscName);
1287   if (!state->font_list)
1288     return;
1289   fputs(dscName, state->fp);
1290   for (ef = state->font_list; ef; ef = ef->next) {
1291     int nameLen = strlen(ef->ps_font);
1292     if (lineLen + nameLen > 100 && lineLen) {
1293       fputs("\n", state->fp);
1294       fputs("%%- \n", state->fp);
1295       lineLen = 5;
1296     } else {
1297       fputs(" ", state->fp);
1298       lineLen++;
1299     }
1300     fputs(ef->ps_font, state->fp);
1301     lineLen += nameLen;
1302   }
1303   fputs("\n", state->fp);
1304 }
1305
1306 static void eps_define_fonts(eps_state *state)
1307 {
1308   eps_font *ef;
1309   if (!state->font_list)
1310     return;
1311   for (ef = state->font_list; ef; ef = ef->next) {
1312     /* PostScript¨ LANGUAGE REFERENCE third edition
1313        page 349 */
1314     fprintf(state->fp,
1315         "%%\n"
1316         "/%s findfont dup length dict begin\n"
1317         "{ 1 index /FID ne {def} {pop pop} ifelse } forall\n"
1318         "/Encoding ISOLatin1Encoding def\n"
1319         "currentdict end\n"
1320         "/%s-ISOLatin1 exch definefont pop\n"
1321         "/SetFont-%s { /%s-ISOLatin1 findfont exch scalefont setfont } bd\n",
1322         ef->ps_font, ef->ps_font, ef->ps_font, ef->ps_font);
1323   }
1324 }
1325
1326 static int eps_prologue(eps_state *state)
1327 {
1328   gfx_node_t *node;
1329   fputs(
1330     "%!PS-Adobe-3.0 EPSF-3.0\n"
1331     "%%Creator: RRDtool 1.1.x, Tobias Oetiker, http://tobi.oetiker.ch\n"
1332     /* can't like weird chars here */
1333     "%%Title: (RRDtool output)\n"
1334     "%%DocumentData: Clean7Bit\n"
1335     "", state->fp);
1336   fprintf(state->fp, "%%%%BoundingBox: 0 0 %d %d\n",
1337     state->page_width, state->page_height);
1338   for (node = state->canvas->firstnode; node; node = node->next) {
1339     if (node->type == GFX_TEXT && eps_add_font(state, node) == -1)
1340       return -1;
1341   }
1342   eps_list_fonts(state, "%%DocumentFonts:");
1343   eps_list_fonts(state, "%%DocumentNeededFonts:");
1344   fputs(
1345       "%%EndComments\n"
1346       "%%BeginProlog\n"
1347       "%%EndProlog\n" /* must have, or BoundingBox is ignored */
1348       "/bd { bind def } bind def\n"
1349       "", state->fp);
1350   fprintf(state->fp, "/X { %.2f add } bd\n", LINEOFFSET);
1351   fputs(
1352       "/X2 {X exch X exch} bd\n"
1353       "/M {X2 moveto} bd\n"
1354       "/L {X2 lineto} bd\n"
1355       "/m {moveto} bd\n"
1356       "/l {lineto} bd\n"
1357       "/S {stroke} bd\n"
1358       "/CP {closepath} bd\n"
1359       "/WS {setlinewidth stroke} bd\n"
1360       "/F {fill} bd\n"
1361       "/TaL { } bd\n"
1362       "/TaC {dup stringwidth pop neg 2 div 0 rmoveto } bd\n"
1363       "/TaR {dup stringwidth pop neg 0 rmoveto } bd\n"
1364       "/TL {moveto TaL show} bd\n"
1365       "/TC {moveto TaC show} bd\n"
1366       "/TR {moveto TaR show} bd\n"
1367       "/Rgb { 255.0 div 3 1 roll\n"
1368       "       255.0 div 3 1 roll \n"
1369       "       255.0 div 3 1 roll setrgbcolor } bd\n"
1370       "", state->fp);
1371   eps_define_fonts(state);
1372   return 0;
1373 }
1374
1375 static void eps_clear_dash(eps_state *state)
1376 {
1377   if (!state->has_dash)
1378     return;
1379   state->has_dash = 0;
1380   fputs("[1 0] 0 setdash\n", state->fp);
1381 }
1382
1383 static void eps_write_linearea(eps_state *state, gfx_node_t *node)
1384 {
1385   int i;
1386   FILE *fp = state->fp;
1387   int useOffset = 0;
1388   int clearDashIfAny = 1;
1389   eps_set_color(state, node->color);
1390   if (node->type == GFX_LINE) {
1391     svg_dash dash_info;
1392     if (state->linecap != 1) {
1393       fputs("1 setlinecap\n", fp);
1394       state->linecap = 1;
1395     }
1396     if (state->linejoin != 1) {
1397       fputs("1 setlinejoin\n", fp);
1398       state->linejoin = 1;
1399     }
1400     svg_get_dash(node, &dash_info);
1401     if (dash_info.dash_enable) {
1402       clearDashIfAny = 0;
1403       state->has_dash = 1;
1404       fputs("[", fp);
1405       svg_write_number(fp, dash_info.adjusted_on);
1406       fputs(" ", fp);
1407       svg_write_number(fp, dash_info.adjusted_off);
1408       fputs("] ", fp);
1409       svg_write_number(fp, dash_info.dash_offset);
1410       fputs(" setdash\n", fp);
1411     }
1412   }
1413   if (clearDashIfAny)
1414     eps_clear_dash(state);
1415   for (i = 0; i < node->points; i++) {
1416     ArtVpath *vec = node->path + i;
1417     double x = vec->x;
1418     double y = state->page_height - vec->y;
1419     if (vec->code == ART_MOVETO_OPEN || vec->code == ART_MOVETO)
1420       useOffset = (fabs(x - floor(x) - 0.5) < 0.01 && fabs(y - floor(y) - 0.5) < 0.01);
1421     if (useOffset) {
1422       x -= LINEOFFSET;
1423       y -= LINEOFFSET;
1424     }
1425     switch (vec->code) {
1426     case ART_MOVETO_OPEN: /* fall-through */
1427     case ART_MOVETO:
1428       svg_write_number(fp, x);
1429       fputc(' ', fp);
1430       svg_write_number(fp, y);
1431       fputc(' ', fp);
1432       fputs(useOffset ? "M\n" : "m\n", fp);
1433       break;
1434     case ART_LINETO:
1435       svg_write_number(fp, x);
1436       fputc(' ', fp);
1437       svg_write_number(fp, y);
1438       fputc(' ', fp);
1439       fputs(useOffset ? "L\n" : "l\n", fp);
1440       break;
1441     case ART_CURVETO: break; /* unsupported */
1442     case ART_END: break; /* nop */
1443     }
1444   }
1445   if (node->type == GFX_LINE) {
1446     if (node->closed_path)
1447       fputs("CP ", fp);
1448     if (node->size != state->line_width) {
1449       state->line_width = node->size;
1450       svg_write_number(fp, state->line_width);
1451       fputs(" WS\n", fp);
1452     } else {
1453       fputs("S\n", fp);
1454     }
1455    } else {
1456     fputs("F\n", fp);
1457    }
1458 }
1459
1460 static void eps_write_text(eps_state *state, gfx_node_t *node)
1461 {
1462   FILE *fp = state->fp;
1463   const unsigned char *p;
1464   const char *ps_font = afm_get_font_postscript_name(node->filename);
1465   char align = 'L';
1466   double x = node->x;
1467   double y = state->page_height - node->y, ydelta = 0;
1468   int lineLen = 0;
1469   eps_set_color(state, node->color);
1470   if (strcmp(ps_font, state->font) || node->size != state->font_size) {
1471     state->font = ps_font;
1472     state->font_size = node->size;
1473     svg_write_number(fp, state->font_size);
1474     fprintf(fp, " SetFont-%s\n", state->font);
1475   }
1476   fputs("(", fp);
1477   lineLen = 20;
1478   for (p = (const unsigned char*)node->text; *p; p++) {
1479     if (lineLen > 70) {
1480       fputs("\\\n", fp); /* backslash and \n */
1481       lineLen = 0;
1482     }
1483     switch (*p) {
1484       case '(':
1485       case ')':
1486       case '\\':
1487       case '\n':
1488       case '\r':
1489       case '\t':
1490         fputc('\\', fp);
1491         lineLen++;
1492         /* fall-through */
1493       default:
1494         if (*p >= 126)
1495           fprintf(fp, "\\%03o", *p);
1496         else
1497           fputc(*p, fp);
1498         lineLen++;
1499     }
1500   }
1501   fputs(") ", fp);
1502   switch(node->valign){
1503   case GFX_V_TOP:    ydelta = -node->size; break;
1504   case GFX_V_CENTER: ydelta = -node->size / 3.0; break;          
1505   case GFX_V_BOTTOM: break;          
1506   case GFX_V_NULL: break;          
1507   }
1508   if (node->angle == 0)
1509     y += ydelta;
1510   switch (node->halign) {
1511   case GFX_H_RIGHT:  align = 'R'; break;
1512   case GFX_H_CENTER: align = 'C'; break;
1513   case GFX_H_LEFT: align= 'L'; break;
1514   case GFX_H_NULL: align= 'L'; break;
1515   }
1516   if (node->angle != 0) {
1517     fputs("\n", fp);
1518     fputs("  gsave ", fp);
1519     svg_write_number(fp, x);
1520     fputc(' ', fp);
1521     svg_write_number(fp, y);
1522     fputs(" translate ", fp);
1523     svg_write_number(fp, -node->angle);
1524     fputs(" rotate 0 ", fp);
1525     svg_write_number(fp, ydelta);
1526     fputs(" moveto ", fp);
1527     fprintf(fp, "Ta%c", align);
1528     fputs(" show grestore\n", fp);
1529   } else {
1530     svg_write_number(fp, x);
1531     fputc(' ', fp);
1532     svg_write_number(fp, y);
1533     fputs(" T", fp);
1534     fputc(align, fp);
1535     fputc('\n', fp);
1536   }
1537 }
1538
1539 static int eps_write_content(eps_state *state)
1540 {
1541   gfx_node_t *node;
1542   fputs("%\n", state->fp);
1543   for (node = state->canvas->firstnode; node; node = node->next) {
1544     switch (node->type) {
1545     case GFX_LINE:
1546     case GFX_AREA:
1547       eps_write_linearea(state, node);
1548       break;
1549     case GFX_TEXT:
1550       eps_write_text(state, node);
1551       break;
1552     }
1553   }
1554   return 0;
1555 }
1556
1557 int       gfx_render_eps (gfx_canvas_t *canvas,
1558                  art_u32 width, art_u32 height,
1559                  gfx_color_t background, FILE *fp){
1560   struct eps_state state;
1561   state.fp = fp;
1562   state.canvas = canvas;
1563   state.page_width = width;
1564   state.page_height = height;
1565   state.font = "no-default-font";
1566   state.font_size = -1;
1567   state.color = 0; /* black */
1568   state.font_list = NULL;
1569   state.linecap = -1;
1570   state.linejoin = -1;
1571   state.has_dash = 0;
1572   if (eps_prologue(&state) == -1)
1573     return -1;
1574   eps_set_color(&state, background);
1575   fprintf(fp, "0 0 M 0 %d L %d %d L %d 0 L fill\n",
1576       height, width, height, width);
1577   if (eps_write_content(&state) == -1)
1578     return 0;
1579   fputs("showpage\n", fp);
1580   fputs("%%EOF\n", fp);
1581   while (state.font_list) {
1582     eps_font *next = state.font_list->next;
1583     free(state.font_list);
1584     state.font_list = next;
1585   }
1586   return 0;
1587 }
1588
1589 /* ------- PDF -------
1590    PDF references page:
1591    http://partners.adobe.com/asn/developer/technotes/acrobatpdf.html
1592 */
1593
1594 typedef struct pdf_buffer
1595 {
1596   int id, is_obj, is_dict, is_stream, pdf_file_pos;
1597   char *data;
1598   int alloc_size, current_size;
1599   struct pdf_buffer *previous_buffer, *next_buffer;
1600   struct pdf_state *state;
1601 } pdf_buffer;
1602
1603 typedef struct pdf_font
1604 {
1605   const char *ps_font;
1606   pdf_buffer obj;
1607   struct pdf_font *next;
1608 } pdf_font;
1609
1610 typedef struct pdf_state
1611 {
1612   FILE *fp;
1613   gfx_canvas_t *canvas;
1614   art_u32 page_width, page_height;
1615   pdf_font *font_list;
1616   pdf_buffer *first_buffer, *last_buffer;
1617   int pdf_file_pos;
1618   int has_failed;
1619   /*--*/
1620   gfx_color_t stroke_color, fill_color;
1621   int font_id;
1622   double font_size;
1623   double line_width;
1624   svg_dash dash;
1625   int linecap, linejoin;
1626   int last_obj_id;
1627   /*--*/
1628   pdf_buffer pdf_header;
1629   pdf_buffer catalog_obj, pages_obj, page1_obj;
1630   pdf_buffer fontsdict_obj;
1631   pdf_buffer graph_stream;
1632 } pdf_state;
1633
1634 static void pdf_init_buffer(pdf_state *state, pdf_buffer *buf)
1635 {
1636   int initial_size = 32;
1637   buf->state = state;
1638   buf->id = -42;
1639   buf->alloc_size = 0;
1640   buf->current_size = 0;
1641   buf->data = (char*)malloc(initial_size);
1642   buf->is_obj = 0;
1643   buf->previous_buffer = NULL;
1644   buf->next_buffer = NULL;
1645   if (buf->data == NULL) {
1646     rrd_set_error("malloc for pdf_buffer data");
1647     state->has_failed = 1;
1648     return;
1649   }
1650   buf->alloc_size = initial_size;
1651   if (state->last_buffer)
1652     state->last_buffer->next_buffer = buf;
1653   if (state->first_buffer == NULL)
1654     state->first_buffer = buf;
1655   buf->previous_buffer = state->last_buffer;
1656   state->last_buffer = buf;
1657 }
1658
1659 static void pdf_put(pdf_buffer *buf, const char *text, int len)
1660 {
1661   if (len <= 0)
1662     return;
1663   if (buf->alloc_size < buf->current_size + len) {
1664     int new_size = buf->alloc_size;
1665     char *new_buf;
1666     while (new_size < buf->current_size + len)
1667       new_size *= 4;
1668     new_buf = (char*)malloc(new_size);
1669     if (new_buf == NULL) {
1670       rrd_set_error("re-malloc for pdf_buffer data");
1671       buf->state->has_failed = 1;
1672       return;
1673     }
1674     memcpy(new_buf, buf->data, buf->current_size);
1675     free(buf->data);
1676     buf->data = new_buf;
1677     buf->alloc_size = new_size;
1678   }
1679   memcpy(buf->data + buf->current_size, text, len);
1680   buf->current_size += len;
1681 }
1682
1683 static void pdf_puts(pdf_buffer *buf, const char *text)
1684 {
1685   pdf_put(buf, text, strlen(text));
1686 }
1687
1688 static void pdf_indent(pdf_buffer *buf)
1689 {
1690   pdf_puts(buf, "\t");
1691 }
1692
1693 static void pdf_putsi(pdf_buffer *buf, const char *text)
1694 {
1695   pdf_indent(buf);
1696   pdf_puts(buf, text);
1697 }
1698
1699 static void pdf_putint(pdf_buffer *buf, int i)
1700 {
1701   char tmp[20];
1702   sprintf(tmp, "%d", i);
1703   pdf_puts(buf, tmp);
1704 }
1705
1706 static void pdf_putnumber(pdf_buffer *buf, double d)
1707 {
1708   char tmp[50];
1709   svg_format_number(tmp, sizeof(tmp), d);
1710   pdf_puts(buf, tmp);
1711 }
1712
1713 static void pdf_init_object(pdf_state *state, pdf_buffer *buf)
1714 {
1715   pdf_init_buffer(state, buf);
1716   buf->id = ++state->last_obj_id;
1717   buf->is_obj = 1;
1718   buf->is_stream = 0;
1719 }
1720
1721 static void pdf_init_dict(pdf_state *state, pdf_buffer *buf)
1722 {
1723   pdf_init_object(state, buf);
1724   buf->is_dict = 1;
1725 }
1726
1727 static void pdf_set_color(pdf_buffer *buf, gfx_color_t color,
1728         gfx_color_t *current_color, const char *op)
1729 {
1730    /* gfx_color_t is RRGGBBAA */
1731   if (*current_color == color)
1732     return;
1733   pdf_putnumber(buf, ((color >> 24) & 255) / 255.0);
1734   pdf_puts(buf, " ");
1735   pdf_putnumber(buf, ((color >> 16) & 255) / 255.0);
1736   pdf_puts(buf, " ");
1737   pdf_putnumber(buf, ((color >>  8) & 255) / 255.0);
1738   pdf_puts(buf, " ");
1739   pdf_puts(buf, op);
1740   pdf_puts(buf, "\n");
1741   *current_color = color;
1742 }
1743
1744 static void pdf_set_stroke_color(pdf_buffer *buf, gfx_color_t color)
1745 {
1746     pdf_set_color(buf, color, &buf->state->stroke_color, "RG");
1747 }
1748
1749 static void pdf_set_fill_color(pdf_buffer *buf, gfx_color_t color)
1750 {
1751     pdf_set_color(buf, color, &buf->state->fill_color, "rg");
1752 }
1753
1754 static pdf_font *pdf_find_font(pdf_state *state, gfx_node_t *node)
1755 {
1756   const char *ps_font = afm_get_font_postscript_name(node->filename);
1757   pdf_font *ef;
1758   for (ef = state->font_list; ef; ef = ef->next) {
1759     if (!strcmp(ps_font, ef->ps_font))
1760       return ef;
1761   }
1762   return NULL;
1763 }
1764
1765 static void pdf_add_font(pdf_state *state, gfx_node_t *node)
1766 {
1767   pdf_font *ef = pdf_find_font(state, node);
1768   if (ef)
1769     return;
1770   ef = malloc(sizeof(pdf_font));
1771   if (ef == NULL) {
1772     rrd_set_error("malloc for pdf_font");
1773     state->has_failed = 1;
1774     return;
1775   }
1776   pdf_init_dict(state, &ef->obj);
1777   ef->next = state->font_list;
1778   ef->ps_font = afm_get_font_postscript_name(node->filename);
1779   state->font_list = ef;
1780   /* fonts dict */
1781   pdf_putsi(&state->fontsdict_obj, "/F");
1782   pdf_putint(&state->fontsdict_obj, ef->obj.id);
1783   pdf_puts(&state->fontsdict_obj, " ");
1784   pdf_putint(&state->fontsdict_obj, ef->obj.id);
1785   pdf_puts(&state->fontsdict_obj, " 0 R\n");
1786   /* fonts def */
1787   pdf_putsi(&ef->obj, "/Type /Font\n");
1788   pdf_putsi(&ef->obj, "/Subtype /Type1\n");
1789   pdf_putsi(&ef->obj, "/Name /F");
1790   pdf_putint(&ef->obj, ef->obj.id);
1791   pdf_puts(&ef->obj, "\n");
1792   pdf_putsi(&ef->obj, "/BaseFont /");
1793   pdf_puts(&ef->obj, ef->ps_font);
1794   pdf_puts(&ef->obj, "\n");
1795   pdf_putsi(&ef->obj, "/Encoding /WinAnsiEncoding\n");
1796   /*  'Cp1252' (this is latin 1 extended with 27 characters;
1797       the encoding is also known as 'winansi')
1798       http://www.lowagie.com/iText/tutorial/ch09.html */
1799 }
1800
1801 static void pdf_create_fonts(pdf_state *state)
1802 {
1803   gfx_node_t *node;
1804   for (node = state->canvas->firstnode; node; node = node->next) {
1805     if (node->type == GFX_TEXT)
1806       pdf_add_font(state, node);
1807   }
1808 }
1809
1810 static void pdf_write_linearea(pdf_state *state, gfx_node_t *node)
1811 {
1812   int i;
1813   pdf_buffer *s = &state->graph_stream;
1814   if (node->type == GFX_LINE) {
1815     svg_dash dash_info;
1816     svg_get_dash(node, &dash_info);
1817     if (!svg_dash_equal(&dash_info, &state->dash)) {
1818       state->dash = dash_info;
1819       if (dash_info.dash_enable) {
1820         pdf_puts(s, "[");
1821         pdf_putnumber(s, dash_info.adjusted_on);
1822         pdf_puts(s, " ");
1823         pdf_putnumber(s, dash_info.adjusted_off);
1824         pdf_puts(s, "] ");
1825         pdf_putnumber(s, dash_info.dash_offset);
1826         pdf_puts(s, " d\n");
1827       } else {
1828         pdf_puts(s, "[] 0 d\n");
1829       }
1830     }
1831     pdf_set_stroke_color(s, node->color);
1832     if (state->linecap != 1) {
1833       pdf_puts(s, "1 j\n");
1834       state->linecap = 1;
1835     }
1836     if (state->linejoin != 1) {
1837       pdf_puts(s, "1 J\n");
1838       state->linejoin = 1;
1839     }
1840     if (node->size != state->line_width) {
1841       state->line_width = node->size;
1842       pdf_putnumber(s, state->line_width);
1843       pdf_puts(s, " w\n");
1844     }
1845   } else {
1846     pdf_set_fill_color(s, node->color);
1847   }
1848   for (i = 0; i < node->points; i++) {
1849     ArtVpath *vec = node->path + i;
1850     double x = vec->x;
1851     double y = state->page_height - vec->y;
1852     if (node->type == GFX_AREA) {
1853       x += LINEOFFSET; /* adjust for libart handling of areas */
1854       y -= LINEOFFSET;
1855     }
1856     switch (vec->code) {
1857     case ART_MOVETO_OPEN: /* fall-through */
1858     case ART_MOVETO:
1859       pdf_putnumber(s, x);
1860       pdf_puts(s, " ");
1861       pdf_putnumber(s, y);
1862       pdf_puts(s, " m\n");
1863       break;
1864     case ART_LINETO:
1865       pdf_putnumber(s, x);
1866       pdf_puts(s, " ");
1867       pdf_putnumber(s, y);
1868       pdf_puts(s, " l\n");
1869       break;
1870     case ART_CURVETO: break; /* unsupported */
1871     case ART_END: break; /* nop */
1872     }
1873   }
1874   if (node->type == GFX_LINE) {
1875     pdf_puts(s, node->closed_path ? "s\n" : "S\n");
1876    } else {
1877     pdf_puts(s, "f\n");
1878    }
1879 }
1880
1881 static void pdf_write_text(pdf_state *state, gfx_node_t *node, 
1882     int last_was_text, int next_is_text)
1883 {
1884   char tmp[30];
1885   pdf_buffer *s = &state->graph_stream;
1886   const unsigned char *p;
1887   pdf_font *font = pdf_find_font(state, node);
1888   double x = node->x;
1889   double y = state->page_height - node->y;
1890   double dx = 0, dy = 0;
1891   double cos_a = 0, sin_a = 0;
1892   if (font == NULL) {
1893     rrd_set_error("font disappeared");
1894     state->has_failed = 1;
1895     return;
1896   }
1897   switch(node->valign){
1898   case GFX_V_TOP:    dy = -node->size; break;
1899   case GFX_V_CENTER: dy = -node->size / 3.0; break;          
1900   case GFX_V_BOTTOM: break;          
1901   case GFX_V_NULL: break;          
1902   }
1903   switch (node->halign) {
1904   case GFX_H_RIGHT:  dx = -afm_get_text_width(0, font->ps_font, 
1905                          node->size, node->tabwidth, node->text);
1906                      break;
1907   case GFX_H_CENTER: dx = -afm_get_text_width(0, font->ps_font, 
1908                          node->size, node->tabwidth, node->text) / 2;
1909                      break;
1910   case GFX_H_LEFT: break;
1911   case GFX_H_NULL: break;
1912   }
1913   pdf_set_fill_color(s, node->color);
1914   if (node->angle != 0) {
1915     double a = 2 * M_PI * -node->angle / 360.0;
1916     double new_x, new_y;
1917     cos_a = cos(a);
1918     sin_a = sin(a);
1919     new_x = cos_a * dx - sin_a * dy + x;
1920     new_y = sin_a * dx + cos_a * dy + y;
1921     x = new_x;
1922     y = new_y;
1923   } else {
1924     x += dx;
1925     y += dy;
1926   }
1927   if (!last_was_text)
1928     pdf_puts(s, "BT\n");
1929   if (state->font_id != font->obj.id || node->size != state->font_size) {
1930     state->font_id = font->obj.id;
1931     state->font_size = node->size;
1932     pdf_puts(s, "/F");
1933     pdf_putint(s, font->obj.id);
1934     pdf_puts(s, " ");
1935     pdf_putnumber(s, node->size);
1936     pdf_puts(s, " Tf\n");
1937   }
1938   if (node->angle == 0) {
1939     pdf_puts(s, "1 0 0 1 ");
1940   } else {
1941     pdf_putnumber(s, cos_a);
1942     pdf_puts(s, " ");
1943     pdf_putnumber(s, sin_a);
1944     pdf_puts(s, " ");
1945     pdf_putnumber(s, -sin_a);
1946     pdf_puts(s, " ");
1947     pdf_putnumber(s, cos_a);
1948     pdf_puts(s, " ");
1949   }
1950   pdf_putnumber(s, x);
1951   pdf_puts(s, " ");
1952   pdf_putnumber(s, y);
1953   pdf_puts(s, " Tm\n");
1954   pdf_puts(s, "(");
1955   for (p = (const unsigned char*)node->text; *p; p++) {
1956     switch (*p) {
1957       case '(':
1958       case ')':
1959       case '\\':
1960       case '\n':
1961       case '\r':
1962       case '\t':
1963         pdf_puts(s, "\\");
1964         /* fall-through */
1965       default:
1966         if (*p >= 126) {
1967           snprintf(tmp, sizeof(tmp), "\\%03o", *p);
1968           pdf_puts(s, tmp);
1969         } else {
1970           pdf_put(s, (const char*)p, 1);
1971         }
1972     }
1973   }
1974   pdf_puts(s, ") Tj\n");
1975   if (!next_is_text)
1976     pdf_puts(s, "ET\n");
1977 }
1978  
1979 static void pdf_write_content(pdf_state *state)
1980 {
1981   gfx_node_t *node;
1982   int last_was_text = 0, next_is_text;
1983   for (node = state->canvas->firstnode; node; node = node->next) {
1984     switch (node->type) {
1985     case GFX_LINE:
1986     case GFX_AREA:
1987       pdf_write_linearea(state, node);
1988       break;
1989     case GFX_TEXT:
1990       next_is_text = node->next && node->next->type == GFX_TEXT;
1991       pdf_write_text(state, node, last_was_text, next_is_text);
1992       break;
1993     }
1994     last_was_text = node->type == GFX_TEXT;
1995   }
1996 }
1997
1998 static void pdf_init_document(pdf_state *state)
1999 {
2000   pdf_init_buffer(state, &state->pdf_header);
2001   pdf_init_dict(state, &state->catalog_obj);
2002   pdf_init_dict(state, &state->pages_obj);
2003   pdf_init_dict(state, &state->page1_obj);
2004   pdf_init_dict(state, &state->fontsdict_obj);
2005   pdf_create_fonts(state);
2006   if (state->has_failed)
2007     return;
2008   /* make stream last object in file */
2009   pdf_init_object(state, &state->graph_stream);
2010   state->graph_stream.is_stream = 1;
2011 }
2012
2013 static void pdf_setup_document(pdf_state *state)
2014 {
2015   /* all objects created by now, so init code can reference them */
2016   /* HEADER */
2017   pdf_puts(&state->pdf_header, "%PDF-1.3\n");
2018   /* following 8 bit comment is recommended by Adobe for
2019      indicating binary file to file transfer applications */
2020   pdf_puts(&state->pdf_header, "%\xE2\xE3\xCF\xD3\n");
2021   /* CATALOG */
2022   pdf_putsi(&state->catalog_obj, "/Type /Catalog\n");
2023   pdf_putsi(&state->catalog_obj, "/Pages ");
2024   pdf_putint(&state->catalog_obj, state->pages_obj.id);
2025   pdf_puts(&state->catalog_obj, " 0 R\n");
2026   /* PAGES */
2027   pdf_putsi(&state->pages_obj, "/Type /Pages\n");
2028   pdf_putsi(&state->pages_obj, "/Kids [");
2029   pdf_putint(&state->pages_obj, state->page1_obj.id);
2030   pdf_puts(&state->pages_obj, " 0 R]\n");
2031   pdf_putsi(&state->pages_obj, "/Count 1\n");
2032   /* PAGE 1 */
2033   pdf_putsi(&state->page1_obj, "/Type /Page\n");
2034   pdf_putsi(&state->page1_obj, "/Parent ");
2035   pdf_putint(&state->page1_obj, state->pages_obj.id);
2036   pdf_puts(&state->page1_obj, " 0 R\n");
2037   pdf_putsi(&state->page1_obj, "/MediaBox [0 0 ");
2038   pdf_putint(&state->page1_obj, state->page_width);
2039   pdf_puts(&state->page1_obj, " ");
2040   pdf_putint(&state->page1_obj, state->page_height);
2041   pdf_puts(&state->page1_obj, "]\n");
2042   pdf_putsi(&state->page1_obj, "/Contents ");
2043   pdf_putint(&state->page1_obj, state->graph_stream.id);
2044   pdf_puts(&state->page1_obj, " 0 R\n");
2045   pdf_putsi(&state->page1_obj, "/Resources << /Font ");
2046   pdf_putint(&state->page1_obj, state->fontsdict_obj.id);
2047   pdf_puts(&state->page1_obj, " 0 R >>\n");
2048 }
2049
2050 static void pdf_write_string_to_file(pdf_state *state, const char *text)
2051 {
2052     fputs(text, state->fp);
2053     state->pdf_file_pos += strlen(text);
2054 }
2055
2056 static void pdf_write_buf_to_file(pdf_state *state, pdf_buffer *buf)
2057 {
2058   char tmp[40];
2059   buf->pdf_file_pos = state->pdf_file_pos;
2060   if (buf->is_obj) {
2061     snprintf(tmp, sizeof(tmp), "%d 0 obj\n", buf->id);
2062     pdf_write_string_to_file(state, tmp);
2063   }
2064   if (buf->is_dict)
2065     pdf_write_string_to_file(state, "<<\n");
2066   if (buf->is_stream) {
2067     snprintf(tmp, sizeof(tmp), "<< /Length %d >>\n", buf->current_size);
2068     pdf_write_string_to_file(state, tmp);
2069     pdf_write_string_to_file(state, "stream\n");
2070   }
2071   fwrite(buf->data, 1, buf->current_size, state->fp);
2072   state->pdf_file_pos += buf->current_size;
2073   if (buf->is_stream)
2074     pdf_write_string_to_file(state, "endstream\n");
2075   if (buf->is_dict)
2076     pdf_write_string_to_file(state, ">>\n");
2077   if (buf->is_obj)
2078     pdf_write_string_to_file(state, "endobj\n");
2079 }
2080
2081 static void pdf_write_to_file(pdf_state *state)
2082 {
2083   pdf_buffer *buf = state->first_buffer;
2084   int xref_pos;
2085   state->pdf_file_pos = 0;
2086   pdf_write_buf_to_file(state, &state->pdf_header);
2087   while (buf) {
2088     if (buf->is_obj)
2089       pdf_write_buf_to_file(state, buf);
2090     buf = buf->next_buffer;
2091   }
2092   xref_pos = state->pdf_file_pos;
2093   fprintf(state->fp, "xref\n");
2094   fprintf(state->fp, "%d %d\n", 0, state->last_obj_id + 1);
2095   /* TOC lines must be exactly 20 bytes including \n */
2096   fprintf(state->fp, "%010d %05d f\x20\n", 0, 65535);
2097   for (buf = state->first_buffer; buf; buf = buf->next_buffer) {
2098     if (buf->is_obj)
2099       fprintf(state->fp, "%010d %05d n\x20\n", buf->pdf_file_pos, 0);
2100   }
2101   fprintf(state->fp, "trailer\n");
2102   fprintf(state->fp, "<<\n");
2103   fprintf(state->fp, "\t/Size %d\n", state->last_obj_id + 1);
2104   fprintf(state->fp, "\t/Root %d 0 R\n", state->catalog_obj.id);
2105   fprintf(state->fp, ">>\n");
2106   fprintf(state->fp, "startxref\n");
2107   fprintf(state->fp, "%d\n", xref_pos);
2108   fputs("%%EOF\n", state->fp);
2109 }
2110
2111 static void pdf_free_resources(pdf_state *state)
2112 {
2113   pdf_buffer *buf = state->first_buffer;
2114   while (buf) {
2115     free(buf->data);
2116     buf->data = NULL;
2117     buf->alloc_size = buf->current_size = 0;
2118     buf = buf->next_buffer;
2119   }
2120   while (state->font_list) {
2121     pdf_font *next = state->font_list->next;
2122     free(state->font_list);
2123     state->font_list = next;
2124   }
2125 }
2126
2127 int       gfx_render_pdf (gfx_canvas_t *canvas,
2128                  art_u32 width, art_u32 height,
2129                  gfx_color_t background, FILE *fp){
2130   struct pdf_state state;
2131   memset(&state, 0, sizeof(pdf_state));
2132   state.fp = fp;
2133   state.canvas = canvas;
2134   state.page_width = width;
2135   state.page_height = height;
2136   state.font_id = -1;
2137   state.font_size = -1;
2138   state.font_list = NULL;
2139   state.linecap = -1;
2140   state.linejoin = -1;
2141   pdf_init_document(&state);
2142   /*
2143   pdf_set_color(&state, background);
2144   fprintf(fp, "0 0 M 0 %d L %d %d L %d 0 L fill\n",
2145       height, width, height, width);
2146   */
2147   if (!state.has_failed)
2148     pdf_write_content(&state);
2149   if (!state.has_failed)
2150     pdf_setup_document(&state);
2151   if (!state.has_failed)
2152     pdf_write_to_file(&state);
2153   pdf_free_resources(&state);
2154   return state.has_failed ? -1 : 0;
2155 }
2156