1 /****************************************************************************
2 * RRDtool 1.2rc7 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 */
376 ft_pen.x = 0; /* start at (0,0) !! */
379 string = (gfx_string) malloc (sizeof(struct gfx_string_s));
382 string->count = strlen (text);
383 string->glyphs = (gfx_char) calloc (string->count,sizeof(struct gfx_char_s));
384 string->num_glyphs = 0;
385 string->transform.xx = (FT_Fixed)( cos(M_PI*(rotation)/180.0)*0x10000);
386 string->transform.xy = (FT_Fixed)(-sin(M_PI*(rotation)/180.0)*0x10000);
387 string->transform.yx = (FT_Fixed)( sin(M_PI*(rotation)/180.0)*0x10000);
388 string->transform.yy = (FT_Fixed)( cos(M_PI*(rotation)/180.0)*0x10000);
390 use_kerning = FT_HAS_KERNING(face);
392 glyph = string->glyphs;
393 for (n=0; n<string->count; n++, glyph++) {
395 /* handle the tabs ...
396 have a witespace glyph inserted, but set its width such that the distance
397 of the new right edge is x times tabwidth from 0,0 where x is an integer. */
398 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++;
474 /* printf ("number of glyphs = %d\n", string->num_glyphs);*/
475 compute_string_bbox( string );
476 /* the last character was a tab */
478 string->width = ft_pen.x;
480 string->width = string->bbox.xMax - string->bbox.xMin;
482 string->height = string->bbox.yMax - string->bbox.yMin;
487 static int gfx_save_png (art_u8 *buffer, FILE *fp,
488 long width, long height, long bytes_per_pixel);
489 /* render grafics into png image */
491 int gfx_render_png (gfx_canvas_t *canvas,
492 art_u32 width, art_u32 height,
493 gfx_color_t background, FILE *fp){
497 gfx_node_t *node = canvas->firstnode;
499 art_u8 red = background >> 24, green = (background >> 16) & 0xff;
500 art_u8 blue = (background >> 8) & 0xff, alpha = ( background & 0xff );
502 unsigned long pys_width = width * canvas->zoom;
503 unsigned long pys_height = height * canvas->zoom;
504 const int bytes_per_pixel = 4;
505 unsigned long rowstride = pys_width*bytes_per_pixel; /* bytes per pixel */
506 art_u8 *buffer = art_new (art_u8, rowstride*pys_height);
507 /* fill that buffer with out background color */
510 for (i=0,buffp=(gfx_color_t *)buffer;
511 i<pys_width*pys_height;
513 *(buffp++)=background;
515 FT_Init_FreeType( &library );
517 switch (node->type) {
523 art_affine_scale(dst,canvas->zoom,canvas->zoom);
524 vec = art_vpath_affine_transform(node->path,dst);
525 if (node->closed_path)
526 gfx_libart_close_path(node, &vec);
527 /* gfx_round_scaled_coordinates(vec); */
528 pvec = art_vpath_perturb(vec);
530 if(node->type == GFX_LINE){
531 svp = art_svp_vpath_stroke ( pvec, ART_PATH_STROKE_JOIN_ROUND,
532 ART_PATH_STROKE_CAP_ROUND,
533 node->size*canvas->zoom,4,0.25);
535 svp = art_svp_from_vpath ( pvec );
536 svpt = art_svp_uncross( svp );
538 svp = art_svp_rewind_uncrossed(svpt,ART_WIND_RULE_NONZERO);
542 /* this is from gnome since libart does not have this yet */
543 gnome_print_art_rgba_svp_alpha (svp ,0,0, pys_width, pys_height,
544 node->color, buffer, rowstride, NULL);
551 art_u8 fcolor[4],falpha;
555 FT_Vector vec; /* 26.6 */
557 float pen_x = 0.0 , pen_y = 0.0;
561 fcolor[0] = node->color >> 24;
562 fcolor[1] = (node->color >> 16) & 0xff;
563 fcolor[2] = (node->color >> 8) & 0xff;
564 falpha = node->color & 0xff;
565 error = FT_New_Face( library,
566 (char *)node->filename,
570 rrd_set_error("failed to load %s",node->filename);
573 error = FT_Set_Char_Size(face, /* handle to face object */
574 (long)(node->size*64),
575 (long)(node->size*64),
576 (long)(100*canvas->zoom),
577 (long)(100*canvas->zoom));
579 pen_x = node->x * canvas->zoom;
580 pen_y = node->y * canvas->zoom;
582 string = gfx_string_create (face, node->text, node->angle, node->tabwidth);
583 switch(node->halign){
584 case GFX_H_RIGHT: vec.x = -string->bbox.xMax;
586 case GFX_H_CENTER: vec.x = abs(string->bbox.xMax) >= abs(string->bbox.xMin) ?
587 -string->bbox.xMax/2:-string->bbox.xMin/2;
589 case GFX_H_LEFT: vec.x = -string->bbox.xMin;
591 case GFX_H_NULL: vec.x = 0;
595 switch(node->valign){
596 case GFX_V_TOP: vec.y = string->bbox.yMax;
598 case GFX_V_CENTER: vec.y = abs(string->bbox.yMax) >= abs(string->bbox.yMin) ?
599 string->bbox.yMax/2:string->bbox.yMin/2;
601 case GFX_V_BOTTOM: vec.y = 0;
603 case GFX_V_NULL: vec.y = 0;
608 glyph = string->glyphs;
609 for(n=0; n<string->num_glyphs; ++n, ++glyph) {
613 /* long buf_x,comp_n; */
614 /* make copy to transform */
615 if (! glyph->image) {
616 fprintf (stderr, "no image\n");
619 error = FT_Glyph_Copy (glyph->image, &image);
621 fprintf (stderr, "couldn't copy image\n");
627 FT_Vector_Transform (&vec, &string->transform);
629 bit = (FT_BitmapGlyph) image;
630 gr = bit->bitmap.num_grays -1;
632 buf_x = (pen_x + 0.5) + (double)bit->left;
633 comp_n = buf_x + bit->bitmap.width > pys_width ? pys_width - buf_x : bit->bitmap.width;
634 if (buf_x < 0 || buf_x >= (long)pys_width) continue;
635 buf_x *= bytes_per_pixel ;
636 for (iy=0; iy < bit->bitmap.rows; iy++){
637 long buf_y = iy+(pen_y+0.5)-(double)bit->top;
638 if (buf_y < 0 || buf_y >= (long)pys_height) continue;
640 for (ix=0;ix < bit->bitmap.width;ix++){
641 *(letter + (ix*bytes_per_pixel+3)) = *(bit->bitmap.buffer + iy * bit->bitmap.width + ix);
643 art_rgba_rgba_composite(buffer + buf_y + buf_x ,letter,comp_n);
648 for (iy=0; iy < bit->bitmap.rows; iy++){
649 long buf_y = iy+(pen_y+0.5)-bit->top;
650 if (buf_y < 0 || buf_y >= (long)pys_height) continue;
652 for (ix=0;ix < bit->bitmap.width;ix++){
653 long buf_x = ix + (pen_x + 0.5) + (double)bit->left ;
656 if (buf_x < 0 || buf_x >= (long)pys_width) continue;
657 buf_x *= bytes_per_pixel ;
658 font_alpha = *(bit->bitmap.buffer + iy * bit->bitmap.width + ix);
660 fcolor[3] = (art_u8)((double)font_alpha / gr * falpha);
661 art_rgba_rgba_composite(buffer + buf_y + buf_x ,fcolor,1);
667 for (iy=0; iy < bit->bitmap.rows; iy++){
668 long buf_y = iy+(pen_y+0.5)-bit->top;
669 if (buf_y < 0 || buf_y >= (long)pys_height) continue;
671 for (ix=0;ix < bit->bitmap.width;ix++){
672 long buf_x = ix + (pen_x + 0.5) + (double)bit->left ;
675 if (buf_x < 0 || buf_x >= (long)pys_width) continue;
676 buf_x *= bytes_per_pixel ;
677 font_alpha = *(bit->bitmap.buffer + iy * bit->bitmap.width + ix);
678 font_alpha = (art_u8)((double)font_alpha / gr * falpha);
679 for (iz = 0; iz < 3; iz++){
680 art_u8 *orig = buffer + buf_y + buf_x + iz;
681 *orig = (art_u8)((double)*orig / gr * ( gr - font_alpha) +
682 (double)fcolor[iz] / gr * (font_alpha));
687 FT_Done_Glyph (image);
689 gfx_string_destroy(string);
694 gfx_save_png(buffer,fp , pys_width,pys_height,bytes_per_pixel);
696 FT_Done_FreeType( library );
700 /* free memory used by nodes this will also remove memory required for
701 associated paths and svcs ... but not for text strings */
703 gfx_destroy (gfx_canvas_t *canvas){
704 gfx_node_t *next,*node = canvas->firstnode;
707 art_free(node->path);
709 free(node->filename);
717 static int gfx_save_png (art_u8 *buffer, FILE *fp, long width, long height, long bytes_per_pixel){
718 png_structp png_ptr = NULL;
719 png_infop info_ptr = NULL;
721 png_bytep *row_pointers;
722 int rowstride = width * bytes_per_pixel;
728 png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING,NULL,NULL,NULL);
733 row_pointers = (png_bytepp)png_malloc(png_ptr,
734 height*sizeof(png_bytep));
736 info_ptr = png_create_info_struct(png_ptr);
738 if (info_ptr == NULL)
740 png_free(png_ptr,row_pointers);
741 png_destroy_write_struct(&png_ptr, (png_infopp)NULL);
745 if (setjmp(png_jmpbuf(png_ptr)))
747 /* If we get here, we had a problem writing the file */
748 png_destroy_write_struct(&png_ptr, &info_ptr);
752 png_init_io(png_ptr, fp);
753 png_set_IHDR (png_ptr, info_ptr,width, height,
754 8, PNG_COLOR_TYPE_RGB_ALPHA,
756 PNG_COMPRESSION_TYPE_DEFAULT,
757 PNG_FILTER_TYPE_DEFAULT);
759 text[0].key = "Software";
760 text[0].text = "RRDtool, Tobias Oetiker <tobi@oetike.ch>, http://tobi.oetiker.ch";
761 text[0].compression = PNG_TEXT_COMPRESSION_NONE;
762 png_set_text (png_ptr, info_ptr, text, 1);
764 /* lets make this fast */
765 png_set_filter(png_ptr,0,PNG_FILTER_NONE);
766 png_set_compression_level(png_ptr,1);
767 png_set_compression_strategy(png_ptr,Z_HUFFMAN_ONLY);
769 png_set_filter(png_ptr,PNG_FILTER_TYPE_BASE,PNG_FILTER_SUB);
770 png_set_compression_strategy(png_ptr,Z_HUFFMAN_ONLY);
771 png_set_compression_level(png_ptr,Z_BEST_SPEED); */
773 /* Write header data */
774 png_write_info (png_ptr, info_ptr);
775 for (i = 0; i < height; i++)
776 row_pointers[i] = (png_bytep) (buffer + i*rowstride);
778 png_write_image(png_ptr, row_pointers);
779 png_write_end(png_ptr, info_ptr);
780 png_free(png_ptr,row_pointers);
781 png_destroy_write_struct(&png_ptr, &info_ptr);
786 /* ------- SVG -------
788 http://www.w3.org/TR/SVG/
790 static int svg_indent = 0;
791 static int svg_single_line = 0;
792 static const char *svg_default_font = "Helvetica";
793 typedef struct svg_dash
796 double dash_adjust, dash_len, dash_offset;
797 double adjusted_on, adjusted_off;
801 static void svg_print_indent(FILE *fp)
804 for (i = svg_indent - svg_single_line; i > 0; i--) {
810 static void svg_start_tag(FILE *fp, const char *name)
812 svg_print_indent(fp);
818 static void svg_close_tag_single_line(FILE *fp)
824 static void svg_close_tag(FILE *fp)
827 if (!svg_single_line)
831 static void svg_end_tag(FILE *fp, const char *name)
833 /* name is NULL if closing empty-node tag */
838 svg_print_indent(fp);
848 static void svg_close_tag_empty_node(FILE *fp)
850 svg_end_tag(fp, NULL);
853 static void svg_write_text(FILE *fp, const char *text)
855 const unsigned char *p, *start, *last;
857 p = (const unsigned char*)text;
860 /* trim leading spaces */
864 /* trim trailing spaces */
866 while ((ch = *p) != 0) {
871 /* encode trimmed text */
875 ch = afm_host2unicode(ch); /* unsafe macro */
877 case '&': fputs("&", fp); break;
878 case '<': fputs("<", fp); break;
879 case '>': fputs(">", fp); break;
880 case '"': fputs(""", fp); break;
883 fprintf(fp, "&#%d;", ch);
890 static void svg_format_number(char *buf, int bufsize, double d)
892 /* omit decimals if integer to reduce filesize */
894 snprintf(buf, bufsize, "%.2f", d);
895 p = buf; /* doesn't trust snprintf return value */
901 *p = '\0'; /* zap trailing zeros */
905 *p = '\0'; /* zap trailing dot */
910 static void svg_write_number(FILE *fp, double d)
913 svg_format_number(buf, sizeof(buf), d);
917 static int svg_color_is_black(int c)
919 /* gfx_color_t is RRGGBBAA */
920 return c == 0x000000FF;
923 static void svg_write_color(FILE *fp, gfx_color_t c, const char *attr)
925 /* gfx_color_t is RRGGBBAA, svg can use #RRGGBB and #RGB like html */
926 gfx_color_t rrggbb = (int)((c >> 8) & 0xFFFFFF);
927 gfx_color_t opacity = c & 0xFF;
928 fprintf(fp, " %s=\"", attr);
929 if ((rrggbb & 0x0F0F0F) == ((rrggbb >> 4) & 0x0F0F0F)) {
930 /* css2 short form, #rgb is #rrggbb, not #r0g0b0 */
931 fprintf(fp, "#%03lX",
932 ( ((rrggbb >> 8) & 0xF00)
933 | ((rrggbb >> 4) & 0x0F0)
934 | ( rrggbb & 0x00F)));
936 fprintf(fp, "#%06lX", rrggbb);
939 if (opacity != 0xFF) {
940 fprintf(fp, " stroke-opacity=\"");
941 svg_write_number(fp, opacity / 255.0);
946 static void svg_get_dash(gfx_node_t *node, svg_dash *d)
950 if (node->dash_on <= 0 || node->dash_off <= 0) {
955 d->dash_len = node->dash_on + node->dash_off;
956 /* dash on/off adjustment due to round caps */
957 d->dash_adjust = 0.8 * node->size;
958 d->adjusted_on = node->dash_on - d->dash_adjust;
959 if (d->adjusted_on < 0.01)
960 d->adjusted_on = 0.01;
961 d->adjusted_off = d->dash_len - d->adjusted_on;
962 /* dash offset calc */
963 if (node->path[0].x == node->path[1].x) /* only good for horz/vert lines */
964 offset = node->path[0].y;
966 offset = node->path[0].x;
967 mult = (int)fabs(offset / d->dash_len);
968 d->dash_offset = offset - mult * d->dash_len;
969 if (node->path[0].x < node->path[1].x || node->path[0].y < node->path[1].y)
970 d->dash_offset = d->dash_len - d->dash_offset;
973 static int svg_dash_equal(svg_dash *a, svg_dash *b)
975 if (a->dash_enable != b->dash_enable)
977 if (a->adjusted_on != b->adjusted_on)
979 if (a->adjusted_off != b->adjusted_off)
981 /* rest of properties will be the same when on+off are */
985 static void svg_common_path_attributes(FILE *fp, gfx_node_t *node)
988 svg_get_dash(node, &dash_info);
989 fputs(" stroke-width=\"", fp);
990 svg_write_number(fp, node->size);
992 svg_write_color(fp, node->color, "stroke");
993 fputs(" fill=\"none\"", fp);
994 if (dash_info.dash_enable) {
995 if (dash_info.dash_offset != 0) {
996 fputs(" stroke-dashoffset=\"", fp);
997 svg_write_number(fp, dash_info.dash_offset);
1000 fputs(" stroke-dasharray=\"", fp);
1001 svg_write_number(fp, dash_info.adjusted_on);
1003 svg_write_number(fp, dash_info.adjusted_off);
1008 static int svg_is_int_step(double a, double b)
1010 double diff = fabs(a - b);
1011 return floor(diff) == diff;
1014 static int svg_path_straight_segment(FILE *fp,
1015 double lastA, double currentA, double currentB,
1017 int segment_idx, int isx, char absChar, char relChar)
1019 if (!svg_is_int_step(lastA, currentA)) {
1021 svg_write_number(fp, currentA);
1024 if (segment_idx < node->points - 1) {
1025 ArtVpath *vec = node->path + segment_idx + 1;
1026 if (vec->code == ART_LINETO) {
1027 double nextA = (isx ? vec->x : vec->y) - LINEOFFSET;
1028 double nextB = (isx ? vec->y : vec->x) - LINEOFFSET;
1029 if (nextB == currentB
1030 && ((currentA >= lastA) == (nextA >= currentA))
1031 && svg_is_int_step(currentA, nextA)) {
1032 return 1; /* skip to next as it is a straight line */
1037 svg_write_number(fp, currentA - lastA);
1041 static void svg_path(FILE *fp, gfx_node_t *node, int multi)
1044 double lastX = 0, lastY = 0;
1045 /* for straight lines <path..> tags take less space than
1046 <line..> tags because of the efficient packing
1047 in the 'd' attribute */
1048 svg_start_tag(fp, "path");
1050 svg_common_path_attributes(fp, node);
1052 /* specification of the 'd' attribute: */
1053 /* http://www.w3.org/TR/SVG/paths.html#PathDataGeneralInformation */
1054 for (i = 0; i < node->points; i++) {
1055 ArtVpath *vec = node->path + i;
1056 double x = vec->x - LINEOFFSET;
1057 double y = vec->y - LINEOFFSET;
1058 switch (vec->code) {
1059 case ART_MOVETO_OPEN: /* fall-through */
1062 svg_write_number(fp, x);
1064 svg_write_number(fp, y);
1067 /* try optimize filesize by using minimal lineto commands */
1068 /* without introducing rounding errors. */
1070 if (svg_path_straight_segment(fp, lastY, y, x, node, i, 0, 'V', 'v'))
1072 } else if (y == lastY) {
1073 if (svg_path_straight_segment(fp, lastX, x, y, node, i, 1, 'H', 'h'))
1077 svg_write_number(fp, x);
1079 svg_write_number(fp, y);
1082 case ART_CURVETO: break; /* unsupported */
1083 case ART_END: break; /* nop */
1088 if (node->closed_path)
1091 svg_close_tag_empty_node(fp);
1094 static void svg_multi_path(FILE *fp, gfx_node_t **nodeR)
1096 /* optimize for multiple paths with the same color, penwidth, etc. */
1098 gfx_node_t *node = *nodeR;
1099 gfx_node_t *next = node->next;
1101 if (next->type != node->type
1102 || next->size != node->size
1103 || next->color != node->color
1104 || next->dash_on != node->dash_on
1105 || next->dash_off != node->dash_off)
1111 svg_path(fp, node, 0);
1114 svg_start_tag(fp, "g");
1115 svg_common_path_attributes(fp, node);
1117 while (num && node) {
1118 svg_path(fp, node, 1);
1124 svg_end_tag(fp, "g");
1127 static void svg_area(FILE *fp, gfx_node_t *node)
1130 double startX = 0, startY = 0;
1131 svg_start_tag(fp, "polygon");
1133 svg_write_color(fp, node->color, "fill");
1134 fputs(" points=\"", fp);
1135 for (i = 0; i < node->points; i++) {
1136 ArtVpath *vec = node->path + i;
1137 double x = vec->x - LINEOFFSET;
1138 double y = vec->y - LINEOFFSET;
1139 switch (vec->code) {
1140 case ART_MOVETO_OPEN: /* fall-through */
1142 svg_write_number(fp, x);
1144 svg_write_number(fp, y);
1149 if (i == node->points - 2
1150 && node->path[i + 1].code == ART_END
1151 && fabs(x - startX) < 0.001 && fabs(y - startY) < 0.001) {
1152 break; /* poly area always closed, no need for last point */
1155 svg_write_number(fp, x);
1157 svg_write_number(fp, y);
1159 case ART_CURVETO: break; /* unsupported */
1160 case ART_END: break; /* nop */
1164 svg_close_tag_empty_node(fp);
1167 static void svg_text(FILE *fp, gfx_node_t *node)
1169 double x = node->x - LINEOFFSET;
1170 double y = node->y - LINEOFFSET;
1171 if (node->angle != 0) {
1172 svg_start_tag(fp, "g");
1173 fputs(" transform=\"translate(", fp);
1174 svg_write_number(fp, x);
1176 svg_write_number(fp, y);
1177 fputs(") rotate(", fp);
1178 svg_write_number(fp, node->angle);
1183 switch (node->valign) {
1184 case GFX_V_TOP: y += node->size; break;
1185 case GFX_V_CENTER: y += node->size / 3; break;
1186 case GFX_V_BOTTOM: break;
1187 case GFX_V_NULL: break;
1189 svg_start_tag(fp, "text");
1191 svg_write_number(fp, x);
1192 fputs("\" y=\"", fp);
1193 svg_write_number(fp, y);
1195 /* if (strcmp(node->filename, svg_default_font))
1196 fprintf(fp, " font-family=\"%s\"", node->filename);
1198 fputs("\" font-family=\"Helvetica", fp);
1199 fputs("\" font-size=\"", fp);
1200 svg_write_number(fp, node->size);
1202 if (!svg_color_is_black(node->color))
1203 svg_write_color(fp, node->color, "fill");
1204 switch (node->halign) {
1205 case GFX_H_RIGHT: fputs(" text-anchor=\"end\"", fp); break;
1206 case GFX_H_CENTER: fputs(" text-anchor=\"middle\"", fp); break;
1207 case GFX_H_LEFT: break;
1208 case GFX_H_NULL: break;
1210 svg_close_tag_single_line(fp);
1211 /* support for node->tabwidth missing */
1212 svg_write_text(fp, node->text);
1213 svg_end_tag(fp, "text");
1214 if (node->angle != 0)
1215 svg_end_tag(fp, "g");
1218 int gfx_render_svg (gfx_canvas_t *canvas,
1219 art_u32 width, art_u32 height,
1220 gfx_color_t background, FILE *fp){
1221 gfx_node_t *node = canvas->firstnode;
1223 "<?xml version=\"1.0\" standalone=\"no\"?>\n"
1224 "<!DOCTYPE svg PUBLIC \"-//W3C//DTD SVG 1.0//EN\"\n"
1225 " \"http://www.w3.org/TR/2001/REC-SVG-20010904/DTD/svg10.dtd\">\n"
1227 " SVG file created by RRDtool,\n"
1228 " Tobias Oetiker <tobi@oetike.ch>, http://tobi.oetiker.ch\n"
1230 " The width/height attributes in the outhermost svg node\n"
1231 " are just default sizes for the browser which is used\n"
1232 " if the svg file is openened directly without being\n"
1233 " embedded in an html file.\n"
1234 " The viewBox is the local coord system for rrdtool.\n"
1236 svg_start_tag(fp, "svg");
1237 fputs(" width=\"", fp);
1238 svg_write_number(fp, width * canvas->zoom);
1239 fputs("\" height=\"", fp);
1240 svg_write_number(fp, height * canvas->zoom);
1241 fputs("\" x=\"0\" y=\"0\" viewBox=\"", fp);
1242 svg_write_number(fp, -LINEOFFSET);
1244 svg_write_number(fp, -LINEOFFSET);
1246 svg_write_number(fp, width - LINEOFFSET);
1248 svg_write_number(fp, height - LINEOFFSET);
1249 fputs("\" preserveAspectRatio=\"xMidYMid\"", fp);
1250 fprintf(fp, " font-family=\"%s\"", svg_default_font); /* default font */
1251 fputs(" stroke-linecap=\"round\" stroke-linejoin=\"round\"", fp);
1253 svg_start_tag(fp, "rect");
1254 fprintf(fp, " x=\"0\" y=\"0\" width=\"%d\" height=\"%d\"", width, height);
1255 svg_write_color(fp, background, "fill");
1256 svg_close_tag_empty_node(fp);
1258 switch (node->type) {
1260 svg_multi_path(fp, &node);
1270 svg_end_tag(fp, "svg");
1274 /* ------- EPS -------
1275 EPS and Postscript references:
1276 http://partners.adobe.com/asn/developer/technotes/postscript.html
1279 typedef struct eps_font
1281 const char *ps_font;
1283 struct eps_font *next;
1286 typedef struct eps_state
1289 gfx_canvas_t *canvas;
1290 art_u32 page_width, page_height;
1291 eps_font *font_list;
1297 int linecap, linejoin;
1301 static void eps_set_color(eps_state *state, gfx_color_t color)
1303 /* gfx_color_t is RRGGBBAA */
1304 if (state->color == color)
1306 fprintf(state->fp, "%d %d %d Rgb\n",
1307 (int)((color >> 24) & 255),
1308 (int)((color >> 16) & 255),
1309 (int)((color >> 8) & 255));
1310 state->color = color;
1313 static int eps_add_font(eps_state *state, gfx_node_t *node)
1315 /* The fonts list could be postponed to the end using
1316 (atend), but let's be nice and have them in the header. */
1317 const char *ps_font = afm_get_font_postscript_name(node->filename);
1319 for (ef = state->font_list; ef; ef = ef->next) {
1320 if (!strcmp(ps_font, ef->ps_font))
1323 ef = malloc(sizeof(eps_font));
1325 rrd_set_error("malloc for eps_font");
1328 ef->next = state->font_list;
1329 ef->ps_font = ps_font;
1330 state->font_list = ef;
1334 static void eps_list_fonts(eps_state *state, const char *dscName)
1337 int lineLen = strlen(dscName);
1338 if (!state->font_list)
1340 fputs(dscName, state->fp);
1341 for (ef = state->font_list; ef; ef = ef->next) {
1342 int nameLen = strlen(ef->ps_font);
1343 if (lineLen + nameLen > 100 && lineLen) {
1344 fputs("\n", state->fp);
1345 fputs("%%- \n", state->fp);
1348 fputs(" ", state->fp);
1351 fputs(ef->ps_font, state->fp);
1354 fputs("\n", state->fp);
1357 static void eps_define_fonts(eps_state *state)
1360 if (!state->font_list)
1362 for (ef = state->font_list; ef; ef = ef->next) {
1363 /* PostScript¨ LANGUAGE REFERENCE third edition
1367 "/%s findfont dup length dict begin\n"
1368 "{ 1 index /FID ne {def} {pop pop} ifelse } forall\n"
1369 "/Encoding ISOLatin1Encoding def\n"
1371 "/%s-ISOLatin1 exch definefont pop\n"
1372 "/SetFont-%s { /%s-ISOLatin1 findfont exch scalefont setfont } bd\n",
1373 ef->ps_font, ef->ps_font, ef->ps_font, ef->ps_font);
1377 static int eps_prologue(eps_state *state)
1381 "%!PS-Adobe-3.0 EPSF-3.0\n"
1382 "%%Creator: RRDtool 1.2rc7 Tobias Oetiker, http://tobi.oetiker.ch\n"
1383 /* can't like weird chars here */
1384 "%%Title: (RRDtool output)\n"
1385 "%%DocumentData: Clean7Bit\n"
1387 fprintf(state->fp, "%%%%BoundingBox: 0 0 %d %d\n",
1388 state->page_width, state->page_height);
1389 for (node = state->canvas->firstnode; node; node = node->next) {
1390 if (node->type == GFX_TEXT && eps_add_font(state, node) == -1)
1393 eps_list_fonts(state, "%%DocumentFonts:");
1394 eps_list_fonts(state, "%%DocumentNeededFonts:");
1398 "%%EndProlog\n" /* must have, or BoundingBox is ignored */
1399 "/bd { bind def } bind def\n"
1401 fprintf(state->fp, "/X { %.2f add } bd\n", LINEOFFSET);
1403 "/X2 {X exch X exch} bd\n"
1404 "/M {X2 moveto} bd\n"
1405 "/L {X2 lineto} bd\n"
1409 "/CP {closepath} bd\n"
1410 "/WS {setlinewidth stroke} bd\n"
1413 "/TaC {dup stringwidth pop neg 2 div 0 rmoveto } bd\n"
1414 "/TaR {dup stringwidth pop neg 0 rmoveto } bd\n"
1415 "/TL {moveto TaL show} bd\n"
1416 "/TC {moveto TaC show} bd\n"
1417 "/TR {moveto TaR show} bd\n"
1418 "/Rgb { 255.0 div 3 1 roll\n"
1419 " 255.0 div 3 1 roll \n"
1420 " 255.0 div 3 1 roll setrgbcolor } bd\n"
1422 eps_define_fonts(state);
1426 static void eps_clear_dash(eps_state *state)
1428 if (!state->has_dash)
1430 state->has_dash = 0;
1431 fputs("[1 0] 0 setdash\n", state->fp);
1434 static void eps_write_linearea(eps_state *state, gfx_node_t *node)
1437 FILE *fp = state->fp;
1439 int clearDashIfAny = 1;
1440 eps_set_color(state, node->color);
1441 if (node->type == GFX_LINE) {
1443 if (state->linecap != 1) {
1444 fputs("1 setlinecap\n", fp);
1447 if (state->linejoin != 1) {
1448 fputs("1 setlinejoin\n", fp);
1449 state->linejoin = 1;
1451 svg_get_dash(node, &dash_info);
1452 if (dash_info.dash_enable) {
1454 state->has_dash = 1;
1456 svg_write_number(fp, dash_info.adjusted_on);
1458 svg_write_number(fp, dash_info.adjusted_off);
1460 svg_write_number(fp, dash_info.dash_offset);
1461 fputs(" setdash\n", fp);
1465 eps_clear_dash(state);
1466 for (i = 0; i < node->points; i++) {
1467 ArtVpath *vec = node->path + i;
1469 double y = state->page_height - vec->y;
1470 if (vec->code == ART_MOVETO_OPEN || vec->code == ART_MOVETO)
1471 useOffset = (fabs(x - floor(x) - 0.5) < 0.01 && fabs(y - floor(y) - 0.5) < 0.01);
1476 switch (vec->code) {
1477 case ART_MOVETO_OPEN: /* fall-through */
1479 svg_write_number(fp, x);
1481 svg_write_number(fp, y);
1483 fputs(useOffset ? "M\n" : "m\n", fp);
1486 svg_write_number(fp, x);
1488 svg_write_number(fp, y);
1490 fputs(useOffset ? "L\n" : "l\n", fp);
1492 case ART_CURVETO: break; /* unsupported */
1493 case ART_END: break; /* nop */
1496 if (node->type == GFX_LINE) {
1497 if (node->closed_path)
1499 if (node->size != state->line_width) {
1500 state->line_width = node->size;
1501 svg_write_number(fp, state->line_width);
1511 static void eps_write_text(eps_state *state, gfx_node_t *node)
1513 FILE *fp = state->fp;
1514 const unsigned char *p;
1515 const char *ps_font = afm_get_font_postscript_name(node->filename);
1518 double y = state->page_height - node->y, ydelta = 0;
1520 eps_set_color(state, node->color);
1521 if (strcmp(ps_font, state->font) || node->size != state->font_size) {
1522 state->font = ps_font;
1523 state->font_size = node->size;
1524 svg_write_number(fp, state->font_size);
1525 fprintf(fp, " SetFont-%s\n", state->font);
1529 for (p = (const unsigned char*)node->text; *p; p++) {
1531 fputs("\\\n", fp); /* backslash and \n */
1546 fprintf(fp, "\\%03o", *p);
1553 switch(node->valign){
1554 case GFX_V_TOP: ydelta = -node->size; break;
1555 case GFX_V_CENTER: ydelta = -node->size / 3.0; break;
1556 case GFX_V_BOTTOM: break;
1557 case GFX_V_NULL: break;
1559 if (node->angle == 0)
1561 switch (node->halign) {
1562 case GFX_H_RIGHT: align = 'R'; break;
1563 case GFX_H_CENTER: align = 'C'; break;
1564 case GFX_H_LEFT: align= 'L'; break;
1565 case GFX_H_NULL: align= 'L'; break;
1567 if (node->angle != 0) {
1569 fputs(" gsave ", fp);
1570 svg_write_number(fp, x);
1572 svg_write_number(fp, y);
1573 fputs(" translate ", fp);
1574 svg_write_number(fp, -node->angle);
1575 fputs(" rotate 0 ", fp);
1576 svg_write_number(fp, ydelta);
1577 fputs(" moveto ", fp);
1578 fprintf(fp, "Ta%c", align);
1579 fputs(" show grestore\n", fp);
1581 svg_write_number(fp, x);
1583 svg_write_number(fp, y);
1590 static int eps_write_content(eps_state *state)
1593 fputs("%\n", state->fp);
1594 for (node = state->canvas->firstnode; node; node = node->next) {
1595 switch (node->type) {
1598 eps_write_linearea(state, node);
1601 eps_write_text(state, node);
1608 int gfx_render_eps (gfx_canvas_t *canvas,
1609 art_u32 width, art_u32 height,
1610 gfx_color_t background, FILE *fp){
1611 struct eps_state state;
1613 state.canvas = canvas;
1614 state.page_width = width;
1615 state.page_height = height;
1616 state.font = "no-default-font";
1617 state.font_size = -1;
1618 state.color = 0; /* black */
1619 state.font_list = NULL;
1621 state.linejoin = -1;
1623 if (eps_prologue(&state) == -1)
1625 eps_set_color(&state, background);
1626 fprintf(fp, "0 0 M 0 %d L %d %d L %d 0 L fill\n",
1627 height, width, height, width);
1628 if (eps_write_content(&state) == -1)
1630 fputs("showpage\n", fp);
1631 fputs("%%EOF\n", fp);
1632 while (state.font_list) {
1633 eps_font *next = state.font_list->next;
1634 free(state.font_list);
1635 state.font_list = next;
1640 /* ------- PDF -------
1641 PDF references page:
1642 http://partners.adobe.com/asn/developer/technotes/acrobatpdf.html
1645 typedef struct pdf_buffer
1647 int id, is_obj, is_dict, is_stream, pdf_file_pos;
1649 int alloc_size, current_size;
1650 struct pdf_buffer *previous_buffer, *next_buffer;
1651 struct pdf_state *state;
1654 typedef struct pdf_font
1656 const char *ps_font;
1658 struct pdf_font *next;
1661 typedef struct pdf_state
1664 gfx_canvas_t *canvas;
1665 art_u32 page_width, page_height;
1666 pdf_font *font_list;
1667 pdf_buffer *first_buffer, *last_buffer;
1671 gfx_color_t stroke_color, fill_color;
1676 int linecap, linejoin;
1679 pdf_buffer pdf_header;
1680 pdf_buffer catalog_obj, pages_obj, page1_obj;
1681 pdf_buffer fontsdict_obj;
1682 pdf_buffer graph_stream;
1685 static void pdf_init_buffer(pdf_state *state, pdf_buffer *buf)
1687 int initial_size = 32;
1690 buf->alloc_size = 0;
1691 buf->current_size = 0;
1692 buf->data = (char*)malloc(initial_size);
1694 buf->previous_buffer = NULL;
1695 buf->next_buffer = NULL;
1696 if (buf->data == NULL) {
1697 rrd_set_error("malloc for pdf_buffer data");
1698 state->has_failed = 1;
1701 buf->alloc_size = initial_size;
1702 if (state->last_buffer)
1703 state->last_buffer->next_buffer = buf;
1704 if (state->first_buffer == NULL)
1705 state->first_buffer = buf;
1706 buf->previous_buffer = state->last_buffer;
1707 state->last_buffer = buf;
1710 static void pdf_put(pdf_buffer *buf, const char *text, int len)
1714 if (buf->alloc_size < buf->current_size + len) {
1715 int new_size = buf->alloc_size;
1717 while (new_size < buf->current_size + len)
1719 new_buf = (char*)malloc(new_size);
1720 if (new_buf == NULL) {
1721 rrd_set_error("re-malloc for pdf_buffer data");
1722 buf->state->has_failed = 1;
1725 memcpy(new_buf, buf->data, buf->current_size);
1727 buf->data = new_buf;
1728 buf->alloc_size = new_size;
1730 memcpy(buf->data + buf->current_size, text, len);
1731 buf->current_size += len;
1734 static void pdf_puts(pdf_buffer *buf, const char *text)
1736 pdf_put(buf, text, strlen(text));
1739 static void pdf_indent(pdf_buffer *buf)
1741 pdf_puts(buf, "\t");
1744 static void pdf_putsi(pdf_buffer *buf, const char *text)
1747 pdf_puts(buf, text);
1750 static void pdf_putint(pdf_buffer *buf, int i)
1753 sprintf(tmp, "%d", i);
1757 static void pdf_putnumber(pdf_buffer *buf, double d)
1760 svg_format_number(tmp, sizeof(tmp), d);
1764 static void pdf_init_object(pdf_state *state, pdf_buffer *buf)
1766 pdf_init_buffer(state, buf);
1767 buf->id = ++state->last_obj_id;
1772 static void pdf_init_dict(pdf_state *state, pdf_buffer *buf)
1774 pdf_init_object(state, buf);
1778 static void pdf_set_color(pdf_buffer *buf, gfx_color_t color,
1779 gfx_color_t *current_color, const char *op)
1781 /* gfx_color_t is RRGGBBAA */
1782 if (*current_color == color)
1784 pdf_putnumber(buf, ((color >> 24) & 255) / 255.0);
1786 pdf_putnumber(buf, ((color >> 16) & 255) / 255.0);
1788 pdf_putnumber(buf, ((color >> 8) & 255) / 255.0);
1791 pdf_puts(buf, "\n");
1792 *current_color = color;
1795 static void pdf_set_stroke_color(pdf_buffer *buf, gfx_color_t color)
1797 pdf_set_color(buf, color, &buf->state->stroke_color, "RG");
1800 static void pdf_set_fill_color(pdf_buffer *buf, gfx_color_t color)
1802 pdf_set_color(buf, color, &buf->state->fill_color, "rg");
1805 static pdf_font *pdf_find_font(pdf_state *state, gfx_node_t *node)
1807 const char *ps_font = afm_get_font_postscript_name(node->filename);
1809 for (ef = state->font_list; ef; ef = ef->next) {
1810 if (!strcmp(ps_font, ef->ps_font))
1816 static void pdf_add_font(pdf_state *state, gfx_node_t *node)
1818 pdf_font *ef = pdf_find_font(state, node);
1821 ef = malloc(sizeof(pdf_font));
1823 rrd_set_error("malloc for pdf_font");
1824 state->has_failed = 1;
1827 pdf_init_dict(state, &ef->obj);
1828 ef->next = state->font_list;
1829 ef->ps_font = afm_get_font_postscript_name(node->filename);
1830 state->font_list = ef;
1832 pdf_putsi(&state->fontsdict_obj, "/F");
1833 pdf_putint(&state->fontsdict_obj, ef->obj.id);
1834 pdf_puts(&state->fontsdict_obj, " ");
1835 pdf_putint(&state->fontsdict_obj, ef->obj.id);
1836 pdf_puts(&state->fontsdict_obj, " 0 R\n");
1838 pdf_putsi(&ef->obj, "/Type /Font\n");
1839 pdf_putsi(&ef->obj, "/Subtype /Type1\n");
1840 pdf_putsi(&ef->obj, "/Name /F");
1841 pdf_putint(&ef->obj, ef->obj.id);
1842 pdf_puts(&ef->obj, "\n");
1843 pdf_putsi(&ef->obj, "/BaseFont /");
1844 pdf_puts(&ef->obj, ef->ps_font);
1845 pdf_puts(&ef->obj, "\n");
1846 pdf_putsi(&ef->obj, "/Encoding /WinAnsiEncoding\n");
1847 /* 'Cp1252' (this is latin 1 extended with 27 characters;
1848 the encoding is also known as 'winansi')
1849 http://www.lowagie.com/iText/tutorial/ch09.html */
1852 static void pdf_create_fonts(pdf_state *state)
1855 for (node = state->canvas->firstnode; node; node = node->next) {
1856 if (node->type == GFX_TEXT)
1857 pdf_add_font(state, node);
1861 static void pdf_write_linearea(pdf_state *state, gfx_node_t *node)
1864 pdf_buffer *s = &state->graph_stream;
1865 if (node->type == GFX_LINE) {
1867 svg_get_dash(node, &dash_info);
1868 if (!svg_dash_equal(&dash_info, &state->dash)) {
1869 state->dash = dash_info;
1870 if (dash_info.dash_enable) {
1872 pdf_putnumber(s, dash_info.adjusted_on);
1874 pdf_putnumber(s, dash_info.adjusted_off);
1876 pdf_putnumber(s, dash_info.dash_offset);
1877 pdf_puts(s, " d\n");
1879 pdf_puts(s, "[] 0 d\n");
1882 pdf_set_stroke_color(s, node->color);
1883 if (state->linecap != 1) {
1884 pdf_puts(s, "1 j\n");
1887 if (state->linejoin != 1) {
1888 pdf_puts(s, "1 J\n");
1889 state->linejoin = 1;
1891 if (node->size != state->line_width) {
1892 state->line_width = node->size;
1893 pdf_putnumber(s, state->line_width);
1894 pdf_puts(s, " w\n");
1897 pdf_set_fill_color(s, node->color);
1899 for (i = 0; i < node->points; i++) {
1900 ArtVpath *vec = node->path + i;
1902 double y = state->page_height - vec->y;
1903 if (node->type == GFX_AREA) {
1904 x += LINEOFFSET; /* adjust for libart handling of areas */
1907 switch (vec->code) {
1908 case ART_MOVETO_OPEN: /* fall-through */
1910 pdf_putnumber(s, x);
1912 pdf_putnumber(s, y);
1913 pdf_puts(s, " m\n");
1916 pdf_putnumber(s, x);
1918 pdf_putnumber(s, y);
1919 pdf_puts(s, " l\n");
1921 case ART_CURVETO: break; /* unsupported */
1922 case ART_END: break; /* nop */
1925 if (node->type == GFX_LINE) {
1926 pdf_puts(s, node->closed_path ? "s\n" : "S\n");
1932 static void pdf_write_text(pdf_state *state, gfx_node_t *node,
1933 int last_was_text, int next_is_text)
1936 pdf_buffer *s = &state->graph_stream;
1937 const unsigned char *p;
1938 pdf_font *font = pdf_find_font(state, node);
1940 double y = state->page_height - node->y;
1941 double dx = 0, dy = 0;
1942 double cos_a = 0, sin_a = 0;
1944 rrd_set_error("font disappeared");
1945 state->has_failed = 1;
1948 switch(node->valign){
1949 case GFX_V_TOP: dy = -node->size; break;
1950 case GFX_V_CENTER: dy = -node->size / 3.0; break;
1951 case GFX_V_BOTTOM: break;
1952 case GFX_V_NULL: break;
1954 switch (node->halign) {
1955 case GFX_H_RIGHT: dx = -afm_get_text_width(0, font->ps_font,
1956 node->size, node->tabwidth, node->text);
1958 case GFX_H_CENTER: dx = -afm_get_text_width(0, font->ps_font,
1959 node->size, node->tabwidth, node->text) / 2;
1961 case GFX_H_LEFT: break;
1962 case GFX_H_NULL: break;
1964 pdf_set_fill_color(s, node->color);
1965 if (node->angle != 0) {
1966 double a = 2 * M_PI * -node->angle / 360.0;
1967 double new_x, new_y;
1970 new_x = cos_a * dx - sin_a * dy + x;
1971 new_y = sin_a * dx + cos_a * dy + y;
1979 pdf_puts(s, "BT\n");
1980 if (state->font_id != font->obj.id || node->size != state->font_size) {
1981 state->font_id = font->obj.id;
1982 state->font_size = node->size;
1984 pdf_putint(s, font->obj.id);
1986 pdf_putnumber(s, node->size);
1987 pdf_puts(s, " Tf\n");
1989 if (node->angle == 0) {
1990 pdf_puts(s, "1 0 0 1 ");
1992 pdf_putnumber(s, cos_a);
1994 pdf_putnumber(s, sin_a);
1996 pdf_putnumber(s, -sin_a);
1998 pdf_putnumber(s, cos_a);
2001 pdf_putnumber(s, x);
2003 pdf_putnumber(s, y);
2004 pdf_puts(s, " Tm\n");
2006 for (p = (const unsigned char*)node->text; *p; p++) {
2018 snprintf(tmp, sizeof(tmp), "\\%03o", *p);
2021 pdf_put(s, (const char*)p, 1);
2025 pdf_puts(s, ") Tj\n");
2027 pdf_puts(s, "ET\n");
2030 static void pdf_write_content(pdf_state *state)
2033 int last_was_text = 0, next_is_text;
2034 for (node = state->canvas->firstnode; node; node = node->next) {
2035 switch (node->type) {
2038 pdf_write_linearea(state, node);
2041 next_is_text = node->next && node->next->type == GFX_TEXT;
2042 pdf_write_text(state, node, last_was_text, next_is_text);
2045 last_was_text = node->type == GFX_TEXT;
2049 static void pdf_init_document(pdf_state *state)
2051 pdf_init_buffer(state, &state->pdf_header);
2052 pdf_init_dict(state, &state->catalog_obj);
2053 pdf_init_dict(state, &state->pages_obj);
2054 pdf_init_dict(state, &state->page1_obj);
2055 pdf_init_dict(state, &state->fontsdict_obj);
2056 pdf_create_fonts(state);
2057 if (state->has_failed)
2059 /* make stream last object in file */
2060 pdf_init_object(state, &state->graph_stream);
2061 state->graph_stream.is_stream = 1;
2064 static void pdf_setup_document(pdf_state *state)
2066 /* all objects created by now, so init code can reference them */
2068 pdf_puts(&state->pdf_header, "%PDF-1.3\n");
2069 /* following 8 bit comment is recommended by Adobe for
2070 indicating binary file to file transfer applications */
2071 pdf_puts(&state->pdf_header, "%\xE2\xE3\xCF\xD3\n");
2073 pdf_putsi(&state->catalog_obj, "/Type /Catalog\n");
2074 pdf_putsi(&state->catalog_obj, "/Pages ");
2075 pdf_putint(&state->catalog_obj, state->pages_obj.id);
2076 pdf_puts(&state->catalog_obj, " 0 R\n");
2078 pdf_putsi(&state->pages_obj, "/Type /Pages\n");
2079 pdf_putsi(&state->pages_obj, "/Kids [");
2080 pdf_putint(&state->pages_obj, state->page1_obj.id);
2081 pdf_puts(&state->pages_obj, " 0 R]\n");
2082 pdf_putsi(&state->pages_obj, "/Count 1\n");
2084 pdf_putsi(&state->page1_obj, "/Type /Page\n");
2085 pdf_putsi(&state->page1_obj, "/Parent ");
2086 pdf_putint(&state->page1_obj, state->pages_obj.id);
2087 pdf_puts(&state->page1_obj, " 0 R\n");
2088 pdf_putsi(&state->page1_obj, "/MediaBox [0 0 ");
2089 pdf_putint(&state->page1_obj, state->page_width);
2090 pdf_puts(&state->page1_obj, " ");
2091 pdf_putint(&state->page1_obj, state->page_height);
2092 pdf_puts(&state->page1_obj, "]\n");
2093 pdf_putsi(&state->page1_obj, "/Contents ");
2094 pdf_putint(&state->page1_obj, state->graph_stream.id);
2095 pdf_puts(&state->page1_obj, " 0 R\n");
2096 pdf_putsi(&state->page1_obj, "/Resources << /Font ");
2097 pdf_putint(&state->page1_obj, state->fontsdict_obj.id);
2098 pdf_puts(&state->page1_obj, " 0 R >>\n");
2101 static void pdf_write_string_to_file(pdf_state *state, const char *text)
2103 fputs(text, state->fp);
2104 state->pdf_file_pos += strlen(text);
2107 static void pdf_write_buf_to_file(pdf_state *state, pdf_buffer *buf)
2110 buf->pdf_file_pos = state->pdf_file_pos;
2112 snprintf(tmp, sizeof(tmp), "%d 0 obj\n", buf->id);
2113 pdf_write_string_to_file(state, tmp);
2116 pdf_write_string_to_file(state, "<<\n");
2117 if (buf->is_stream) {
2118 snprintf(tmp, sizeof(tmp), "<< /Length %d >>\n", buf->current_size);
2119 pdf_write_string_to_file(state, tmp);
2120 pdf_write_string_to_file(state, "stream\n");
2122 fwrite(buf->data, 1, buf->current_size, state->fp);
2123 state->pdf_file_pos += buf->current_size;
2125 pdf_write_string_to_file(state, "endstream\n");
2127 pdf_write_string_to_file(state, ">>\n");
2129 pdf_write_string_to_file(state, "endobj\n");
2132 static void pdf_write_to_file(pdf_state *state)
2134 pdf_buffer *buf = state->first_buffer;
2136 state->pdf_file_pos = 0;
2137 pdf_write_buf_to_file(state, &state->pdf_header);
2140 pdf_write_buf_to_file(state, buf);
2141 buf = buf->next_buffer;
2143 xref_pos = state->pdf_file_pos;
2144 fprintf(state->fp, "xref\n");
2145 fprintf(state->fp, "%d %d\n", 0, state->last_obj_id + 1);
2146 /* TOC lines must be exactly 20 bytes including \n */
2147 fprintf(state->fp, "%010d %05d f\x20\n", 0, 65535);
2148 for (buf = state->first_buffer; buf; buf = buf->next_buffer) {
2150 fprintf(state->fp, "%010d %05d n\x20\n", buf->pdf_file_pos, 0);
2152 fprintf(state->fp, "trailer\n");
2153 fprintf(state->fp, "<<\n");
2154 fprintf(state->fp, "\t/Size %d\n", state->last_obj_id + 1);
2155 fprintf(state->fp, "\t/Root %d 0 R\n", state->catalog_obj.id);
2156 fprintf(state->fp, ">>\n");
2157 fprintf(state->fp, "startxref\n");
2158 fprintf(state->fp, "%d\n", xref_pos);
2159 fputs("%%EOF\n", state->fp);
2162 static void pdf_free_resources(pdf_state *state)
2164 pdf_buffer *buf = state->first_buffer;
2168 buf->alloc_size = buf->current_size = 0;
2169 buf = buf->next_buffer;
2171 while (state->font_list) {
2172 pdf_font *next = state->font_list->next;
2173 free(state->font_list);
2174 state->font_list = next;
2178 int gfx_render_pdf (gfx_canvas_t *canvas,
2179 art_u32 width, art_u32 height,
2180 gfx_color_t background, FILE *fp){
2181 struct pdf_state state;
2182 memset(&state, 0, sizeof(pdf_state));
2184 state.canvas = canvas;
2185 state.page_width = width;
2186 state.page_height = height;
2188 state.font_size = -1;
2189 state.font_list = NULL;
2191 state.linejoin = -1;
2192 pdf_init_document(&state);
2194 pdf_set_color(&state, background);
2195 fprintf(fp, "0 0 M 0 %d L %d %d L %d 0 L fill\n",
2196 height, width, height, width);
2198 if (!state.has_failed)
2199 pdf_write_content(&state);
2200 if (!state.has_failed)
2201 pdf_setup_document(&state);
2202 if (!state.has_failed)
2203 pdf_write_to_file(&state);
2204 pdf_free_resources(&state);
2205 return state.has_failed ? -1 : 0;