1 /****************************************************************************
2 * RRDtool 1.2.8 Copyright by Tobi Oetiker, 1997-2005
3 ****************************************************************************
4 * rrd_gfx.c graphics wrapper for rrdtool
5 **************************************************************************/
10 # define DPRINT(x) (void)(printf x, printf("\n"))
17 #include FT_FREETYPE_H
24 /* lines are better drawn on the pixle than between pixles */
25 #define LINEOFFSET 0.5
27 #define USE_PDF_FAKE_ALPHA 1
28 #define USE_EPS_FAKE_ALPHA 1
30 typedef struct gfx_char_s *gfx_char;
32 FT_UInt index; /* glyph index */
33 FT_Vector pos; /* location from baseline in 26.6 */
34 FT_Glyph image; /* glyph bitmap */
37 typedef struct gfx_string_s *gfx_string;
41 size_t count; /* number of characters */
48 /* compute string bbox */
49 static void compute_string_bbox(gfx_string string);
51 /* create a freetype glyph string */
52 gfx_string gfx_string_create ( gfx_canvas_t *canvas, FT_Face face,
53 const char *text, int rotation, double tabwidth, double size);
55 /* create a freetype glyph string */
56 static void gfx_string_destroy ( gfx_string string );
59 gfx_node_t *gfx_new_node( gfx_canvas_t *canvas,enum gfx_en type){
60 gfx_node_t *node = art_new(gfx_node_t,1);
61 if (node == NULL) return NULL;
63 node->color = 0x0; /* color of element 0xRRGGBBAA alpha 0xff is solid*/
64 node->size =0.0; /* font size, line width */
65 node->path = NULL; /* path */
68 node->closed_path = 0;
69 node->filename = NULL; /* font or image filename */
72 node->y = 0.0; /* position */
74 node->halign = GFX_H_NULL; /* text alignement */
75 node->valign = GFX_V_NULL; /* text alignement */
78 if (canvas->lastnode != NULL){
79 canvas->lastnode->next = node;
81 if (canvas->firstnode == NULL){
82 canvas->firstnode = node;
84 canvas->lastnode = node;
88 gfx_canvas_t *gfx_new_canvas (void) {
89 gfx_canvas_t *canvas = art_new(gfx_canvas_t,1);
90 canvas->firstnode = NULL;
91 canvas->lastnode = NULL;
92 canvas->imgformat = IF_PNG; /* we default to PNG output */
93 canvas->interlaced = 0;
95 canvas->font_aa_threshold = -1.0;
96 canvas->aa_type = AA_NORMAL;
100 /* create a new line */
101 gfx_node_t *gfx_new_line(gfx_canvas_t *canvas,
102 double X0, double Y0,
103 double X1, double Y1,
104 double width, gfx_color_t color){
105 return gfx_new_dashed_line(canvas, X0, Y0, X1, Y1, width, color, 0, 0);
108 gfx_node_t *gfx_new_dashed_line(gfx_canvas_t *canvas,
109 double X0, double Y0,
110 double X1, double Y1,
111 double width, gfx_color_t color,
112 double dash_on, double dash_off){
116 node = gfx_new_node(canvas,GFX_LINE);
117 if (node == NULL) return NULL;
118 vec = art_new(ArtVpath, 3);
119 if (vec == NULL) return NULL;
120 vec[0].code = ART_MOVETO_OPEN; vec[0].x=X0+LINEOFFSET; vec[0].y=Y0+LINEOFFSET;
121 vec[1].code = ART_LINETO; vec[1].x=X1+LINEOFFSET; vec[1].y=Y1+LINEOFFSET;
122 vec[2].code = ART_END; vec[2].x=0;vec[2].y=0;
125 node->points_max = 3;
128 node->dash_on = dash_on;
129 node->dash_off = dash_off;
134 /* create a new area */
135 gfx_node_t *gfx_new_area (gfx_canvas_t *canvas,
136 double X0, double Y0,
137 double X1, double Y1,
138 double X2, double Y2,
143 node = gfx_new_node(canvas,GFX_AREA);
144 if (node == NULL) return NULL;
145 vec = art_new(ArtVpath, 5);
146 if (vec == NULL) return NULL;
147 vec[0].code = ART_MOVETO; vec[0].x=X0; vec[0].y=Y0;
148 vec[1].code = ART_LINETO; vec[1].x=X1; vec[1].y=Y1;
149 vec[2].code = ART_LINETO; vec[2].x=X2; vec[2].y=Y2;
150 vec[3].code = ART_LINETO; vec[3].x=X0; vec[3].y=Y0;
151 vec[4].code = ART_END; vec[4].x=0; vec[4].y=0;
154 node->points_max = 5;
161 /* add a point to a line or to an area */
162 int gfx_add_point (gfx_node_t *node,
164 if (node == NULL) return 1;
165 if (node->type == GFX_AREA) {
166 double X0 = node->path[0].x;
167 double Y0 = node->path[0].y;
169 art_vpath_add_point (&(node->path),
174 art_vpath_add_point (&(node->path),
179 art_vpath_add_point (&(node->path),
184 } else if (node->type == GFX_LINE) {
186 art_vpath_add_point (&(node->path),
190 x+LINEOFFSET,y+LINEOFFSET);
191 art_vpath_add_point (&(node->path),
198 /* can only add point to areas and lines */
204 void gfx_close_path (gfx_node_t *node) {
205 node->closed_path = 1;
206 if (node->path[0].code == ART_MOVETO_OPEN)
207 node->path[0].code = ART_MOVETO;
210 /* create a text node */
211 gfx_node_t *gfx_new_text (gfx_canvas_t *canvas,
212 double x, double y, gfx_color_t color,
213 char* font, double size,
214 double tabwidth, double angle,
215 enum gfx_h_align_en h_align,
216 enum gfx_v_align_en v_align,
218 gfx_node_t *node = gfx_new_node(canvas,GFX_TEXT);
220 node->text = strdup(text);
222 node->filename = strdup(font);
227 node->tabwidth = tabwidth;
228 node->halign = h_align;
229 node->valign = v_align;
231 /* debugging: show text anchor
232 green is along x-axis, red is downward y-axis */
234 double a = 2 * M_PI * -node->angle / 360.0;
235 double cos_a = cos(a);
236 double sin_a = sin(a);
240 x + len * cos_a, y - len * sin_a,
244 x + len * sin_a, y + len * cos_a,
251 int gfx_render(gfx_canvas_t *canvas,
252 art_u32 width, art_u32 height,
253 gfx_color_t background, FILE *fp){
254 switch (canvas->imgformat) {
256 return gfx_render_png (canvas, width, height, background, fp);
258 return gfx_render_svg (canvas, width, height, background, fp);
260 return gfx_render_eps (canvas, width, height, background, fp);
262 return gfx_render_pdf (canvas, width, height, background, fp);
268 static void gfx_string_destroy ( gfx_string string ) {
270 if (string->glyphs) {
271 for (n=0; n<string->num_glyphs; ++n)
272 FT_Done_Glyph (string->glyphs[n].image);
273 free (string->glyphs);
279 double gfx_get_text_width ( gfx_canvas_t *canvas,
280 double start, char* font, double size,
281 double tabwidth, char* text, int rotation){
282 switch (canvas->imgformat) {
284 return gfx_get_text_width_libart (canvas, start, font, size, tabwidth, text, rotation);
285 case IF_SVG: /* fall through */
288 return afm_get_text_width(start, font, size, tabwidth, text);
290 return size * strlen(text);
294 double gfx_get_text_width_libart (
295 gfx_canvas_t *canvas, double UNUSED(start), char* font, double size,
296 double tabwidth, char* text, int rotation ){
301 FT_Library library=NULL;
304 FT_Init_FreeType( &library );
305 error = FT_New_Face( library, font, 0, &face );
306 if ( error ) return -1;
307 error = FT_Set_Char_Size(face, size*64,size*64, 100,100);
308 if ( error ) return -1;
310 string = gfx_string_create( canvas, face, text, rotation, tabwidth, size );
311 text_width = string->width;
312 gfx_string_destroy(string);
313 FT_Done_FreeType(library);
314 return text_width/64;
317 static void gfx_libart_close_path(gfx_node_t *node, ArtVpath **vec)
319 /* libart must have end==start for closed paths,
320 even if using ART_MOVETO and not ART_MOVETO_OPEN
321 so add extra point which is the same as the starting point */
322 int points_max = node->points; /* scaled array has exact size */
323 int points = node->points - 1;
324 art_vpath_add_point (vec, &points, &points_max, ART_LINETO,
325 (**vec).x, (**vec).y);
326 art_vpath_add_point (vec, &points, &points_max, ART_END, 0, 0);
330 /* find bbox of a string */
331 static void compute_string_bbox(gfx_string string) {
335 bbox.xMin = bbox.yMin = 32000;
336 bbox.xMax = bbox.yMax = -32000;
337 for ( n = 0; n < string->num_glyphs; n++ ) {
339 FT_Glyph_Get_CBox( string->glyphs[n].image, ft_glyph_bbox_gridfit,
341 if (glyph_bbox.xMin < bbox.xMin) {
342 bbox.xMin = glyph_bbox.xMin;
344 if (glyph_bbox.yMin < bbox.yMin) {
345 bbox.yMin = glyph_bbox.yMin;
347 if (glyph_bbox.xMax > bbox.xMax) {
348 bbox.xMax = glyph_bbox.xMax;
350 if (glyph_bbox.yMax > bbox.yMax) {
351 bbox.yMax = glyph_bbox.yMax;
354 if ( bbox.xMin > bbox.xMax ) {
360 string->bbox.xMin = bbox.xMin;
361 string->bbox.xMax = bbox.xMax;
362 string->bbox.yMin = bbox.yMin;
363 string->bbox.yMax = bbox.yMax;
366 /* create a free type glyph string */
367 gfx_string gfx_string_create(gfx_canvas_t *canvas, FT_Face face,const char *text,
368 int rotation, double tabwidth, double size )
371 FT_GlyphSlot slot = face->glyph; /* a small shortcut */
376 gfx_string string = (gfx_string) malloc (sizeof(struct gfx_string_s));
378 gfx_char glyph; /* current glyph in table */
385 size_t clen = strlen(text)+1;
386 cstr = malloc(sizeof(wchar_t) * clen); /* yes we are allocating probably too much here, I know */
387 string->count=mbstowcs(cstr,text,clen);
388 if ( string->count == -1){
389 string->count=mbstowcs(cstr,"Enc-Err",6);
392 char *cstr = strdup(text);
393 string->count = strlen (text);
396 ft_pen.x = 0; /* start at (0,0) !! */
402 string->glyphs = (gfx_char) calloc (string->count,sizeof(struct gfx_char_s));
403 string->num_glyphs = 0;
404 string->transform.xx = (FT_Fixed)( cos(M_PI*(rotation)/180.0)*0x10000);
405 string->transform.xy = (FT_Fixed)(-sin(M_PI*(rotation)/180.0)*0x10000);
406 string->transform.yx = (FT_Fixed)( sin(M_PI*(rotation)/180.0)*0x10000);
407 string->transform.yy = (FT_Fixed)( cos(M_PI*(rotation)/180.0)*0x10000);
409 use_kerning = FT_HAS_KERNING(face);
411 glyph = string->glyphs;
412 for (n=0; n<string->count;glyph++) {
414 /* handle the tabs ...
415 have a witespace glyph inserted, but set its width such that the distance
416 of the new right edge is x times tabwidth from 0,0 where x is an integer. */
417 unsigned int letter = cstr[n];
420 if (letter == '\\' && n+1 < string->count && cstr[n+1] == 't'){
421 /* we have a tab here so skip the backslash and
422 set t to ' ' so that we get a white space */
431 /* initialize each struct gfx_char_s */
436 glyph->index = FT_Get_Char_Index( face, letter );
438 /* compute glyph origin */
439 if ( use_kerning && previous && glyph->index ) {
441 FT_Get_Kerning (face, previous, glyph->index,
442 ft_kerning_default, &kerning);
443 ft_pen.x += kerning.x;
444 ft_pen.y += kerning.y;
447 /* load the glyph image (in its native format) */
448 /* for now, we take a monochrome glyph bitmap */
449 error = FT_Load_Glyph (face, glyph->index, size > canvas->font_aa_threshold ?
450 canvas->aa_type == AA_NORMAL ? FT_LOAD_TARGET_NORMAL :
451 canvas->aa_type == AA_LIGHT ? FT_LOAD_TARGET_LIGHT :
452 FT_LOAD_TARGET_MONO : FT_LOAD_TARGET_MONO);
454 fprintf (stderr, "couldn't load glyph: %c\n", letter);
457 error = FT_Get_Glyph (slot, &glyph->image);
459 fprintf (stderr, "couldn't get glyph from slot: %c\n", letter);
462 /* if we are in tabbing mode, we replace the tab with a space and shift the position
463 of the space so that its left edge is where the tab was supposed to land us */
465 /* we are in gridfitting mode so the calculations happen in 1/64 pixles */
466 ft_pen.x = tabwidth*64.0 * (float)(1 + (long)(ft_pen.x / (tabwidth * 64.0))) - slot->advance.x;
468 /* store current pen position */
469 glyph->pos.x = ft_pen.x;
470 glyph->pos.y = ft_pen.y;
473 ft_pen.x += slot->advance.x;
474 ft_pen.y += slot->advance.y;
478 FT_Vector_Transform (&vec, &string->transform);
479 error = FT_Glyph_Transform (glyph->image, &string->transform, &vec);
481 fprintf (stderr, "couldn't transform glyph\n");
485 /* convert to a bitmap - destroy native image */
486 error = FT_Glyph_To_Bitmap (&glyph->image, size > canvas->font_aa_threshold ?
487 canvas->aa_type == AA_NORMAL ? FT_RENDER_MODE_NORMAL :
488 canvas->aa_type == AA_LIGHT ? FT_RENDER_MODE_LIGHT :
489 FT_RENDER_MODE_MONO : FT_RENDER_MODE_MONO, 0, 1);
491 fprintf (stderr, "couldn't convert glyph to bitmap\n");
495 /* increment number of glyphs */
496 previous = glyph->index;
497 string->num_glyphs++;
502 /* printf ("number of glyphs = %d\n", string->num_glyphs);*/
503 compute_string_bbox( string );
504 /* the last character was a tab */
506 string->width = ft_pen.x;
508 string->width = string->bbox.xMax - string->bbox.xMin;
510 string->height = string->bbox.yMax - string->bbox.yMin;
515 static int gfx_save_png (art_u8 *buffer, FILE *fp,
516 long width, long height, long bytes_per_pixel);
517 /* render grafics into png image */
519 int gfx_render_png (gfx_canvas_t *canvas,
520 art_u32 width, art_u32 height,
521 gfx_color_t background, FILE *fp){
525 gfx_node_t *node = canvas->firstnode;
527 art_u8 red = background >> 24, green = (background >> 16) & 0xff;
528 art_u8 blue = (background >> 8) & 0xff, alpha = ( background & 0xff );
530 unsigned long pys_width = width * canvas->zoom;
531 unsigned long pys_height = height * canvas->zoom;
532 const int bytes_per_pixel = 4;
533 unsigned long rowstride = pys_width*bytes_per_pixel; /* bytes per pixel */
535 /* fill that buffer with out background color */
536 gfx_color_t *buffp = art_new (gfx_color_t, pys_width*pys_height);
537 art_u8 *buffer = (art_u8 *)buffp;
539 for (i=0;i<pys_width*pys_height;
541 *(buffp++)=background;
543 FT_Init_FreeType( &library );
545 switch (node->type) {
551 art_affine_scale(dst,canvas->zoom,canvas->zoom);
552 vec = art_vpath_affine_transform(node->path,dst);
553 if (node->closed_path)
554 gfx_libart_close_path(node, &vec);
555 /* gfx_round_scaled_coordinates(vec); */
556 /* pvec = art_vpath_perturb(vec);
558 if(node->type == GFX_LINE){
559 svp = art_svp_vpath_stroke ( vec, ART_PATH_STROKE_JOIN_ROUND,
560 ART_PATH_STROKE_CAP_ROUND,
561 node->size*canvas->zoom,4,0.25);
563 svp = art_svp_from_vpath ( vec );
564 /* this takes time and is unnecessary since we make
565 sure elsewhere that the areas are going clock-whise */
566 /* svpt = art_svp_uncross( svp );
568 svp = art_svp_rewind_uncrossed(svpt,ART_WIND_RULE_NONZERO);
573 /* this is from gnome since libart does not have this yet */
574 gnome_print_art_rgba_svp_alpha (svp ,0,0, pys_width, pys_height,
575 node->color, buffer, rowstride, NULL);
582 art_u8 fcolor[4],falpha;
586 FT_Vector vec; /* 26.6 */
588 float pen_x = 0.0 , pen_y = 0.0;
592 fcolor[0] = node->color >> 24;
593 fcolor[1] = (node->color >> 16) & 0xff;
594 fcolor[2] = (node->color >> 8) & 0xff;
595 falpha = node->color & 0xff;
596 error = FT_New_Face( library,
597 (char *)node->filename,
601 rrd_set_error("failed to load %s",node->filename);
604 error = FT_Set_Char_Size(face, /* handle to face object */
605 (long)(node->size*64),
606 (long)(node->size*64),
607 (long)(100*canvas->zoom),
608 (long)(100*canvas->zoom));
610 pen_x = node->x * canvas->zoom;
611 pen_y = node->y * canvas->zoom;
613 string = gfx_string_create (canvas, face, node->text, node->angle, node->tabwidth, node->size);
614 switch(node->halign){
615 case GFX_H_RIGHT: vec.x = -string->bbox.xMax;
617 case GFX_H_CENTER: vec.x = abs(string->bbox.xMax) >= abs(string->bbox.xMin) ?
618 -string->bbox.xMax/2:-string->bbox.xMin/2;
620 case GFX_H_LEFT: vec.x = -string->bbox.xMin;
622 case GFX_H_NULL: vec.x = 0;
626 switch(node->valign){
627 case GFX_V_TOP: vec.y = string->bbox.yMax;
629 case GFX_V_CENTER: vec.y = abs(string->bbox.yMax) >= abs(string->bbox.yMin) ?
630 string->bbox.yMax/2:string->bbox.yMin/2;
632 case GFX_V_BOTTOM: vec.y = 0;
634 case GFX_V_NULL: vec.y = 0;
639 glyph = string->glyphs;
640 for(n=0; n<string->num_glyphs; ++n, ++glyph) {
644 /* long buf_x,comp_n; */
645 /* make copy to transform */
646 if (! glyph->image) {
647 fprintf (stderr, "no image\n");
650 error = FT_Glyph_Copy (glyph->image, &image);
652 fprintf (stderr, "couldn't copy image\n");
658 FT_Vector_Transform (&vec, &string->transform);
660 bit = (FT_BitmapGlyph) image;
661 gr = bit->bitmap.num_grays -1;
663 buf_x = (pen_x + 0.5) + (double)bit->left;
664 comp_n = buf_x + bit->bitmap.width > pys_width ? pys_width - buf_x : bit->bitmap.width;
665 if (buf_x < 0 || buf_x >= (long)pys_width) continue;
666 buf_x *= bytes_per_pixel ;
667 for (iy=0; iy < bit->bitmap.rows; iy++){
668 long buf_y = iy+(pen_y+0.5)-(double)bit->top;
669 if (buf_y < 0 || buf_y >= (long)pys_height) continue;
671 for (ix=0;ix < bit->bitmap.width;ix++){
672 *(letter + (ix*bytes_per_pixel+3)) = *(bit->bitmap.buffer + iy * bit->bitmap.width + ix);
674 art_rgba_rgba_composite(buffer + buf_y + buf_x ,letter,comp_n);
678 switch ( bit->bitmap.pixel_mode ) {
679 case FT_PIXEL_MODE_GRAY:
680 for (iy=0; iy < bit->bitmap.rows; iy++){
681 long buf_y = iy+(pen_y+0.5)-bit->top;
682 if (buf_y < 0 || buf_y >= (long)pys_height) continue;
684 for (ix=0;ix < bit->bitmap.width;ix++){
685 long buf_x = ix + (pen_x + 0.5) + (double)bit->left ;
688 if (buf_x < 0 || buf_x >= (long)pys_width) continue;
689 buf_x *= bytes_per_pixel ;
690 font_alpha = *(bit->bitmap.buffer + iy * bit->bitmap.pitch + ix);
692 fcolor[3] = (art_u8)((double)font_alpha / gr * falpha);
693 art_rgba_rgba_composite(buffer + buf_y + buf_x ,fcolor,1);
699 case FT_PIXEL_MODE_MONO:
700 for (iy=0; iy < bit->bitmap.rows; iy++){
701 long buf_y = iy+(pen_y+0.5)-bit->top;
702 if (buf_y < 0 || buf_y >= (long)pys_height) continue;
704 for (ix=0;ix < bit->bitmap.width;ix++){
705 long buf_x = ix + (pen_x + 0.5) + (double)bit->left ;
707 if (buf_x < 0 || buf_x >= (long)pys_width) continue;
708 buf_x *= bytes_per_pixel ;
709 if ( (fcolor[3] = falpha * ((*(bit->bitmap.buffer + iy * bit->bitmap.pitch + ix/8) >> (7 - (ix % 8))) & 1)) > 0 )
710 art_rgba_rgba_composite(buffer + buf_y + buf_x ,fcolor,1);
716 rrd_set_error("unknown freetype pixel mode: %d", bit->bitmap.pixel_mode);
721 for (iy=0; iy < bit->bitmap.rows; iy++){
722 long buf_y = iy+(pen_y+0.5)-bit->top;
723 if (buf_y < 0 || buf_y >= (long)pys_height) continue;
725 for (ix=0;ix < bit->bitmap.width;ix++){
726 long buf_x = ix + (pen_x + 0.5) + (double)bit->left ;
729 if (buf_x < 0 || buf_x >= (long)pys_width) continue;
730 buf_x *= bytes_per_pixel ;
731 font_alpha = *(bit->bitmap.buffer + iy * bit->bitmap.width + ix);
732 font_alpha = (art_u8)((double)font_alpha / gr * falpha);
733 for (iz = 0; iz < 3; iz++){
734 art_u8 *orig = buffer + buf_y + buf_x + iz;
735 *orig = (art_u8)((double)*orig / gr * ( gr - font_alpha) +
736 (double)fcolor[iz] / gr * (font_alpha));
741 FT_Done_Glyph (image);
743 gfx_string_destroy(string);
748 gfx_save_png(buffer,fp , pys_width,pys_height,bytes_per_pixel);
750 FT_Done_FreeType( library );
754 /* free memory used by nodes this will also remove memory required for
755 associated paths and svcs ... but not for text strings */
757 gfx_destroy (gfx_canvas_t *canvas){
758 gfx_node_t *next,*node = canvas->firstnode;
761 art_free(node->path);
763 free(node->filename);
771 static int gfx_save_png (art_u8 *buffer, FILE *fp, long width, long height, long bytes_per_pixel){
772 png_structp png_ptr = NULL;
773 png_infop info_ptr = NULL;
775 png_bytep *row_pointers;
776 int rowstride = width * bytes_per_pixel;
782 png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING,NULL,NULL,NULL);
787 row_pointers = (png_bytepp)png_malloc(png_ptr,
788 height*sizeof(png_bytep));
790 info_ptr = png_create_info_struct(png_ptr);
792 if (info_ptr == NULL)
794 png_free(png_ptr,row_pointers);
795 png_destroy_write_struct(&png_ptr, (png_infopp)NULL);
799 if (setjmp(png_jmpbuf(png_ptr)))
801 /* If we get here, we had a problem writing the file */
802 png_destroy_write_struct(&png_ptr, &info_ptr);
806 png_init_io(png_ptr, fp);
807 png_set_IHDR (png_ptr, info_ptr,width, height,
808 8, PNG_COLOR_TYPE_RGB_ALPHA,
810 PNG_COMPRESSION_TYPE_DEFAULT,
811 PNG_FILTER_TYPE_DEFAULT);
813 text[0].key = "Software";
814 text[0].text = "RRDtool, Tobias Oetiker <tobi@oetike.ch>, http://tobi.oetiker.ch";
815 text[0].compression = PNG_TEXT_COMPRESSION_NONE;
816 png_set_text (png_ptr, info_ptr, text, 1);
818 /* lets make this fast while ending up with some increass in image size */
819 png_set_filter(png_ptr,0,PNG_FILTER_NONE);
820 /* png_set_filter(png_ptr,0,PNG_FILTER_SUB); */
821 png_set_compression_level(png_ptr,1);
822 /* png_set_compression_strategy(png_ptr,Z_HUFFMAN_ONLY); */
824 png_set_filter(png_ptr,PNG_FILTER_TYPE_BASE,PNG_FILTER_SUB);
825 png_set_compression_strategy(png_ptr,Z_HUFFMAN_ONLY);
826 png_set_compression_level(png_ptr,Z_BEST_SPEED); */
828 /* Write header data */
829 png_write_info (png_ptr, info_ptr);
830 for (i = 0; i < height; i++)
831 row_pointers[i] = (png_bytep) (buffer + i*rowstride);
833 png_write_image(png_ptr, row_pointers);
834 png_write_end(png_ptr, info_ptr);
835 png_free(png_ptr,row_pointers);
836 png_destroy_write_struct(&png_ptr, &info_ptr);
841 /* ----- COMMON ROUTINES for pdf, svg and eps */
842 #define min3(a, b, c) (a < b ? (a < c ? a : c) : (b < c ? b : c))
843 #define max3(a, b, c) (a > b ? (a > c ? a : c) : (b > c ? b : c))
845 #define PDF_CALC_DEBUG 0
847 typedef struct pdf_point
854 double ascender, descender, baselineY;
855 pdf_point sizep, minp, maxp;
856 double x, y, tdx, tdy;
857 double r, cos_r, sin_r;
858 double ma, mb, mc, md, mx, my; /* pdf coord matrix */
859 double tmx, tmy; /* last 2 coords of text coord matrix */
866 static void pdf_dump_calc(gfx_node_t *node, pdf_coords *g)
868 fprintf(stderr, "PDF CALC =============================\n");
869 fprintf(stderr, " '%s' at %f pt\n", node->text, node->size);
870 fprintf(stderr, " align h = %s, v = %s, sizep = %f, %f\n",
871 (node->halign == GFX_H_RIGHT ? "r" :
872 (node->halign == GFX_H_CENTER ? "c" :
873 (node->halign == GFX_H_LEFT ? "l" : "N"))),
874 (node->valign == GFX_V_TOP ? "t" :
875 (node->valign == GFX_V_CENTER ? "c" :
876 (node->valign == GFX_V_BOTTOM ? "b" : "N"))),
877 g->sizep.x, g->sizep.y);
878 fprintf(stderr, " r = %f = %f, cos = %f, sin = %f\n",
879 g->r, node->angle, g->cos_r, g->sin_r);
880 fprintf(stderr, " ascender = %f, descender = %f, baselineY = %f\n",
881 g->ascender, g->descender, g->baselineY);
882 fprintf(stderr, " sizep: %f, %f\n", g->sizep.x, g->sizep.y);
883 fprintf(stderr, " minp: %f, %f maxp = %f, %f\n",
884 g->minp.x, g->minp.y, g->maxp.x, g->maxp.y);
885 fprintf(stderr, " x = %f, y = %f\n", g->x, g->y);
886 fprintf(stderr, " tdx = %f, tdy = %f\n", g->tdx, g->tdy);
887 fprintf(stderr, " GM = %f, %f, %f, %f, %f, %f\n",
888 g->ma, g->mb, g->mc, g->md, g->mx, g->my);
889 fprintf(stderr, " TM = %f, %f, %f, %f, %f, %f\n",
890 g->ma, g->mb, g->mc, g->md, g->tmx, g->tmy);
895 #define PDF_DD(x) if (g->debug) x;
900 static void pdf_rotate(pdf_coords *g, pdf_point *p)
902 double x2 = g->cos_r * p->x - g->sin_r * p->y;
903 double y2 = g->sin_r * p->x + g->cos_r * p->y;
904 PDF_DD( fprintf(stderr, " rotate(%f, %f) -> %f, %f\n", p->x, p->y, x2, y2))
910 static void pdf_calc(int page_height, gfx_node_t *node, pdf_coords *g)
914 /* g->debug = !!strstr(node->text, "RevProxy-1") || !!strstr(node->text, "08:00"); */
915 g->debug = !!strstr(node->text, "sekunder") || !!strstr(node->text, "Web");
918 g->y = page_height - node->y;
920 g->r = 2 * M_PI * node->angle / 360.0;
921 g->cos_r = cos(g->r);
922 g->sin_r = sin(g->r);
928 g->ascender = afm_get_ascender(node->filename, node->size);
929 g->descender = afm_get_descender(node->filename, node->size);
930 g->sizep.x = afm_get_text_width(0, node->filename, node->size, node->tabwidth, node->text);
931 /* seems like libart ignores the descender when doing vertial-align = bottom,
932 so we do that too, to get labels v-aligning properly */
933 g->sizep.y = -g->ascender; /* + afm_get_descender(font->ps_font, node->size); */
934 g->baselineY = -g->ascender - g->sizep.y / 2;
935 a.x = g->sizep.x; a.y = g->sizep.y;
936 b.x = g->sizep.x; b.y = 0;
937 c.x = 0; c.y = g->sizep.y;
943 g->minp.x = min3(a.x, b.x, c.x);
944 g->minp.y = min3(a.y, b.y, c.y);
945 g->maxp.x = max3(a.x, b.x, c.x);
946 g->maxp.y = max3(a.y, b.y, c.y);
947 /* The alignment parameters in node->valign and node->halign
948 specifies the alignment in the non-rotated coordinate system
949 (very unlike pdf/postscript), which complicates matters.
951 switch (node->halign) {
952 case GFX_H_RIGHT: g->tdx = -g->maxp.x; break;
953 case GFX_H_CENTER: g->tdx = -(g->maxp.x + g->minp.x) / 2; break;
954 case GFX_H_LEFT: g->tdx = -g->minp.x; break;
955 case GFX_H_NULL: g->tdx = 0; break;
957 switch(node->valign){
958 case GFX_V_TOP: g->tdy = -g->maxp.y; break;
959 case GFX_V_CENTER: g->tdy = -(g->maxp.y + g->minp.y) / 2; break;
960 case GFX_V_BOTTOM: g->tdy = -g->minp.y; break;
961 case GFX_V_NULL: g->tdy = 0; break;
967 g->mx = g->x + g->tdx;
968 g->my = g->y + g->tdy;
969 g->tmx = g->mx - g->ascender * g->mc;
970 g->tmy = g->my - g->ascender * g->md;
971 PDF_DD(pdf_dump_calc(node, g))
974 /* ------- SVG -------
976 http://www.w3.org/TR/SVG/
978 static int svg_indent = 0;
979 static int svg_single_line = 0;
980 static const char *svg_default_font = "-dummy-";
981 typedef struct svg_dash
984 double dash_adjust, dash_len, dash_offset;
985 double adjusted_on, adjusted_off;
989 static void svg_print_indent(FILE *fp)
992 for (i = svg_indent - svg_single_line; i > 0; i--) {
998 static void svg_start_tag(FILE *fp, const char *name)
1000 svg_print_indent(fp);
1006 static void svg_close_tag_single_line(FILE *fp)
1012 static void svg_close_tag(FILE *fp)
1015 if (!svg_single_line)
1019 static void svg_end_tag(FILE *fp, const char *name)
1021 /* name is NULL if closing empty-node tag */
1023 if (svg_single_line)
1026 svg_print_indent(fp);
1036 static void svg_close_tag_empty_node(FILE *fp)
1038 svg_end_tag(fp, NULL);
1041 static void svg_write_text(FILE *fp, const char *text)
1043 const unsigned char *p, *start, *last;
1045 p = (const unsigned char*)text;
1048 /* trim leading spaces */
1052 /* trim trailing spaces */
1054 while ((ch = *p) != 0) {
1059 /* encode trimmed text */
1063 ch = afm_host2unicode(ch); /* unsafe macro */
1065 case '&': fputs("&", fp); break;
1066 case '<': fputs("<", fp); break;
1067 case '>': fputs(">", fp); break;
1068 case '"': fputs(""", fp); break;
1071 fprintf(fp, "&#%d;", ch);
1078 static void svg_format_number(char *buf, int bufsize, double d)
1080 /* omit decimals if integer to reduce filesize */
1082 snprintf(buf, bufsize, "%.2f", d);
1083 p = buf; /* doesn't trust snprintf return value */
1089 *p = '\0'; /* zap trailing zeros */
1093 *p = '\0'; /* zap trailing dot */
1098 static void svg_write_number(FILE *fp, double d)
1101 svg_format_number(buf, sizeof(buf), d);
1105 static int svg_color_is_black(int c)
1107 /* gfx_color_t is RRGGBBAA */
1108 return c == 0x000000FF;
1111 static void svg_write_color(FILE *fp, gfx_color_t c, const char *attr)
1113 /* gfx_color_t is RRGGBBAA, svg can use #RRGGBB and #RGB like html */
1114 gfx_color_t rrggbb = (int)((c >> 8) & 0xFFFFFF);
1115 gfx_color_t opacity = c & 0xFF;
1116 fprintf(fp, " %s=\"", attr);
1117 if ((rrggbb & 0x0F0F0F) == ((rrggbb >> 4) & 0x0F0F0F)) {
1118 /* css2 short form, #rgb is #rrggbb, not #r0g0b0 */
1119 fprintf(fp, "#%03lX",
1120 ( ((rrggbb >> 8) & 0xF00)
1121 | ((rrggbb >> 4) & 0x0F0)
1122 | ( rrggbb & 0x00F)));
1124 fprintf(fp, "#%06lX", rrggbb);
1127 if (opacity != 0xFF) {
1128 fprintf(fp, " opacity=\"");
1129 svg_write_number(fp, opacity / 255.0);
1134 static void svg_get_dash(gfx_node_t *node, svg_dash *d)
1138 if (node->dash_on <= 0 || node->dash_off <= 0) {
1143 d->dash_len = node->dash_on + node->dash_off;
1144 /* dash on/off adjustment due to round caps */
1145 d->dash_adjust = 0.8 * node->size;
1146 d->adjusted_on = node->dash_on - d->dash_adjust;
1147 if (d->adjusted_on < 0.01)
1148 d->adjusted_on = 0.01;
1149 d->adjusted_off = d->dash_len - d->adjusted_on;
1150 /* dash offset calc */
1151 if (node->path[0].x == node->path[1].x) /* only good for horz/vert lines */
1152 offset = node->path[0].y;
1154 offset = node->path[0].x;
1155 mult = (int)fabs(offset / d->dash_len);
1156 d->dash_offset = offset - mult * d->dash_len;
1157 if (node->path[0].x < node->path[1].x || node->path[0].y < node->path[1].y)
1158 d->dash_offset = d->dash_len - d->dash_offset;
1161 static int svg_dash_equal(svg_dash *a, svg_dash *b)
1163 if (a->dash_enable != b->dash_enable)
1165 if (a->adjusted_on != b->adjusted_on)
1167 if (a->adjusted_off != b->adjusted_off)
1169 /* rest of properties will be the same when on+off are */
1173 static void svg_common_path_attributes(FILE *fp, gfx_node_t *node)
1176 svg_get_dash(node, &dash_info);
1177 fputs(" stroke-width=\"", fp);
1178 svg_write_number(fp, node->size);
1180 svg_write_color(fp, node->color, "stroke");
1181 fputs(" fill=\"none\"", fp);
1182 if (dash_info.dash_enable) {
1183 if (dash_info.dash_offset != 0) {
1184 fputs(" stroke-dashoffset=\"", fp);
1185 svg_write_number(fp, dash_info.dash_offset);
1188 fputs(" stroke-dasharray=\"", fp);
1189 svg_write_number(fp, dash_info.adjusted_on);
1191 svg_write_number(fp, dash_info.adjusted_off);
1196 static int svg_is_int_step(double a, double b)
1198 double diff = fabs(a - b);
1199 return floor(diff) == diff;
1202 static int svg_path_straight_segment(FILE *fp,
1203 double lastA, double currentA, double currentB,
1205 int segment_idx, int isx, char absChar, char relChar)
1207 if (!svg_is_int_step(lastA, currentA)) {
1209 svg_write_number(fp, currentA);
1212 if (segment_idx < node->points - 1) {
1213 ArtVpath *vec = node->path + segment_idx + 1;
1214 if (vec->code == ART_LINETO) {
1215 double nextA = (isx ? vec->x : vec->y) - LINEOFFSET;
1216 double nextB = (isx ? vec->y : vec->x) - LINEOFFSET;
1217 if (nextB == currentB
1218 && ((currentA >= lastA) == (nextA >= currentA))
1219 && svg_is_int_step(currentA, nextA)) {
1220 return 1; /* skip to next as it is a straight line */
1225 svg_write_number(fp, currentA - lastA);
1229 static void svg_path(FILE *fp, gfx_node_t *node, int multi)
1232 double lastX = 0, lastY = 0;
1233 /* for straight lines <path..> tags take less space than
1234 <line..> tags because of the efficient packing
1235 in the 'd' attribute */
1236 svg_start_tag(fp, "path");
1238 svg_common_path_attributes(fp, node);
1240 /* specification of the 'd' attribute: */
1241 /* http://www.w3.org/TR/SVG/paths.html#PathDataGeneralInformation */
1242 for (i = 0; i < node->points; i++) {
1243 ArtVpath *vec = node->path + i;
1244 double x = vec->x - LINEOFFSET;
1245 double y = vec->y - LINEOFFSET;
1246 switch (vec->code) {
1247 case ART_MOVETO_OPEN: /* fall-through */
1250 svg_write_number(fp, x);
1252 svg_write_number(fp, y);
1255 /* try optimize filesize by using minimal lineto commands */
1256 /* without introducing rounding errors. */
1258 if (svg_path_straight_segment(fp, lastY, y, x, node, i, 0, 'V', 'v'))
1260 } else if (y == lastY) {
1261 if (svg_path_straight_segment(fp, lastX, x, y, node, i, 1, 'H', 'h'))
1265 svg_write_number(fp, x);
1267 svg_write_number(fp, y);
1270 case ART_CURVETO: break; /* unsupported */
1271 case ART_END: break; /* nop */
1276 if (node->closed_path)
1279 svg_close_tag_empty_node(fp);
1282 static void svg_multi_path(FILE *fp, gfx_node_t **nodeR)
1284 /* optimize for multiple paths with the same color, penwidth, etc. */
1286 gfx_node_t *node = *nodeR;
1287 gfx_node_t *next = node->next;
1289 if (next->type != node->type
1290 || next->size != node->size
1291 || next->color != node->color
1292 || next->dash_on != node->dash_on
1293 || next->dash_off != node->dash_off)
1299 svg_path(fp, node, 0);
1302 svg_start_tag(fp, "g");
1303 svg_common_path_attributes(fp, node);
1305 while (num && node) {
1306 svg_path(fp, node, 1);
1312 svg_end_tag(fp, "g");
1315 static void svg_area(FILE *fp, gfx_node_t *node)
1318 double startX = 0, startY = 0;
1319 svg_start_tag(fp, "polygon");
1321 svg_write_color(fp, node->color, "fill");
1322 fputs(" points=\"", fp);
1323 for (i = 0; i < node->points; i++) {
1324 ArtVpath *vec = node->path + i;
1325 double x = vec->x - LINEOFFSET;
1326 double y = vec->y - LINEOFFSET;
1327 switch (vec->code) {
1328 case ART_MOVETO_OPEN: /* fall-through */
1330 svg_write_number(fp, x);
1332 svg_write_number(fp, y);
1337 if (i == node->points - 2
1338 && node->path[i + 1].code == ART_END
1339 && fabs(x - startX) < 0.001 && fabs(y - startY) < 0.001) {
1340 break; /* poly area always closed, no need for last point */
1343 svg_write_number(fp, x);
1345 svg_write_number(fp, y);
1347 case ART_CURVETO: break; /* unsupported */
1348 case ART_END: break; /* nop */
1352 svg_close_tag_empty_node(fp);
1355 static void svg_text(FILE *fp, gfx_node_t *node)
1358 const char *fontname;
1359 /* as svg has 0,0 in top-left corner (like most screens) instead of
1360 bottom-left corner like pdf and eps, we have to fake the coords
1361 using offset and inverse sin(r) value */
1362 int page_height = 1000;
1363 pdf_calc(page_height, node, &g);
1364 if (node->angle != 0) {
1365 svg_start_tag(fp, "g");
1366 /* can't use svg_write_number as 2 decimals is far from enough to avoid
1368 fprintf(fp, " transform=\"matrix(%f,%f,%f,%f,%f,%f)\"",
1369 g.ma, -g.mb, -g.mc, g.md, g.tmx, page_height - g.tmy);
1372 svg_start_tag(fp, "text");
1375 svg_write_number(fp, g.tmx);
1376 fputs("\" y=\"", fp);
1377 svg_write_number(fp, page_height - g.tmy);
1380 fontname = afm_get_font_name(node->filename);
1381 if (strcmp(fontname, svg_default_font))
1382 fprintf(fp, " font-family=\"%s\"", fontname);
1383 fputs(" font-size=\"", fp);
1384 svg_write_number(fp, node->size);
1386 if (!svg_color_is_black(node->color))
1387 svg_write_color(fp, node->color, "fill");
1388 svg_close_tag_single_line(fp);
1389 /* support for node->tabwidth missing */
1390 svg_write_text(fp, node->text);
1391 svg_end_tag(fp, "text");
1392 if (node->angle != 0)
1393 svg_end_tag(fp, "g");
1396 int gfx_render_svg (gfx_canvas_t *canvas,
1397 art_u32 width, art_u32 height,
1398 gfx_color_t background, FILE *fp){
1399 gfx_node_t *node = canvas->firstnode;
1400 /* Find the first font used, and assume it is the mostly used
1401 one. It reduces the number of font-familty attributes. */
1403 if (node->type == GFX_TEXT && node->filename) {
1404 svg_default_font = afm_get_font_name(node->filename);
1410 "<?xml version=\"1.0\" standalone=\"no\"?>\n"
1411 "<!DOCTYPE svg PUBLIC \"-//W3C//DTD SVG 1.0//EN\"\n"
1412 " \"http://www.w3.org/TR/2001/REC-SVG-20010904/DTD/svg10.dtd\">\n"
1414 " SVG file created by\n"
1415 " RRDtool " PACKAGE_VERSION " Tobias Oetiker, http://tobi.oetiker.ch\n"
1417 " The width/height attributes in the outhermost svg node\n"
1418 " are just default sizes for the browser which is used\n"
1419 " if the svg file is openened directly without being\n"
1420 " embedded in an html file.\n"
1421 " The viewBox is the local coord system for rrdtool.\n"
1423 svg_start_tag(fp, "svg");
1424 fputs(" width=\"", fp);
1425 svg_write_number(fp, width * canvas->zoom);
1426 fputs("\" height=\"", fp);
1427 svg_write_number(fp, height * canvas->zoom);
1428 fputs("\" x=\"0\" y=\"0\" viewBox=\"", fp);
1429 svg_write_number(fp, -LINEOFFSET);
1431 svg_write_number(fp, -LINEOFFSET);
1433 svg_write_number(fp, width - LINEOFFSET);
1435 svg_write_number(fp, height - LINEOFFSET);
1436 fputs("\" preserveAspectRatio=\"xMidYMid\"", fp);
1437 fprintf(fp, " font-family=\"%s\"", svg_default_font); /* default font */
1438 fputs(" stroke-linecap=\"round\" stroke-linejoin=\"round\"", fp);
1440 svg_start_tag(fp, "rect");
1441 fprintf(fp, " x=\"0\" y=\"0\" width=\"%d\" height=\"%d\"", width, height);
1442 svg_write_color(fp, background, "fill");
1443 svg_close_tag_empty_node(fp);
1444 node = canvas->firstnode;
1446 switch (node->type) {
1448 svg_multi_path(fp, &node);
1458 svg_end_tag(fp, "svg");
1462 /* ------- EPS -------
1463 EPS and Postscript references:
1464 http://partners.adobe.com/asn/developer/technotes/postscript.html
1467 typedef struct eps_font
1469 const char *ps_font;
1471 struct eps_font *next;
1474 typedef struct eps_state
1477 gfx_canvas_t *canvas;
1478 art_u32 page_width, page_height;
1479 eps_font *font_list;
1485 int linecap, linejoin;
1489 static void eps_set_color(eps_state *state, gfx_color_t color)
1491 #if USE_EPS_FAKE_ALPHA
1494 /* gfx_color_t is RRGGBBAA */
1495 if (state->color == color)
1497 #if USE_EPS_FAKE_ALPHA
1498 a1 = (color & 255) / 255.0;
1499 a2 = 255 * (1 - a1);
1500 #define eps_color_calc(x) (int)( ((x) & 255) * a1 + a2)
1502 #define eps_color_calc(x) (int)( (x) & 255)
1504 /* gfx_color_t is RRGGBBAA */
1505 if (state->color == color)
1507 fprintf(state->fp, "%d %d %d Rgb\n",
1508 eps_color_calc(color >> 24),
1509 eps_color_calc(color >> 16),
1510 eps_color_calc(color >> 8));
1511 state->color = color;
1514 static int eps_add_font(eps_state *state, gfx_node_t *node)
1516 /* The fonts list could be postponed to the end using
1517 (atend), but let's be nice and have them in the header. */
1518 const char *ps_font = afm_get_font_postscript_name(node->filename);
1520 for (ef = state->font_list; ef; ef = ef->next) {
1521 if (!strcmp(ps_font, ef->ps_font))
1524 ef = malloc(sizeof(eps_font));
1526 rrd_set_error("malloc for eps_font");
1529 ef->next = state->font_list;
1530 ef->ps_font = ps_font;
1531 state->font_list = ef;
1535 static void eps_list_fonts(eps_state *state, const char *dscName)
1538 int lineLen = strlen(dscName);
1539 if (!state->font_list)
1541 fputs(dscName, state->fp);
1542 for (ef = state->font_list; ef; ef = ef->next) {
1543 int nameLen = strlen(ef->ps_font);
1544 if (lineLen + nameLen > 100 && lineLen) {
1545 fputs("\n", state->fp);
1546 fputs("%%- \n", state->fp);
1549 fputs(" ", state->fp);
1552 fputs(ef->ps_font, state->fp);
1555 fputs("\n", state->fp);
1558 static void eps_define_fonts(eps_state *state)
1561 if (!state->font_list)
1563 for (ef = state->font_list; ef; ef = ef->next) {
1564 /* PostScript¨ LANGUAGE REFERENCE third edition
1568 "/%s findfont dup length dict begin\n"
1569 "{ 1 index /FID ne {def} {pop pop} ifelse } forall\n"
1570 "/Encoding ISOLatin1Encoding def\n"
1572 "/%s-ISOLatin1 exch definefont pop\n"
1573 "/SetFont-%s { /%s-ISOLatin1 findfont exch scalefont setfont } bd\n",
1574 ef->ps_font, ef->ps_font, ef->ps_font, ef->ps_font);
1578 static int eps_prologue(eps_state *state)
1582 "%!PS-Adobe-3.0 EPSF-3.0\n"
1583 "%%Creator: RRDtool " PACKAGE_VERSION " Tobias Oetiker, http://tobi.oetiker.ch\n"
1584 /* can't like weird chars here */
1585 "%%Title: (RRDtool output)\n"
1586 "%%DocumentData: Clean7Bit\n"
1588 fprintf(state->fp, "%%%%BoundingBox: 0 0 %d %d\n",
1589 state->page_width, state->page_height);
1590 for (node = state->canvas->firstnode; node; node = node->next) {
1591 if (node->type == GFX_TEXT && eps_add_font(state, node) == -1)
1594 eps_list_fonts(state, "%%DocumentFonts:");
1595 eps_list_fonts(state, "%%DocumentNeededFonts:");
1599 "%%EndProlog\n" /* must have, or BoundingBox is ignored */
1600 "/bd { bind def } bind def\n"
1602 fprintf(state->fp, "/X { %.2f add } bd\n", LINEOFFSET);
1604 "/X2 {X exch X exch} bd\n"
1605 "/M {X2 moveto} bd\n"
1606 "/L {X2 lineto} bd\n"
1610 "/CP {closepath} bd\n"
1611 "/WS {setlinewidth stroke} bd\n"
1614 "/T2 {concat 0 0 moveto show grestore} bd\n"
1615 "/T {moveto show} bd\n"
1616 "/Rgb { 255.0 div 3 1 roll\n"
1617 " 255.0 div 3 1 roll \n"
1618 " 255.0 div 3 1 roll setrgbcolor } bd\n"
1620 eps_define_fonts(state);
1624 static void eps_clear_dash(eps_state *state)
1626 if (!state->has_dash)
1628 state->has_dash = 0;
1629 fputs("[1 0] 0 setdash\n", state->fp);
1632 static void eps_write_linearea(eps_state *state, gfx_node_t *node)
1635 FILE *fp = state->fp;
1637 int clearDashIfAny = 1;
1638 eps_set_color(state, node->color);
1639 if (node->type == GFX_LINE) {
1641 if (state->linecap != 1) {
1642 fputs("1 setlinecap\n", fp);
1645 if (state->linejoin != 1) {
1646 fputs("1 setlinejoin\n", fp);
1647 state->linejoin = 1;
1649 svg_get_dash(node, &dash_info);
1650 if (dash_info.dash_enable) {
1652 state->has_dash = 1;
1654 svg_write_number(fp, dash_info.adjusted_on);
1656 svg_write_number(fp, dash_info.adjusted_off);
1658 svg_write_number(fp, dash_info.dash_offset);
1659 fputs(" setdash\n", fp);
1663 eps_clear_dash(state);
1664 for (i = 0; i < node->points; i++) {
1665 ArtVpath *vec = node->path + i;
1667 double y = state->page_height - vec->y;
1668 if (vec->code == ART_MOVETO_OPEN || vec->code == ART_MOVETO)
1669 useOffset = (fabs(x - floor(x) - 0.5) < 0.01 && fabs(y - floor(y) - 0.5) < 0.01);
1674 switch (vec->code) {
1675 case ART_MOVETO_OPEN: /* fall-through */
1677 svg_write_number(fp, x);
1679 svg_write_number(fp, y);
1681 fputs(useOffset ? "M\n" : "m\n", fp);
1684 svg_write_number(fp, x);
1686 svg_write_number(fp, y);
1688 fputs(useOffset ? "L\n" : "l\n", fp);
1690 case ART_CURVETO: break; /* unsupported */
1691 case ART_END: break; /* nop */
1694 if (node->type == GFX_LINE) {
1695 if (node->closed_path)
1697 if (node->size != state->line_width) {
1698 state->line_width = node->size;
1699 svg_write_number(fp, state->line_width);
1709 static void eps_write_text(eps_state *state, gfx_node_t *node)
1711 FILE *fp = state->fp;
1713 const char *ps_font = afm_get_font_postscript_name(node->filename);
1716 pdf_calc(state->page_height, node, &g);
1717 eps_set_color(state, node->color);
1718 if (strcmp(ps_font, state->font) || node->size != state->font_size) {
1719 state->font = ps_font;
1720 state->font_size = node->size;
1721 svg_write_number(fp, state->font_size);
1722 fprintf(fp, " SetFont-%s\n", state->font);
1730 unsigned char ch = *(unsigned char*)p;
1733 if (++lineLen > 70) {
1734 fputs("\\\n", fp); /* backslash and \n */
1755 if (ch >= 126 || ch < 32) {
1756 fprintf(fp, "\\%03o", ch);
1765 /* can't use svg_write_number as 2 decimals is far from enough to avoid
1767 fprintf(fp, ") [%f %f %f %f %f %f] T2\n",
1768 g.ma, g.mb, g.mc, g.md, g.tmx, g.tmy);
1771 svg_write_number(fp, g.tmx);
1773 svg_write_number(fp, g.tmy);
1778 static int eps_write_content(eps_state *state)
1781 fputs("%\n", state->fp);
1782 for (node = state->canvas->firstnode; node; node = node->next) {
1783 switch (node->type) {
1786 eps_write_linearea(state, node);
1789 eps_write_text(state, node);
1796 int gfx_render_eps (gfx_canvas_t *canvas,
1797 art_u32 width, art_u32 height,
1798 gfx_color_t background, FILE *fp){
1799 struct eps_state state;
1801 state.canvas = canvas;
1802 state.page_width = width;
1803 state.page_height = height;
1804 state.font = "no-default-font";
1805 state.font_size = -1;
1806 state.color = 0; /* black */
1807 state.font_list = NULL;
1809 state.linejoin = -1;
1811 if (eps_prologue(&state) == -1)
1813 eps_set_color(&state, background);
1814 fprintf(fp, "0 0 M 0 %d L %d %d L %d 0 L fill\n",
1815 height, width, height, width);
1816 if (eps_write_content(&state) == -1)
1818 fputs("showpage\n", fp);
1819 fputs("%%EOF\n", fp);
1820 while (state.font_list) {
1821 eps_font *next = state.font_list->next;
1822 free(state.font_list);
1823 state.font_list = next;
1828 /* ------- PDF -------
1829 PDF references page:
1830 http://partners.adobe.com/public/developer/pdf/index_reference.html
1833 typedef struct pdf_buffer
1835 int id, is_obj, is_dict, is_stream, pdf_file_pos;
1837 int alloc_size, current_size;
1838 struct pdf_buffer *previous_buffer, *next_buffer;
1839 struct pdf_state *state;
1842 typedef struct pdf_font
1844 const char *ps_font;
1846 struct pdf_font *next;
1849 typedef struct pdf_state
1852 gfx_canvas_t *canvas;
1853 art_u32 page_width, page_height;
1854 pdf_font *font_list;
1855 pdf_buffer *first_buffer, *last_buffer;
1859 gfx_color_t stroke_color, fill_color;
1864 int linecap, linejoin;
1867 pdf_buffer pdf_header;
1868 pdf_buffer info_obj, catalog_obj, pages_obj, page1_obj;
1869 pdf_buffer fontsdict_obj;
1870 pdf_buffer graph_stream;
1873 static void pdf_init_buffer(pdf_state *state, pdf_buffer *buf)
1875 int initial_size = 32;
1878 buf->alloc_size = 0;
1879 buf->current_size = 0;
1880 buf->data = (char*)malloc(initial_size);
1882 buf->previous_buffer = NULL;
1883 buf->next_buffer = NULL;
1884 if (buf->data == NULL) {
1885 rrd_set_error("malloc for pdf_buffer data");
1886 state->has_failed = 1;
1889 buf->alloc_size = initial_size;
1890 if (state->last_buffer)
1891 state->last_buffer->next_buffer = buf;
1892 if (state->first_buffer == NULL)
1893 state->first_buffer = buf;
1894 buf->previous_buffer = state->last_buffer;
1895 state->last_buffer = buf;
1898 static void pdf_put(pdf_buffer *buf, const char *text, int len)
1902 if (buf->alloc_size < buf->current_size + len) {
1903 int new_size = buf->alloc_size;
1905 while (new_size < buf->current_size + len)
1907 new_buf = (char*)malloc(new_size);
1908 if (new_buf == NULL) {
1909 rrd_set_error("re-malloc for pdf_buffer data");
1910 buf->state->has_failed = 1;
1913 memcpy(new_buf, buf->data, buf->current_size);
1915 buf->data = new_buf;
1916 buf->alloc_size = new_size;
1918 memcpy(buf->data + buf->current_size, text, len);
1919 buf->current_size += len;
1922 static void pdf_puts(pdf_buffer *buf, const char *text)
1924 pdf_put(buf, text, strlen(text));
1927 static void pdf_indent(pdf_buffer *buf)
1929 pdf_puts(buf, "\t");
1932 static void pdf_putsi(pdf_buffer *buf, const char *text)
1935 pdf_puts(buf, text);
1938 static void pdf_putint(pdf_buffer *buf, int i)
1941 sprintf(tmp, "%d", i);
1945 static void pdf_putnumber(pdf_buffer *buf, double d)
1948 svg_format_number(tmp, sizeof(tmp), d);
1952 static void pdf_put_string_contents(pdf_buffer *buf, const char *text)
1954 const char *p = text;
1956 unsigned char ch = *(unsigned char*)p;
1962 pdf_puts(buf, "\\");
1966 pdf_puts(buf, "\\n");
1969 pdf_puts(buf, "\\r");
1972 pdf_puts(buf, "\\t");
1975 if (ch >= 126 || ch < 32) {
1977 snprintf(tmp, sizeof(tmp), "\\%03o", ch);
1987 static void pdf_init_object(pdf_state *state, pdf_buffer *buf)
1989 pdf_init_buffer(state, buf);
1990 buf->id = ++state->last_obj_id;
1995 static void pdf_init_dict(pdf_state *state, pdf_buffer *buf)
1997 pdf_init_object(state, buf);
2001 static void pdf_set_color(pdf_buffer *buf, gfx_color_t color,
2002 gfx_color_t *current_color, const char *op)
2004 #if USE_PDF_FAKE_ALPHA
2007 /* gfx_color_t is RRGGBBAA */
2008 if (*current_color == color)
2010 #if USE_PDF_FAKE_ALPHA
2011 a1 = (color & 255) / 255.0;
2013 #define pdf_color_calc(x) ( ((x) & 255) / 255.0 * a1 + a2)
2015 #define pdf_color_calc(x) ( ((x) & 255) / 255.0)
2017 pdf_putnumber(buf, pdf_color_calc(color >> 24));
2019 pdf_putnumber(buf, pdf_color_calc(color >> 16));
2021 pdf_putnumber(buf, pdf_color_calc(color >> 8));
2024 pdf_puts(buf, "\n");
2025 *current_color = color;
2028 static void pdf_set_stroke_color(pdf_buffer *buf, gfx_color_t color)
2030 pdf_set_color(buf, color, &buf->state->stroke_color, "RG");
2033 static void pdf_set_fill_color(pdf_buffer *buf, gfx_color_t color)
2035 pdf_set_color(buf, color, &buf->state->fill_color, "rg");
2038 static pdf_font *pdf_find_font(pdf_state *state, gfx_node_t *node)
2040 const char *ps_font = afm_get_font_postscript_name(node->filename);
2042 for (ef = state->font_list; ef; ef = ef->next) {
2043 if (!strcmp(ps_font, ef->ps_font))
2049 static void pdf_add_font(pdf_state *state, gfx_node_t *node)
2051 pdf_font *ef = pdf_find_font(state, node);
2054 ef = malloc(sizeof(pdf_font));
2056 rrd_set_error("malloc for pdf_font");
2057 state->has_failed = 1;
2060 pdf_init_dict(state, &ef->obj);
2061 ef->next = state->font_list;
2062 ef->ps_font = afm_get_font_postscript_name(node->filename);
2063 state->font_list = ef;
2065 pdf_putsi(&state->fontsdict_obj, "/F");
2066 pdf_putint(&state->fontsdict_obj, ef->obj.id);
2067 pdf_puts(&state->fontsdict_obj, " ");
2068 pdf_putint(&state->fontsdict_obj, ef->obj.id);
2069 pdf_puts(&state->fontsdict_obj, " 0 R\n");
2071 pdf_putsi(&ef->obj, "/Type /Font\n");
2072 pdf_putsi(&ef->obj, "/Subtype /Type1\n");
2073 pdf_putsi(&ef->obj, "/Name /F");
2074 pdf_putint(&ef->obj, ef->obj.id);
2075 pdf_puts(&ef->obj, "\n");
2076 pdf_putsi(&ef->obj, "/BaseFont /");
2077 pdf_puts(&ef->obj, ef->ps_font);
2078 pdf_puts(&ef->obj, "\n");
2079 pdf_putsi(&ef->obj, "/Encoding /WinAnsiEncoding\n");
2080 /* 'Cp1252' (this is latin 1 extended with 27 characters;
2081 the encoding is also known as 'winansi')
2082 http://www.lowagie.com/iText/tutorial/ch09.html */
2085 static void pdf_create_fonts(pdf_state *state)
2088 for (node = state->canvas->firstnode; node; node = node->next) {
2089 if (node->type == GFX_TEXT)
2090 pdf_add_font(state, node);
2094 static void pdf_write_linearea(pdf_state *state, gfx_node_t *node)
2097 pdf_buffer *s = &state->graph_stream;
2098 if (node->type == GFX_LINE) {
2100 svg_get_dash(node, &dash_info);
2101 if (!svg_dash_equal(&dash_info, &state->dash)) {
2102 state->dash = dash_info;
2103 if (dash_info.dash_enable) {
2105 pdf_putnumber(s, dash_info.adjusted_on);
2107 pdf_putnumber(s, dash_info.adjusted_off);
2109 pdf_putnumber(s, dash_info.dash_offset);
2110 pdf_puts(s, " d\n");
2112 pdf_puts(s, "[] 0 d\n");
2115 pdf_set_stroke_color(s, node->color);
2116 if (state->linecap != 1) {
2117 pdf_puts(s, "1 j\n");
2120 if (state->linejoin != 1) {
2121 pdf_puts(s, "1 J\n");
2122 state->linejoin = 1;
2124 if (node->size != state->line_width) {
2125 state->line_width = node->size;
2126 pdf_putnumber(s, state->line_width);
2127 pdf_puts(s, " w\n");
2130 pdf_set_fill_color(s, node->color);
2132 for (i = 0; i < node->points; i++) {
2133 ArtVpath *vec = node->path + i;
2135 double y = state->page_height - vec->y;
2136 if (node->type == GFX_AREA) {
2137 x += LINEOFFSET; /* adjust for libart handling of areas */
2140 switch (vec->code) {
2141 case ART_MOVETO_OPEN: /* fall-through */
2143 pdf_putnumber(s, x);
2145 pdf_putnumber(s, y);
2146 pdf_puts(s, " m\n");
2149 pdf_putnumber(s, x);
2151 pdf_putnumber(s, y);
2152 pdf_puts(s, " l\n");
2154 case ART_CURVETO: break; /* unsupported */
2155 case ART_END: break; /* nop */
2158 if (node->type == GFX_LINE) {
2159 pdf_puts(s, node->closed_path ? "s\n" : "S\n");
2166 static void pdf_write_matrix(pdf_state *state, gfx_node_t *node, pdf_coords *g, int useTM)
2169 pdf_buffer *s = &state->graph_stream;
2170 if (node->angle == 0) {
2171 pdf_puts(s, "1 0 0 1 ");
2172 pdf_putnumber(s, useTM ? g->tmx : g->mx);
2174 pdf_putnumber(s, useTM ? g->tmy : g->my);
2176 /* can't use svg_write_number as 2 decimals is far from enough to avoid
2178 sprintf(tmp, "%f %f %f %f %f %f",
2179 g->ma, g->mb, g->mc, g->md,
2180 useTM ? g->tmx : g->mx,
2181 useTM ? g->tmy : g->my);
2186 static void pdf_write_text(pdf_state *state, gfx_node_t *node,
2187 int last_was_text, int next_is_text)
2190 pdf_buffer *s = &state->graph_stream;
2191 pdf_font *font = pdf_find_font(state, node);
2193 rrd_set_error("font disappeared");
2194 state->has_failed = 1;
2197 pdf_calc(state->page_height, node, &g);
2199 pdf_puts(s, "q % debug green box\n");
2200 pdf_write_matrix(state, node, &g, 0);
2201 pdf_puts(s, " cm\n");
2202 pdf_set_fill_color(s, 0x90FF9000);
2203 pdf_puts(s, "0 0.4 0 rg\n");
2204 pdf_puts(s, "0 0 ");
2205 pdf_putnumber(s, g.sizep.x);
2207 pdf_putnumber(s, g.sizep.y);
2208 pdf_puts(s, " re\n");
2212 pdf_set_fill_color(s, node->color);
2213 if (PDF_CALC_DEBUG || !last_was_text)
2214 pdf_puts(s, "BT\n");
2215 if (state->font_id != font->obj.id || node->size != state->font_size) {
2216 state->font_id = font->obj.id;
2217 state->font_size = node->size;
2219 pdf_putint(s, font->obj.id);
2221 pdf_putnumber(s, node->size);
2222 pdf_puts(s, " Tf\n");
2224 pdf_write_matrix(state, node, &g, 1);
2225 pdf_puts(s, " Tm\n");
2227 pdf_put_string_contents(s, node->text);
2228 pdf_puts(s, ") Tj\n");
2229 if (PDF_CALC_DEBUG || !next_is_text)
2230 pdf_puts(s, "ET\n");
2233 static void pdf_write_content(pdf_state *state)
2236 int last_was_text = 0, next_is_text;
2237 for (node = state->canvas->firstnode; node; node = node->next) {
2238 switch (node->type) {
2241 pdf_write_linearea(state, node);
2244 next_is_text = node->next && node->next->type == GFX_TEXT;
2245 pdf_write_text(state, node, last_was_text, next_is_text);
2248 last_was_text = node->type == GFX_TEXT;
2252 static void pdf_init_document(pdf_state *state)
2254 pdf_init_buffer(state, &state->pdf_header);
2255 pdf_init_dict(state, &state->catalog_obj);
2256 pdf_init_dict(state, &state->info_obj);
2257 pdf_init_dict(state, &state->pages_obj);
2258 pdf_init_dict(state, &state->page1_obj);
2259 pdf_init_dict(state, &state->fontsdict_obj);
2260 pdf_create_fonts(state);
2261 if (state->has_failed)
2263 /* make stream last object in file */
2264 pdf_init_object(state, &state->graph_stream);
2265 state->graph_stream.is_stream = 1;
2268 static void pdf_setup_document(pdf_state *state)
2270 const char *creator = "RRDtool " PACKAGE_VERSION " Tobias Oetiker, http://tobi.oetiker.ch";
2271 /* all objects created by now, so init code can reference them */
2273 pdf_puts(&state->pdf_header, "%PDF-1.3\n");
2274 /* following 8 bit comment is recommended by Adobe for
2275 indicating binary file to file transfer applications */
2276 pdf_puts(&state->pdf_header, "%\xE2\xE3\xCF\xD3\n");
2278 pdf_putsi(&state->info_obj, "/Creator (");
2279 pdf_put_string_contents(&state->info_obj, creator);
2280 pdf_puts(&state->info_obj, ")\n");
2282 pdf_putsi(&state->catalog_obj, "/Type /Catalog\n");
2283 pdf_putsi(&state->catalog_obj, "/Pages ");
2284 pdf_putint(&state->catalog_obj, state->pages_obj.id);
2285 pdf_puts(&state->catalog_obj, " 0 R\n");
2287 pdf_putsi(&state->pages_obj, "/Type /Pages\n");
2288 pdf_putsi(&state->pages_obj, "/Kids [");
2289 pdf_putint(&state->pages_obj, state->page1_obj.id);
2290 pdf_puts(&state->pages_obj, " 0 R]\n");
2291 pdf_putsi(&state->pages_obj, "/Count 1\n");
2293 pdf_putsi(&state->page1_obj, "/Type /Page\n");
2294 pdf_putsi(&state->page1_obj, "/Parent ");
2295 pdf_putint(&state->page1_obj, state->pages_obj.id);
2296 pdf_puts(&state->page1_obj, " 0 R\n");
2297 pdf_putsi(&state->page1_obj, "/MediaBox [0 0 ");
2298 pdf_putint(&state->page1_obj, state->page_width);
2299 pdf_puts(&state->page1_obj, " ");
2300 pdf_putint(&state->page1_obj, state->page_height);
2301 pdf_puts(&state->page1_obj, "]\n");
2302 pdf_putsi(&state->page1_obj, "/Contents ");
2303 pdf_putint(&state->page1_obj, state->graph_stream.id);
2304 pdf_puts(&state->page1_obj, " 0 R\n");
2305 pdf_putsi(&state->page1_obj, "/Resources << /Font ");
2306 pdf_putint(&state->page1_obj, state->fontsdict_obj.id);
2307 pdf_puts(&state->page1_obj, " 0 R >>\n");
2310 static void pdf_write_string_to_file(pdf_state *state, const char *text)
2312 fputs(text, state->fp);
2313 state->pdf_file_pos += strlen(text);
2316 static void pdf_write_buf_to_file(pdf_state *state, pdf_buffer *buf)
2319 buf->pdf_file_pos = state->pdf_file_pos;
2321 snprintf(tmp, sizeof(tmp), "%d 0 obj\n", buf->id);
2322 pdf_write_string_to_file(state, tmp);
2325 pdf_write_string_to_file(state, "<<\n");
2326 if (buf->is_stream) {
2327 snprintf(tmp, sizeof(tmp), "<< /Length %d >>\n", buf->current_size);
2328 pdf_write_string_to_file(state, tmp);
2329 pdf_write_string_to_file(state, "stream\n");
2331 fwrite(buf->data, 1, buf->current_size, state->fp);
2332 state->pdf_file_pos += buf->current_size;
2334 pdf_write_string_to_file(state, "endstream\n");
2336 pdf_write_string_to_file(state, ">>\n");
2338 pdf_write_string_to_file(state, "endobj\n");
2341 static void pdf_write_to_file(pdf_state *state)
2343 pdf_buffer *buf = state->first_buffer;
2345 state->pdf_file_pos = 0;
2346 pdf_write_buf_to_file(state, &state->pdf_header);
2349 pdf_write_buf_to_file(state, buf);
2350 buf = buf->next_buffer;
2352 xref_pos = state->pdf_file_pos;
2353 fprintf(state->fp, "xref\n");
2354 fprintf(state->fp, "%d %d\n", 0, state->last_obj_id + 1);
2355 /* TOC lines must be exactly 20 bytes including \n */
2356 fprintf(state->fp, "%010d %05d f\x20\n", 0, 65535);
2357 for (buf = state->first_buffer; buf; buf = buf->next_buffer) {
2359 fprintf(state->fp, "%010d %05d n\x20\n", buf->pdf_file_pos, 0);
2361 fprintf(state->fp, "trailer\n");
2362 fprintf(state->fp, "<<\n");
2363 fprintf(state->fp, "\t/Size %d\n", state->last_obj_id + 1);
2364 fprintf(state->fp, "\t/Root %d 0 R\n", state->catalog_obj.id);
2365 fprintf(state->fp, "\t/Info %d 0 R\n", state->info_obj.id);
2366 fprintf(state->fp, ">>\n");
2367 fprintf(state->fp, "startxref\n");
2368 fprintf(state->fp, "%d\n", xref_pos);
2369 fputs("%%EOF\n", state->fp);
2372 static void pdf_free_resources(pdf_state *state)
2374 pdf_buffer *buf = state->first_buffer;
2378 buf->alloc_size = buf->current_size = 0;
2379 buf = buf->next_buffer;
2381 while (state->font_list) {
2382 pdf_font *next = state->font_list->next;
2383 free(state->font_list);
2384 state->font_list = next;
2388 int gfx_render_pdf (gfx_canvas_t *canvas,
2389 art_u32 width, art_u32 height,
2390 gfx_color_t UNUSED(background), FILE *fp){
2391 struct pdf_state state;
2392 memset(&state, 0, sizeof(pdf_state));
2394 state.canvas = canvas;
2395 state.page_width = width;
2396 state.page_height = height;
2398 state.font_size = -1;
2399 state.font_list = NULL;
2401 state.linejoin = -1;
2402 pdf_init_document(&state);
2404 pdf_set_color(&state, background);
2405 fprintf(fp, "0 0 M 0 %d L %d %d L %d 0 L fill\n",
2406 height, width, height, width);
2408 if (!state.has_failed)
2409 pdf_write_content(&state);
2410 if (!state.has_failed)
2411 pdf_setup_document(&state);
2412 if (!state.has_failed)
2413 pdf_write_to_file(&state);
2414 pdf_free_resources(&state);
2415 return state.has_failed ? -1 : 0;