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 */
379 ft_pen.x = 0; /* start at (0,0) !! */
382 string = (gfx_string) malloc (sizeof(struct gfx_string_s));
385 string->count = strlen (text);
386 string->glyphs = (gfx_char) calloc (string->count,sizeof(struct gfx_char_s));
387 string->num_glyphs = 0;
388 string->transform.xx = (FT_Fixed)( cos(M_PI*(rotation)/180.0)*0x10000);
389 string->transform.xy = (FT_Fixed)(-sin(M_PI*(rotation)/180.0)*0x10000);
390 string->transform.yx = (FT_Fixed)( sin(M_PI*(rotation)/180.0)*0x10000);
391 string->transform.yy = (FT_Fixed)( cos(M_PI*(rotation)/180.0)*0x10000);
394 w_text = (wchar_t) calloc (string->count,sizeof(wchar_t));
395 mbstowcs(w_text,text,string->count);
398 use_kerning = FT_HAS_KERNING(face);
400 glyph = string->glyphs;
401 for (n=0; n<string->count; n++, glyph++) {
403 /* handle the tabs ...
404 have a witespace glyph inserted, but set its width such that the distance
405 of the new right edge is x times tabwidth from 0,0 where x is an integer. */
406 unsigned char letter = text[n];
408 if (letter == '\\' && n+1 < string->count && text[n+1] == 't'){
409 /* we have a tab here so skip the backslash and
410 set t to ' ' so that we get a white space */
419 /* initialize each struct gfx_char_s */
426 glyph->index = FT_Get_Char_Index( face, w_text[n] );
428 glyph->index = FT_Get_Char_Index( face, letter );
431 /* compute glyph origin */
432 if ( use_kerning && previous && glyph->index ) {
434 FT_Get_Kerning (face, previous, glyph->index,
435 ft_kerning_default, &kerning);
436 ft_pen.x += kerning.x;
437 ft_pen.y += kerning.y;
440 /* load the glyph image (in its native format) */
441 /* for now, we take a monochrome glyph bitmap */
442 error = FT_Load_Glyph (face, glyph->index, FT_LOAD_DEFAULT);
444 fprintf (stderr, "couldn't load glyph: %c\n", letter);
447 error = FT_Get_Glyph (slot, &glyph->image);
449 fprintf (stderr, "couldn't get glyph from slot: %c\n", letter);
452 /* if we are in tabbing mode, we replace the tab with a space and shift the position
453 of the space so that its left edge is where the tab was supposed to land us */
455 /* we are in gridfitting mode so the calculations happen in 1/64 pixles */
456 ft_pen.x = tabwidth*64.0 * (float)(1 + (long)(ft_pen.x / (tabwidth * 64.0))) - slot->advance.x;
458 /* store current pen position */
459 glyph->pos.x = ft_pen.x;
460 glyph->pos.y = ft_pen.y;
463 ft_pen.x += slot->advance.x;
464 ft_pen.y += slot->advance.y;
468 FT_Vector_Transform (&vec, &string->transform);
469 error = FT_Glyph_Transform (glyph->image, &string->transform, &vec);
471 fprintf (stderr, "couldn't transform glyph\n");
475 /* convert to a bitmap - destroy native image */
476 error = FT_Glyph_To_Bitmap (&glyph->image, FT_RENDER_MODE_NORMAL, 0, 1);
478 fprintf (stderr, "couldn't convert glyph to bitmap\n");
482 /* increment number of glyphs */
483 previous = glyph->index;
484 string->num_glyphs++;
486 /* printf ("number of glyphs = %d\n", string->num_glyphs);*/
487 compute_string_bbox( string );
488 /* the last character was a tab */
490 string->width = ft_pen.x;
492 string->width = string->bbox.xMax - string->bbox.xMin;
494 string->height = string->bbox.yMax - string->bbox.yMin;
503 static int gfx_save_png (art_u8 *buffer, FILE *fp,
504 long width, long height, long bytes_per_pixel);
505 /* render grafics into png image */
507 int gfx_render_png (gfx_canvas_t *canvas,
508 art_u32 width, art_u32 height,
509 gfx_color_t background, FILE *fp){
513 gfx_node_t *node = canvas->firstnode;
515 art_u8 red = background >> 24, green = (background >> 16) & 0xff;
516 art_u8 blue = (background >> 8) & 0xff, alpha = ( background & 0xff );
518 unsigned long pys_width = width * canvas->zoom;
519 unsigned long pys_height = height * canvas->zoom;
520 const int bytes_per_pixel = 4;
521 unsigned long rowstride = pys_width*bytes_per_pixel; /* bytes per pixel */
522 art_u8 *buffer = art_new (art_u8, rowstride*pys_height);
523 /* fill that buffer with out background color */
526 for (i=0,buffp=(gfx_color_t *)buffer;
527 i<pys_width*pys_height;
529 *(buffp++)=background;
531 FT_Init_FreeType( &library );
533 switch (node->type) {
539 art_affine_scale(dst,canvas->zoom,canvas->zoom);
540 vec = art_vpath_affine_transform(node->path,dst);
541 if (node->closed_path)
542 gfx_libart_close_path(node, &vec);
543 /* gfx_round_scaled_coordinates(vec); */
544 pvec = art_vpath_perturb(vec);
546 if(node->type == GFX_LINE){
547 svp = art_svp_vpath_stroke ( pvec, ART_PATH_STROKE_JOIN_ROUND,
548 ART_PATH_STROKE_CAP_ROUND,
549 node->size*canvas->zoom,4,0.25);
551 svp = art_svp_from_vpath ( pvec );
552 svpt = art_svp_uncross( svp );
554 svp = art_svp_rewind_uncrossed(svpt,ART_WIND_RULE_NONZERO);
558 /* this is from gnome since libart does not have this yet */
559 gnome_print_art_rgba_svp_alpha (svp ,0,0, pys_width, pys_height,
560 node->color, buffer, rowstride, NULL);
567 art_u8 fcolor[4],falpha;
571 FT_Vector vec; /* 26.6 */
573 float pen_x = 0.0 , pen_y = 0.0;
577 fcolor[0] = node->color >> 24;
578 fcolor[1] = (node->color >> 16) & 0xff;
579 fcolor[2] = (node->color >> 8) & 0xff;
580 falpha = node->color & 0xff;
581 error = FT_New_Face( library,
582 (char *)node->filename,
586 rrd_set_error("failed to load %s",node->filename);
589 error = FT_Set_Char_Size(face, /* handle to face object */
590 (long)(node->size*64),
591 (long)(node->size*64),
592 (long)(100*canvas->zoom),
593 (long)(100*canvas->zoom));
595 pen_x = node->x * canvas->zoom;
596 pen_y = node->y * canvas->zoom;
598 string = gfx_string_create (face, node->text, node->angle, node->tabwidth);
599 switch(node->halign){
600 case GFX_H_RIGHT: vec.x = -string->bbox.xMax;
602 case GFX_H_CENTER: vec.x = abs(string->bbox.xMax) >= abs(string->bbox.xMin) ?
603 -string->bbox.xMax/2:-string->bbox.xMin/2;
605 case GFX_H_LEFT: vec.x = -string->bbox.xMin;
607 case GFX_H_NULL: vec.x = 0;
611 switch(node->valign){
612 case GFX_V_TOP: vec.y = string->bbox.yMax;
614 case GFX_V_CENTER: vec.y = abs(string->bbox.yMax) >= abs(string->bbox.yMin) ?
615 string->bbox.yMax/2:string->bbox.yMin/2;
617 case GFX_V_BOTTOM: vec.y = 0;
619 case GFX_V_NULL: vec.y = 0;
624 glyph = string->glyphs;
625 for(n=0; n<string->num_glyphs; ++n, ++glyph) {
629 /* long buf_x,comp_n; */
630 /* make copy to transform */
631 if (! glyph->image) {
632 fprintf (stderr, "no image\n");
635 error = FT_Glyph_Copy (glyph->image, &image);
637 fprintf (stderr, "couldn't copy image\n");
643 FT_Vector_Transform (&vec, &string->transform);
645 bit = (FT_BitmapGlyph) image;
646 gr = bit->bitmap.num_grays -1;
648 buf_x = (pen_x + 0.5) + (double)bit->left;
649 comp_n = buf_x + bit->bitmap.width > pys_width ? pys_width - buf_x : bit->bitmap.width;
650 if (buf_x < 0 || buf_x >= (long)pys_width) continue;
651 buf_x *= bytes_per_pixel ;
652 for (iy=0; iy < bit->bitmap.rows; iy++){
653 long buf_y = iy+(pen_y+0.5)-(double)bit->top;
654 if (buf_y < 0 || buf_y >= (long)pys_height) continue;
656 for (ix=0;ix < bit->bitmap.width;ix++){
657 *(letter + (ix*bytes_per_pixel+3)) = *(bit->bitmap.buffer + iy * bit->bitmap.width + ix);
659 art_rgba_rgba_composite(buffer + buf_y + buf_x ,letter,comp_n);
664 for (iy=0; iy < bit->bitmap.rows; iy++){
665 long buf_y = iy+(pen_y+0.5)-bit->top;
666 if (buf_y < 0 || buf_y >= (long)pys_height) continue;
668 for (ix=0;ix < bit->bitmap.width;ix++){
669 long buf_x = ix + (pen_x + 0.5) + (double)bit->left ;
672 if (buf_x < 0 || buf_x >= (long)pys_width) continue;
673 buf_x *= bytes_per_pixel ;
674 font_alpha = *(bit->bitmap.buffer + iy * bit->bitmap.width + ix);
676 fcolor[3] = (art_u8)((double)font_alpha / gr * falpha);
677 art_rgba_rgba_composite(buffer + buf_y + buf_x ,fcolor,1);
683 for (iy=0; iy < bit->bitmap.rows; iy++){
684 long buf_y = iy+(pen_y+0.5)-bit->top;
685 if (buf_y < 0 || buf_y >= (long)pys_height) continue;
687 for (ix=0;ix < bit->bitmap.width;ix++){
688 long buf_x = ix + (pen_x + 0.5) + (double)bit->left ;
691 if (buf_x < 0 || buf_x >= (long)pys_width) continue;
692 buf_x *= bytes_per_pixel ;
693 font_alpha = *(bit->bitmap.buffer + iy * bit->bitmap.width + ix);
694 font_alpha = (art_u8)((double)font_alpha / gr * falpha);
695 for (iz = 0; iz < 3; iz++){
696 art_u8 *orig = buffer + buf_y + buf_x + iz;
697 *orig = (art_u8)((double)*orig / gr * ( gr - font_alpha) +
698 (double)fcolor[iz] / gr * (font_alpha));
703 FT_Done_Glyph (image);
705 gfx_string_destroy(string);
710 gfx_save_png(buffer,fp , pys_width,pys_height,bytes_per_pixel);
712 FT_Done_FreeType( library );
716 /* free memory used by nodes this will also remove memory required for
717 associated paths and svcs ... but not for text strings */
719 gfx_destroy (gfx_canvas_t *canvas){
720 gfx_node_t *next,*node = canvas->firstnode;
723 art_free(node->path);
725 free(node->filename);
733 static int gfx_save_png (art_u8 *buffer, FILE *fp, long width, long height, long bytes_per_pixel){
734 png_structp png_ptr = NULL;
735 png_infop info_ptr = NULL;
737 png_bytep *row_pointers;
738 int rowstride = width * bytes_per_pixel;
744 png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING,NULL,NULL,NULL);
749 row_pointers = (png_bytepp)png_malloc(png_ptr,
750 height*sizeof(png_bytep));
752 info_ptr = png_create_info_struct(png_ptr);
754 if (info_ptr == NULL)
756 png_free(png_ptr,row_pointers);
757 png_destroy_write_struct(&png_ptr, (png_infopp)NULL);
761 if (setjmp(png_jmpbuf(png_ptr)))
763 /* If we get here, we had a problem writing the file */
764 png_destroy_write_struct(&png_ptr, &info_ptr);
768 png_init_io(png_ptr, fp);
769 png_set_IHDR (png_ptr, info_ptr,width, height,
770 8, PNG_COLOR_TYPE_RGB_ALPHA,
772 PNG_COMPRESSION_TYPE_DEFAULT,
773 PNG_FILTER_TYPE_DEFAULT);
775 text[0].key = "Software";
776 text[0].text = "RRDtool, Tobias Oetiker <tobi@oetike.ch>, http://tobi.oetiker.ch";
777 text[0].compression = PNG_TEXT_COMPRESSION_NONE;
778 png_set_text (png_ptr, info_ptr, text, 1);
780 /* lets make this fast */
781 /* png_set_filter(png_ptr,0,PNG_FILTER_NONE); */
782 png_set_compression_level(png_ptr,1);
783 /* png_set_compression_strategy(png_ptr,Z_HUFFMAN_ONLY); */
785 png_set_filter(png_ptr,PNG_FILTER_TYPE_BASE,PNG_FILTER_SUB);
786 png_set_compression_strategy(png_ptr,Z_HUFFMAN_ONLY);
787 png_set_compression_level(png_ptr,Z_BEST_SPEED); */
789 /* Write header data */
790 png_write_info (png_ptr, info_ptr);
791 for (i = 0; i < height; i++)
792 row_pointers[i] = (png_bytep) (buffer + i*rowstride);
794 png_write_image(png_ptr, row_pointers);
795 png_write_end(png_ptr, info_ptr);
796 png_free(png_ptr,row_pointers);
797 png_destroy_write_struct(&png_ptr, &info_ptr);
802 /* ------- SVG -------
804 http://www.w3.org/TR/SVG/
806 static int svg_indent = 0;
807 static int svg_single_line = 0;
808 static const char *svg_default_font = "Helvetica";
809 typedef struct svg_dash
812 double dash_adjust, dash_len, dash_offset;
813 double adjusted_on, adjusted_off;
817 static void svg_print_indent(FILE *fp)
820 for (i = svg_indent - svg_single_line; i > 0; i--) {
826 static void svg_start_tag(FILE *fp, const char *name)
828 svg_print_indent(fp);
834 static void svg_close_tag_single_line(FILE *fp)
840 static void svg_close_tag(FILE *fp)
843 if (!svg_single_line)
847 static void svg_end_tag(FILE *fp, const char *name)
849 /* name is NULL if closing empty-node tag */
854 svg_print_indent(fp);
864 static void svg_close_tag_empty_node(FILE *fp)
866 svg_end_tag(fp, NULL);
869 static void svg_write_text(FILE *fp, const char *text)
871 const unsigned char *p, *start, *last;
873 p = (const unsigned char*)text;
876 /* trim leading spaces */
880 /* trim trailing spaces */
882 while ((ch = *p) != 0) {
887 /* encode trimmed text */
891 ch = afm_host2unicode(ch); /* unsafe macro */
893 case '&': fputs("&", fp); break;
894 case '<': fputs("<", fp); break;
895 case '>': fputs(">", fp); break;
896 case '"': fputs(""", fp); break;
899 fprintf(fp, "&#%d;", ch);
906 static void svg_format_number(char *buf, int bufsize, double d)
908 /* omit decimals if integer to reduce filesize */
910 snprintf(buf, bufsize, "%.2f", d);
911 p = buf; /* doesn't trust snprintf return value */
917 *p = '\0'; /* zap trailing zeros */
921 *p = '\0'; /* zap trailing dot */
926 static void svg_write_number(FILE *fp, double d)
929 svg_format_number(buf, sizeof(buf), d);
933 static int svg_color_is_black(int c)
935 /* gfx_color_t is RRGGBBAA */
936 return c == 0x000000FF;
939 static void svg_write_color(FILE *fp, gfx_color_t c, const char *attr)
941 /* gfx_color_t is RRGGBBAA, svg can use #RRGGBB and #RGB like html */
942 gfx_color_t rrggbb = (int)((c >> 8) & 0xFFFFFF);
943 gfx_color_t opacity = c & 0xFF;
944 fprintf(fp, " %s=\"", attr);
945 if ((rrggbb & 0x0F0F0F) == ((rrggbb >> 4) & 0x0F0F0F)) {
946 /* css2 short form, #rgb is #rrggbb, not #r0g0b0 */
947 fprintf(fp, "#%03lX",
948 ( ((rrggbb >> 8) & 0xF00)
949 | ((rrggbb >> 4) & 0x0F0)
950 | ( rrggbb & 0x00F)));
952 fprintf(fp, "#%06lX", rrggbb);
955 if (opacity != 0xFF) {
956 fprintf(fp, " stroke-opacity=\"");
957 svg_write_number(fp, opacity / 255.0);
962 static void svg_get_dash(gfx_node_t *node, svg_dash *d)
966 if (node->dash_on <= 0 || node->dash_off <= 0) {
971 d->dash_len = node->dash_on + node->dash_off;
972 /* dash on/off adjustment due to round caps */
973 d->dash_adjust = 0.8 * node->size;
974 d->adjusted_on = node->dash_on - d->dash_adjust;
975 if (d->adjusted_on < 0.01)
976 d->adjusted_on = 0.01;
977 d->adjusted_off = d->dash_len - d->adjusted_on;
978 /* dash offset calc */
979 if (node->path[0].x == node->path[1].x) /* only good for horz/vert lines */
980 offset = node->path[0].y;
982 offset = node->path[0].x;
983 mult = (int)fabs(offset / d->dash_len);
984 d->dash_offset = offset - mult * d->dash_len;
985 if (node->path[0].x < node->path[1].x || node->path[0].y < node->path[1].y)
986 d->dash_offset = d->dash_len - d->dash_offset;
989 static int svg_dash_equal(svg_dash *a, svg_dash *b)
991 if (a->dash_enable != b->dash_enable)
993 if (a->adjusted_on != b->adjusted_on)
995 if (a->adjusted_off != b->adjusted_off)
997 /* rest of properties will be the same when on+off are */
1001 static void svg_common_path_attributes(FILE *fp, gfx_node_t *node)
1004 svg_get_dash(node, &dash_info);
1005 fputs(" stroke-width=\"", fp);
1006 svg_write_number(fp, node->size);
1008 svg_write_color(fp, node->color, "stroke");
1009 fputs(" fill=\"none\"", fp);
1010 if (dash_info.dash_enable) {
1011 if (dash_info.dash_offset != 0) {
1012 fputs(" stroke-dashoffset=\"", fp);
1013 svg_write_number(fp, dash_info.dash_offset);
1016 fputs(" stroke-dasharray=\"", fp);
1017 svg_write_number(fp, dash_info.adjusted_on);
1019 svg_write_number(fp, dash_info.adjusted_off);
1024 static int svg_is_int_step(double a, double b)
1026 double diff = fabs(a - b);
1027 return floor(diff) == diff;
1030 static int svg_path_straight_segment(FILE *fp,
1031 double lastA, double currentA, double currentB,
1033 int segment_idx, int isx, char absChar, char relChar)
1035 if (!svg_is_int_step(lastA, currentA)) {
1037 svg_write_number(fp, currentA);
1040 if (segment_idx < node->points - 1) {
1041 ArtVpath *vec = node->path + segment_idx + 1;
1042 if (vec->code == ART_LINETO) {
1043 double nextA = (isx ? vec->x : vec->y) - LINEOFFSET;
1044 double nextB = (isx ? vec->y : vec->x) - LINEOFFSET;
1045 if (nextB == currentB
1046 && ((currentA >= lastA) == (nextA >= currentA))
1047 && svg_is_int_step(currentA, nextA)) {
1048 return 1; /* skip to next as it is a straight line */
1053 svg_write_number(fp, currentA - lastA);
1057 static void svg_path(FILE *fp, gfx_node_t *node, int multi)
1060 double lastX = 0, lastY = 0;
1061 /* for straight lines <path..> tags take less space than
1062 <line..> tags because of the efficient packing
1063 in the 'd' attribute */
1064 svg_start_tag(fp, "path");
1066 svg_common_path_attributes(fp, node);
1068 /* specification of the 'd' attribute: */
1069 /* http://www.w3.org/TR/SVG/paths.html#PathDataGeneralInformation */
1070 for (i = 0; i < node->points; i++) {
1071 ArtVpath *vec = node->path + i;
1072 double x = vec->x - LINEOFFSET;
1073 double y = vec->y - LINEOFFSET;
1074 switch (vec->code) {
1075 case ART_MOVETO_OPEN: /* fall-through */
1078 svg_write_number(fp, x);
1080 svg_write_number(fp, y);
1083 /* try optimize filesize by using minimal lineto commands */
1084 /* without introducing rounding errors. */
1086 if (svg_path_straight_segment(fp, lastY, y, x, node, i, 0, 'V', 'v'))
1088 } else if (y == lastY) {
1089 if (svg_path_straight_segment(fp, lastX, x, y, node, i, 1, 'H', 'h'))
1093 svg_write_number(fp, x);
1095 svg_write_number(fp, y);
1098 case ART_CURVETO: break; /* unsupported */
1099 case ART_END: break; /* nop */
1104 if (node->closed_path)
1107 svg_close_tag_empty_node(fp);
1110 static void svg_multi_path(FILE *fp, gfx_node_t **nodeR)
1112 /* optimize for multiple paths with the same color, penwidth, etc. */
1114 gfx_node_t *node = *nodeR;
1115 gfx_node_t *next = node->next;
1117 if (next->type != node->type
1118 || next->size != node->size
1119 || next->color != node->color
1120 || next->dash_on != node->dash_on
1121 || next->dash_off != node->dash_off)
1127 svg_path(fp, node, 0);
1130 svg_start_tag(fp, "g");
1131 svg_common_path_attributes(fp, node);
1133 while (num && node) {
1134 svg_path(fp, node, 1);
1140 svg_end_tag(fp, "g");
1143 static void svg_area(FILE *fp, gfx_node_t *node)
1146 double startX = 0, startY = 0;
1147 svg_start_tag(fp, "polygon");
1149 svg_write_color(fp, node->color, "fill");
1150 fputs(" points=\"", fp);
1151 for (i = 0; i < node->points; i++) {
1152 ArtVpath *vec = node->path + i;
1153 double x = vec->x - LINEOFFSET;
1154 double y = vec->y - LINEOFFSET;
1155 switch (vec->code) {
1156 case ART_MOVETO_OPEN: /* fall-through */
1158 svg_write_number(fp, x);
1160 svg_write_number(fp, y);
1165 if (i == node->points - 2
1166 && node->path[i + 1].code == ART_END
1167 && fabs(x - startX) < 0.001 && fabs(y - startY) < 0.001) {
1168 break; /* poly area always closed, no need for last point */
1171 svg_write_number(fp, x);
1173 svg_write_number(fp, y);
1175 case ART_CURVETO: break; /* unsupported */
1176 case ART_END: break; /* nop */
1180 svg_close_tag_empty_node(fp);
1183 static void svg_text(FILE *fp, gfx_node_t *node)
1185 double x = node->x - LINEOFFSET;
1186 double y = node->y - LINEOFFSET;
1187 if (node->angle != 0) {
1188 svg_start_tag(fp, "g");
1189 fputs(" transform=\"translate(", fp);
1190 svg_write_number(fp, x);
1192 svg_write_number(fp, y);
1193 fputs(") rotate(", fp);
1194 svg_write_number(fp, node->angle);
1199 switch (node->valign) {
1200 case GFX_V_TOP: y += node->size; break;
1201 case GFX_V_CENTER: y += node->size / 3; break;
1202 case GFX_V_BOTTOM: break;
1203 case GFX_V_NULL: break;
1205 svg_start_tag(fp, "text");
1207 svg_write_number(fp, x);
1208 fputs("\" y=\"", fp);
1209 svg_write_number(fp, y);
1211 /* if (strcmp(node->filename, svg_default_font))
1212 fprintf(fp, " font-family=\"%s\"", node->filename);
1214 fputs("\" font-family=\"Helvetica", fp);
1215 fputs("\" font-size=\"", fp);
1216 svg_write_number(fp, node->size);
1218 if (!svg_color_is_black(node->color))
1219 svg_write_color(fp, node->color, "fill");
1220 switch (node->halign) {
1221 case GFX_H_RIGHT: fputs(" text-anchor=\"end\"", fp); break;
1222 case GFX_H_CENTER: fputs(" text-anchor=\"middle\"", fp); break;
1223 case GFX_H_LEFT: break;
1224 case GFX_H_NULL: break;
1226 svg_close_tag_single_line(fp);
1227 /* support for node->tabwidth missing */
1228 svg_write_text(fp, node->text);
1229 svg_end_tag(fp, "text");
1230 if (node->angle != 0)
1231 svg_end_tag(fp, "g");
1234 int gfx_render_svg (gfx_canvas_t *canvas,
1235 art_u32 width, art_u32 height,
1236 gfx_color_t background, FILE *fp){
1237 gfx_node_t *node = canvas->firstnode;
1239 "<?xml version=\"1.0\" standalone=\"no\"?>\n"
1240 "<!DOCTYPE svg PUBLIC \"-//W3C//DTD SVG 1.0//EN\"\n"
1241 " \"http://www.w3.org/TR/2001/REC-SVG-20010904/DTD/svg10.dtd\">\n"
1243 " SVG file created by RRDtool,\n"
1244 " Tobias Oetiker <tobi@oetike.ch>, http://tobi.oetiker.ch\n"
1246 " The width/height attributes in the outhermost svg node\n"
1247 " are just default sizes for the browser which is used\n"
1248 " if the svg file is openened directly without being\n"
1249 " embedded in an html file.\n"
1250 " The viewBox is the local coord system for rrdtool.\n"
1252 svg_start_tag(fp, "svg");
1253 fputs(" width=\"", fp);
1254 svg_write_number(fp, width * canvas->zoom);
1255 fputs("\" height=\"", fp);
1256 svg_write_number(fp, height * canvas->zoom);
1257 fputs("\" x=\"0\" y=\"0\" viewBox=\"", fp);
1258 svg_write_number(fp, -LINEOFFSET);
1260 svg_write_number(fp, -LINEOFFSET);
1262 svg_write_number(fp, width - LINEOFFSET);
1264 svg_write_number(fp, height - LINEOFFSET);
1265 fputs("\" preserveAspectRatio=\"xMidYMid\"", fp);
1266 fprintf(fp, " font-family=\"%s\"", svg_default_font); /* default font */
1267 fputs(" stroke-linecap=\"round\" stroke-linejoin=\"round\"", fp);
1269 svg_start_tag(fp, "rect");
1270 fprintf(fp, " x=\"0\" y=\"0\" width=\"%d\" height=\"%d\"", width, height);
1271 svg_write_color(fp, background, "fill");
1272 svg_close_tag_empty_node(fp);
1274 switch (node->type) {
1276 svg_multi_path(fp, &node);
1286 svg_end_tag(fp, "svg");
1290 /* ------- EPS -------
1291 EPS and Postscript references:
1292 http://partners.adobe.com/asn/developer/technotes/postscript.html
1295 typedef struct eps_font
1297 const char *ps_font;
1299 struct eps_font *next;
1302 typedef struct eps_state
1305 gfx_canvas_t *canvas;
1306 art_u32 page_width, page_height;
1307 eps_font *font_list;
1313 int linecap, linejoin;
1317 static void eps_set_color(eps_state *state, gfx_color_t color)
1319 /* gfx_color_t is RRGGBBAA */
1320 if (state->color == color)
1322 fprintf(state->fp, "%d %d %d Rgb\n",
1323 (int)((color >> 24) & 255),
1324 (int)((color >> 16) & 255),
1325 (int)((color >> 8) & 255));
1326 state->color = color;
1329 static int eps_add_font(eps_state *state, gfx_node_t *node)
1331 /* The fonts list could be postponed to the end using
1332 (atend), but let's be nice and have them in the header. */
1333 const char *ps_font = afm_get_font_postscript_name(node->filename);
1335 for (ef = state->font_list; ef; ef = ef->next) {
1336 if (!strcmp(ps_font, ef->ps_font))
1339 ef = malloc(sizeof(eps_font));
1341 rrd_set_error("malloc for eps_font");
1344 ef->next = state->font_list;
1345 ef->ps_font = ps_font;
1346 state->font_list = ef;
1350 static void eps_list_fonts(eps_state *state, const char *dscName)
1353 int lineLen = strlen(dscName);
1354 if (!state->font_list)
1356 fputs(dscName, state->fp);
1357 for (ef = state->font_list; ef; ef = ef->next) {
1358 int nameLen = strlen(ef->ps_font);
1359 if (lineLen + nameLen > 100 && lineLen) {
1360 fputs("\n", state->fp);
1361 fputs("%%- \n", state->fp);
1364 fputs(" ", state->fp);
1367 fputs(ef->ps_font, state->fp);
1370 fputs("\n", state->fp);
1373 static void eps_define_fonts(eps_state *state)
1376 if (!state->font_list)
1378 for (ef = state->font_list; ef; ef = ef->next) {
1379 /* PostScript¨ LANGUAGE REFERENCE third edition
1383 "/%s findfont dup length dict begin\n"
1384 "{ 1 index /FID ne {def} {pop pop} ifelse } forall\n"
1385 "/Encoding ISOLatin1Encoding def\n"
1387 "/%s-ISOLatin1 exch definefont pop\n"
1388 "/SetFont-%s { /%s-ISOLatin1 findfont exch scalefont setfont } bd\n",
1389 ef->ps_font, ef->ps_font, ef->ps_font, ef->ps_font);
1393 static int eps_prologue(eps_state *state)
1397 "%!PS-Adobe-3.0 EPSF-3.0\n"
1398 "%%Creator: RRDtool 1.2.0 Tobias Oetiker, http://tobi.oetiker.ch\n"
1399 /* can't like weird chars here */
1400 "%%Title: (RRDtool output)\n"
1401 "%%DocumentData: Clean7Bit\n"
1403 fprintf(state->fp, "%%%%BoundingBox: 0 0 %d %d\n",
1404 state->page_width, state->page_height);
1405 for (node = state->canvas->firstnode; node; node = node->next) {
1406 if (node->type == GFX_TEXT && eps_add_font(state, node) == -1)
1409 eps_list_fonts(state, "%%DocumentFonts:");
1410 eps_list_fonts(state, "%%DocumentNeededFonts:");
1414 "%%EndProlog\n" /* must have, or BoundingBox is ignored */
1415 "/bd { bind def } bind def\n"
1417 fprintf(state->fp, "/X { %.2f add } bd\n", LINEOFFSET);
1419 "/X2 {X exch X exch} bd\n"
1420 "/M {X2 moveto} bd\n"
1421 "/L {X2 lineto} bd\n"
1425 "/CP {closepath} bd\n"
1426 "/WS {setlinewidth stroke} bd\n"
1429 "/TaC {dup stringwidth pop neg 2 div 0 rmoveto } bd\n"
1430 "/TaR {dup stringwidth pop neg 0 rmoveto } bd\n"
1431 "/TL {moveto TaL show} bd\n"
1432 "/TC {moveto TaC show} bd\n"
1433 "/TR {moveto TaR show} bd\n"
1434 "/Rgb { 255.0 div 3 1 roll\n"
1435 " 255.0 div 3 1 roll \n"
1436 " 255.0 div 3 1 roll setrgbcolor } bd\n"
1438 eps_define_fonts(state);
1442 static void eps_clear_dash(eps_state *state)
1444 if (!state->has_dash)
1446 state->has_dash = 0;
1447 fputs("[1 0] 0 setdash\n", state->fp);
1450 static void eps_write_linearea(eps_state *state, gfx_node_t *node)
1453 FILE *fp = state->fp;
1455 int clearDashIfAny = 1;
1456 eps_set_color(state, node->color);
1457 if (node->type == GFX_LINE) {
1459 if (state->linecap != 1) {
1460 fputs("1 setlinecap\n", fp);
1463 if (state->linejoin != 1) {
1464 fputs("1 setlinejoin\n", fp);
1465 state->linejoin = 1;
1467 svg_get_dash(node, &dash_info);
1468 if (dash_info.dash_enable) {
1470 state->has_dash = 1;
1472 svg_write_number(fp, dash_info.adjusted_on);
1474 svg_write_number(fp, dash_info.adjusted_off);
1476 svg_write_number(fp, dash_info.dash_offset);
1477 fputs(" setdash\n", fp);
1481 eps_clear_dash(state);
1482 for (i = 0; i < node->points; i++) {
1483 ArtVpath *vec = node->path + i;
1485 double y = state->page_height - vec->y;
1486 if (vec->code == ART_MOVETO_OPEN || vec->code == ART_MOVETO)
1487 useOffset = (fabs(x - floor(x) - 0.5) < 0.01 && fabs(y - floor(y) - 0.5) < 0.01);
1492 switch (vec->code) {
1493 case ART_MOVETO_OPEN: /* fall-through */
1495 svg_write_number(fp, x);
1497 svg_write_number(fp, y);
1499 fputs(useOffset ? "M\n" : "m\n", fp);
1502 svg_write_number(fp, x);
1504 svg_write_number(fp, y);
1506 fputs(useOffset ? "L\n" : "l\n", fp);
1508 case ART_CURVETO: break; /* unsupported */
1509 case ART_END: break; /* nop */
1512 if (node->type == GFX_LINE) {
1513 if (node->closed_path)
1515 if (node->size != state->line_width) {
1516 state->line_width = node->size;
1517 svg_write_number(fp, state->line_width);
1527 static void eps_write_text(eps_state *state, gfx_node_t *node)
1529 FILE *fp = state->fp;
1530 const unsigned char *p;
1531 const char *ps_font = afm_get_font_postscript_name(node->filename);
1534 double y = state->page_height - node->y, ydelta = 0;
1536 eps_set_color(state, node->color);
1537 if (strcmp(ps_font, state->font) || node->size != state->font_size) {
1538 state->font = ps_font;
1539 state->font_size = node->size;
1540 svg_write_number(fp, state->font_size);
1541 fprintf(fp, " SetFont-%s\n", state->font);
1545 for (p = (const unsigned char*)node->text; *p; p++) {
1547 fputs("\\\n", fp); /* backslash and \n */
1562 fprintf(fp, "\\%03o", *p);
1569 switch(node->valign){
1570 case GFX_V_TOP: ydelta = -node->size; break;
1571 case GFX_V_CENTER: ydelta = -node->size / 3.0; break;
1572 case GFX_V_BOTTOM: break;
1573 case GFX_V_NULL: break;
1575 if (node->angle == 0)
1577 switch (node->halign) {
1578 case GFX_H_RIGHT: align = 'R'; break;
1579 case GFX_H_CENTER: align = 'C'; break;
1580 case GFX_H_LEFT: align= 'L'; break;
1581 case GFX_H_NULL: align= 'L'; break;
1583 if (node->angle != 0) {
1585 fputs(" gsave ", fp);
1586 svg_write_number(fp, x);
1588 svg_write_number(fp, y);
1589 fputs(" translate ", fp);
1590 svg_write_number(fp, -node->angle);
1591 fputs(" rotate 0 ", fp);
1592 svg_write_number(fp, ydelta);
1593 fputs(" moveto ", fp);
1594 fprintf(fp, "Ta%c", align);
1595 fputs(" show grestore\n", fp);
1597 svg_write_number(fp, x);
1599 svg_write_number(fp, y);
1606 static int eps_write_content(eps_state *state)
1609 fputs("%\n", state->fp);
1610 for (node = state->canvas->firstnode; node; node = node->next) {
1611 switch (node->type) {
1614 eps_write_linearea(state, node);
1617 eps_write_text(state, node);
1624 int gfx_render_eps (gfx_canvas_t *canvas,
1625 art_u32 width, art_u32 height,
1626 gfx_color_t background, FILE *fp){
1627 struct eps_state state;
1629 state.canvas = canvas;
1630 state.page_width = width;
1631 state.page_height = height;
1632 state.font = "no-default-font";
1633 state.font_size = -1;
1634 state.color = 0; /* black */
1635 state.font_list = NULL;
1637 state.linejoin = -1;
1639 if (eps_prologue(&state) == -1)
1641 eps_set_color(&state, background);
1642 fprintf(fp, "0 0 M 0 %d L %d %d L %d 0 L fill\n",
1643 height, width, height, width);
1644 if (eps_write_content(&state) == -1)
1646 fputs("showpage\n", fp);
1647 fputs("%%EOF\n", fp);
1648 while (state.font_list) {
1649 eps_font *next = state.font_list->next;
1650 free(state.font_list);
1651 state.font_list = next;
1656 /* ------- PDF -------
1657 PDF references page:
1658 http://partners.adobe.com/asn/developer/technotes/acrobatpdf.html
1661 typedef struct pdf_buffer
1663 int id, is_obj, is_dict, is_stream, pdf_file_pos;
1665 int alloc_size, current_size;
1666 struct pdf_buffer *previous_buffer, *next_buffer;
1667 struct pdf_state *state;
1670 typedef struct pdf_font
1672 const char *ps_font;
1674 struct pdf_font *next;
1677 typedef struct pdf_state
1680 gfx_canvas_t *canvas;
1681 art_u32 page_width, page_height;
1682 pdf_font *font_list;
1683 pdf_buffer *first_buffer, *last_buffer;
1687 gfx_color_t stroke_color, fill_color;
1692 int linecap, linejoin;
1695 pdf_buffer pdf_header;
1696 pdf_buffer catalog_obj, pages_obj, page1_obj;
1697 pdf_buffer fontsdict_obj;
1698 pdf_buffer graph_stream;
1701 static void pdf_init_buffer(pdf_state *state, pdf_buffer *buf)
1703 int initial_size = 32;
1706 buf->alloc_size = 0;
1707 buf->current_size = 0;
1708 buf->data = (char*)malloc(initial_size);
1710 buf->previous_buffer = NULL;
1711 buf->next_buffer = NULL;
1712 if (buf->data == NULL) {
1713 rrd_set_error("malloc for pdf_buffer data");
1714 state->has_failed = 1;
1717 buf->alloc_size = initial_size;
1718 if (state->last_buffer)
1719 state->last_buffer->next_buffer = buf;
1720 if (state->first_buffer == NULL)
1721 state->first_buffer = buf;
1722 buf->previous_buffer = state->last_buffer;
1723 state->last_buffer = buf;
1726 static void pdf_put(pdf_buffer *buf, const char *text, int len)
1730 if (buf->alloc_size < buf->current_size + len) {
1731 int new_size = buf->alloc_size;
1733 while (new_size < buf->current_size + len)
1735 new_buf = (char*)malloc(new_size);
1736 if (new_buf == NULL) {
1737 rrd_set_error("re-malloc for pdf_buffer data");
1738 buf->state->has_failed = 1;
1741 memcpy(new_buf, buf->data, buf->current_size);
1743 buf->data = new_buf;
1744 buf->alloc_size = new_size;
1746 memcpy(buf->data + buf->current_size, text, len);
1747 buf->current_size += len;
1750 static void pdf_puts(pdf_buffer *buf, const char *text)
1752 pdf_put(buf, text, strlen(text));
1755 static void pdf_indent(pdf_buffer *buf)
1757 pdf_puts(buf, "\t");
1760 static void pdf_putsi(pdf_buffer *buf, const char *text)
1763 pdf_puts(buf, text);
1766 static void pdf_putint(pdf_buffer *buf, int i)
1769 sprintf(tmp, "%d", i);
1773 static void pdf_putnumber(pdf_buffer *buf, double d)
1776 svg_format_number(tmp, sizeof(tmp), d);
1780 static void pdf_init_object(pdf_state *state, pdf_buffer *buf)
1782 pdf_init_buffer(state, buf);
1783 buf->id = ++state->last_obj_id;
1788 static void pdf_init_dict(pdf_state *state, pdf_buffer *buf)
1790 pdf_init_object(state, buf);
1794 static void pdf_set_color(pdf_buffer *buf, gfx_color_t color,
1795 gfx_color_t *current_color, const char *op)
1797 /* gfx_color_t is RRGGBBAA */
1798 if (*current_color == color)
1800 pdf_putnumber(buf, ((color >> 24) & 255) / 255.0);
1802 pdf_putnumber(buf, ((color >> 16) & 255) / 255.0);
1804 pdf_putnumber(buf, ((color >> 8) & 255) / 255.0);
1807 pdf_puts(buf, "\n");
1808 *current_color = color;
1811 static void pdf_set_stroke_color(pdf_buffer *buf, gfx_color_t color)
1813 pdf_set_color(buf, color, &buf->state->stroke_color, "RG");
1816 static void pdf_set_fill_color(pdf_buffer *buf, gfx_color_t color)
1818 pdf_set_color(buf, color, &buf->state->fill_color, "rg");
1821 static pdf_font *pdf_find_font(pdf_state *state, gfx_node_t *node)
1823 const char *ps_font = afm_get_font_postscript_name(node->filename);
1825 for (ef = state->font_list; ef; ef = ef->next) {
1826 if (!strcmp(ps_font, ef->ps_font))
1832 static void pdf_add_font(pdf_state *state, gfx_node_t *node)
1834 pdf_font *ef = pdf_find_font(state, node);
1837 ef = malloc(sizeof(pdf_font));
1839 rrd_set_error("malloc for pdf_font");
1840 state->has_failed = 1;
1843 pdf_init_dict(state, &ef->obj);
1844 ef->next = state->font_list;
1845 ef->ps_font = afm_get_font_postscript_name(node->filename);
1846 state->font_list = ef;
1848 pdf_putsi(&state->fontsdict_obj, "/F");
1849 pdf_putint(&state->fontsdict_obj, ef->obj.id);
1850 pdf_puts(&state->fontsdict_obj, " ");
1851 pdf_putint(&state->fontsdict_obj, ef->obj.id);
1852 pdf_puts(&state->fontsdict_obj, " 0 R\n");
1854 pdf_putsi(&ef->obj, "/Type /Font\n");
1855 pdf_putsi(&ef->obj, "/Subtype /Type1\n");
1856 pdf_putsi(&ef->obj, "/Name /F");
1857 pdf_putint(&ef->obj, ef->obj.id);
1858 pdf_puts(&ef->obj, "\n");
1859 pdf_putsi(&ef->obj, "/BaseFont /");
1860 pdf_puts(&ef->obj, ef->ps_font);
1861 pdf_puts(&ef->obj, "\n");
1862 pdf_putsi(&ef->obj, "/Encoding /WinAnsiEncoding\n");
1863 /* 'Cp1252' (this is latin 1 extended with 27 characters;
1864 the encoding is also known as 'winansi')
1865 http://www.lowagie.com/iText/tutorial/ch09.html */
1868 static void pdf_create_fonts(pdf_state *state)
1871 for (node = state->canvas->firstnode; node; node = node->next) {
1872 if (node->type == GFX_TEXT)
1873 pdf_add_font(state, node);
1877 static void pdf_write_linearea(pdf_state *state, gfx_node_t *node)
1880 pdf_buffer *s = &state->graph_stream;
1881 if (node->type == GFX_LINE) {
1883 svg_get_dash(node, &dash_info);
1884 if (!svg_dash_equal(&dash_info, &state->dash)) {
1885 state->dash = dash_info;
1886 if (dash_info.dash_enable) {
1888 pdf_putnumber(s, dash_info.adjusted_on);
1890 pdf_putnumber(s, dash_info.adjusted_off);
1892 pdf_putnumber(s, dash_info.dash_offset);
1893 pdf_puts(s, " d\n");
1895 pdf_puts(s, "[] 0 d\n");
1898 pdf_set_stroke_color(s, node->color);
1899 if (state->linecap != 1) {
1900 pdf_puts(s, "1 j\n");
1903 if (state->linejoin != 1) {
1904 pdf_puts(s, "1 J\n");
1905 state->linejoin = 1;
1907 if (node->size != state->line_width) {
1908 state->line_width = node->size;
1909 pdf_putnumber(s, state->line_width);
1910 pdf_puts(s, " w\n");
1913 pdf_set_fill_color(s, node->color);
1915 for (i = 0; i < node->points; i++) {
1916 ArtVpath *vec = node->path + i;
1918 double y = state->page_height - vec->y;
1919 if (node->type == GFX_AREA) {
1920 x += LINEOFFSET; /* adjust for libart handling of areas */
1923 switch (vec->code) {
1924 case ART_MOVETO_OPEN: /* fall-through */
1926 pdf_putnumber(s, x);
1928 pdf_putnumber(s, y);
1929 pdf_puts(s, " m\n");
1932 pdf_putnumber(s, x);
1934 pdf_putnumber(s, y);
1935 pdf_puts(s, " l\n");
1937 case ART_CURVETO: break; /* unsupported */
1938 case ART_END: break; /* nop */
1941 if (node->type == GFX_LINE) {
1942 pdf_puts(s, node->closed_path ? "s\n" : "S\n");
1948 static void pdf_write_text(pdf_state *state, gfx_node_t *node,
1949 int last_was_text, int next_is_text)
1952 pdf_buffer *s = &state->graph_stream;
1953 const unsigned char *p;
1954 pdf_font *font = pdf_find_font(state, node);
1956 double y = state->page_height - node->y;
1957 double dx = 0, dy = 0;
1958 double cos_a = 0, sin_a = 0;
1960 rrd_set_error("font disappeared");
1961 state->has_failed = 1;
1964 switch(node->valign){
1965 case GFX_V_TOP: dy = -node->size; break;
1966 case GFX_V_CENTER: dy = -node->size / 3.0; break;
1967 case GFX_V_BOTTOM: break;
1968 case GFX_V_NULL: break;
1970 switch (node->halign) {
1971 case GFX_H_RIGHT: dx = -afm_get_text_width(0, font->ps_font,
1972 node->size, node->tabwidth, node->text);
1974 case GFX_H_CENTER: dx = -afm_get_text_width(0, font->ps_font,
1975 node->size, node->tabwidth, node->text) / 2;
1977 case GFX_H_LEFT: break;
1978 case GFX_H_NULL: break;
1980 pdf_set_fill_color(s, node->color);
1981 if (node->angle != 0) {
1982 double a = 2 * M_PI * -node->angle / 360.0;
1983 double new_x, new_y;
1986 new_x = cos_a * dx - sin_a * dy + x;
1987 new_y = sin_a * dx + cos_a * dy + y;
1995 pdf_puts(s, "BT\n");
1996 if (state->font_id != font->obj.id || node->size != state->font_size) {
1997 state->font_id = font->obj.id;
1998 state->font_size = node->size;
2000 pdf_putint(s, font->obj.id);
2002 pdf_putnumber(s, node->size);
2003 pdf_puts(s, " Tf\n");
2005 if (node->angle == 0) {
2006 pdf_puts(s, "1 0 0 1 ");
2008 pdf_putnumber(s, cos_a);
2010 pdf_putnumber(s, sin_a);
2012 pdf_putnumber(s, -sin_a);
2014 pdf_putnumber(s, cos_a);
2017 pdf_putnumber(s, x);
2019 pdf_putnumber(s, y);
2020 pdf_puts(s, " Tm\n");
2022 for (p = (const unsigned char*)node->text; *p; p++) {
2034 snprintf(tmp, sizeof(tmp), "\\%03o", *p);
2037 pdf_put(s, (const char*)p, 1);
2041 pdf_puts(s, ") Tj\n");
2043 pdf_puts(s, "ET\n");
2046 static void pdf_write_content(pdf_state *state)
2049 int last_was_text = 0, next_is_text;
2050 for (node = state->canvas->firstnode; node; node = node->next) {
2051 switch (node->type) {
2054 pdf_write_linearea(state, node);
2057 next_is_text = node->next && node->next->type == GFX_TEXT;
2058 pdf_write_text(state, node, last_was_text, next_is_text);
2061 last_was_text = node->type == GFX_TEXT;
2065 static void pdf_init_document(pdf_state *state)
2067 pdf_init_buffer(state, &state->pdf_header);
2068 pdf_init_dict(state, &state->catalog_obj);
2069 pdf_init_dict(state, &state->pages_obj);
2070 pdf_init_dict(state, &state->page1_obj);
2071 pdf_init_dict(state, &state->fontsdict_obj);
2072 pdf_create_fonts(state);
2073 if (state->has_failed)
2075 /* make stream last object in file */
2076 pdf_init_object(state, &state->graph_stream);
2077 state->graph_stream.is_stream = 1;
2080 static void pdf_setup_document(pdf_state *state)
2082 /* all objects created by now, so init code can reference them */
2084 pdf_puts(&state->pdf_header, "%PDF-1.3\n");
2085 /* following 8 bit comment is recommended by Adobe for
2086 indicating binary file to file transfer applications */
2087 pdf_puts(&state->pdf_header, "%\xE2\xE3\xCF\xD3\n");
2089 pdf_putsi(&state->catalog_obj, "/Type /Catalog\n");
2090 pdf_putsi(&state->catalog_obj, "/Pages ");
2091 pdf_putint(&state->catalog_obj, state->pages_obj.id);
2092 pdf_puts(&state->catalog_obj, " 0 R\n");
2094 pdf_putsi(&state->pages_obj, "/Type /Pages\n");
2095 pdf_putsi(&state->pages_obj, "/Kids [");
2096 pdf_putint(&state->pages_obj, state->page1_obj.id);
2097 pdf_puts(&state->pages_obj, " 0 R]\n");
2098 pdf_putsi(&state->pages_obj, "/Count 1\n");
2100 pdf_putsi(&state->page1_obj, "/Type /Page\n");
2101 pdf_putsi(&state->page1_obj, "/Parent ");
2102 pdf_putint(&state->page1_obj, state->pages_obj.id);
2103 pdf_puts(&state->page1_obj, " 0 R\n");
2104 pdf_putsi(&state->page1_obj, "/MediaBox [0 0 ");
2105 pdf_putint(&state->page1_obj, state->page_width);
2106 pdf_puts(&state->page1_obj, " ");
2107 pdf_putint(&state->page1_obj, state->page_height);
2108 pdf_puts(&state->page1_obj, "]\n");
2109 pdf_putsi(&state->page1_obj, "/Contents ");
2110 pdf_putint(&state->page1_obj, state->graph_stream.id);
2111 pdf_puts(&state->page1_obj, " 0 R\n");
2112 pdf_putsi(&state->page1_obj, "/Resources << /Font ");
2113 pdf_putint(&state->page1_obj, state->fontsdict_obj.id);
2114 pdf_puts(&state->page1_obj, " 0 R >>\n");
2117 static void pdf_write_string_to_file(pdf_state *state, const char *text)
2119 fputs(text, state->fp);
2120 state->pdf_file_pos += strlen(text);
2123 static void pdf_write_buf_to_file(pdf_state *state, pdf_buffer *buf)
2126 buf->pdf_file_pos = state->pdf_file_pos;
2128 snprintf(tmp, sizeof(tmp), "%d 0 obj\n", buf->id);
2129 pdf_write_string_to_file(state, tmp);
2132 pdf_write_string_to_file(state, "<<\n");
2133 if (buf->is_stream) {
2134 snprintf(tmp, sizeof(tmp), "<< /Length %d >>\n", buf->current_size);
2135 pdf_write_string_to_file(state, tmp);
2136 pdf_write_string_to_file(state, "stream\n");
2138 fwrite(buf->data, 1, buf->current_size, state->fp);
2139 state->pdf_file_pos += buf->current_size;
2141 pdf_write_string_to_file(state, "endstream\n");
2143 pdf_write_string_to_file(state, ">>\n");
2145 pdf_write_string_to_file(state, "endobj\n");
2148 static void pdf_write_to_file(pdf_state *state)
2150 pdf_buffer *buf = state->first_buffer;
2152 state->pdf_file_pos = 0;
2153 pdf_write_buf_to_file(state, &state->pdf_header);
2156 pdf_write_buf_to_file(state, buf);
2157 buf = buf->next_buffer;
2159 xref_pos = state->pdf_file_pos;
2160 fprintf(state->fp, "xref\n");
2161 fprintf(state->fp, "%d %d\n", 0, state->last_obj_id + 1);
2162 /* TOC lines must be exactly 20 bytes including \n */
2163 fprintf(state->fp, "%010d %05d f\x20\n", 0, 65535);
2164 for (buf = state->first_buffer; buf; buf = buf->next_buffer) {
2166 fprintf(state->fp, "%010d %05d n\x20\n", buf->pdf_file_pos, 0);
2168 fprintf(state->fp, "trailer\n");
2169 fprintf(state->fp, "<<\n");
2170 fprintf(state->fp, "\t/Size %d\n", state->last_obj_id + 1);
2171 fprintf(state->fp, "\t/Root %d 0 R\n", state->catalog_obj.id);
2172 fprintf(state->fp, ">>\n");
2173 fprintf(state->fp, "startxref\n");
2174 fprintf(state->fp, "%d\n", xref_pos);
2175 fputs("%%EOF\n", state->fp);
2178 static void pdf_free_resources(pdf_state *state)
2180 pdf_buffer *buf = state->first_buffer;
2184 buf->alloc_size = buf->current_size = 0;
2185 buf = buf->next_buffer;
2187 while (state->font_list) {
2188 pdf_font *next = state->font_list->next;
2189 free(state->font_list);
2190 state->font_list = next;
2194 int gfx_render_pdf (gfx_canvas_t *canvas,
2195 art_u32 width, art_u32 height,
2196 gfx_color_t background, FILE *fp){
2197 struct pdf_state state;
2198 memset(&state, 0, sizeof(pdf_state));
2200 state.canvas = canvas;
2201 state.page_width = width;
2202 state.page_height = height;
2204 state.font_size = -1;
2205 state.font_list = NULL;
2207 state.linejoin = -1;
2208 pdf_init_document(&state);
2210 pdf_set_color(&state, background);
2211 fprintf(fp, "0 0 M 0 %d L %d %d L %d 0 L fill\n",
2212 height, width, height, width);
2214 if (!state.has_failed)
2215 pdf_write_content(&state);
2216 if (!state.has_failed)
2217 pdf_setup_document(&state);
2218 if (!state.has_failed)
2219 pdf_write_to_file(&state);
2220 pdf_free_resources(&state);
2221 return state.has_failed ? -1 : 0;