1 /****************************************************************************
2 * RRDtool 1.2.0 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
23 /* lines are better drawn on the pixle than between pixles */
24 #define LINEOFFSET 0.5
26 typedef struct gfx_char_s *gfx_char;
28 FT_UInt index; /* glyph index */
29 FT_Vector pos; /* location from baseline in 26.6 */
30 FT_Glyph image; /* glyph bitmap */
33 typedef struct gfx_string_s *gfx_string;
37 size_t count; /* number of characters */
44 /* compute string bbox */
45 static void compute_string_bbox(gfx_string string);
47 /* create a freetype glyph string */
48 gfx_string gfx_string_create ( FT_Face face,
49 const char *text, int rotation, double tabwidth);
51 /* create a freetype glyph string */
52 static void gfx_string_destroy ( gfx_string string );
55 gfx_node_t *gfx_new_node( gfx_canvas_t *canvas,enum gfx_en type){
56 gfx_node_t *node = art_new(gfx_node_t,1);
57 if (node == NULL) return NULL;
59 node->color = 0x0; /* color of element 0xRRGGBBAA alpha 0xff is solid*/
60 node->size =0.0; /* font size, line width */
61 node->path = NULL; /* path */
64 node->closed_path = 0;
65 node->filename = NULL; /* font or image filename */
68 node->y = 0.0; /* position */
70 node->halign = GFX_H_NULL; /* text alignement */
71 node->valign = GFX_V_NULL; /* text alignement */
74 if (canvas->lastnode != NULL){
75 canvas->lastnode->next = node;
77 if (canvas->firstnode == NULL){
78 canvas->firstnode = node;
80 canvas->lastnode = node;
84 gfx_canvas_t *gfx_new_canvas (void) {
85 gfx_canvas_t *canvas = art_new(gfx_canvas_t,1);
86 canvas->firstnode = NULL;
87 canvas->lastnode = NULL;
88 canvas->imgformat = IF_PNG; /* we default to PNG output */
89 canvas->interlaced = 0;
94 /* create a new line */
95 gfx_node_t *gfx_new_line(gfx_canvas_t *canvas,
98 double width, gfx_color_t color){
99 return gfx_new_dashed_line(canvas, X0, Y0, X1, Y1, width, color, 0, 0);
102 gfx_node_t *gfx_new_dashed_line(gfx_canvas_t *canvas,
103 double X0, double Y0,
104 double X1, double Y1,
105 double width, gfx_color_t color,
106 double dash_on, double dash_off){
110 node = gfx_new_node(canvas,GFX_LINE);
111 if (node == NULL) return NULL;
112 vec = art_new(ArtVpath, 3);
113 if (vec == NULL) return NULL;
114 vec[0].code = ART_MOVETO_OPEN; vec[0].x=X0+LINEOFFSET; vec[0].y=Y0+LINEOFFSET;
115 vec[1].code = ART_LINETO; vec[1].x=X1+LINEOFFSET; vec[1].y=Y1+LINEOFFSET;
116 vec[2].code = ART_END; vec[2].x=0;vec[2].y=0;
119 node->points_max = 3;
122 node->dash_on = dash_on;
123 node->dash_off = dash_off;
128 /* create a new area */
129 gfx_node_t *gfx_new_area (gfx_canvas_t *canvas,
130 double X0, double Y0,
131 double X1, double Y1,
132 double X2, double Y2,
137 node = gfx_new_node(canvas,GFX_AREA);
138 if (node == NULL) return NULL;
139 vec = art_new(ArtVpath, 5);
140 if (vec == NULL) return NULL;
141 vec[0].code = ART_MOVETO; vec[0].x=X0; vec[0].y=Y0;
142 vec[1].code = ART_LINETO; vec[1].x=X1; vec[1].y=Y1;
143 vec[2].code = ART_LINETO; vec[2].x=X2; vec[2].y=Y2;
144 vec[3].code = ART_LINETO; vec[3].x=X0; vec[3].y=Y0;
145 vec[4].code = ART_END; vec[4].x=0; vec[4].y=0;
148 node->points_max = 5;
155 /* add a point to a line or to an area */
156 int gfx_add_point (gfx_node_t *node,
158 if (node == NULL) return 1;
159 if (node->type == GFX_AREA) {
160 double X0 = node->path[0].x;
161 double Y0 = node->path[0].y;
163 art_vpath_add_point (&(node->path),
168 art_vpath_add_point (&(node->path),
173 art_vpath_add_point (&(node->path),
178 } else if (node->type == GFX_LINE) {
180 art_vpath_add_point (&(node->path),
184 x+LINEOFFSET,y+LINEOFFSET);
185 art_vpath_add_point (&(node->path),
192 /* can only add point to areas and lines */
198 void gfx_close_path (gfx_node_t *node) {
199 node->closed_path = 1;
200 if (node->path[0].code == ART_MOVETO_OPEN)
201 node->path[0].code = ART_MOVETO;
204 /* create a text node */
205 gfx_node_t *gfx_new_text (gfx_canvas_t *canvas,
206 double x, double y, gfx_color_t color,
207 char* font, double size,
208 double tabwidth, double angle,
209 enum gfx_h_align_en h_align,
210 enum gfx_v_align_en v_align,
212 gfx_node_t *node = gfx_new_node(canvas,GFX_TEXT);
214 node->text = strdup(text);
216 node->filename = strdup(font);
221 node->tabwidth = tabwidth;
222 node->halign = h_align;
223 node->valign = v_align;
225 /* debugging: show text anchor
226 green is along x-axis, red is downward y-axis */
228 double a = 2 * M_PI * -node->angle / 360.0;
229 double cos_a = cos(a);
230 double sin_a = sin(a);
234 x + len * cos_a, y - len * sin_a,
238 x + len * sin_a, y + len * cos_a,
245 int gfx_render(gfx_canvas_t *canvas,
246 art_u32 width, art_u32 height,
247 gfx_color_t background, FILE *fp){
248 switch (canvas->imgformat) {
250 return gfx_render_png (canvas, width, height, background, fp);
252 return gfx_render_svg (canvas, width, height, background, fp);
254 return gfx_render_eps (canvas, width, height, background, fp);
256 return gfx_render_pdf (canvas, width, height, background, fp);
262 static void gfx_string_destroy ( gfx_string string ) {
264 if (string->glyphs) {
265 for (n=0; n<string->num_glyphs; ++n)
266 FT_Done_Glyph (string->glyphs[n].image);
267 free (string->glyphs);
273 double gfx_get_text_width ( gfx_canvas_t *canvas,
274 double start, char* font, double size,
275 double tabwidth, char* text, int rotation){
276 switch (canvas->imgformat) {
278 return gfx_get_text_width_libart (start, font, size, tabwidth, text, rotation);
279 case IF_SVG: /* fall through */
282 return afm_get_text_width(start, font, size, tabwidth, text);
284 return size * strlen(text);
288 double gfx_get_text_width_libart (
289 double start, char* font, double size,
290 double tabwidth, char* text, int rotation){
295 FT_Library library=NULL;
298 FT_Init_FreeType( &library );
299 error = FT_New_Face( library, font, 0, &face );
300 if ( error ) return -1;
301 error = FT_Set_Char_Size(face, size*64,size*64, 100,100);
302 if ( error ) return -1;
304 string = gfx_string_create( face, text, rotation,tabwidth);
305 text_width = string->width;
306 gfx_string_destroy(string);
307 FT_Done_FreeType(library);
308 return text_width/64;
311 static void gfx_libart_close_path(gfx_node_t *node, ArtVpath **vec)
313 /* libart must have end==start for closed paths,
314 even if using ART_MOVETO and not ART_MOVETO_OPEN
315 so add extra point which is the same as the starting point */
316 int points_max = node->points; /* scaled array has exact size */
317 int points = node->points - 1;
318 art_vpath_add_point (vec, &points, &points_max, ART_LINETO,
319 (**vec).x, (**vec).y);
320 art_vpath_add_point (vec, &points, &points_max, ART_END, 0, 0);
324 /* find bbox of a string */
325 static void compute_string_bbox(gfx_string string) {
329 bbox.xMin = bbox.yMin = 32000;
330 bbox.xMax = bbox.yMax = -32000;
331 for ( n = 0; n < string->num_glyphs; n++ ) {
333 FT_Glyph_Get_CBox( string->glyphs[n].image, ft_glyph_bbox_gridfit,
335 if (glyph_bbox.xMin < bbox.xMin) {
336 bbox.xMin = glyph_bbox.xMin;
338 if (glyph_bbox.yMin < bbox.yMin) {
339 bbox.yMin = glyph_bbox.yMin;
341 if (glyph_bbox.xMax > bbox.xMax) {
342 bbox.xMax = glyph_bbox.xMax;
344 if (glyph_bbox.yMax > bbox.yMax) {
345 bbox.yMax = glyph_bbox.yMax;
348 if ( bbox.xMin > bbox.xMax ) {
354 string->bbox.xMin = bbox.xMin;
355 string->bbox.xMax = bbox.xMax;
356 string->bbox.yMin = bbox.yMin;
357 string->bbox.yMax = bbox.yMax;
360 /* create a free type glyph string */
361 gfx_string gfx_string_create(FT_Face face,const char *text,
362 int rotation, double tabwidth)
365 FT_GlyphSlot slot = face->glyph; /* a small shortcut */
371 gfx_char glyph; /* current glyph in table */
375 ft_pen.x = 0; /* start at (0,0) !! */
378 string = (gfx_string) malloc (sizeof(struct gfx_string_s));
381 string->count = strlen (text);
382 string->glyphs = (gfx_char) calloc (string->count,sizeof(struct gfx_char_s));
383 string->num_glyphs = 0;
384 string->transform.xx = (FT_Fixed)( cos(M_PI*(rotation)/180.0)*0x10000);
385 string->transform.xy = (FT_Fixed)(-sin(M_PI*(rotation)/180.0)*0x10000);
386 string->transform.yx = (FT_Fixed)( sin(M_PI*(rotation)/180.0)*0x10000);
387 string->transform.yy = (FT_Fixed)( cos(M_PI*(rotation)/180.0)*0x10000);
389 use_kerning = FT_HAS_KERNING(face);
391 glyph = string->glyphs;
392 for (n=0; n<string->count;glyph++) {
394 /* handle the tabs ...
395 have a witespace glyph inserted, but set its width such that the distance
396 of the new right edge is x times tabwidth from 0,0 where x is an integer. */
397 unsigned char letter = text[n];
400 if (letter == '\\' && n+1 < string->count && text[n+1] == 't'){
401 /* we have a tab here so skip the backslash and
402 set t to ' ' so that we get a white space */
411 /* initialize each struct gfx_char_s */
417 glyph->index = FT_Get_Char_Index( face, letter );
419 /* compute glyph origin */
420 if ( use_kerning && previous && glyph->index ) {
422 FT_Get_Kerning (face, previous, glyph->index,
423 ft_kerning_default, &kerning);
424 ft_pen.x += kerning.x;
425 ft_pen.y += kerning.y;
428 /* load the glyph image (in its native format) */
429 /* for now, we take a monochrome glyph bitmap */
430 error = FT_Load_Glyph (face, glyph->index, FT_LOAD_DEFAULT);
432 fprintf (stderr, "couldn't load glyph: %c\n", letter);
435 error = FT_Get_Glyph (slot, &glyph->image);
437 fprintf (stderr, "couldn't get glyph from slot: %c\n", letter);
440 /* if we are in tabbing mode, we replace the tab with a space and shift the position
441 of the space so that its left edge is where the tab was supposed to land us */
443 /* we are in gridfitting mode so the calculations happen in 1/64 pixles */
444 ft_pen.x = tabwidth*64.0 * (float)(1 + (long)(ft_pen.x / (tabwidth * 64.0))) - slot->advance.x;
446 /* store current pen position */
447 glyph->pos.x = ft_pen.x;
448 glyph->pos.y = ft_pen.y;
451 ft_pen.x += slot->advance.x;
452 ft_pen.y += slot->advance.y;
456 FT_Vector_Transform (&vec, &string->transform);
457 error = FT_Glyph_Transform (glyph->image, &string->transform, &vec);
459 fprintf (stderr, "couldn't transform glyph\n");
463 /* convert to a bitmap - destroy native image */
464 error = FT_Glyph_To_Bitmap (&glyph->image, FT_RENDER_MODE_NORMAL, 0, 1);
466 fprintf (stderr, "couldn't convert glyph to bitmap\n");
470 /* increment number of glyphs */
471 previous = glyph->index;
472 string->num_glyphs++;
476 /* printf ("number of glyphs = %d\n", string->num_glyphs);*/
477 compute_string_bbox( string );
478 /* the last character was a tab */
480 string->width = ft_pen.x;
482 string->width = string->bbox.xMax - string->bbox.xMin;
484 string->height = string->bbox.yMax - string->bbox.yMin;
490 static int gfx_save_png (art_u8 *buffer, FILE *fp,
491 long width, long height, long bytes_per_pixel);
492 /* render grafics into png image */
494 int gfx_render_png (gfx_canvas_t *canvas,
495 art_u32 width, art_u32 height,
496 gfx_color_t background, FILE *fp){
500 gfx_node_t *node = canvas->firstnode;
502 art_u8 red = background >> 24, green = (background >> 16) & 0xff;
503 art_u8 blue = (background >> 8) & 0xff, alpha = ( background & 0xff );
505 unsigned long pys_width = width * canvas->zoom;
506 unsigned long pys_height = height * canvas->zoom;
507 const int bytes_per_pixel = 4;
508 unsigned long rowstride = pys_width*bytes_per_pixel; /* bytes per pixel */
509 art_u8 *buffer = art_new (art_u8, rowstride*pys_height);
510 /* fill that buffer with out background color */
513 for (i=0,buffp=(gfx_color_t *)buffer;
514 i<pys_width*pys_height;
516 *(buffp++)=background;
518 FT_Init_FreeType( &library );
520 switch (node->type) {
526 art_affine_scale(dst,canvas->zoom,canvas->zoom);
527 vec = art_vpath_affine_transform(node->path,dst);
528 if (node->closed_path)
529 gfx_libart_close_path(node, &vec);
530 /* gfx_round_scaled_coordinates(vec); */
531 pvec = art_vpath_perturb(vec);
533 if(node->type == GFX_LINE){
534 svp = art_svp_vpath_stroke ( pvec, ART_PATH_STROKE_JOIN_ROUND,
535 ART_PATH_STROKE_CAP_ROUND,
536 node->size*canvas->zoom,4,0.25);
538 svp = art_svp_from_vpath ( pvec );
539 svpt = art_svp_uncross( svp );
541 svp = art_svp_rewind_uncrossed(svpt,ART_WIND_RULE_NONZERO);
545 /* this is from gnome since libart does not have this yet */
546 gnome_print_art_rgba_svp_alpha (svp ,0,0, pys_width, pys_height,
547 node->color, buffer, rowstride, NULL);
554 art_u8 fcolor[4],falpha;
558 FT_Vector vec; /* 26.6 */
560 float pen_x = 0.0 , pen_y = 0.0;
564 fcolor[0] = node->color >> 24;
565 fcolor[1] = (node->color >> 16) & 0xff;
566 fcolor[2] = (node->color >> 8) & 0xff;
567 falpha = node->color & 0xff;
568 error = FT_New_Face( library,
569 (char *)node->filename,
573 rrd_set_error("failed to load %s",node->filename);
576 error = FT_Set_Char_Size(face, /* handle to face object */
577 (long)(node->size*64),
578 (long)(node->size*64),
579 (long)(100*canvas->zoom),
580 (long)(100*canvas->zoom));
582 pen_x = node->x * canvas->zoom;
583 pen_y = node->y * canvas->zoom;
585 string = gfx_string_create (face, node->text, node->angle, node->tabwidth);
586 switch(node->halign){
587 case GFX_H_RIGHT: vec.x = -string->bbox.xMax;
589 case GFX_H_CENTER: vec.x = abs(string->bbox.xMax) >= abs(string->bbox.xMin) ?
590 -string->bbox.xMax/2:-string->bbox.xMin/2;
592 case GFX_H_LEFT: vec.x = -string->bbox.xMin;
594 case GFX_H_NULL: vec.x = 0;
598 switch(node->valign){
599 case GFX_V_TOP: vec.y = string->bbox.yMax;
601 case GFX_V_CENTER: vec.y = abs(string->bbox.yMax) >= abs(string->bbox.yMin) ?
602 string->bbox.yMax/2:string->bbox.yMin/2;
604 case GFX_V_BOTTOM: vec.y = 0;
606 case GFX_V_NULL: vec.y = 0;
611 glyph = string->glyphs;
612 for(n=0; n<string->num_glyphs; ++n, ++glyph) {
616 /* long buf_x,comp_n; */
617 /* make copy to transform */
618 if (! glyph->image) {
619 fprintf (stderr, "no image\n");
622 error = FT_Glyph_Copy (glyph->image, &image);
624 fprintf (stderr, "couldn't copy image\n");
630 FT_Vector_Transform (&vec, &string->transform);
632 bit = (FT_BitmapGlyph) image;
633 gr = bit->bitmap.num_grays -1;
635 buf_x = (pen_x + 0.5) + (double)bit->left;
636 comp_n = buf_x + bit->bitmap.width > pys_width ? pys_width - buf_x : bit->bitmap.width;
637 if (buf_x < 0 || buf_x >= (long)pys_width) continue;
638 buf_x *= bytes_per_pixel ;
639 for (iy=0; iy < bit->bitmap.rows; iy++){
640 long buf_y = iy+(pen_y+0.5)-(double)bit->top;
641 if (buf_y < 0 || buf_y >= (long)pys_height) continue;
643 for (ix=0;ix < bit->bitmap.width;ix++){
644 *(letter + (ix*bytes_per_pixel+3)) = *(bit->bitmap.buffer + iy * bit->bitmap.width + ix);
646 art_rgba_rgba_composite(buffer + buf_y + buf_x ,letter,comp_n);
651 for (iy=0; iy < bit->bitmap.rows; iy++){
652 long buf_y = iy+(pen_y+0.5)-bit->top;
653 if (buf_y < 0 || buf_y >= (long)pys_height) continue;
655 for (ix=0;ix < bit->bitmap.width;ix++){
656 long buf_x = ix + (pen_x + 0.5) + (double)bit->left ;
659 if (buf_x < 0 || buf_x >= (long)pys_width) continue;
660 buf_x *= bytes_per_pixel ;
661 font_alpha = *(bit->bitmap.buffer + iy * bit->bitmap.width + ix);
663 fcolor[3] = (art_u8)((double)font_alpha / gr * falpha);
664 art_rgba_rgba_composite(buffer + buf_y + buf_x ,fcolor,1);
670 for (iy=0; iy < bit->bitmap.rows; iy++){
671 long buf_y = iy+(pen_y+0.5)-bit->top;
672 if (buf_y < 0 || buf_y >= (long)pys_height) continue;
674 for (ix=0;ix < bit->bitmap.width;ix++){
675 long buf_x = ix + (pen_x + 0.5) + (double)bit->left ;
678 if (buf_x < 0 || buf_x >= (long)pys_width) continue;
679 buf_x *= bytes_per_pixel ;
680 font_alpha = *(bit->bitmap.buffer + iy * bit->bitmap.width + ix);
681 font_alpha = (art_u8)((double)font_alpha / gr * falpha);
682 for (iz = 0; iz < 3; iz++){
683 art_u8 *orig = buffer + buf_y + buf_x + iz;
684 *orig = (art_u8)((double)*orig / gr * ( gr - font_alpha) +
685 (double)fcolor[iz] / gr * (font_alpha));
690 FT_Done_Glyph (image);
692 gfx_string_destroy(string);
697 gfx_save_png(buffer,fp , pys_width,pys_height,bytes_per_pixel);
699 FT_Done_FreeType( library );
703 /* free memory used by nodes this will also remove memory required for
704 associated paths and svcs ... but not for text strings */
706 gfx_destroy (gfx_canvas_t *canvas){
707 gfx_node_t *next,*node = canvas->firstnode;
710 art_free(node->path);
712 free(node->filename);
720 static int gfx_save_png (art_u8 *buffer, FILE *fp, long width, long height, long bytes_per_pixel){
721 png_structp png_ptr = NULL;
722 png_infop info_ptr = NULL;
724 png_bytep *row_pointers;
725 int rowstride = width * bytes_per_pixel;
731 png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING,NULL,NULL,NULL);
736 row_pointers = (png_bytepp)png_malloc(png_ptr,
737 height*sizeof(png_bytep));
739 info_ptr = png_create_info_struct(png_ptr);
741 if (info_ptr == NULL)
743 png_free(png_ptr,row_pointers);
744 png_destroy_write_struct(&png_ptr, (png_infopp)NULL);
748 if (setjmp(png_jmpbuf(png_ptr)))
750 /* If we get here, we had a problem writing the file */
751 png_destroy_write_struct(&png_ptr, &info_ptr);
755 png_init_io(png_ptr, fp);
756 png_set_IHDR (png_ptr, info_ptr,width, height,
757 8, PNG_COLOR_TYPE_RGB_ALPHA,
759 PNG_COMPRESSION_TYPE_DEFAULT,
760 PNG_FILTER_TYPE_DEFAULT);
762 text[0].key = "Software";
763 text[0].text = "RRDtool, Tobias Oetiker <tobi@oetike.ch>, http://tobi.oetiker.ch";
764 text[0].compression = PNG_TEXT_COMPRESSION_NONE;
765 png_set_text (png_ptr, info_ptr, text, 1);
767 /* lets make this fast */
768 /* png_set_filter(png_ptr,0,PNG_FILTER_NONE); */
769 png_set_compression_level(png_ptr,1);
770 /* png_set_compression_strategy(png_ptr,Z_HUFFMAN_ONLY); */
772 png_set_filter(png_ptr,PNG_FILTER_TYPE_BASE,PNG_FILTER_SUB);
773 png_set_compression_strategy(png_ptr,Z_HUFFMAN_ONLY);
774 png_set_compression_level(png_ptr,Z_BEST_SPEED); */
776 /* Write header data */
777 png_write_info (png_ptr, info_ptr);
778 for (i = 0; i < height; i++)
779 row_pointers[i] = (png_bytep) (buffer + i*rowstride);
781 png_write_image(png_ptr, row_pointers);
782 png_write_end(png_ptr, info_ptr);
783 png_free(png_ptr,row_pointers);
784 png_destroy_write_struct(&png_ptr, &info_ptr);
789 /* ------- SVG -------
791 http://www.w3.org/TR/SVG/
793 static int svg_indent = 0;
794 static int svg_single_line = 0;
795 static const char *svg_default_font = "Helvetica";
796 typedef struct svg_dash
799 double dash_adjust, dash_len, dash_offset;
800 double adjusted_on, adjusted_off;
804 static void svg_print_indent(FILE *fp)
807 for (i = svg_indent - svg_single_line; i > 0; i--) {
813 static void svg_start_tag(FILE *fp, const char *name)
815 svg_print_indent(fp);
821 static void svg_close_tag_single_line(FILE *fp)
827 static void svg_close_tag(FILE *fp)
830 if (!svg_single_line)
834 static void svg_end_tag(FILE *fp, const char *name)
836 /* name is NULL if closing empty-node tag */
841 svg_print_indent(fp);
851 static void svg_close_tag_empty_node(FILE *fp)
853 svg_end_tag(fp, NULL);
856 static void svg_write_text(FILE *fp, const char *text)
858 const unsigned char *p, *start, *last;
860 p = (const unsigned char*)text;
863 /* trim leading spaces */
867 /* trim trailing spaces */
869 while ((ch = *p) != 0) {
874 /* encode trimmed text */
878 ch = afm_host2unicode(ch); /* unsafe macro */
880 case '&': fputs("&", fp); break;
881 case '<': fputs("<", fp); break;
882 case '>': fputs(">", fp); break;
883 case '"': fputs(""", fp); break;
886 fprintf(fp, "&#%d;", ch);
893 static void svg_format_number(char *buf, int bufsize, double d)
895 /* omit decimals if integer to reduce filesize */
897 snprintf(buf, bufsize, "%.2f", d);
898 p = buf; /* doesn't trust snprintf return value */
904 *p = '\0'; /* zap trailing zeros */
908 *p = '\0'; /* zap trailing dot */
913 static void svg_write_number(FILE *fp, double d)
916 svg_format_number(buf, sizeof(buf), d);
920 static int svg_color_is_black(int c)
922 /* gfx_color_t is RRGGBBAA */
923 return c == 0x000000FF;
926 static void svg_write_color(FILE *fp, gfx_color_t c, const char *attr)
928 /* gfx_color_t is RRGGBBAA, svg can use #RRGGBB and #RGB like html */
929 gfx_color_t rrggbb = (int)((c >> 8) & 0xFFFFFF);
930 gfx_color_t opacity = c & 0xFF;
931 fprintf(fp, " %s=\"", attr);
932 if ((rrggbb & 0x0F0F0F) == ((rrggbb >> 4) & 0x0F0F0F)) {
933 /* css2 short form, #rgb is #rrggbb, not #r0g0b0 */
934 fprintf(fp, "#%03lX",
935 ( ((rrggbb >> 8) & 0xF00)
936 | ((rrggbb >> 4) & 0x0F0)
937 | ( rrggbb & 0x00F)));
939 fprintf(fp, "#%06lX", rrggbb);
942 if (opacity != 0xFF) {
943 fprintf(fp, " stroke-opacity=\"");
944 svg_write_number(fp, opacity / 255.0);
949 static void svg_get_dash(gfx_node_t *node, svg_dash *d)
953 if (node->dash_on <= 0 || node->dash_off <= 0) {
958 d->dash_len = node->dash_on + node->dash_off;
959 /* dash on/off adjustment due to round caps */
960 d->dash_adjust = 0.8 * node->size;
961 d->adjusted_on = node->dash_on - d->dash_adjust;
962 if (d->adjusted_on < 0.01)
963 d->adjusted_on = 0.01;
964 d->adjusted_off = d->dash_len - d->adjusted_on;
965 /* dash offset calc */
966 if (node->path[0].x == node->path[1].x) /* only good for horz/vert lines */
967 offset = node->path[0].y;
969 offset = node->path[0].x;
970 mult = (int)fabs(offset / d->dash_len);
971 d->dash_offset = offset - mult * d->dash_len;
972 if (node->path[0].x < node->path[1].x || node->path[0].y < node->path[1].y)
973 d->dash_offset = d->dash_len - d->dash_offset;
976 static int svg_dash_equal(svg_dash *a, svg_dash *b)
978 if (a->dash_enable != b->dash_enable)
980 if (a->adjusted_on != b->adjusted_on)
982 if (a->adjusted_off != b->adjusted_off)
984 /* rest of properties will be the same when on+off are */
988 static void svg_common_path_attributes(FILE *fp, gfx_node_t *node)
991 svg_get_dash(node, &dash_info);
992 fputs(" stroke-width=\"", fp);
993 svg_write_number(fp, node->size);
995 svg_write_color(fp, node->color, "stroke");
996 fputs(" fill=\"none\"", fp);
997 if (dash_info.dash_enable) {
998 if (dash_info.dash_offset != 0) {
999 fputs(" stroke-dashoffset=\"", fp);
1000 svg_write_number(fp, dash_info.dash_offset);
1003 fputs(" stroke-dasharray=\"", fp);
1004 svg_write_number(fp, dash_info.adjusted_on);
1006 svg_write_number(fp, dash_info.adjusted_off);
1011 static int svg_is_int_step(double a, double b)
1013 double diff = fabs(a - b);
1014 return floor(diff) == diff;
1017 static int svg_path_straight_segment(FILE *fp,
1018 double lastA, double currentA, double currentB,
1020 int segment_idx, int isx, char absChar, char relChar)
1022 if (!svg_is_int_step(lastA, currentA)) {
1024 svg_write_number(fp, currentA);
1027 if (segment_idx < node->points - 1) {
1028 ArtVpath *vec = node->path + segment_idx + 1;
1029 if (vec->code == ART_LINETO) {
1030 double nextA = (isx ? vec->x : vec->y) - LINEOFFSET;
1031 double nextB = (isx ? vec->y : vec->x) - LINEOFFSET;
1032 if (nextB == currentB
1033 && ((currentA >= lastA) == (nextA >= currentA))
1034 && svg_is_int_step(currentA, nextA)) {
1035 return 1; /* skip to next as it is a straight line */
1040 svg_write_number(fp, currentA - lastA);
1044 static void svg_path(FILE *fp, gfx_node_t *node, int multi)
1047 double lastX = 0, lastY = 0;
1048 /* for straight lines <path..> tags take less space than
1049 <line..> tags because of the efficient packing
1050 in the 'd' attribute */
1051 svg_start_tag(fp, "path");
1053 svg_common_path_attributes(fp, node);
1055 /* specification of the 'd' attribute: */
1056 /* http://www.w3.org/TR/SVG/paths.html#PathDataGeneralInformation */
1057 for (i = 0; i < node->points; i++) {
1058 ArtVpath *vec = node->path + i;
1059 double x = vec->x - LINEOFFSET;
1060 double y = vec->y - LINEOFFSET;
1061 switch (vec->code) {
1062 case ART_MOVETO_OPEN: /* fall-through */
1065 svg_write_number(fp, x);
1067 svg_write_number(fp, y);
1070 /* try optimize filesize by using minimal lineto commands */
1071 /* without introducing rounding errors. */
1073 if (svg_path_straight_segment(fp, lastY, y, x, node, i, 0, 'V', 'v'))
1075 } else if (y == lastY) {
1076 if (svg_path_straight_segment(fp, lastX, x, y, node, i, 1, 'H', 'h'))
1080 svg_write_number(fp, x);
1082 svg_write_number(fp, y);
1085 case ART_CURVETO: break; /* unsupported */
1086 case ART_END: break; /* nop */
1091 if (node->closed_path)
1094 svg_close_tag_empty_node(fp);
1097 static void svg_multi_path(FILE *fp, gfx_node_t **nodeR)
1099 /* optimize for multiple paths with the same color, penwidth, etc. */
1101 gfx_node_t *node = *nodeR;
1102 gfx_node_t *next = node->next;
1104 if (next->type != node->type
1105 || next->size != node->size
1106 || next->color != node->color
1107 || next->dash_on != node->dash_on
1108 || next->dash_off != node->dash_off)
1114 svg_path(fp, node, 0);
1117 svg_start_tag(fp, "g");
1118 svg_common_path_attributes(fp, node);
1120 while (num && node) {
1121 svg_path(fp, node, 1);
1127 svg_end_tag(fp, "g");
1130 static void svg_area(FILE *fp, gfx_node_t *node)
1133 double startX = 0, startY = 0;
1134 svg_start_tag(fp, "polygon");
1136 svg_write_color(fp, node->color, "fill");
1137 fputs(" points=\"", fp);
1138 for (i = 0; i < node->points; i++) {
1139 ArtVpath *vec = node->path + i;
1140 double x = vec->x - LINEOFFSET;
1141 double y = vec->y - LINEOFFSET;
1142 switch (vec->code) {
1143 case ART_MOVETO_OPEN: /* fall-through */
1145 svg_write_number(fp, x);
1147 svg_write_number(fp, y);
1152 if (i == node->points - 2
1153 && node->path[i + 1].code == ART_END
1154 && fabs(x - startX) < 0.001 && fabs(y - startY) < 0.001) {
1155 break; /* poly area always closed, no need for last point */
1158 svg_write_number(fp, x);
1160 svg_write_number(fp, y);
1162 case ART_CURVETO: break; /* unsupported */
1163 case ART_END: break; /* nop */
1167 svg_close_tag_empty_node(fp);
1170 static void svg_text(FILE *fp, gfx_node_t *node)
1172 double x = node->x - LINEOFFSET;
1173 double y = node->y - LINEOFFSET;
1174 if (node->angle != 0) {
1175 svg_start_tag(fp, "g");
1176 fputs(" transform=\"translate(", fp);
1177 svg_write_number(fp, x);
1179 svg_write_number(fp, y);
1180 fputs(") rotate(", fp);
1181 svg_write_number(fp, node->angle);
1186 switch (node->valign) {
1187 case GFX_V_TOP: y += node->size; break;
1188 case GFX_V_CENTER: y += node->size / 3; break;
1189 case GFX_V_BOTTOM: break;
1190 case GFX_V_NULL: break;
1192 svg_start_tag(fp, "text");
1194 svg_write_number(fp, x);
1195 fputs("\" y=\"", fp);
1196 svg_write_number(fp, y);
1198 /* if (strcmp(node->filename, svg_default_font))
1199 fprintf(fp, " font-family=\"%s\"", node->filename);
1201 fputs("\" font-family=\"Helvetica", fp);
1202 fputs("\" font-size=\"", fp);
1203 svg_write_number(fp, node->size);
1205 if (!svg_color_is_black(node->color))
1206 svg_write_color(fp, node->color, "fill");
1207 switch (node->halign) {
1208 case GFX_H_RIGHT: fputs(" text-anchor=\"end\"", fp); break;
1209 case GFX_H_CENTER: fputs(" text-anchor=\"middle\"", fp); break;
1210 case GFX_H_LEFT: break;
1211 case GFX_H_NULL: break;
1213 svg_close_tag_single_line(fp);
1214 /* support for node->tabwidth missing */
1215 svg_write_text(fp, node->text);
1216 svg_end_tag(fp, "text");
1217 if (node->angle != 0)
1218 svg_end_tag(fp, "g");
1221 int gfx_render_svg (gfx_canvas_t *canvas,
1222 art_u32 width, art_u32 height,
1223 gfx_color_t background, FILE *fp){
1224 gfx_node_t *node = canvas->firstnode;
1226 "<?xml version=\"1.0\" standalone=\"no\"?>\n"
1227 "<!DOCTYPE svg PUBLIC \"-//W3C//DTD SVG 1.0//EN\"\n"
1228 " \"http://www.w3.org/TR/2001/REC-SVG-20010904/DTD/svg10.dtd\">\n"
1230 " SVG file created by RRDtool,\n"
1231 " Tobias Oetiker <tobi@oetike.ch>, http://tobi.oetiker.ch\n"
1233 " The width/height attributes in the outhermost svg node\n"
1234 " are just default sizes for the browser which is used\n"
1235 " if the svg file is openened directly without being\n"
1236 " embedded in an html file.\n"
1237 " The viewBox is the local coord system for rrdtool.\n"
1239 svg_start_tag(fp, "svg");
1240 fputs(" width=\"", fp);
1241 svg_write_number(fp, width * canvas->zoom);
1242 fputs("\" height=\"", fp);
1243 svg_write_number(fp, height * canvas->zoom);
1244 fputs("\" x=\"0\" y=\"0\" viewBox=\"", fp);
1245 svg_write_number(fp, -LINEOFFSET);
1247 svg_write_number(fp, -LINEOFFSET);
1249 svg_write_number(fp, width - LINEOFFSET);
1251 svg_write_number(fp, height - LINEOFFSET);
1252 fputs("\" preserveAspectRatio=\"xMidYMid\"", fp);
1253 fprintf(fp, " font-family=\"%s\"", svg_default_font); /* default font */
1254 fputs(" stroke-linecap=\"round\" stroke-linejoin=\"round\"", fp);
1256 svg_start_tag(fp, "rect");
1257 fprintf(fp, " x=\"0\" y=\"0\" width=\"%d\" height=\"%d\"", width, height);
1258 svg_write_color(fp, background, "fill");
1259 svg_close_tag_empty_node(fp);
1261 switch (node->type) {
1263 svg_multi_path(fp, &node);
1273 svg_end_tag(fp, "svg");
1277 /* ------- EPS -------
1278 EPS and Postscript references:
1279 http://partners.adobe.com/asn/developer/technotes/postscript.html
1282 typedef struct eps_font
1284 const char *ps_font;
1286 struct eps_font *next;
1289 typedef struct eps_state
1292 gfx_canvas_t *canvas;
1293 art_u32 page_width, page_height;
1294 eps_font *font_list;
1300 int linecap, linejoin;
1304 static void eps_set_color(eps_state *state, gfx_color_t color)
1306 /* gfx_color_t is RRGGBBAA */
1307 if (state->color == color)
1309 fprintf(state->fp, "%d %d %d Rgb\n",
1310 (int)((color >> 24) & 255),
1311 (int)((color >> 16) & 255),
1312 (int)((color >> 8) & 255));
1313 state->color = color;
1316 static int eps_add_font(eps_state *state, gfx_node_t *node)
1318 /* The fonts list could be postponed to the end using
1319 (atend), but let's be nice and have them in the header. */
1320 const char *ps_font = afm_get_font_postscript_name(node->filename);
1322 for (ef = state->font_list; ef; ef = ef->next) {
1323 if (!strcmp(ps_font, ef->ps_font))
1326 ef = malloc(sizeof(eps_font));
1328 rrd_set_error("malloc for eps_font");
1331 ef->next = state->font_list;
1332 ef->ps_font = ps_font;
1333 state->font_list = ef;
1337 static void eps_list_fonts(eps_state *state, const char *dscName)
1340 int lineLen = strlen(dscName);
1341 if (!state->font_list)
1343 fputs(dscName, state->fp);
1344 for (ef = state->font_list; ef; ef = ef->next) {
1345 int nameLen = strlen(ef->ps_font);
1346 if (lineLen + nameLen > 100 && lineLen) {
1347 fputs("\n", state->fp);
1348 fputs("%%- \n", state->fp);
1351 fputs(" ", state->fp);
1354 fputs(ef->ps_font, state->fp);
1357 fputs("\n", state->fp);
1360 static void eps_define_fonts(eps_state *state)
1363 if (!state->font_list)
1365 for (ef = state->font_list; ef; ef = ef->next) {
1366 /* PostScript¨ LANGUAGE REFERENCE third edition
1370 "/%s findfont dup length dict begin\n"
1371 "{ 1 index /FID ne {def} {pop pop} ifelse } forall\n"
1372 "/Encoding ISOLatin1Encoding def\n"
1374 "/%s-ISOLatin1 exch definefont pop\n"
1375 "/SetFont-%s { /%s-ISOLatin1 findfont exch scalefont setfont } bd\n",
1376 ef->ps_font, ef->ps_font, ef->ps_font, ef->ps_font);
1380 static int eps_prologue(eps_state *state)
1384 "%!PS-Adobe-3.0 EPSF-3.0\n"
1385 "%%Creator: RRDtool 1.2.0 Tobias Oetiker, http://tobi.oetiker.ch\n"
1386 /* can't like weird chars here */
1387 "%%Title: (RRDtool output)\n"
1388 "%%DocumentData: Clean7Bit\n"
1390 fprintf(state->fp, "%%%%BoundingBox: 0 0 %d %d\n",
1391 state->page_width, state->page_height);
1392 for (node = state->canvas->firstnode; node; node = node->next) {
1393 if (node->type == GFX_TEXT && eps_add_font(state, node) == -1)
1396 eps_list_fonts(state, "%%DocumentFonts:");
1397 eps_list_fonts(state, "%%DocumentNeededFonts:");
1401 "%%EndProlog\n" /* must have, or BoundingBox is ignored */
1402 "/bd { bind def } bind def\n"
1404 fprintf(state->fp, "/X { %.2f add } bd\n", LINEOFFSET);
1406 "/X2 {X exch X exch} bd\n"
1407 "/M {X2 moveto} bd\n"
1408 "/L {X2 lineto} bd\n"
1412 "/CP {closepath} bd\n"
1413 "/WS {setlinewidth stroke} bd\n"
1416 "/TaC {dup stringwidth pop neg 2 div 0 rmoveto } bd\n"
1417 "/TaR {dup stringwidth pop neg 0 rmoveto } bd\n"
1418 "/TL {moveto TaL show} bd\n"
1419 "/TC {moveto TaC show} bd\n"
1420 "/TR {moveto TaR show} bd\n"
1421 "/Rgb { 255.0 div 3 1 roll\n"
1422 " 255.0 div 3 1 roll \n"
1423 " 255.0 div 3 1 roll setrgbcolor } bd\n"
1425 eps_define_fonts(state);
1429 static void eps_clear_dash(eps_state *state)
1431 if (!state->has_dash)
1433 state->has_dash = 0;
1434 fputs("[1 0] 0 setdash\n", state->fp);
1437 static void eps_write_linearea(eps_state *state, gfx_node_t *node)
1440 FILE *fp = state->fp;
1442 int clearDashIfAny = 1;
1443 eps_set_color(state, node->color);
1444 if (node->type == GFX_LINE) {
1446 if (state->linecap != 1) {
1447 fputs("1 setlinecap\n", fp);
1450 if (state->linejoin != 1) {
1451 fputs("1 setlinejoin\n", fp);
1452 state->linejoin = 1;
1454 svg_get_dash(node, &dash_info);
1455 if (dash_info.dash_enable) {
1457 state->has_dash = 1;
1459 svg_write_number(fp, dash_info.adjusted_on);
1461 svg_write_number(fp, dash_info.adjusted_off);
1463 svg_write_number(fp, dash_info.dash_offset);
1464 fputs(" setdash\n", fp);
1468 eps_clear_dash(state);
1469 for (i = 0; i < node->points; i++) {
1470 ArtVpath *vec = node->path + i;
1472 double y = state->page_height - vec->y;
1473 if (vec->code == ART_MOVETO_OPEN || vec->code == ART_MOVETO)
1474 useOffset = (fabs(x - floor(x) - 0.5) < 0.01 && fabs(y - floor(y) - 0.5) < 0.01);
1479 switch (vec->code) {
1480 case ART_MOVETO_OPEN: /* fall-through */
1482 svg_write_number(fp, x);
1484 svg_write_number(fp, y);
1486 fputs(useOffset ? "M\n" : "m\n", fp);
1489 svg_write_number(fp, x);
1491 svg_write_number(fp, y);
1493 fputs(useOffset ? "L\n" : "l\n", fp);
1495 case ART_CURVETO: break; /* unsupported */
1496 case ART_END: break; /* nop */
1499 if (node->type == GFX_LINE) {
1500 if (node->closed_path)
1502 if (node->size != state->line_width) {
1503 state->line_width = node->size;
1504 svg_write_number(fp, state->line_width);
1514 static void eps_write_text(eps_state *state, gfx_node_t *node)
1516 FILE *fp = state->fp;
1517 const unsigned char *p;
1518 const char *ps_font = afm_get_font_postscript_name(node->filename);
1521 double y = state->page_height - node->y, ydelta = 0;
1523 eps_set_color(state, node->color);
1524 if (strcmp(ps_font, state->font) || node->size != state->font_size) {
1525 state->font = ps_font;
1526 state->font_size = node->size;
1527 svg_write_number(fp, state->font_size);
1528 fprintf(fp, " SetFont-%s\n", state->font);
1532 for (p = (const unsigned char*)node->text; *p; p++) {
1534 fputs("\\\n", fp); /* backslash and \n */
1549 fprintf(fp, "\\%03o", *p);
1556 switch(node->valign){
1557 case GFX_V_TOP: ydelta = -node->size; break;
1558 case GFX_V_CENTER: ydelta = -node->size / 3.0; break;
1559 case GFX_V_BOTTOM: break;
1560 case GFX_V_NULL: break;
1562 if (node->angle == 0)
1564 switch (node->halign) {
1565 case GFX_H_RIGHT: align = 'R'; break;
1566 case GFX_H_CENTER: align = 'C'; break;
1567 case GFX_H_LEFT: align= 'L'; break;
1568 case GFX_H_NULL: align= 'L'; break;
1570 if (node->angle != 0) {
1572 fputs(" gsave ", fp);
1573 svg_write_number(fp, x);
1575 svg_write_number(fp, y);
1576 fputs(" translate ", fp);
1577 svg_write_number(fp, -node->angle);
1578 fputs(" rotate 0 ", fp);
1579 svg_write_number(fp, ydelta);
1580 fputs(" moveto ", fp);
1581 fprintf(fp, "Ta%c", align);
1582 fputs(" show grestore\n", fp);
1584 svg_write_number(fp, x);
1586 svg_write_number(fp, y);
1593 static int eps_write_content(eps_state *state)
1596 fputs("%\n", state->fp);
1597 for (node = state->canvas->firstnode; node; node = node->next) {
1598 switch (node->type) {
1601 eps_write_linearea(state, node);
1604 eps_write_text(state, node);
1611 int gfx_render_eps (gfx_canvas_t *canvas,
1612 art_u32 width, art_u32 height,
1613 gfx_color_t background, FILE *fp){
1614 struct eps_state state;
1616 state.canvas = canvas;
1617 state.page_width = width;
1618 state.page_height = height;
1619 state.font = "no-default-font";
1620 state.font_size = -1;
1621 state.color = 0; /* black */
1622 state.font_list = NULL;
1624 state.linejoin = -1;
1626 if (eps_prologue(&state) == -1)
1628 eps_set_color(&state, background);
1629 fprintf(fp, "0 0 M 0 %d L %d %d L %d 0 L fill\n",
1630 height, width, height, width);
1631 if (eps_write_content(&state) == -1)
1633 fputs("showpage\n", fp);
1634 fputs("%%EOF\n", fp);
1635 while (state.font_list) {
1636 eps_font *next = state.font_list->next;
1637 free(state.font_list);
1638 state.font_list = next;
1643 /* ------- PDF -------
1644 PDF references page:
1645 http://partners.adobe.com/asn/developer/technotes/acrobatpdf.html
1648 typedef struct pdf_buffer
1650 int id, is_obj, is_dict, is_stream, pdf_file_pos;
1652 int alloc_size, current_size;
1653 struct pdf_buffer *previous_buffer, *next_buffer;
1654 struct pdf_state *state;
1657 typedef struct pdf_font
1659 const char *ps_font;
1661 struct pdf_font *next;
1664 typedef struct pdf_state
1667 gfx_canvas_t *canvas;
1668 art_u32 page_width, page_height;
1669 pdf_font *font_list;
1670 pdf_buffer *first_buffer, *last_buffer;
1674 gfx_color_t stroke_color, fill_color;
1679 int linecap, linejoin;
1682 pdf_buffer pdf_header;
1683 pdf_buffer catalog_obj, pages_obj, page1_obj;
1684 pdf_buffer fontsdict_obj;
1685 pdf_buffer graph_stream;
1688 static void pdf_init_buffer(pdf_state *state, pdf_buffer *buf)
1690 int initial_size = 32;
1693 buf->alloc_size = 0;
1694 buf->current_size = 0;
1695 buf->data = (char*)malloc(initial_size);
1697 buf->previous_buffer = NULL;
1698 buf->next_buffer = NULL;
1699 if (buf->data == NULL) {
1700 rrd_set_error("malloc for pdf_buffer data");
1701 state->has_failed = 1;
1704 buf->alloc_size = initial_size;
1705 if (state->last_buffer)
1706 state->last_buffer->next_buffer = buf;
1707 if (state->first_buffer == NULL)
1708 state->first_buffer = buf;
1709 buf->previous_buffer = state->last_buffer;
1710 state->last_buffer = buf;
1713 static void pdf_put(pdf_buffer *buf, const char *text, int len)
1717 if (buf->alloc_size < buf->current_size + len) {
1718 int new_size = buf->alloc_size;
1720 while (new_size < buf->current_size + len)
1722 new_buf = (char*)malloc(new_size);
1723 if (new_buf == NULL) {
1724 rrd_set_error("re-malloc for pdf_buffer data");
1725 buf->state->has_failed = 1;
1728 memcpy(new_buf, buf->data, buf->current_size);
1730 buf->data = new_buf;
1731 buf->alloc_size = new_size;
1733 memcpy(buf->data + buf->current_size, text, len);
1734 buf->current_size += len;
1737 static void pdf_puts(pdf_buffer *buf, const char *text)
1739 pdf_put(buf, text, strlen(text));
1742 static void pdf_indent(pdf_buffer *buf)
1744 pdf_puts(buf, "\t");
1747 static void pdf_putsi(pdf_buffer *buf, const char *text)
1750 pdf_puts(buf, text);
1753 static void pdf_putint(pdf_buffer *buf, int i)
1756 sprintf(tmp, "%d", i);
1760 static void pdf_putnumber(pdf_buffer *buf, double d)
1763 svg_format_number(tmp, sizeof(tmp), d);
1767 static void pdf_init_object(pdf_state *state, pdf_buffer *buf)
1769 pdf_init_buffer(state, buf);
1770 buf->id = ++state->last_obj_id;
1775 static void pdf_init_dict(pdf_state *state, pdf_buffer *buf)
1777 pdf_init_object(state, buf);
1781 static void pdf_set_color(pdf_buffer *buf, gfx_color_t color,
1782 gfx_color_t *current_color, const char *op)
1784 /* gfx_color_t is RRGGBBAA */
1785 if (*current_color == color)
1787 pdf_putnumber(buf, ((color >> 24) & 255) / 255.0);
1789 pdf_putnumber(buf, ((color >> 16) & 255) / 255.0);
1791 pdf_putnumber(buf, ((color >> 8) & 255) / 255.0);
1794 pdf_puts(buf, "\n");
1795 *current_color = color;
1798 static void pdf_set_stroke_color(pdf_buffer *buf, gfx_color_t color)
1800 pdf_set_color(buf, color, &buf->state->stroke_color, "RG");
1803 static void pdf_set_fill_color(pdf_buffer *buf, gfx_color_t color)
1805 pdf_set_color(buf, color, &buf->state->fill_color, "rg");
1808 static pdf_font *pdf_find_font(pdf_state *state, gfx_node_t *node)
1810 const char *ps_font = afm_get_font_postscript_name(node->filename);
1812 for (ef = state->font_list; ef; ef = ef->next) {
1813 if (!strcmp(ps_font, ef->ps_font))
1819 static void pdf_add_font(pdf_state *state, gfx_node_t *node)
1821 pdf_font *ef = pdf_find_font(state, node);
1824 ef = malloc(sizeof(pdf_font));
1826 rrd_set_error("malloc for pdf_font");
1827 state->has_failed = 1;
1830 pdf_init_dict(state, &ef->obj);
1831 ef->next = state->font_list;
1832 ef->ps_font = afm_get_font_postscript_name(node->filename);
1833 state->font_list = ef;
1835 pdf_putsi(&state->fontsdict_obj, "/F");
1836 pdf_putint(&state->fontsdict_obj, ef->obj.id);
1837 pdf_puts(&state->fontsdict_obj, " ");
1838 pdf_putint(&state->fontsdict_obj, ef->obj.id);
1839 pdf_puts(&state->fontsdict_obj, " 0 R\n");
1841 pdf_putsi(&ef->obj, "/Type /Font\n");
1842 pdf_putsi(&ef->obj, "/Subtype /Type1\n");
1843 pdf_putsi(&ef->obj, "/Name /F");
1844 pdf_putint(&ef->obj, ef->obj.id);
1845 pdf_puts(&ef->obj, "\n");
1846 pdf_putsi(&ef->obj, "/BaseFont /");
1847 pdf_puts(&ef->obj, ef->ps_font);
1848 pdf_puts(&ef->obj, "\n");
1849 pdf_putsi(&ef->obj, "/Encoding /WinAnsiEncoding\n");
1850 /* 'Cp1252' (this is latin 1 extended with 27 characters;
1851 the encoding is also known as 'winansi')
1852 http://www.lowagie.com/iText/tutorial/ch09.html */
1855 static void pdf_create_fonts(pdf_state *state)
1858 for (node = state->canvas->firstnode; node; node = node->next) {
1859 if (node->type == GFX_TEXT)
1860 pdf_add_font(state, node);
1864 static void pdf_write_linearea(pdf_state *state, gfx_node_t *node)
1867 pdf_buffer *s = &state->graph_stream;
1868 if (node->type == GFX_LINE) {
1870 svg_get_dash(node, &dash_info);
1871 if (!svg_dash_equal(&dash_info, &state->dash)) {
1872 state->dash = dash_info;
1873 if (dash_info.dash_enable) {
1875 pdf_putnumber(s, dash_info.adjusted_on);
1877 pdf_putnumber(s, dash_info.adjusted_off);
1879 pdf_putnumber(s, dash_info.dash_offset);
1880 pdf_puts(s, " d\n");
1882 pdf_puts(s, "[] 0 d\n");
1885 pdf_set_stroke_color(s, node->color);
1886 if (state->linecap != 1) {
1887 pdf_puts(s, "1 j\n");
1890 if (state->linejoin != 1) {
1891 pdf_puts(s, "1 J\n");
1892 state->linejoin = 1;
1894 if (node->size != state->line_width) {
1895 state->line_width = node->size;
1896 pdf_putnumber(s, state->line_width);
1897 pdf_puts(s, " w\n");
1900 pdf_set_fill_color(s, node->color);
1902 for (i = 0; i < node->points; i++) {
1903 ArtVpath *vec = node->path + i;
1905 double y = state->page_height - vec->y;
1906 if (node->type == GFX_AREA) {
1907 x += LINEOFFSET; /* adjust for libart handling of areas */
1910 switch (vec->code) {
1911 case ART_MOVETO_OPEN: /* fall-through */
1913 pdf_putnumber(s, x);
1915 pdf_putnumber(s, y);
1916 pdf_puts(s, " m\n");
1919 pdf_putnumber(s, x);
1921 pdf_putnumber(s, y);
1922 pdf_puts(s, " l\n");
1924 case ART_CURVETO: break; /* unsupported */
1925 case ART_END: break; /* nop */
1928 if (node->type == GFX_LINE) {
1929 pdf_puts(s, node->closed_path ? "s\n" : "S\n");
1935 static void pdf_write_text(pdf_state *state, gfx_node_t *node,
1936 int last_was_text, int next_is_text)
1939 pdf_buffer *s = &state->graph_stream;
1940 const unsigned char *p;
1941 pdf_font *font = pdf_find_font(state, node);
1943 double y = state->page_height - node->y;
1944 double dx = 0, dy = 0;
1945 double cos_a = 0, sin_a = 0;
1947 rrd_set_error("font disappeared");
1948 state->has_failed = 1;
1951 switch(node->valign){
1952 case GFX_V_TOP: dy = -node->size; break;
1953 case GFX_V_CENTER: dy = -node->size / 3.0; break;
1954 case GFX_V_BOTTOM: break;
1955 case GFX_V_NULL: break;
1957 switch (node->halign) {
1958 case GFX_H_RIGHT: dx = -afm_get_text_width(0, font->ps_font,
1959 node->size, node->tabwidth, node->text);
1961 case GFX_H_CENTER: dx = -afm_get_text_width(0, font->ps_font,
1962 node->size, node->tabwidth, node->text) / 2;
1964 case GFX_H_LEFT: break;
1965 case GFX_H_NULL: break;
1967 pdf_set_fill_color(s, node->color);
1968 if (node->angle != 0) {
1969 double a = 2 * M_PI * -node->angle / 360.0;
1970 double new_x, new_y;
1973 new_x = cos_a * dx - sin_a * dy + x;
1974 new_y = sin_a * dx + cos_a * dy + y;
1982 pdf_puts(s, "BT\n");
1983 if (state->font_id != font->obj.id || node->size != state->font_size) {
1984 state->font_id = font->obj.id;
1985 state->font_size = node->size;
1987 pdf_putint(s, font->obj.id);
1989 pdf_putnumber(s, node->size);
1990 pdf_puts(s, " Tf\n");
1992 if (node->angle == 0) {
1993 pdf_puts(s, "1 0 0 1 ");
1995 pdf_putnumber(s, cos_a);
1997 pdf_putnumber(s, sin_a);
1999 pdf_putnumber(s, -sin_a);
2001 pdf_putnumber(s, cos_a);
2004 pdf_putnumber(s, x);
2006 pdf_putnumber(s, y);
2007 pdf_puts(s, " Tm\n");
2009 for (p = (const unsigned char*)node->text; *p; p++) {
2021 snprintf(tmp, sizeof(tmp), "\\%03o", *p);
2024 pdf_put(s, (const char*)p, 1);
2028 pdf_puts(s, ") Tj\n");
2030 pdf_puts(s, "ET\n");
2033 static void pdf_write_content(pdf_state *state)
2036 int last_was_text = 0, next_is_text;
2037 for (node = state->canvas->firstnode; node; node = node->next) {
2038 switch (node->type) {
2041 pdf_write_linearea(state, node);
2044 next_is_text = node->next && node->next->type == GFX_TEXT;
2045 pdf_write_text(state, node, last_was_text, next_is_text);
2048 last_was_text = node->type == GFX_TEXT;
2052 static void pdf_init_document(pdf_state *state)
2054 pdf_init_buffer(state, &state->pdf_header);
2055 pdf_init_dict(state, &state->catalog_obj);
2056 pdf_init_dict(state, &state->pages_obj);
2057 pdf_init_dict(state, &state->page1_obj);
2058 pdf_init_dict(state, &state->fontsdict_obj);
2059 pdf_create_fonts(state);
2060 if (state->has_failed)
2062 /* make stream last object in file */
2063 pdf_init_object(state, &state->graph_stream);
2064 state->graph_stream.is_stream = 1;
2067 static void pdf_setup_document(pdf_state *state)
2069 /* all objects created by now, so init code can reference them */
2071 pdf_puts(&state->pdf_header, "%PDF-1.3\n");
2072 /* following 8 bit comment is recommended by Adobe for
2073 indicating binary file to file transfer applications */
2074 pdf_puts(&state->pdf_header, "%\xE2\xE3\xCF\xD3\n");
2076 pdf_putsi(&state->catalog_obj, "/Type /Catalog\n");
2077 pdf_putsi(&state->catalog_obj, "/Pages ");
2078 pdf_putint(&state->catalog_obj, state->pages_obj.id);
2079 pdf_puts(&state->catalog_obj, " 0 R\n");
2081 pdf_putsi(&state->pages_obj, "/Type /Pages\n");
2082 pdf_putsi(&state->pages_obj, "/Kids [");
2083 pdf_putint(&state->pages_obj, state->page1_obj.id);
2084 pdf_puts(&state->pages_obj, " 0 R]\n");
2085 pdf_putsi(&state->pages_obj, "/Count 1\n");
2087 pdf_putsi(&state->page1_obj, "/Type /Page\n");
2088 pdf_putsi(&state->page1_obj, "/Parent ");
2089 pdf_putint(&state->page1_obj, state->pages_obj.id);
2090 pdf_puts(&state->page1_obj, " 0 R\n");
2091 pdf_putsi(&state->page1_obj, "/MediaBox [0 0 ");
2092 pdf_putint(&state->page1_obj, state->page_width);
2093 pdf_puts(&state->page1_obj, " ");
2094 pdf_putint(&state->page1_obj, state->page_height);
2095 pdf_puts(&state->page1_obj, "]\n");
2096 pdf_putsi(&state->page1_obj, "/Contents ");
2097 pdf_putint(&state->page1_obj, state->graph_stream.id);
2098 pdf_puts(&state->page1_obj, " 0 R\n");
2099 pdf_putsi(&state->page1_obj, "/Resources << /Font ");
2100 pdf_putint(&state->page1_obj, state->fontsdict_obj.id);
2101 pdf_puts(&state->page1_obj, " 0 R >>\n");
2104 static void pdf_write_string_to_file(pdf_state *state, const char *text)
2106 fputs(text, state->fp);
2107 state->pdf_file_pos += strlen(text);
2110 static void pdf_write_buf_to_file(pdf_state *state, pdf_buffer *buf)
2113 buf->pdf_file_pos = state->pdf_file_pos;
2115 snprintf(tmp, sizeof(tmp), "%d 0 obj\n", buf->id);
2116 pdf_write_string_to_file(state, tmp);
2119 pdf_write_string_to_file(state, "<<\n");
2120 if (buf->is_stream) {
2121 snprintf(tmp, sizeof(tmp), "<< /Length %d >>\n", buf->current_size);
2122 pdf_write_string_to_file(state, tmp);
2123 pdf_write_string_to_file(state, "stream\n");
2125 fwrite(buf->data, 1, buf->current_size, state->fp);
2126 state->pdf_file_pos += buf->current_size;
2128 pdf_write_string_to_file(state, "endstream\n");
2130 pdf_write_string_to_file(state, ">>\n");
2132 pdf_write_string_to_file(state, "endobj\n");
2135 static void pdf_write_to_file(pdf_state *state)
2137 pdf_buffer *buf = state->first_buffer;
2139 state->pdf_file_pos = 0;
2140 pdf_write_buf_to_file(state, &state->pdf_header);
2143 pdf_write_buf_to_file(state, buf);
2144 buf = buf->next_buffer;
2146 xref_pos = state->pdf_file_pos;
2147 fprintf(state->fp, "xref\n");
2148 fprintf(state->fp, "%d %d\n", 0, state->last_obj_id + 1);
2149 /* TOC lines must be exactly 20 bytes including \n */
2150 fprintf(state->fp, "%010d %05d f\x20\n", 0, 65535);
2151 for (buf = state->first_buffer; buf; buf = buf->next_buffer) {
2153 fprintf(state->fp, "%010d %05d n\x20\n", buf->pdf_file_pos, 0);
2155 fprintf(state->fp, "trailer\n");
2156 fprintf(state->fp, "<<\n");
2157 fprintf(state->fp, "\t/Size %d\n", state->last_obj_id + 1);
2158 fprintf(state->fp, "\t/Root %d 0 R\n", state->catalog_obj.id);
2159 fprintf(state->fp, ">>\n");
2160 fprintf(state->fp, "startxref\n");
2161 fprintf(state->fp, "%d\n", xref_pos);
2162 fputs("%%EOF\n", state->fp);
2165 static void pdf_free_resources(pdf_state *state)
2167 pdf_buffer *buf = state->first_buffer;
2171 buf->alloc_size = buf->current_size = 0;
2172 buf = buf->next_buffer;
2174 while (state->font_list) {
2175 pdf_font *next = state->font_list->next;
2176 free(state->font_list);
2177 state->font_list = next;
2181 int gfx_render_pdf (gfx_canvas_t *canvas,
2182 art_u32 width, art_u32 height,
2183 gfx_color_t background, FILE *fp){
2184 struct pdf_state state;
2185 memset(&state, 0, sizeof(pdf_state));
2187 state.canvas = canvas;
2188 state.page_width = width;
2189 state.page_height = height;
2191 state.font_size = -1;
2192 state.font_list = NULL;
2194 state.linejoin = -1;
2195 pdf_init_document(&state);
2197 pdf_set_color(&state, background);
2198 fprintf(fp, "0 0 M 0 %d L %d %d L %d 0 L fill\n",
2199 height, width, height, width);
2201 if (!state.has_failed)
2202 pdf_write_content(&state);
2203 if (!state.has_failed)
2204 pdf_setup_document(&state);
2205 if (!state.has_failed)
2206 pdf_write_to_file(&state);
2207 pdf_free_resources(&state);
2208 return state.has_failed ? -1 : 0;