Improvement of svg/eps dash code so it adjusts dash-lengths for round caps.
[rrdtool.git] / src / rrd_gfx.c
1 /****************************************************************************
2  * RRDtool 1.1.x  Copyright Tobias Oetiker, 1997 - 2002
3  ****************************************************************************
4  * rrd_gfx.c  graphics wrapper for rrdtool
5   **************************************************************************/
6
7 /* #define DEBUG */
8
9 #ifdef DEBUG
10 # define DPRINT(x)    (void)(printf x, printf("\n"))
11 #else
12 # define DPRINT(x)
13 #endif
14 #include "rrd_tool.h"
15 #include <png.h>
16 #include <ft2build.h>
17 #include FT_FREETYPE_H
18
19 #include "rrd_gfx.h"
20 #include "rrd_afm.h"
21
22 /* lines are better drawn on the pixle than between pixles */
23 #define LINEOFFSET 0.5
24
25 static
26 gfx_node_t *gfx_new_node( gfx_canvas_t *canvas,enum gfx_en type){
27   gfx_node_t *node = art_new(gfx_node_t,1);
28   if (node == NULL) return NULL;
29   node->type = type;
30   node->color = 0x0;        /* color of element  0xRRGGBBAA  alpha 0xff is solid*/
31   node->size =0.0;         /* font size, line width */
32   node->path = NULL;        /* path */
33   node->points = 0;
34   node->points_max =0;
35   node->closed_path = 0;
36   node->svp = NULL;         /* svp */
37   node->filename = NULL;             /* font or image filename */
38   node->text = NULL;
39   node->x = 0.0;
40   node->y = 0.0;          /* position */
41   node->angle = 0;  
42   node->halign = GFX_H_NULL; /* text alignement */
43   node->valign = GFX_V_NULL; /* text alignement */
44   node->tabwidth = 0.0; 
45   node->next = NULL; 
46   if (canvas->lastnode != NULL){
47       canvas->lastnode->next = node;
48   }
49   if (canvas->firstnode == NULL){
50       canvas->firstnode = node;
51   }  
52   canvas->lastnode = node;
53   return node;
54 }
55
56 gfx_canvas_t *gfx_new_canvas (void) {
57     gfx_canvas_t *canvas = art_new(gfx_canvas_t,1);
58     canvas->firstnode = NULL;
59     canvas->lastnode = NULL;
60     canvas->imgformat = IF_PNG; /* we default to PNG output */
61     canvas->interlaced = 0;
62     canvas->zoom = 1.0;
63     return canvas;    
64 }
65
66 /* create a new line */
67 gfx_node_t  *gfx_new_line(gfx_canvas_t *canvas, 
68                            double X0, double Y0, 
69                            double X1, double Y1,
70                            double width, gfx_color_t color){
71   return gfx_new_dashed_line(canvas, X0, Y0, X1, Y1, width, color, 0, 0);
72 }
73
74 gfx_node_t  *gfx_new_dashed_line(gfx_canvas_t *canvas, 
75                            double X0, double Y0, 
76                            double X1, double Y1,
77                            double width, gfx_color_t color,
78                            double dash_on, double dash_off){
79
80   gfx_node_t *node;
81   ArtVpath *vec;
82   node = gfx_new_node(canvas,GFX_LINE);
83   if (node == NULL) return NULL;
84   vec = art_new(ArtVpath, 3);
85   if (vec == NULL) return NULL;
86   vec[0].code = ART_MOVETO_OPEN; vec[0].x=X0+LINEOFFSET; vec[0].y=Y0+LINEOFFSET;
87   vec[1].code = ART_LINETO; vec[1].x=X1+LINEOFFSET; vec[1].y=Y1+LINEOFFSET;
88   vec[2].code = ART_END;
89   
90   node->points = 3;
91   node->points_max = 3;
92   node->color = color;
93   node->size  = width;
94   node->dash_on = dash_on;
95   node->dash_off = dash_off;
96   node->path  = vec;
97   return node;
98 }
99
100 /* create a new area */
101 gfx_node_t   *gfx_new_area   (gfx_canvas_t *canvas, 
102                               double X0, double Y0,
103                               double X1, double Y1,
104                               double X2, double Y2,
105                               gfx_color_t color) {
106
107   gfx_node_t *node;
108   ArtVpath *vec;
109   node = gfx_new_node(canvas,GFX_AREA);
110   if (node == NULL) return NULL;
111   vec = art_new(ArtVpath, 5);
112   if (vec == NULL) return NULL;
113   vec[0].code = ART_MOVETO; vec[0].x=X0; vec[0].y=Y0;
114   vec[1].code = ART_LINETO; vec[1].x=X1; vec[1].y=Y1;
115   vec[2].code = ART_LINETO; vec[2].x=X2; vec[2].y=Y2;
116   vec[3].code = ART_LINETO; vec[3].x=X0; vec[3].y=Y0;
117   vec[4].code = ART_END;
118   
119   node->points = 5;
120   node->points_max = 5;
121   node->color = color;
122   node->path  = vec;
123
124   return node;
125 }
126
127 /* add a point to a line or to an area */
128 int           gfx_add_point  (gfx_node_t *node, 
129                               double x, double y){
130   if (node == NULL) return 1;
131   if (node->type == GFX_AREA) {
132     double X0 = node->path[0].x;
133     double Y0 = node->path[0].y;
134     node->points -= 2;
135     art_vpath_add_point (&(node->path),
136                          &(node->points),
137                          &(node->points_max),
138                          ART_LINETO,
139                          x,y);
140     art_vpath_add_point (&(node->path),
141                          &(node->points),
142                          &(node->points_max),
143                          ART_LINETO,
144                          X0,Y0);
145     art_vpath_add_point (&(node->path),
146                          &(node->points),
147                          &(node->points_max),
148                          ART_END,
149                          0,0);
150   } else if (node->type == GFX_LINE) {
151     node->points -= 1;
152     art_vpath_add_point (&(node->path),
153                          &(node->points),
154                          &(node->points_max),
155                          ART_LINETO,
156                          x+LINEOFFSET,y+LINEOFFSET);
157     art_vpath_add_point (&(node->path),
158                          &(node->points),
159                          &(node->points_max),
160                          ART_END,
161                          0,0);
162     
163   } else {
164     /* can only add point to areas and lines */
165     return 1;
166   }
167   return 0;
168 }
169
170 void           gfx_close_path  (gfx_node_t *node) {
171     node->closed_path = 1;
172     if (node->path[0].code == ART_MOVETO_OPEN)
173         node->path[0].code = ART_MOVETO;
174 }
175
176 /* create a text node */
177 gfx_node_t   *gfx_new_text   (gfx_canvas_t *canvas,  
178                               double x, double y, gfx_color_t color,
179                               char* font, double size,                        
180                               double tabwidth, double angle,
181                               enum gfx_h_align_en h_align,
182                               enum gfx_v_align_en v_align,
183                               char* text){
184    gfx_node_t *node = gfx_new_node(canvas,GFX_TEXT);
185    if (angle != 0.0){
186        /* currently we only support 0 and 270 */
187        angle = 270.0;
188    }
189    
190    node->text = strdup(text);
191    node->size = size;
192    node->filename = strdup(font);
193    node->x = x;
194    node->y = y;
195    node->angle = angle;   
196    node->color = color;
197    node->tabwidth = tabwidth;
198    node->halign = h_align;
199    node->valign = v_align;
200 #if 0
201   /* debugging: show text anchor */
202    gfx_new_line(canvas, x - 3, y + 0, x, y, 0.2, 0x00FF0000);
203    gfx_new_line(canvas, x - 0, y + 3, x, y, 0.2, 0x00FF0000);
204 #endif
205    return node;
206 }
207
208 int           gfx_render(gfx_canvas_t *canvas, 
209                               art_u32 width, art_u32 height, 
210                               gfx_color_t background, FILE *fp){
211   switch (canvas->imgformat) {
212   case IF_PNG: 
213     return gfx_render_png (canvas, width, height, background, fp);
214   case IF_SVG: 
215     return gfx_render_svg (canvas, width, height, background, fp);
216   case IF_EPS:
217     return gfx_render_eps (canvas, width, height, background, fp);
218   default:
219     return -1;
220   }
221 }
222
223 double gfx_get_text_width ( gfx_canvas_t *canvas,
224                             double start, char* font, double size,
225                             double tabwidth, char* text){
226   switch (canvas->imgformat) {
227   case IF_PNG: 
228     return gfx_get_text_width_libart (canvas, start, font, size, tabwidth, text);
229   case IF_SVG: /* fall through */ 
230   case IF_EPS:
231     return afm_get_text_width(start, font, size, tabwidth, text);
232   default:
233     return size * strlen(text);
234   }
235 }
236
237 double gfx_get_text_width_libart ( gfx_canvas_t *canvas,
238                             double start, char* font, double size,
239                             double tabwidth, char* text){
240
241   FT_GlyphSlot  slot;
242   FT_UInt       previous=0;
243   FT_UInt       glyph_index=0;
244   FT_Bool       use_kerning;
245   int           error;
246   FT_Face       face;
247   FT_Library    library=NULL;  
248   double        text_width=0;
249   FT_Init_FreeType( &library );
250   error = FT_New_Face( library, font, 0, &face );
251   if ( error ) return -1;
252   error = FT_Set_Char_Size(face,  size*64,size*64,  100,100);
253   if ( error ) return -1;
254
255   use_kerning = FT_HAS_KERNING(face);
256   slot = face->glyph;
257   for(;*text;text++) {  
258     previous = glyph_index;
259     glyph_index = FT_Get_Char_Index( face, *text);
260     
261     if (use_kerning && previous && glyph_index){
262       FT_Vector  delta;
263       FT_Get_Kerning( face, previous, glyph_index,
264                       0, &delta );
265       text_width += (double)delta.x / 64.0;
266       
267     }
268     error = FT_Load_Glyph( face, glyph_index, 0 );
269     if ( error ) {
270       FT_Done_FreeType(library);
271       return -1;
272     }
273     if (! previous) {
274       text_width -= (double)slot->metrics.horiBearingX / 64.0; /* add just char width */        
275     }
276     text_width += (double)slot->metrics.horiAdvance / 64.0;
277   }
278   text_width -= (double)slot->metrics.horiAdvance / 64.0; /* remove last step */
279   text_width += (double)slot->metrics.width / 64.0; /* add just char width */
280   text_width += (double)slot->metrics.horiBearingX / 64.0; /* add just char width */
281   FT_Done_FreeType(library);
282   return text_width;
283 }
284  
285 static void gfx_libart_close_path(gfx_canvas_t *canvas,
286         gfx_node_t *node, ArtVpath **vec)
287 {
288     /* libart must have end==start for closed paths,
289        even if using ART_MOVETO and not ART_MOVETO_OPEN
290        so add extra point which is the same as the starting point */
291     int points_max = node->points; /* scaled array has exact size */
292     int points = node->points - 1;
293     art_vpath_add_point (vec, &points, &points_max, ART_LINETO,
294             (**vec).x, (**vec).y);
295     art_vpath_add_point (vec, &points, &points_max, ART_END, 0, 0);
296 }
297
298 static void gfx_round_scaled_coordinates(gfx_canvas_t *canvas,
299         gfx_node_t *node, ArtVpath *vec)
300 {
301     while (vec->code != ART_END) {
302         vec->x = floor(vec->x - LINEOFFSET + 0.5) + LINEOFFSET;
303         vec->y = floor(vec->y - LINEOFFSET + 0.5) + LINEOFFSET;
304         vec++;
305     }
306 }
307
308 static int gfx_save_png (art_u8 *buffer, FILE *fp,
309                      long width, long height, long bytes_per_pixel);
310 /* render grafics into png image */
311 int           gfx_render_png (gfx_canvas_t *canvas, 
312                               art_u32 width, art_u32 height, 
313                               gfx_color_t background, FILE *fp){
314     
315     
316     FT_Library    library;
317     gfx_node_t *node = canvas->firstnode;    
318     art_u8 red = background >> 24, green = (background >> 16) & 0xff;
319     art_u8 blue = (background >> 8) & 0xff, alpha = ( background & 0xff );
320     unsigned long pys_width = width * canvas->zoom;
321     unsigned long pys_height = height * canvas->zoom;
322     const int bytes_per_pixel = 3;
323     unsigned long rowstride = pys_width*bytes_per_pixel; /* bytes per pixel */
324     art_u8 *buffer = art_new (art_u8, rowstride*pys_height);
325     art_rgb_run_alpha (buffer, red, green, blue, alpha, pys_width*pys_height);
326     FT_Init_FreeType( &library );
327     while(node){
328         switch (node->type) {
329         case GFX_LINE:
330         case GFX_AREA: {   
331             ArtVpath *vec;
332             double dst[6];     
333             ArtSVP *svp;
334             art_affine_scale(dst,canvas->zoom,canvas->zoom);
335             vec = art_vpath_affine_transform(node->path,dst);
336             if (node->closed_path)
337                 gfx_libart_close_path(canvas, node, &vec);
338             gfx_round_scaled_coordinates(canvas, node, vec);
339             if(node->type == GFX_LINE){
340                 svp = art_svp_vpath_stroke ( vec, ART_PATH_STROKE_JOIN_ROUND,
341                                              ART_PATH_STROKE_CAP_ROUND,
342                                              node->size*canvas->zoom,1,1);
343             } else {
344                 svp = art_svp_from_vpath ( vec );
345             }
346             art_free(vec);
347             art_rgb_svp_alpha (svp ,0,0, pys_width, pys_height,
348                                node->color, buffer, rowstride, NULL);
349             art_free(svp);
350             break;
351         }
352         case GFX_TEXT: {
353             int  error;
354             float text_width=0.0, text_height = 0.0;
355             unsigned char *text;
356             art_u8 fcolor[3],falpha;
357             FT_Face       face;
358             FT_GlyphSlot  slot;
359             FT_UInt       previous=0;
360             FT_UInt       glyph_index=0;
361             FT_Bool       use_kerning;
362
363             float pen_x = 0.0 , pen_y = 0.0;
364             /* double x,y; */
365             long   ix,iy,iz;
366             
367             fcolor[0] = node->color >> 24;
368             fcolor[1] = (node->color >> 16) & 0xff;
369             fcolor[2] = (node->color >> 8) & 0xff;
370             falpha = node->color & 0xff;
371             error = FT_New_Face( library,
372                                  (char *)node->filename,
373                                  0,
374                                  &face );
375             if ( error ) break;
376             use_kerning = FT_HAS_KERNING(face);
377
378             error = FT_Set_Char_Size(face,   /* handle to face object            */
379                                      (long)(node->size*64),
380                                      (long)(node->size*64),
381                                      (long)(100*canvas->zoom),
382                                      (long)(100*canvas->zoom));
383             if ( error ) break;
384             pen_x = node->x * canvas->zoom;
385             pen_y = node->y * canvas->zoom;
386             slot = face->glyph;
387
388             for(text=(unsigned char *)node->text;*text;text++) {        
389                 previous = glyph_index;
390                 glyph_index = FT_Get_Char_Index( face, *text);
391                 
392                 if (use_kerning && previous && glyph_index){
393                     FT_Vector  delta;
394                     FT_Get_Kerning( face, previous, glyph_index,
395                                     0, &delta );
396                     text_width += (double)delta.x / 64.0;
397                     
398                 }
399                 error = FT_Load_Glyph( face, glyph_index, 0 );
400                 if ( error ) break;
401                 if (previous == 0){
402                   pen_x -= (double)slot->metrics.horiBearingX / 64.0; /* adjust pos for first char */   
403                   text_width -= (double)slot->metrics.horiBearingX / 64.0; /* add just char width */    
404                 }
405                 if ( text_height < (double)slot->metrics.horiBearingY / 64.0 ) {
406                   text_height = (double)slot->metrics.horiBearingY / 64.0;
407                 }
408                 text_width += (double)slot->metrics.horiAdvance / 64.0;
409             }
410             text_width -= (double)slot->metrics.horiAdvance / 64.0; /* remove last step */
411             text_width += (double)slot->metrics.width / 64.0; /* add just char width */
412             text_width += (double)slot->metrics.horiBearingX / 64.0; /* add just char width */
413             
414             switch(node->halign){
415             case GFX_H_RIGHT:  pen_x -= text_width; break;
416             case GFX_H_CENTER: pen_x -= text_width / 2.0; break;          
417             case GFX_H_LEFT: break;          
418             case GFX_H_NULL: break;          
419             }
420
421             switch(node->valign){
422             case GFX_V_TOP:    pen_y += text_height; break;
423             case GFX_V_CENTER: pen_y += text_height / 2.0; break;          
424             case GFX_V_BOTTOM: break;          
425             case GFX_V_NULL: break;          
426             }
427
428             glyph_index=0;
429             for(text=(unsigned char *)node->text;*text;text++) {
430                 int gr;          
431                 previous = glyph_index;
432                 glyph_index = FT_Get_Char_Index( face, *text);
433                 
434                 if (use_kerning && previous && glyph_index){
435                     FT_Vector  delta;
436                     FT_Get_Kerning( face, previous, glyph_index,
437                                     0, &delta );
438                     pen_x += (double)delta.x / 64.0;
439                     
440                 }
441                 error = FT_Load_Glyph( face, glyph_index, FT_LOAD_RENDER );
442                 if ( error ) break;
443                 gr = slot->bitmap.num_grays -1;
444                 for (iy=0; iy < slot->bitmap.rows; iy++){
445                     long buf_y = iy+(pen_y+0.5)-slot->bitmap_top;
446                     if (buf_y < 0 || buf_y >= pys_height) continue;
447                     buf_y *= rowstride;
448                     for (ix=0;ix < slot->bitmap.width;ix++){
449                         long buf_x = ix + (pen_x + 0.5) + (double)slot->bitmap_left ;
450                         art_u8 font_alpha;
451                         
452                         if (buf_x < 0 || buf_x >= pys_width) continue;
453                         buf_x *=  bytes_per_pixel ;
454                         font_alpha =  *(slot->bitmap.buffer + iy * slot->bitmap.width + ix);
455                         font_alpha =  (art_u8)((double)font_alpha / gr * falpha);
456                         for (iz = 0; iz < 3; iz++){
457                             art_u8 *orig = buffer + buf_y + buf_x + iz;
458                             *orig =  (art_u8)((double)*orig / gr * ( gr - font_alpha) +
459                                               (double)fcolor[iz] / gr * (font_alpha));
460                         }
461                     }
462                 }
463                 pen_x += (double)slot->metrics.horiAdvance / 64.0;
464             }
465         }
466         }
467         node = node->next;
468     }  
469     gfx_save_png(buffer,fp , pys_width,pys_height,bytes_per_pixel);
470     art_free(buffer);
471     FT_Done_FreeType( library );
472     return 0;    
473 }
474
475 /* free memory used by nodes this will also remove memory required for
476    associated paths and svcs ... but not for text strings */
477 int
478 gfx_destroy    (gfx_canvas_t *canvas){  
479   gfx_node_t *next,*node = canvas->firstnode;
480   while(node){
481     next = node->next;
482     art_free(node->path);
483     art_free(node->svp);
484     free(node->text);
485     free(node->filename);
486     art_free(node);
487     node = next;
488   }
489   return 0;
490 }
491  
492 static int gfx_save_png (art_u8 *buffer, FILE *fp,  long width, long height, long bytes_per_pixel){
493   png_structp png_ptr = NULL;
494   png_infop   info_ptr = NULL;
495   int i;
496   png_bytep *row_pointers;
497   int rowstride = width * bytes_per_pixel;
498   png_text text[2];
499   
500   if (fp == NULL)
501     return (1);
502
503   png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING,NULL,NULL,NULL);
504   if (png_ptr == NULL)
505    {
506       return (1);
507    }
508    row_pointers = (png_bytepp)png_malloc(png_ptr,
509                                      height*sizeof(png_bytep));
510
511   info_ptr = png_create_info_struct(png_ptr);
512
513   if (info_ptr == NULL)
514     {
515       png_destroy_write_struct(&png_ptr,  (png_infopp)NULL);
516       return (1);
517     }
518
519   if (setjmp(png_jmpbuf(png_ptr)))
520     {
521       /* If we get here, we had a problem writing the file */
522       png_destroy_write_struct(&png_ptr, &info_ptr);
523       return (1);
524     }
525
526   png_init_io(png_ptr, fp);
527   png_set_IHDR (png_ptr, info_ptr,width, height,
528                 8, PNG_COLOR_TYPE_RGB,
529                 PNG_INTERLACE_NONE,
530                 PNG_COMPRESSION_TYPE_DEFAULT,
531                 PNG_FILTER_TYPE_DEFAULT);
532
533   text[0].key = "Software";
534   text[0].text = "RRDtool, Tobias Oetiker <tobi@oetike.ch>, http://tobi.oetiker.ch";
535   text[0].compression = PNG_TEXT_COMPRESSION_NONE;
536   png_set_text (png_ptr, info_ptr, text, 1);
537
538   /* Write header data */
539   png_write_info (png_ptr, info_ptr);
540
541   for (i = 0; i < height; i++)
542     row_pointers[i] = (png_bytep) (buffer + i*rowstride);
543
544   png_write_image(png_ptr, row_pointers);
545   png_write_end(png_ptr, info_ptr);
546   png_destroy_write_struct(&png_ptr, &info_ptr);
547   return 1;
548 }
549
550  
551 /* ------- SVG -------
552    SVG reference:
553    http://www.w3.org/TR/SVG/
554 */
555 static int svg_indent = 0;
556 static int svg_single_line = 0;
557 static const char *svg_default_font = "Helvetica";
558 typedef struct svg_dash
559 {
560   int dash_enable;
561   double dash_adjust, dash_len, dash_offset;
562   double adjusted_on, adjusted_off;
563 } svg_dash;
564
565
566 static void svg_print_indent(FILE *fp)
567 {
568   int i;
569    for (i = svg_indent - svg_single_line; i > 0; i--) {
570      putc(' ', fp);
571      putc(' ', fp);
572    }
573 }
574  
575 static void svg_start_tag(FILE *fp, const char *name)
576 {
577    svg_print_indent(fp);
578    putc('<', fp);
579    fputs(name, fp);
580    svg_indent++;
581 }
582  
583 static void svg_close_tag_single_line(FILE *fp)
584 {
585    svg_single_line++;
586    putc('>', fp);
587 }
588  
589 static void svg_close_tag(FILE *fp)
590 {
591    putc('>', fp);
592    if (!svg_single_line)
593      putc('\n', fp);
594 }
595  
596 static void svg_end_tag(FILE *fp, const char *name)
597 {
598    /* name is NULL if closing empty-node tag */
599    svg_indent--;
600    if (svg_single_line)
601      svg_single_line--;
602    else if (name)
603      svg_print_indent(fp);
604    if (name != NULL) {
605      fputs("</", fp);
606      fputs(name, fp);
607    } else {
608      putc('/', fp);
609    }
610    svg_close_tag(fp);
611 }
612  
613 static void svg_close_tag_empty_node(FILE *fp)
614 {
615    svg_end_tag(fp, NULL);
616 }
617  
618 static void svg_write_text(FILE *fp, const char *text)
619 {
620    const unsigned char *p, *start, *last;
621    unsigned int ch;
622    p = (const unsigned char*)text;
623    if (!p)
624      return;
625    /* trim leading spaces */
626    while (*p == ' ')
627      p++;
628    start = p;
629    /* trim trailing spaces */
630    last = p - 1;
631    while ((ch = *p) != 0) {
632      if (ch != ' ')
633        last = p;
634      p++;
635   }
636   /* encode trimmed text */
637   p = start;
638   while (p <= last) {
639     ch = *p++;
640     ch = afm_host2unicode(ch); /* unsafe macro */
641     switch (ch) {
642     case '&': fputs("&amp;", fp); break;
643     case '<': fputs("&lt;", fp); break;
644     case '>': fputs("&gt;", fp); break;
645     case '"': fputs("&quot;", fp); break;
646     default:
647       if (ch >= 127)
648         fprintf(fp, "&#%d;", ch);
649       else
650         putc(ch, fp);
651      }
652    }
653 }
654  
655 static void svg_write_number(FILE *fp, double d)
656 {
657    /* omit decimals if integer to reduce filesize */
658    char buf[60], *p;
659    snprintf(buf, sizeof(buf), "%.2f", d);
660    p = buf; /* doesn't trust snprintf return value */
661    while (*p)
662      p++;
663    while (--p > buf) {
664      char ch = *p;
665      if (ch == '0') {
666        *p = '\0'; /* zap trailing zeros */
667        continue;
668      }
669      if (ch == '.')
670        *p = '\0'; /* zap trailing dot */
671      break;
672    }
673    fputs(buf, fp);
674 }
675  
676 static int svg_color_is_black(int c)
677 {
678   /* gfx_color_t is RRGGBBAA */
679   return c == 0x000000FF;
680 }
681  
682 static void svg_write_color(FILE *fp, gfx_color_t c, const char *attr)
683 {
684   /* gfx_color_t is RRGGBBAA, svg can use #RRGGBB and #RGB like html */
685   gfx_color_t rrggbb = (int)((c >> 8) & 0xFFFFFF);
686   gfx_color_t opacity = c & 0xFF;
687   fprintf(fp, " %s=\"", attr);
688   if ((rrggbb & 0x0F0F0F) == ((rrggbb >> 4) & 0x0F0F0F)) {
689      /* css2 short form, #rgb is #rrggbb, not #r0g0b0 */
690     fprintf(fp, "#%03lX",
691           ( ((rrggbb >> 8) & 0xF00)
692           | ((rrggbb >> 4) & 0x0F0)
693           | ( rrggbb       & 0x00F)));
694    } else {
695     fprintf(fp, "#%06lX", rrggbb);
696    }
697   fputs("\"", fp);
698   if (opacity != 0xFF) {
699     fprintf(fp, " stroke-opacity=\"");
700     svg_write_number(fp, opacity / 255.0);
701     fputs("\"", fp);
702  }
703 }
704  
705 static void svg_get_dash(gfx_node_t *node, svg_dash *d)
706 {
707   double offset;
708   int mult;
709   if (node->dash_on <= 0 || node->dash_off <= 0) {
710     d->dash_enable = 0;
711     return;
712   }
713   d->dash_enable = 1;
714   d->dash_len = node->dash_on + node->dash_off;
715   /* dash on/off adjustment due to round caps */
716   d->dash_adjust = 0.8 * node->size;
717   d->adjusted_on = node->dash_on - d->dash_adjust;
718   if (d->adjusted_on < 0.01)
719       d->adjusted_on = 0.01;
720   d->adjusted_off = d->dash_len - d->adjusted_on;
721   /* dash offset calc */
722   if (node->path[0].x == node->path[1].x) /* only good for horz/vert lines */
723     offset = node->path[0].y;
724   else
725     offset = node->path[0].x;
726   mult = (int)fabs(offset / d->dash_len);
727   d->dash_offset = offset - mult * d->dash_len;
728   if (node->path[0].x < node->path[1].x || node->path[0].y < node->path[1].y)
729     d->dash_offset = d->dash_len - d->dash_offset;
730 }
731
732 static void svg_common_path_attributes(FILE *fp, gfx_node_t *node)
733 {
734   svg_dash dash_info;
735   svg_get_dash(node, &dash_info);
736   fputs(" stroke-width=\"", fp);
737   svg_write_number(fp, node->size);
738   fputs("\"", fp);
739   svg_write_color(fp, node->color, "stroke");
740   fputs(" fill=\"none\"", fp);
741   if (dash_info.dash_enable) {
742     if (dash_info.dash_offset != 0) {
743       fputs(" stroke-dashoffset=\"", fp);
744       svg_write_number(fp, dash_info.dash_offset);
745       fputs("\"", fp);
746     }
747     fputs(" stroke-dasharray=\"", fp);
748     svg_write_number(fp, dash_info.adjusted_on);
749     fputs(",", fp);
750     svg_write_number(fp, dash_info.adjusted_off);
751     fputs("\"", fp);
752   }
753 }
754
755 static int svg_is_int_step(double a, double b)
756 {
757    double diff = fabs(a - b);
758    return floor(diff) == diff;
759 }
760  
761 static int svg_path_straight_segment(FILE *fp,
762      double lastA, double currentA, double currentB,
763      gfx_node_t *node,
764      int segment_idx, int isx, char absChar, char relChar)
765 {
766    if (!svg_is_int_step(lastA, currentA)) {
767      putc(absChar, fp);
768      svg_write_number(fp, currentA);
769      return 0;
770    }
771    if (segment_idx < node->points - 1) {
772      ArtVpath *vec = node->path + segment_idx + 1;
773      if (vec->code == ART_LINETO) {
774        double nextA = (isx ? vec->x : vec->y) - LINEOFFSET;
775        double nextB = (isx ? vec->y : vec->x) - LINEOFFSET;
776        if (nextB == currentB
777            && ((currentA >= lastA) == (nextA >= currentA))
778            && svg_is_int_step(currentA, nextA)) {
779          return 1; /* skip to next as it is a straight line  */
780        }
781      }
782    }
783    putc(relChar, fp);
784    svg_write_number(fp, currentA - lastA);
785    return 0;
786 }
787  
788 static void svg_path(FILE *fp, gfx_node_t *node, int multi)
789 {
790    int i;
791    double lastX = 0, lastY = 0;
792    /* for straight lines <path..> tags take less space than
793       <line..> tags because of the efficient packing
794       in the 'd' attribute */
795    svg_start_tag(fp, "path");
796   if (!multi)
797     svg_common_path_attributes(fp, node);
798    fputs(" d=\"", fp);
799    /* specification of the 'd' attribute: */
800    /* http://www.w3.org/TR/SVG/paths.html#PathDataGeneralInformation */
801    for (i = 0; i < node->points; i++) {
802      ArtVpath *vec = node->path + i;
803      double x = vec->x - LINEOFFSET;
804      double y = vec->y - LINEOFFSET;
805      switch (vec->code) {
806      case ART_MOVETO_OPEN: /* fall-through */
807      case ART_MOVETO:
808        putc('M', fp);
809        svg_write_number(fp, x);
810        putc(',', fp);
811        svg_write_number(fp, y);
812        break;
813      case ART_LINETO:
814        /* try optimize filesize by using minimal lineto commands */
815        /* without introducing rounding errors. */
816        if (x == lastX) {
817          if (svg_path_straight_segment(fp, lastY, y, x, node, i, 0, 'V', 'v'))
818            continue;
819        } else if (y == lastY) {
820          if (svg_path_straight_segment(fp, lastX, x, y, node, i, 1, 'H', 'h'))
821            continue;
822        } else {
823          putc('L', fp);
824          svg_write_number(fp, x);
825          putc(',', fp);
826          svg_write_number(fp, y);
827        }
828        break;
829      case ART_CURVETO: break; /* unsupported */
830      case ART_END: break; /* nop */
831      }
832      lastX = x;
833      lastY = y;
834    }
835   if (node->closed_path)
836     fputs(" Z", fp);
837    fputs("\"", fp);
838    svg_close_tag_empty_node(fp);
839 }
840  
841 static void svg_multi_path(FILE *fp, gfx_node_t **nodeR)
842 {
843    /* optimize for multiple paths with the same color, penwidth, etc. */
844    int num = 1;
845    gfx_node_t *node = *nodeR;
846    gfx_node_t *next = node->next;
847    while (next) {
848      if (next->type != node->type
849          || next->size != node->size
850         || next->color != node->color
851         || next->dash_on != node->dash_on
852         || next->dash_off != node->dash_off)
853        break;
854      next = next->next;
855      num++;
856    }
857    if (num == 1) {
858      svg_path(fp, node, 0);
859      return;
860    }
861    svg_start_tag(fp, "g");
862   svg_common_path_attributes(fp, node);
863    svg_close_tag(fp);
864    while (num && node) {
865      svg_path(fp, node, 1);
866      if (!--num)
867        break;
868      node = node->next;
869      *nodeR = node;
870    }
871    svg_end_tag(fp, "g");
872 }
873  
874 static void svg_area(FILE *fp, gfx_node_t *node)
875 {
876    int i;
877    double startX = 0, startY = 0;
878    svg_start_tag(fp, "polygon");
879   fputs(" ", fp);
880   svg_write_color(fp, node->color, "fill");
881   fputs(" points=\"", fp);
882    for (i = 0; i < node->points; i++) {
883      ArtVpath *vec = node->path + i;
884      double x = vec->x - LINEOFFSET;
885      double y = vec->y - LINEOFFSET;
886      switch (vec->code) {
887        case ART_MOVETO_OPEN: /* fall-through */
888        case ART_MOVETO:
889          svg_write_number(fp, x);
890          putc(',', fp);
891          svg_write_number(fp, y);
892          startX = x;
893          startY = y;
894          break;
895        case ART_LINETO:
896          if (i == node->points - 2
897                         && node->path[i + 1].code == ART_END
898              && fabs(x - startX) < 0.001 && fabs(y - startY) < 0.001) {
899            break; /* poly area always closed, no need for last point */
900          }
901          putc(' ', fp);
902          svg_write_number(fp, x);
903          putc(',', fp);
904          svg_write_number(fp, y);
905          break;
906        case ART_CURVETO: break; /* unsupported */
907        case ART_END: break; /* nop */
908      }
909    }
910    fputs("\"", fp);
911    svg_close_tag_empty_node(fp);
912 }
913  
914 static void svg_text(FILE *fp, gfx_node_t *node)
915 {
916    double x = node->x - LINEOFFSET;
917    double y = node->y - LINEOFFSET;
918    if (node->angle != 0) {
919      svg_start_tag(fp, "g");
920      fputs(" transform=\"translate(", fp);
921      svg_write_number(fp, x);
922      fputs(",", fp);
923      svg_write_number(fp, y);
924      fputs(") rotate(", fp);
925      svg_write_number(fp, node->angle);
926      fputs(")\"", fp);
927      x = y = 0;
928      svg_close_tag(fp);
929    }
930    switch (node->valign) {
931    case GFX_V_TOP:  y += node->size; break;
932    case GFX_V_CENTER: y += node->size / 3; break;
933    case GFX_V_BOTTOM: break;
934    case GFX_V_NULL: break;
935    }
936    svg_start_tag(fp, "text");
937    fputs(" x=\"", fp);
938    svg_write_number(fp, x);
939    fputs("\" y=\"", fp);
940    svg_write_number(fp, y);
941   if (strcmp(node->filename, svg_default_font))
942     fprintf(fp, " font-family=\"%s\"", node->filename);
943    fputs("\" font-size=\"", fp);
944    svg_write_number(fp, node->size);
945    fputs("\"", fp);
946   if (!svg_color_is_black(node->color))
947     svg_write_color(fp, node->color, "fill");
948    switch (node->halign) {
949    case GFX_H_RIGHT:  fputs(" text-anchor=\"end\"", fp); break;
950    case GFX_H_CENTER: fputs(" text-anchor=\"middle\"", fp); break;
951    case GFX_H_LEFT: break;
952    case GFX_H_NULL: break;
953    }
954    svg_close_tag_single_line(fp);
955    /* support for node->tabwidth missing */
956    svg_write_text(fp, node->text);
957    svg_end_tag(fp, "text");
958    if (node->angle != 0)
959      svg_end_tag(fp, "g");
960 }
961  
962 int       gfx_render_svg (gfx_canvas_t *canvas,
963                  art_u32 width, art_u32 height,
964                  gfx_color_t background, FILE *fp){
965    gfx_node_t *node = canvas->firstnode;
966    fputs(
967 "<?xml version=\"1.0\" standalone=\"no\"?>\n"
968 "<!DOCTYPE svg PUBLIC \"-//W3C//DTD SVG 1.0//EN\"\n"
969 "   \"http://www.w3.org/TR/2001/REC-SVG-20010904/DTD/svg10.dtd\">\n"
970 "<!--\n"
971 "   SVG file created by RRDtool,\n"
972 "   Tobias Oetiker <tobi@oetike.ch>, http://tobi.oetiker.ch\n"
973 "\n"
974 "   The width/height attributes in the outhermost svg node\n"
975 "   are just default sizes for the browser which is used\n"
976 "   if the svg file is openened directly without being\n"
977 "   embedded in an html file.\n"
978 "   The viewBox is the local coord system for rrdtool.\n"
979 "-->\n", fp);
980    svg_start_tag(fp, "svg");
981    fputs(" width=\"", fp);
982   svg_write_number(fp, width * canvas->zoom);
983    fputs("\" height=\"", fp);
984   svg_write_number(fp, height * canvas->zoom);
985    fputs("\" x=\"0\" y=\"0\" viewBox=\"", fp);
986    svg_write_number(fp, -LINEOFFSET);
987    fputs(" ", fp);
988    svg_write_number(fp, -LINEOFFSET);
989    fputs(" ", fp);
990    svg_write_number(fp, width - LINEOFFSET);
991    fputs(" ", fp);
992    svg_write_number(fp, height - LINEOFFSET);
993    fputs("\" preserveAspectRatio=\"xMidYMid\"", fp);
994   fprintf(fp, " font-family=\"%s\"", svg_default_font); /* default font */
995   fputs(" stroke-linecap=\"round\" stroke-linejoin=\"round\"", fp);
996    svg_close_tag(fp);
997    svg_start_tag(fp, "rect");
998    fprintf(fp, " x=\"0\" y=\"0\" width=\"%d\" height=\"%d\"", width, height);
999   svg_write_color(fp, background, "fill");
1000    svg_close_tag_empty_node(fp);
1001    while (node) {
1002      switch (node->type) {
1003      case GFX_LINE:
1004        svg_multi_path(fp, &node);
1005        break;
1006      case GFX_AREA:
1007        svg_area(fp, node);
1008        break;
1009      case GFX_TEXT:
1010        svg_text(fp, node);
1011      }
1012      node = node->next;
1013    }
1014    svg_end_tag(fp, "svg");
1015    return 0;
1016 }
1017
1018 /* ------- EPS -------
1019    EPS and Postscript references:
1020    http://partners.adobe.com/asn/developer/technotes/postscript.html
1021 */
1022
1023 typedef struct eps_font
1024 {
1025   const char *ps_font;
1026   int id;
1027   struct eps_font *next;
1028 } eps_font;
1029
1030 typedef struct eps_state
1031 {
1032   FILE *fp;
1033   gfx_canvas_t *canvas;
1034   art_u32 page_width, page_height;
1035   eps_font *font_list;
1036   /*--*/
1037   gfx_color_t color;
1038   const char *font;
1039   double font_size;
1040   double line_width;
1041   int linecap, linejoin;
1042   int has_dash;
1043 } eps_state;
1044
1045 static void eps_set_color(eps_state *state, gfx_color_t color)
1046 {
1047    /* gfx_color_t is RRGGBBAA */
1048   if (state->color == color)
1049     return;
1050   fprintf(state->fp, "%d %d %d Rgb\n",
1051       (int)((color >> 24) & 255),
1052       (int)((color >> 16) & 255),
1053       (int)((color >>  8) & 255));
1054   state->color = color;
1055 }
1056
1057 static int eps_add_font(eps_state *state, gfx_node_t *node)
1058 {
1059   /* The fonts list could be postponed to the end using
1060      (atend), but let's be nice and have them in the header. */
1061   const char *ps_font = afm_get_font_postscript_name(node->filename);
1062   eps_font *ef;
1063   for (ef = state->font_list; ef; ef = ef->next) {
1064     if (!strcmp(ps_font, ef->ps_font))
1065       return 0;
1066   }
1067   ef = malloc(sizeof(eps_font));
1068   if (ef == NULL) {
1069     rrd_set_error("malloc for eps_font");
1070     return -1;
1071   }
1072   ef->next = state->font_list;
1073   ef->ps_font = ps_font;
1074   state->font_list = ef;
1075   return 0;
1076 }
1077
1078 static void eps_list_fonts(eps_state *state, const char *dscName)
1079 {
1080   eps_font *ef;
1081   int lineLen = strlen(dscName);
1082   if (!state->font_list)
1083     return;
1084   fputs(dscName, state->fp);
1085   for (ef = state->font_list; ef; ef = ef->next) {
1086     int nameLen = strlen(ef->ps_font);
1087     if (lineLen + nameLen > 100 && lineLen) {
1088       fputs("\n", state->fp);
1089       fputs("%%- \n", state->fp);
1090       lineLen = 5;
1091     } else {
1092       fputs(" ", state->fp);
1093       lineLen++;
1094     }
1095     fputs(ef->ps_font, state->fp);
1096     lineLen += nameLen;
1097   }
1098   fputs("\n", state->fp);
1099 }
1100
1101 static void eps_define_fonts(eps_state *state)
1102 {
1103   eps_font *ef;
1104   if (!state->font_list)
1105     return;
1106   for (ef = state->font_list; ef; ef = ef->next) {
1107     /* PostScript¨ LANGUAGE REFERENCE third edition
1108        page 349 */
1109     fprintf(state->fp,
1110         "%%\n"
1111         "/%s findfont dup length dict begin\n"
1112         "{ 1 index /FID ne {def} {pop pop} ifelse } forall\n"
1113         "/Encoding ISOLatin1Encoding def\n"
1114         "currentdict end\n"
1115         "/%s-ISOLatin1 exch definefont pop\n"
1116         "/SetFont-%s { /%s-ISOLatin1 findfont exch scalefont setfont } bd\n",
1117         ef->ps_font, ef->ps_font, ef->ps_font, ef->ps_font);
1118   }
1119 }
1120
1121 static int eps_prologue(eps_state *state)
1122 {
1123   gfx_node_t *node;
1124   fputs(
1125     "%!PS-Adobe-3.0 EPSF-3.0\n"
1126     "%%Creator: RRDtool 1.1.x, Tobias Oetiker, http://tobi.oetiker.ch\n"
1127     /* can't like weird chars here */
1128     "%%Title: (RRDTool output)\n"
1129     "%%DocumentData: Clean7Bit\n"
1130     "", state->fp);
1131   fprintf(state->fp, "%%%%BoundingBox: 0 0 %d %d\n",
1132     state->page_width, state->page_height);
1133   for (node = state->canvas->firstnode; node; node = node->next) {
1134     if (node->type == GFX_TEXT && eps_add_font(state, node) == -1)
1135       return -1;
1136   }
1137   eps_list_fonts(state, "%%DocumentFonts:");
1138   eps_list_fonts(state, "%%DocumentNeededFonts:");
1139   fputs(
1140       "%%EndComments\n"
1141       "%%BeginProlog\n"
1142       "%%EndProlog\n" /* must have, or BoundingBox is ignored */
1143       "/bd { bind def } bind def\n"
1144       "", state->fp);
1145   fprintf(state->fp, "/X { %.2f add } bd\n", LINEOFFSET);
1146   fputs(
1147       "/X2 {X exch X exch} bd\n"
1148       "/M {X2 moveto} bd\n"
1149       "/L {X2 lineto} bd\n"
1150       "/m {moveto} bd\n"
1151       "/l {lineto} bd\n"
1152       "/S {stroke} bd\n"
1153       "/CP {closepath} bd\n"
1154       "/WS {setlinewidth stroke} bd\n"
1155       "/F {fill} bd\n"
1156       "/TaL { } bd\n"
1157       "/TaC {dup stringwidth pop neg 2 div 0 rmoveto } bd\n"
1158       "/TaR {dup stringwidth pop neg 0 rmoveto } bd\n"
1159       "/TL {moveto TaL show} bd\n"
1160       "/TC {moveto TaC show} bd\n"
1161       "/TR {moveto TaR show} bd\n"
1162       "/Rgb { 255.0 div 3 1 roll\n"
1163       "       255.0 div 3 1 roll \n"
1164       "       255.0 div 3 1 roll setrgbcolor } bd\n"
1165       "", state->fp);
1166   eps_define_fonts(state);
1167   return 0;
1168 }
1169
1170 static void eps_clear_dash(eps_state *state)
1171 {
1172   if (!state->has_dash)
1173     return;
1174   state->has_dash = 0;
1175   fputs("[1 0] 0 setdash\n", state->fp);
1176 }
1177
1178 static void eps_write_linearea(eps_state *state, gfx_node_t *node)
1179 {
1180   int i;
1181   FILE *fp = state->fp;
1182   int useOffset = 0;
1183   int clearDashIfAny = 1;
1184   eps_set_color(state, node->color);
1185   if (node->type == GFX_LINE) {
1186     svg_dash dash_info;
1187     if (state->linecap != 1) {
1188       fputs("1 setlinecap\n", fp);
1189       state->linecap = 1;
1190     }
1191     if (state->linejoin != 1) {
1192       fputs("1 setlinejoin\n", fp);
1193       state->linejoin = 1;
1194     }
1195     svg_get_dash(node, &dash_info);
1196     if (dash_info.dash_enable) {
1197       clearDashIfAny = 0;
1198       state->has_dash = 1;
1199       fputs("[", fp);
1200       svg_write_number(fp, dash_info.adjusted_on);
1201       fputs(" ", fp);
1202       svg_write_number(fp, dash_info.adjusted_off);
1203       fputs("] ", fp);
1204       svg_write_number(fp, dash_info.dash_offset);
1205       fputs(" setdash\n", fp);
1206     }
1207   }
1208   if (clearDashIfAny)
1209     eps_clear_dash(state);
1210   for (i = 0; i < node->points; i++) {
1211     ArtVpath *vec = node->path + i;
1212     double x = vec->x;
1213     double y = state->page_height - vec->y;
1214     if (vec->code == ART_MOVETO_OPEN || vec->code == ART_MOVETO)
1215       useOffset = (fabs(x - floor(x) - 0.5) < 0.01 && fabs(y - floor(y) - 0.5) < 0.01);
1216     if (useOffset) {
1217       x -= LINEOFFSET;
1218       y -= LINEOFFSET;
1219     }
1220     switch (vec->code) {
1221     case ART_MOVETO_OPEN: /* fall-through */
1222     case ART_MOVETO:
1223       svg_write_number(fp, x);
1224       fputc(' ', fp);
1225       svg_write_number(fp, y);
1226       fputc(' ', fp);
1227       fputs(useOffset ? "M\n" : "m\n", fp);
1228       break;
1229     case ART_LINETO:
1230       svg_write_number(fp, x);
1231       fputc(' ', fp);
1232       svg_write_number(fp, y);
1233       fputc(' ', fp);
1234       fputs(useOffset ? "L\n" : "l\n", fp);
1235       break;
1236     case ART_CURVETO: break; /* unsupported */
1237     case ART_END: break; /* nop */
1238     }
1239   }
1240   if (node->type == GFX_LINE) {
1241     if (node->closed_path)
1242       fputs("CP ", fp);
1243     if (node->size != state->line_width) {
1244       state->line_width = node->size;
1245       svg_write_number(fp, state->line_width);
1246       fputs(" WS\n", fp);
1247     } else {
1248       fputs("S\n", fp);
1249     }
1250    } else {
1251     fputs("F\n", fp);
1252    }
1253 }
1254
1255 static void eps_write_text(eps_state *state, gfx_node_t *node)
1256 {
1257   FILE *fp = state->fp;
1258   const unsigned char *p;
1259   const char *ps_font = afm_get_font_postscript_name(node->filename);
1260   char align = 'L';
1261   double x = node->x;
1262   double y = state->page_height - node->y, ydelta = 0;
1263   int lineLen = 0;
1264   eps_set_color(state, node->color);
1265   if (strcmp(ps_font, state->font) || node->size != state->font_size) {
1266     state->font = ps_font;
1267     state->font_size = node->size;
1268     svg_write_number(fp, state->font_size);
1269     fprintf(fp, " SetFont-%s\n", state->font);
1270   }
1271   fputs("(", fp);
1272   lineLen = 20;
1273   for (p = (const unsigned char*)node->text; *p; p++) {
1274     if (lineLen > 70) {
1275       fputs("\\\n", fp); /* backslash and \n */
1276       lineLen = 0;
1277     }
1278     switch (*p) {
1279       case '(':
1280       case ')':
1281       case '\\':
1282       case '\n':
1283       case '\r':
1284       case '\t':
1285         fputc('\\', fp);
1286         lineLen++;
1287         /* fall-through */
1288       default:
1289         if (*p >= 126)
1290           fprintf(fp, "\\%03o", *p);
1291         else
1292           fputc(*p, fp);
1293         lineLen++;
1294     }
1295   }
1296   fputs(") ", fp);
1297   switch(node->valign){
1298   case GFX_V_TOP:    ydelta = -node->size; break;
1299   case GFX_V_CENTER: ydelta = -node->size / 3.0; break;          
1300   case GFX_V_BOTTOM: break;          
1301   case GFX_V_NULL: break;          
1302   }
1303   if (node->angle == 0)
1304     y += ydelta;
1305   switch (node->halign) {
1306   case GFX_H_RIGHT:  align = 'R'; break;
1307   case GFX_H_CENTER: align = 'C'; break;
1308   case GFX_H_LEFT: align= 'L'; break;
1309   case GFX_H_NULL: align= 'L'; break;
1310   }
1311   if (node->angle != 0) {
1312     fputs("\n", fp);
1313     fputs("  gsave ", fp);
1314     svg_write_number(fp, x);
1315     fputc(' ', fp);
1316     svg_write_number(fp, y);
1317     fputs(" translate ", fp);
1318     svg_write_number(fp, -node->angle);
1319     fputs(" rotate 0 ", fp);
1320     svg_write_number(fp, ydelta);
1321     fputs(" moveto ", fp);
1322     fprintf(fp, "Ta%c", align);
1323     fputs(" show grestore\n", fp);
1324   } else {
1325     svg_write_number(fp, x);
1326     fputc(' ', fp);
1327     svg_write_number(fp, y);
1328     fputs(" T", fp);
1329     fputc(align, fp);
1330     fputc('\n', fp);
1331   }
1332 }
1333
1334 static int eps_write_content(eps_state *state)
1335 {
1336   gfx_node_t *node;
1337   fputs("%\n", state->fp);
1338   for (node = state->canvas->firstnode; node; node = node->next) {
1339     switch (node->type) {
1340     case GFX_LINE:
1341     case GFX_AREA:
1342       eps_write_linearea(state, node);
1343       break;
1344     case GFX_TEXT:
1345       eps_write_text(state, node);
1346       break;
1347     }
1348   }
1349   return 0;
1350 }
1351
1352 int       gfx_render_eps (gfx_canvas_t *canvas,
1353                  art_u32 width, art_u32 height,
1354                  gfx_color_t background, FILE *fp){
1355   struct eps_state state;
1356   state.fp = fp;
1357   state.canvas = canvas;
1358   state.page_width = width;
1359   state.page_height = height;
1360   state.font = "no-default-font";
1361   state.font_size = -1;
1362   state.color = 0; /* black */
1363   state.font_list = NULL;
1364   state.linecap = -1;
1365   state.linejoin = -1;
1366   state.has_dash = 0;
1367   if (eps_prologue(&state) == -1)
1368     return -1;
1369   eps_set_color(&state, background);
1370   fprintf(fp, "0 0 M 0 %d L %d %d L %d 0 L fill\n",
1371       height, width, height, width);
1372   if (eps_write_content(&state) == -1)
1373     return 0;
1374   fputs("showpage\n", fp);
1375   fputs("%%EOF\n", fp);
1376   while (state.font_list) {
1377     eps_font *next = state.font_list->next;
1378     free(state.font_list);
1379     state.font_list = next;
1380   }
1381   return 0;
1382 }