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