1 /****************************************************************************
2 * RRDtool 1.2.x Copyright Tobias 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->svp = NULL; /* svp */
66 node->filename = NULL; /* font or image filename */
69 node->y = 0.0; /* position */
71 node->halign = GFX_H_NULL; /* text alignement */
72 node->valign = GFX_V_NULL; /* text alignement */
75 if (canvas->lastnode != NULL){
76 canvas->lastnode->next = node;
78 if (canvas->firstnode == NULL){
79 canvas->firstnode = node;
81 canvas->lastnode = node;
85 gfx_canvas_t *gfx_new_canvas (void) {
86 gfx_canvas_t *canvas = art_new(gfx_canvas_t,1);
87 canvas->firstnode = NULL;
88 canvas->lastnode = NULL;
89 canvas->imgformat = IF_PNG; /* we default to PNG output */
90 canvas->interlaced = 0;
95 /* create a new line */
96 gfx_node_t *gfx_new_line(gfx_canvas_t *canvas,
99 double width, gfx_color_t color){
100 return gfx_new_dashed_line(canvas, X0, Y0, X1, Y1, width, color, 0, 0);
103 gfx_node_t *gfx_new_dashed_line(gfx_canvas_t *canvas,
104 double X0, double Y0,
105 double X1, double Y1,
106 double width, gfx_color_t color,
107 double dash_on, double dash_off){
111 node = gfx_new_node(canvas,GFX_LINE);
112 if (node == NULL) return NULL;
113 vec = art_new(ArtVpath, 3);
114 if (vec == NULL) return NULL;
115 vec[0].code = ART_MOVETO_OPEN; vec[0].x=X0+LINEOFFSET; vec[0].y=Y0+LINEOFFSET;
116 vec[1].code = ART_LINETO; vec[1].x=X1+LINEOFFSET; vec[1].y=Y1+LINEOFFSET;
117 vec[2].code = ART_END;
120 node->points_max = 3;
123 node->dash_on = dash_on;
124 node->dash_off = dash_off;
129 /* create a new area */
130 gfx_node_t *gfx_new_area (gfx_canvas_t *canvas,
131 double X0, double Y0,
132 double X1, double Y1,
133 double X2, double Y2,
138 node = gfx_new_node(canvas,GFX_AREA);
139 if (node == NULL) return NULL;
140 vec = art_new(ArtVpath, 5);
141 if (vec == NULL) return NULL;
142 vec[0].code = ART_MOVETO; vec[0].x=X0; vec[0].y=Y0;
143 vec[1].code = ART_LINETO; vec[1].x=X1; vec[1].y=Y1;
144 vec[2].code = ART_LINETO; vec[2].x=X2; vec[2].y=Y2;
145 vec[3].code = ART_LINETO; vec[3].x=X0; vec[3].y=Y0;
146 vec[4].code = ART_END;
149 node->points_max = 5;
156 /* add a point to a line or to an area */
157 int gfx_add_point (gfx_node_t *node,
159 if (node == NULL) return 1;
160 if (node->type == GFX_AREA) {
161 double X0 = node->path[0].x;
162 double Y0 = node->path[0].y;
164 art_vpath_add_point (&(node->path),
169 art_vpath_add_point (&(node->path),
174 art_vpath_add_point (&(node->path),
179 } else if (node->type == GFX_LINE) {
181 art_vpath_add_point (&(node->path),
185 x+LINEOFFSET,y+LINEOFFSET);
186 art_vpath_add_point (&(node->path),
193 /* can only add point to areas and lines */
199 void gfx_close_path (gfx_node_t *node) {
200 node->closed_path = 1;
201 if (node->path[0].code == ART_MOVETO_OPEN)
202 node->path[0].code = ART_MOVETO;
205 /* create a text node */
206 gfx_node_t *gfx_new_text (gfx_canvas_t *canvas,
207 double x, double y, gfx_color_t color,
208 char* font, double size,
209 double tabwidth, double angle,
210 enum gfx_h_align_en h_align,
211 enum gfx_v_align_en v_align,
213 gfx_node_t *node = gfx_new_node(canvas,GFX_TEXT);
214 /* if (angle != 0.0){*/
215 /* currently we only support 0 and 270 */
219 node->text = strdup(text);
221 node->filename = strdup(font);
226 node->tabwidth = tabwidth;
227 node->halign = h_align;
228 node->valign = v_align;
230 /* debugging: show text anchor
231 green is along x-axis, red is downward y-axis */
233 double a = 2 * M_PI * -node->angle / 360.0;
234 double cos_a = cos(a);
235 double sin_a = sin(a);
239 x + len * cos_a, y - len * sin_a,
243 x + len * sin_a, y + len * cos_a,
250 int gfx_render(gfx_canvas_t *canvas,
251 art_u32 width, art_u32 height,
252 gfx_color_t background, FILE *fp){
253 switch (canvas->imgformat) {
255 return gfx_render_png (canvas, width, height, background, fp);
257 return gfx_render_svg (canvas, width, height, background, fp);
259 return gfx_render_eps (canvas, width, height, background, fp);
261 return gfx_render_pdf (canvas, width, height, background, fp);
267 static void gfx_string_destroy ( gfx_string string ) {
269 if (string->glyphs) {
270 for (n=0; n<string->num_glyphs; ++n)
271 FT_Done_Glyph (string->glyphs[n].image);
272 free (string->glyphs);
278 double gfx_get_text_width ( gfx_canvas_t *canvas,
279 double start, char* font, double size,
280 double tabwidth, char* text, int rotation){
281 switch (canvas->imgformat) {
283 return gfx_get_text_width_libart (start, font, size, tabwidth, text, rotation);
284 case IF_SVG: /* fall through */
287 return afm_get_text_width(start, font, size, tabwidth, text);
289 return size * strlen(text);
293 double gfx_get_text_width_libart (
294 double start, char* font, double size,
295 double tabwidth, char* text, int rotation){
300 FT_Library library=NULL;
303 FT_Init_FreeType( &library );
304 error = FT_New_Face( library, font, 0, &face );
305 if ( error ) return -1;
306 error = FT_Set_Char_Size(face, size*64,size*64, 100,100);
307 if ( error ) return -1;
309 string = gfx_string_create( face, text, rotation,tabwidth);
310 text_width = string->width;
311 gfx_string_destroy(string);
312 FT_Done_FreeType(library);
313 return text_width/64;
316 static void gfx_libart_close_path(gfx_node_t *node, ArtVpath **vec)
318 /* libart must have end==start for closed paths,
319 even if using ART_MOVETO and not ART_MOVETO_OPEN
320 so add extra point which is the same as the starting point */
321 int points_max = node->points; /* scaled array has exact size */
322 int points = node->points - 1;
323 art_vpath_add_point (vec, &points, &points_max, ART_LINETO,
324 (**vec).x, (**vec).y);
325 art_vpath_add_point (vec, &points, &points_max, ART_END, 0, 0);
328 static void gfx_round_scaled_coordinates(ArtVpath *vec)
330 while (vec->code != ART_END) {
331 vec->x = floor(vec->x - LINEOFFSET + 0.5) + LINEOFFSET;
332 vec->y = floor(vec->y - LINEOFFSET + 0.5) + LINEOFFSET;
337 /* find bbox of a string */
338 static void compute_string_bbox(gfx_string string) {
342 bbox.xMin = bbox.yMin = 32000;
343 bbox.xMax = bbox.yMax = -32000;
344 for ( n = 0; n < string->num_glyphs; n++ ) {
346 FT_Glyph_Get_CBox( string->glyphs[n].image, ft_glyph_bbox_gridfit,
348 if (glyph_bbox.xMin < bbox.xMin) {
349 bbox.xMin = glyph_bbox.xMin;
351 if (glyph_bbox.yMin < bbox.yMin) {
352 bbox.yMin = glyph_bbox.yMin;
354 if (glyph_bbox.xMax > bbox.xMax) {
355 bbox.xMax = glyph_bbox.xMax;
357 if (glyph_bbox.yMax > bbox.yMax) {
358 bbox.yMax = glyph_bbox.yMax;
361 if ( bbox.xMin > bbox.xMax ) {
367 string->bbox.xMin = bbox.xMin;
368 string->bbox.xMax = bbox.xMax;
369 string->bbox.yMin = bbox.yMin;
370 string->bbox.yMax = bbox.yMax;
373 /* create a free type glyph string */
374 gfx_string gfx_string_create(FT_Face face,const char *text,
375 int rotation, double tabwidth)
378 FT_GlyphSlot slot = face->glyph; /* a small shortcut */
384 gfx_char glyph; /* current glyph in table */
389 ft_pen.x = 0; /* start at (0,0) !! */
392 string = (gfx_string) malloc (sizeof(struct gfx_string_s));
395 string->count = strlen (text);
396 string->glyphs = (gfx_char) calloc (string->count,sizeof(struct gfx_char_s));
397 string->num_glyphs = 0;
398 string->transform.xx = (FT_Fixed)( cos(M_PI*(rotation)/180.0)*0x10000);
399 string->transform.xy = (FT_Fixed)(-sin(M_PI*(rotation)/180.0)*0x10000);
400 string->transform.yx = (FT_Fixed)( sin(M_PI*(rotation)/180.0)*0x10000);
401 string->transform.yy = (FT_Fixed)( cos(M_PI*(rotation)/180.0)*0x10000);
403 use_kerning = FT_HAS_KERNING(face);
405 glyph = string->glyphs;
406 for (n=0; n<string->count; n++, glyph++) {
408 /* handle the tabs ...
409 have a witespace glyph inserted, but set its width such that the distance
410 of the new right edge is x times tabwidth from 0,0 where x is an integer. */
411 char letter = text[n];
413 if (letter == '\\' && n+1 < string->count && text[n+1] == 't'){
414 /* we have a tab here so skip the backslash and
415 set t to ' ' so that we get a white space */
424 /* initialize each struct gfx_char_s */
430 glyph->index = FT_Get_Char_Index( face, letter );
432 /* compute glyph origin */
433 if ( use_kerning && previous && glyph->index ) {
435 FT_Get_Kerning (face, previous, glyph->index,
436 ft_kerning_default, &kerning);
437 ft_pen.x += kerning.x;
438 ft_pen.y += kerning.y;
441 /* load the glyph image (in its native format) */
442 /* for now, we take a monochrome glyph bitmap */
443 error = FT_Load_Glyph (face, glyph->index, FT_LOAD_DEFAULT);
445 fprintf (stderr, "couldn't load glyph: %c\n", letter);
448 error = FT_Get_Glyph (slot, &glyph->image);
450 fprintf (stderr, "couldn't get glyph from slot: %c\n", letter);
453 /* if we are in tabbing mode, we replace the tab with a space and shift the position
454 of the space so that its left edge is where the tab was supposed to land us */
456 /* we are in gridfitting mode so the calculations happen in 1/64 pixles */
457 ft_pen.x = tabwidth*64.0 * (float)(1 + (long)(ft_pen.x / (tabwidth * 64.0))) - slot->advance.x;
459 /* store current pen position */
460 glyph->pos.x = ft_pen.x;
461 glyph->pos.y = ft_pen.y;
464 ft_pen.x += slot->advance.x;
465 ft_pen.y += slot->advance.y;
469 FT_Vector_Transform (&vec, &string->transform);
470 error = FT_Glyph_Transform (glyph->image, &string->transform, &vec);
472 fprintf (stderr, "couldn't transform glyph\n");
476 /* convert to a bitmap - destroy native image */
477 error = FT_Glyph_To_Bitmap (&glyph->image, FT_RENDER_MODE_NORMAL, 0, 1);
479 fprintf (stderr, "couldn't convert glyph to bitmap\n");
483 /* increment number of glyphs */
484 previous = glyph->index;
485 string->num_glyphs++;
487 /* printf ("number of glyphs = %d\n", string->num_glyphs);*/
488 compute_string_bbox( string );
489 /* the last character was a tab */
491 string->width = ft_pen.x;
493 string->width = string->bbox.xMax - string->bbox.xMin;
495 string->height = string->bbox.yMax - string->bbox.yMin;
500 static int gfx_save_png (art_u8 *buffer, FILE *fp,
501 long width, long height, long bytes_per_pixel);
502 /* render grafics into png image */
504 int gfx_render_png (gfx_canvas_t *canvas,
505 art_u32 width, art_u32 height,
506 gfx_color_t background, FILE *fp){
510 gfx_node_t *node = canvas->firstnode;
511 art_u8 red = background >> 24, green = (background >> 16) & 0xff;
512 art_u8 blue = (background >> 8) & 0xff, alpha = ( background & 0xff );
513 unsigned long pys_width = width * canvas->zoom;
514 unsigned long pys_height = height * canvas->zoom;
515 const int bytes_per_pixel = 3;
516 unsigned long rowstride = pys_width*bytes_per_pixel; /* bytes per pixel */
517 art_u8 *buffer = art_new (art_u8, rowstride*pys_height);
518 art_rgb_run_alpha (buffer, red, green, blue, alpha, pys_width*pys_height);
519 FT_Init_FreeType( &library );
521 switch (node->type) {
527 art_affine_scale(dst,canvas->zoom,canvas->zoom);
528 vec = art_vpath_affine_transform(node->path,dst);
529 if (node->closed_path)
530 gfx_libart_close_path(node, &vec);
531 gfx_round_scaled_coordinates(vec);
532 if(node->type == GFX_LINE){
533 svp = art_svp_vpath_stroke ( vec, ART_PATH_STROKE_JOIN_ROUND,
534 ART_PATH_STROKE_CAP_ROUND,
535 node->size*canvas->zoom,1,1);
537 svp = art_svp_from_vpath ( vec );
540 art_rgb_svp_alpha (svp ,0,0, pys_width, pys_height,
541 node->color, buffer, rowstride, NULL);
548 art_u8 fcolor[3],falpha;
552 FT_Vector vec; /* 26.6 */
554 float pen_x = 0.0 , pen_y = 0.0;
558 fcolor[0] = node->color >> 24;
559 fcolor[1] = (node->color >> 16) & 0xff;
560 fcolor[2] = (node->color >> 8) & 0xff;
561 falpha = node->color & 0xff;
562 error = FT_New_Face( library,
563 (char *)node->filename,
568 error = FT_Set_Char_Size(face, /* handle to face object */
569 (long)(node->size*64),
570 (long)(node->size*64),
571 (long)(100*canvas->zoom),
572 (long)(100*canvas->zoom));
574 pen_x = node->x * canvas->zoom;
575 pen_y = node->y * canvas->zoom;
577 string = gfx_string_create (face, node->text, node->angle, node->tabwidth);
578 switch(node->halign){
579 case GFX_H_RIGHT: vec.x = -string->bbox.xMax;
581 case GFX_H_CENTER: vec.x = abs(string->bbox.xMax) >= abs(string->bbox.xMin) ?
582 -string->bbox.xMax/2:-string->bbox.xMin/2;
584 case GFX_H_LEFT: vec.x = -string->bbox.xMin;
586 case GFX_H_NULL: vec.x = 0;
590 switch(node->valign){
591 case GFX_V_TOP: vec.y = string->bbox.yMax;
593 case GFX_V_CENTER: vec.y = abs(string->bbox.yMax) >= abs(string->bbox.yMin) ?
594 string->bbox.yMax/2:string->bbox.yMin/2;
596 case GFX_V_BOTTOM: vec.y = 0;
598 case GFX_V_NULL: vec.y = 0;
603 glyph = string->glyphs;
604 for(n=0; n<string->num_glyphs; ++n, ++glyph) {
609 /* make copy to transform */
610 if (! glyph->image) {
611 fprintf (stderr, "no image\n");
614 error = FT_Glyph_Copy (glyph->image, &image);
616 fprintf (stderr, "couldn't copy image\n");
622 FT_Vector_Transform (&vec, &string->transform);
624 bit = (FT_BitmapGlyph) image;
626 gr = bit->bitmap.num_grays -1;
627 for (iy=0; iy < bit->bitmap.rows; iy++){
628 long buf_y = iy+(pen_y+0.5)-bit->top;
629 if (buf_y < 0 || buf_y >= (long)pys_height) continue;
631 for (ix=0;ix < bit->bitmap.width;ix++){
632 long buf_x = ix + (pen_x + 0.5) + (double)bit->left ;
635 if (buf_x < 0 || buf_x >= (long)pys_width) continue;
636 buf_x *= bytes_per_pixel ;
637 font_alpha = *(bit->bitmap.buffer + iy * bit->bitmap.width + ix);
638 font_alpha = (art_u8)((double)font_alpha / gr * falpha);
639 for (iz = 0; iz < 3; iz++){
640 art_u8 *orig = buffer + buf_y + buf_x + iz;
641 *orig = (art_u8)((double)*orig / gr * ( gr - font_alpha) +
642 (double)fcolor[iz] / gr * (font_alpha));
646 FT_Done_Glyph (image);
648 gfx_string_destroy(string);
653 gfx_save_png(buffer,fp , pys_width,pys_height,bytes_per_pixel);
655 FT_Done_FreeType( library );
659 /* free memory used by nodes this will also remove memory required for
660 associated paths and svcs ... but not for text strings */
662 gfx_destroy (gfx_canvas_t *canvas){
663 gfx_node_t *next,*node = canvas->firstnode;
666 art_free(node->path);
669 free(node->filename);
676 static int gfx_save_png (art_u8 *buffer, FILE *fp, long width, long height, long bytes_per_pixel){
677 png_structp png_ptr = NULL;
678 png_infop info_ptr = NULL;
680 png_bytep *row_pointers;
681 int rowstride = width * bytes_per_pixel;
687 png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING,NULL,NULL,NULL);
692 row_pointers = (png_bytepp)png_malloc(png_ptr,
693 height*sizeof(png_bytep));
695 info_ptr = png_create_info_struct(png_ptr);
697 if (info_ptr == NULL)
699 png_destroy_write_struct(&png_ptr, (png_infopp)NULL);
703 if (setjmp(png_jmpbuf(png_ptr)))
705 /* If we get here, we had a problem writing the file */
706 png_destroy_write_struct(&png_ptr, &info_ptr);
710 png_init_io(png_ptr, fp);
711 png_set_IHDR (png_ptr, info_ptr,width, height,
712 8, PNG_COLOR_TYPE_RGB,
714 PNG_COMPRESSION_TYPE_DEFAULT,
715 PNG_FILTER_TYPE_DEFAULT);
717 text[0].key = "Software";
718 text[0].text = "RRDtool, Tobias Oetiker <tobi@oetike.ch>, http://tobi.oetiker.ch";
719 text[0].compression = PNG_TEXT_COMPRESSION_NONE;
720 png_set_text (png_ptr, info_ptr, text, 1);
722 /* lets make this fast */
723 png_set_compression_level(png_ptr,1);
724 png_set_filter(png_ptr,PNG_FILTER_TYPE_BASE,PNG_NO_FILTERS);
726 png_set_filter(png_ptr,PNG_FILTER_TYPE_BASE,PNG_FILTER_SUB);
727 png_set_compression_strategy(png_ptr,Z_HUFFMAN_ONLY);
728 png_set_compression_level(png_ptr,Z_BEST_SPEED); */
730 /* Write header data */
731 png_write_info (png_ptr, info_ptr);
732 for (i = 0; i < height; i++)
733 row_pointers[i] = (png_bytep) (buffer + i*rowstride);
735 png_write_image(png_ptr, row_pointers);
736 png_write_end(png_ptr, info_ptr);
737 png_destroy_write_struct(&png_ptr, &info_ptr);
742 /* ------- SVG -------
744 http://www.w3.org/TR/SVG/
746 static int svg_indent = 0;
747 static int svg_single_line = 0;
748 static const char *svg_default_font = "Helvetica";
749 typedef struct svg_dash
752 double dash_adjust, dash_len, dash_offset;
753 double adjusted_on, adjusted_off;
757 static void svg_print_indent(FILE *fp)
760 for (i = svg_indent - svg_single_line; i > 0; i--) {
766 static void svg_start_tag(FILE *fp, const char *name)
768 svg_print_indent(fp);
774 static void svg_close_tag_single_line(FILE *fp)
780 static void svg_close_tag(FILE *fp)
783 if (!svg_single_line)
787 static void svg_end_tag(FILE *fp, const char *name)
789 /* name is NULL if closing empty-node tag */
794 svg_print_indent(fp);
804 static void svg_close_tag_empty_node(FILE *fp)
806 svg_end_tag(fp, NULL);
809 static void svg_write_text(FILE *fp, const char *text)
811 const unsigned char *p, *start, *last;
813 p = (const unsigned char*)text;
816 /* trim leading spaces */
820 /* trim trailing spaces */
822 while ((ch = *p) != 0) {
827 /* encode trimmed text */
831 ch = afm_host2unicode(ch); /* unsafe macro */
833 case '&': fputs("&", fp); break;
834 case '<': fputs("<", fp); break;
835 case '>': fputs(">", fp); break;
836 case '"': fputs(""", fp); break;
839 fprintf(fp, "&#%d;", ch);
846 static void svg_format_number(char *buf, int bufsize, double d)
848 /* omit decimals if integer to reduce filesize */
850 snprintf(buf, bufsize, "%.2f", d);
851 p = buf; /* doesn't trust snprintf return value */
857 *p = '\0'; /* zap trailing zeros */
861 *p = '\0'; /* zap trailing dot */
866 static void svg_write_number(FILE *fp, double d)
869 svg_format_number(buf, sizeof(buf), d);
873 static int svg_color_is_black(int c)
875 /* gfx_color_t is RRGGBBAA */
876 return c == 0x000000FF;
879 static void svg_write_color(FILE *fp, gfx_color_t c, const char *attr)
881 /* gfx_color_t is RRGGBBAA, svg can use #RRGGBB and #RGB like html */
882 gfx_color_t rrggbb = (int)((c >> 8) & 0xFFFFFF);
883 gfx_color_t opacity = c & 0xFF;
884 fprintf(fp, " %s=\"", attr);
885 if ((rrggbb & 0x0F0F0F) == ((rrggbb >> 4) & 0x0F0F0F)) {
886 /* css2 short form, #rgb is #rrggbb, not #r0g0b0 */
887 fprintf(fp, "#%03lX",
888 ( ((rrggbb >> 8) & 0xF00)
889 | ((rrggbb >> 4) & 0x0F0)
890 | ( rrggbb & 0x00F)));
892 fprintf(fp, "#%06lX", rrggbb);
895 if (opacity != 0xFF) {
896 fprintf(fp, " stroke-opacity=\"");
897 svg_write_number(fp, opacity / 255.0);
902 static void svg_get_dash(gfx_node_t *node, svg_dash *d)
906 if (node->dash_on <= 0 || node->dash_off <= 0) {
911 d->dash_len = node->dash_on + node->dash_off;
912 /* dash on/off adjustment due to round caps */
913 d->dash_adjust = 0.8 * node->size;
914 d->adjusted_on = node->dash_on - d->dash_adjust;
915 if (d->adjusted_on < 0.01)
916 d->adjusted_on = 0.01;
917 d->adjusted_off = d->dash_len - d->adjusted_on;
918 /* dash offset calc */
919 if (node->path[0].x == node->path[1].x) /* only good for horz/vert lines */
920 offset = node->path[0].y;
922 offset = node->path[0].x;
923 mult = (int)fabs(offset / d->dash_len);
924 d->dash_offset = offset - mult * d->dash_len;
925 if (node->path[0].x < node->path[1].x || node->path[0].y < node->path[1].y)
926 d->dash_offset = d->dash_len - d->dash_offset;
929 static int svg_dash_equal(svg_dash *a, svg_dash *b)
931 if (a->dash_enable != b->dash_enable)
933 if (a->adjusted_on != b->adjusted_on)
935 if (a->adjusted_off != b->adjusted_off)
937 /* rest of properties will be the same when on+off are */
941 static void svg_common_path_attributes(FILE *fp, gfx_node_t *node)
944 svg_get_dash(node, &dash_info);
945 fputs(" stroke-width=\"", fp);
946 svg_write_number(fp, node->size);
948 svg_write_color(fp, node->color, "stroke");
949 fputs(" fill=\"none\"", fp);
950 if (dash_info.dash_enable) {
951 if (dash_info.dash_offset != 0) {
952 fputs(" stroke-dashoffset=\"", fp);
953 svg_write_number(fp, dash_info.dash_offset);
956 fputs(" stroke-dasharray=\"", fp);
957 svg_write_number(fp, dash_info.adjusted_on);
959 svg_write_number(fp, dash_info.adjusted_off);
964 static int svg_is_int_step(double a, double b)
966 double diff = fabs(a - b);
967 return floor(diff) == diff;
970 static int svg_path_straight_segment(FILE *fp,
971 double lastA, double currentA, double currentB,
973 int segment_idx, int isx, char absChar, char relChar)
975 if (!svg_is_int_step(lastA, currentA)) {
977 svg_write_number(fp, currentA);
980 if (segment_idx < node->points - 1) {
981 ArtVpath *vec = node->path + segment_idx + 1;
982 if (vec->code == ART_LINETO) {
983 double nextA = (isx ? vec->x : vec->y) - LINEOFFSET;
984 double nextB = (isx ? vec->y : vec->x) - LINEOFFSET;
985 if (nextB == currentB
986 && ((currentA >= lastA) == (nextA >= currentA))
987 && svg_is_int_step(currentA, nextA)) {
988 return 1; /* skip to next as it is a straight line */
993 svg_write_number(fp, currentA - lastA);
997 static void svg_path(FILE *fp, gfx_node_t *node, int multi)
1000 double lastX = 0, lastY = 0;
1001 /* for straight lines <path..> tags take less space than
1002 <line..> tags because of the efficient packing
1003 in the 'd' attribute */
1004 svg_start_tag(fp, "path");
1006 svg_common_path_attributes(fp, node);
1008 /* specification of the 'd' attribute: */
1009 /* http://www.w3.org/TR/SVG/paths.html#PathDataGeneralInformation */
1010 for (i = 0; i < node->points; i++) {
1011 ArtVpath *vec = node->path + i;
1012 double x = vec->x - LINEOFFSET;
1013 double y = vec->y - LINEOFFSET;
1014 switch (vec->code) {
1015 case ART_MOVETO_OPEN: /* fall-through */
1018 svg_write_number(fp, x);
1020 svg_write_number(fp, y);
1023 /* try optimize filesize by using minimal lineto commands */
1024 /* without introducing rounding errors. */
1026 if (svg_path_straight_segment(fp, lastY, y, x, node, i, 0, 'V', 'v'))
1028 } else if (y == lastY) {
1029 if (svg_path_straight_segment(fp, lastX, x, y, node, i, 1, 'H', 'h'))
1033 svg_write_number(fp, x);
1035 svg_write_number(fp, y);
1038 case ART_CURVETO: break; /* unsupported */
1039 case ART_END: break; /* nop */
1044 if (node->closed_path)
1047 svg_close_tag_empty_node(fp);
1050 static void svg_multi_path(FILE *fp, gfx_node_t **nodeR)
1052 /* optimize for multiple paths with the same color, penwidth, etc. */
1054 gfx_node_t *node = *nodeR;
1055 gfx_node_t *next = node->next;
1057 if (next->type != node->type
1058 || next->size != node->size
1059 || next->color != node->color
1060 || next->dash_on != node->dash_on
1061 || next->dash_off != node->dash_off)
1067 svg_path(fp, node, 0);
1070 svg_start_tag(fp, "g");
1071 svg_common_path_attributes(fp, node);
1073 while (num && node) {
1074 svg_path(fp, node, 1);
1080 svg_end_tag(fp, "g");
1083 static void svg_area(FILE *fp, gfx_node_t *node)
1086 double startX = 0, startY = 0;
1087 svg_start_tag(fp, "polygon");
1089 svg_write_color(fp, node->color, "fill");
1090 fputs(" points=\"", fp);
1091 for (i = 0; i < node->points; i++) {
1092 ArtVpath *vec = node->path + i;
1093 double x = vec->x - LINEOFFSET;
1094 double y = vec->y - LINEOFFSET;
1095 switch (vec->code) {
1096 case ART_MOVETO_OPEN: /* fall-through */
1098 svg_write_number(fp, x);
1100 svg_write_number(fp, y);
1105 if (i == node->points - 2
1106 && node->path[i + 1].code == ART_END
1107 && fabs(x - startX) < 0.001 && fabs(y - startY) < 0.001) {
1108 break; /* poly area always closed, no need for last point */
1111 svg_write_number(fp, x);
1113 svg_write_number(fp, y);
1115 case ART_CURVETO: break; /* unsupported */
1116 case ART_END: break; /* nop */
1120 svg_close_tag_empty_node(fp);
1123 static void svg_text(FILE *fp, gfx_node_t *node)
1125 double x = node->x - LINEOFFSET;
1126 double y = node->y - LINEOFFSET;
1127 if (node->angle != 0) {
1128 svg_start_tag(fp, "g");
1129 fputs(" transform=\"translate(", fp);
1130 svg_write_number(fp, x);
1132 svg_write_number(fp, y);
1133 fputs(") rotate(", fp);
1134 svg_write_number(fp, node->angle);
1139 switch (node->valign) {
1140 case GFX_V_TOP: y += node->size; break;
1141 case GFX_V_CENTER: y += node->size / 3; break;
1142 case GFX_V_BOTTOM: break;
1143 case GFX_V_NULL: break;
1145 svg_start_tag(fp, "text");
1147 svg_write_number(fp, x);
1148 fputs("\" y=\"", fp);
1149 svg_write_number(fp, y);
1151 /* if (strcmp(node->filename, svg_default_font))
1152 fprintf(fp, " font-family=\"%s\"", node->filename);
1154 fputs("\" font-family=\"Helvetica", fp);
1155 fputs("\" font-size=\"", fp);
1156 svg_write_number(fp, node->size);
1158 if (!svg_color_is_black(node->color))
1159 svg_write_color(fp, node->color, "fill");
1160 switch (node->halign) {
1161 case GFX_H_RIGHT: fputs(" text-anchor=\"end\"", fp); break;
1162 case GFX_H_CENTER: fputs(" text-anchor=\"middle\"", fp); break;
1163 case GFX_H_LEFT: break;
1164 case GFX_H_NULL: break;
1166 svg_close_tag_single_line(fp);
1167 /* support for node->tabwidth missing */
1168 svg_write_text(fp, node->text);
1169 svg_end_tag(fp, "text");
1170 if (node->angle != 0)
1171 svg_end_tag(fp, "g");
1174 int gfx_render_svg (gfx_canvas_t *canvas,
1175 art_u32 width, art_u32 height,
1176 gfx_color_t background, FILE *fp){
1177 gfx_node_t *node = canvas->firstnode;
1179 "<?xml version=\"1.0\" standalone=\"no\"?>\n"
1180 "<!DOCTYPE svg PUBLIC \"-//W3C//DTD SVG 1.0//EN\"\n"
1181 " \"http://www.w3.org/TR/2001/REC-SVG-20010904/DTD/svg10.dtd\">\n"
1183 " SVG file created by RRDtool,\n"
1184 " Tobias Oetiker <tobi@oetike.ch>, http://tobi.oetiker.ch\n"
1186 " The width/height attributes in the outhermost svg node\n"
1187 " are just default sizes for the browser which is used\n"
1188 " if the svg file is openened directly without being\n"
1189 " embedded in an html file.\n"
1190 " The viewBox is the local coord system for rrdtool.\n"
1192 svg_start_tag(fp, "svg");
1193 fputs(" width=\"", fp);
1194 svg_write_number(fp, width * canvas->zoom);
1195 fputs("\" height=\"", fp);
1196 svg_write_number(fp, height * canvas->zoom);
1197 fputs("\" x=\"0\" y=\"0\" viewBox=\"", fp);
1198 svg_write_number(fp, -LINEOFFSET);
1200 svg_write_number(fp, -LINEOFFSET);
1202 svg_write_number(fp, width - LINEOFFSET);
1204 svg_write_number(fp, height - LINEOFFSET);
1205 fputs("\" preserveAspectRatio=\"xMidYMid\"", fp);
1206 fprintf(fp, " font-family=\"%s\"", svg_default_font); /* default font */
1207 fputs(" stroke-linecap=\"round\" stroke-linejoin=\"round\"", fp);
1209 svg_start_tag(fp, "rect");
1210 fprintf(fp, " x=\"0\" y=\"0\" width=\"%d\" height=\"%d\"", width, height);
1211 svg_write_color(fp, background, "fill");
1212 svg_close_tag_empty_node(fp);
1214 switch (node->type) {
1216 svg_multi_path(fp, &node);
1226 svg_end_tag(fp, "svg");
1230 /* ------- EPS -------
1231 EPS and Postscript references:
1232 http://partners.adobe.com/asn/developer/technotes/postscript.html
1235 typedef struct eps_font
1237 const char *ps_font;
1239 struct eps_font *next;
1242 typedef struct eps_state
1245 gfx_canvas_t *canvas;
1246 art_u32 page_width, page_height;
1247 eps_font *font_list;
1253 int linecap, linejoin;
1257 static void eps_set_color(eps_state *state, gfx_color_t color)
1259 /* gfx_color_t is RRGGBBAA */
1260 if (state->color == color)
1262 fprintf(state->fp, "%d %d %d Rgb\n",
1263 (int)((color >> 24) & 255),
1264 (int)((color >> 16) & 255),
1265 (int)((color >> 8) & 255));
1266 state->color = color;
1269 static int eps_add_font(eps_state *state, gfx_node_t *node)
1271 /* The fonts list could be postponed to the end using
1272 (atend), but let's be nice and have them in the header. */
1273 const char *ps_font = afm_get_font_postscript_name(node->filename);
1275 for (ef = state->font_list; ef; ef = ef->next) {
1276 if (!strcmp(ps_font, ef->ps_font))
1279 ef = malloc(sizeof(eps_font));
1281 rrd_set_error("malloc for eps_font");
1284 ef->next = state->font_list;
1285 ef->ps_font = ps_font;
1286 state->font_list = ef;
1290 static void eps_list_fonts(eps_state *state, const char *dscName)
1293 int lineLen = strlen(dscName);
1294 if (!state->font_list)
1296 fputs(dscName, state->fp);
1297 for (ef = state->font_list; ef; ef = ef->next) {
1298 int nameLen = strlen(ef->ps_font);
1299 if (lineLen + nameLen > 100 && lineLen) {
1300 fputs("\n", state->fp);
1301 fputs("%%- \n", state->fp);
1304 fputs(" ", state->fp);
1307 fputs(ef->ps_font, state->fp);
1310 fputs("\n", state->fp);
1313 static void eps_define_fonts(eps_state *state)
1316 if (!state->font_list)
1318 for (ef = state->font_list; ef; ef = ef->next) {
1319 /* PostScript¨ LANGUAGE REFERENCE third edition
1323 "/%s findfont dup length dict begin\n"
1324 "{ 1 index /FID ne {def} {pop pop} ifelse } forall\n"
1325 "/Encoding ISOLatin1Encoding def\n"
1327 "/%s-ISOLatin1 exch definefont pop\n"
1328 "/SetFont-%s { /%s-ISOLatin1 findfont exch scalefont setfont } bd\n",
1329 ef->ps_font, ef->ps_font, ef->ps_font, ef->ps_font);
1333 static int eps_prologue(eps_state *state)
1337 "%!PS-Adobe-3.0 EPSF-3.0\n"
1338 "%%Creator: RRDtool 1.1.x, Tobias Oetiker, http://tobi.oetiker.ch\n"
1339 /* can't like weird chars here */
1340 "%%Title: (RRDtool output)\n"
1341 "%%DocumentData: Clean7Bit\n"
1343 fprintf(state->fp, "%%%%BoundingBox: 0 0 %d %d\n",
1344 state->page_width, state->page_height);
1345 for (node = state->canvas->firstnode; node; node = node->next) {
1346 if (node->type == GFX_TEXT && eps_add_font(state, node) == -1)
1349 eps_list_fonts(state, "%%DocumentFonts:");
1350 eps_list_fonts(state, "%%DocumentNeededFonts:");
1354 "%%EndProlog\n" /* must have, or BoundingBox is ignored */
1355 "/bd { bind def } bind def\n"
1357 fprintf(state->fp, "/X { %.2f add } bd\n", LINEOFFSET);
1359 "/X2 {X exch X exch} bd\n"
1360 "/M {X2 moveto} bd\n"
1361 "/L {X2 lineto} bd\n"
1365 "/CP {closepath} bd\n"
1366 "/WS {setlinewidth stroke} bd\n"
1369 "/TaC {dup stringwidth pop neg 2 div 0 rmoveto } bd\n"
1370 "/TaR {dup stringwidth pop neg 0 rmoveto } bd\n"
1371 "/TL {moveto TaL show} bd\n"
1372 "/TC {moveto TaC show} bd\n"
1373 "/TR {moveto TaR show} bd\n"
1374 "/Rgb { 255.0 div 3 1 roll\n"
1375 " 255.0 div 3 1 roll \n"
1376 " 255.0 div 3 1 roll setrgbcolor } bd\n"
1378 eps_define_fonts(state);
1382 static void eps_clear_dash(eps_state *state)
1384 if (!state->has_dash)
1386 state->has_dash = 0;
1387 fputs("[1 0] 0 setdash\n", state->fp);
1390 static void eps_write_linearea(eps_state *state, gfx_node_t *node)
1393 FILE *fp = state->fp;
1395 int clearDashIfAny = 1;
1396 eps_set_color(state, node->color);
1397 if (node->type == GFX_LINE) {
1399 if (state->linecap != 1) {
1400 fputs("1 setlinecap\n", fp);
1403 if (state->linejoin != 1) {
1404 fputs("1 setlinejoin\n", fp);
1405 state->linejoin = 1;
1407 svg_get_dash(node, &dash_info);
1408 if (dash_info.dash_enable) {
1410 state->has_dash = 1;
1412 svg_write_number(fp, dash_info.adjusted_on);
1414 svg_write_number(fp, dash_info.adjusted_off);
1416 svg_write_number(fp, dash_info.dash_offset);
1417 fputs(" setdash\n", fp);
1421 eps_clear_dash(state);
1422 for (i = 0; i < node->points; i++) {
1423 ArtVpath *vec = node->path + i;
1425 double y = state->page_height - vec->y;
1426 if (vec->code == ART_MOVETO_OPEN || vec->code == ART_MOVETO)
1427 useOffset = (fabs(x - floor(x) - 0.5) < 0.01 && fabs(y - floor(y) - 0.5) < 0.01);
1432 switch (vec->code) {
1433 case ART_MOVETO_OPEN: /* fall-through */
1435 svg_write_number(fp, x);
1437 svg_write_number(fp, y);
1439 fputs(useOffset ? "M\n" : "m\n", fp);
1442 svg_write_number(fp, x);
1444 svg_write_number(fp, y);
1446 fputs(useOffset ? "L\n" : "l\n", fp);
1448 case ART_CURVETO: break; /* unsupported */
1449 case ART_END: break; /* nop */
1452 if (node->type == GFX_LINE) {
1453 if (node->closed_path)
1455 if (node->size != state->line_width) {
1456 state->line_width = node->size;
1457 svg_write_number(fp, state->line_width);
1467 static void eps_write_text(eps_state *state, gfx_node_t *node)
1469 FILE *fp = state->fp;
1470 const unsigned char *p;
1471 const char *ps_font = afm_get_font_postscript_name(node->filename);
1474 double y = state->page_height - node->y, ydelta = 0;
1476 eps_set_color(state, node->color);
1477 if (strcmp(ps_font, state->font) || node->size != state->font_size) {
1478 state->font = ps_font;
1479 state->font_size = node->size;
1480 svg_write_number(fp, state->font_size);
1481 fprintf(fp, " SetFont-%s\n", state->font);
1485 for (p = (const unsigned char*)node->text; *p; p++) {
1487 fputs("\\\n", fp); /* backslash and \n */
1502 fprintf(fp, "\\%03o", *p);
1509 switch(node->valign){
1510 case GFX_V_TOP: ydelta = -node->size; break;
1511 case GFX_V_CENTER: ydelta = -node->size / 3.0; break;
1512 case GFX_V_BOTTOM: break;
1513 case GFX_V_NULL: break;
1515 if (node->angle == 0)
1517 switch (node->halign) {
1518 case GFX_H_RIGHT: align = 'R'; break;
1519 case GFX_H_CENTER: align = 'C'; break;
1520 case GFX_H_LEFT: align= 'L'; break;
1521 case GFX_H_NULL: align= 'L'; break;
1523 if (node->angle != 0) {
1525 fputs(" gsave ", fp);
1526 svg_write_number(fp, x);
1528 svg_write_number(fp, y);
1529 fputs(" translate ", fp);
1530 svg_write_number(fp, -node->angle);
1531 fputs(" rotate 0 ", fp);
1532 svg_write_number(fp, ydelta);
1533 fputs(" moveto ", fp);
1534 fprintf(fp, "Ta%c", align);
1535 fputs(" show grestore\n", fp);
1537 svg_write_number(fp, x);
1539 svg_write_number(fp, y);
1546 static int eps_write_content(eps_state *state)
1549 fputs("%\n", state->fp);
1550 for (node = state->canvas->firstnode; node; node = node->next) {
1551 switch (node->type) {
1554 eps_write_linearea(state, node);
1557 eps_write_text(state, node);
1564 int gfx_render_eps (gfx_canvas_t *canvas,
1565 art_u32 width, art_u32 height,
1566 gfx_color_t background, FILE *fp){
1567 struct eps_state state;
1569 state.canvas = canvas;
1570 state.page_width = width;
1571 state.page_height = height;
1572 state.font = "no-default-font";
1573 state.font_size = -1;
1574 state.color = 0; /* black */
1575 state.font_list = NULL;
1577 state.linejoin = -1;
1579 if (eps_prologue(&state) == -1)
1581 eps_set_color(&state, background);
1582 fprintf(fp, "0 0 M 0 %d L %d %d L %d 0 L fill\n",
1583 height, width, height, width);
1584 if (eps_write_content(&state) == -1)
1586 fputs("showpage\n", fp);
1587 fputs("%%EOF\n", fp);
1588 while (state.font_list) {
1589 eps_font *next = state.font_list->next;
1590 free(state.font_list);
1591 state.font_list = next;
1596 /* ------- PDF -------
1597 PDF references page:
1598 http://partners.adobe.com/asn/developer/technotes/acrobatpdf.html
1601 typedef struct pdf_buffer
1603 int id, is_obj, is_dict, is_stream, pdf_file_pos;
1605 int alloc_size, current_size;
1606 struct pdf_buffer *previous_buffer, *next_buffer;
1607 struct pdf_state *state;
1610 typedef struct pdf_font
1612 const char *ps_font;
1614 struct pdf_font *next;
1617 typedef struct pdf_state
1620 gfx_canvas_t *canvas;
1621 art_u32 page_width, page_height;
1622 pdf_font *font_list;
1623 pdf_buffer *first_buffer, *last_buffer;
1627 gfx_color_t stroke_color, fill_color;
1632 int linecap, linejoin;
1635 pdf_buffer pdf_header;
1636 pdf_buffer catalog_obj, pages_obj, page1_obj;
1637 pdf_buffer fontsdict_obj;
1638 pdf_buffer graph_stream;
1641 static void pdf_init_buffer(pdf_state *state, pdf_buffer *buf)
1643 int initial_size = 32;
1646 buf->alloc_size = 0;
1647 buf->current_size = 0;
1648 buf->data = (char*)malloc(initial_size);
1650 buf->previous_buffer = NULL;
1651 buf->next_buffer = NULL;
1652 if (buf->data == NULL) {
1653 rrd_set_error("malloc for pdf_buffer data");
1654 state->has_failed = 1;
1657 buf->alloc_size = initial_size;
1658 if (state->last_buffer)
1659 state->last_buffer->next_buffer = buf;
1660 if (state->first_buffer == NULL)
1661 state->first_buffer = buf;
1662 buf->previous_buffer = state->last_buffer;
1663 state->last_buffer = buf;
1666 static void pdf_put(pdf_buffer *buf, const char *text, int len)
1670 if (buf->alloc_size < buf->current_size + len) {
1671 int new_size = buf->alloc_size;
1673 while (new_size < buf->current_size + len)
1675 new_buf = (char*)malloc(new_size);
1676 if (new_buf == NULL) {
1677 rrd_set_error("re-malloc for pdf_buffer data");
1678 buf->state->has_failed = 1;
1681 memcpy(new_buf, buf->data, buf->current_size);
1683 buf->data = new_buf;
1684 buf->alloc_size = new_size;
1686 memcpy(buf->data + buf->current_size, text, len);
1687 buf->current_size += len;
1690 static void pdf_puts(pdf_buffer *buf, const char *text)
1692 pdf_put(buf, text, strlen(text));
1695 static void pdf_indent(pdf_buffer *buf)
1697 pdf_puts(buf, "\t");
1700 static void pdf_putsi(pdf_buffer *buf, const char *text)
1703 pdf_puts(buf, text);
1706 static void pdf_putint(pdf_buffer *buf, int i)
1709 sprintf(tmp, "%d", i);
1713 static void pdf_putnumber(pdf_buffer *buf, double d)
1716 svg_format_number(tmp, sizeof(tmp), d);
1720 static void pdf_init_object(pdf_state *state, pdf_buffer *buf)
1722 pdf_init_buffer(state, buf);
1723 buf->id = ++state->last_obj_id;
1728 static void pdf_init_dict(pdf_state *state, pdf_buffer *buf)
1730 pdf_init_object(state, buf);
1734 static void pdf_set_color(pdf_buffer *buf, gfx_color_t color,
1735 gfx_color_t *current_color, const char *op)
1737 /* gfx_color_t is RRGGBBAA */
1738 if (*current_color == color)
1740 pdf_putnumber(buf, ((color >> 24) & 255) / 255.0);
1742 pdf_putnumber(buf, ((color >> 16) & 255) / 255.0);
1744 pdf_putnumber(buf, ((color >> 8) & 255) / 255.0);
1747 pdf_puts(buf, "\n");
1748 *current_color = color;
1751 static void pdf_set_stroke_color(pdf_buffer *buf, gfx_color_t color)
1753 pdf_set_color(buf, color, &buf->state->stroke_color, "RG");
1756 static void pdf_set_fill_color(pdf_buffer *buf, gfx_color_t color)
1758 pdf_set_color(buf, color, &buf->state->fill_color, "rg");
1761 static pdf_font *pdf_find_font(pdf_state *state, gfx_node_t *node)
1763 const char *ps_font = afm_get_font_postscript_name(node->filename);
1765 for (ef = state->font_list; ef; ef = ef->next) {
1766 if (!strcmp(ps_font, ef->ps_font))
1772 static void pdf_add_font(pdf_state *state, gfx_node_t *node)
1774 pdf_font *ef = pdf_find_font(state, node);
1777 ef = malloc(sizeof(pdf_font));
1779 rrd_set_error("malloc for pdf_font");
1780 state->has_failed = 1;
1783 pdf_init_dict(state, &ef->obj);
1784 ef->next = state->font_list;
1785 ef->ps_font = afm_get_font_postscript_name(node->filename);
1786 state->font_list = ef;
1788 pdf_putsi(&state->fontsdict_obj, "/F");
1789 pdf_putint(&state->fontsdict_obj, ef->obj.id);
1790 pdf_puts(&state->fontsdict_obj, " ");
1791 pdf_putint(&state->fontsdict_obj, ef->obj.id);
1792 pdf_puts(&state->fontsdict_obj, " 0 R\n");
1794 pdf_putsi(&ef->obj, "/Type /Font\n");
1795 pdf_putsi(&ef->obj, "/Subtype /Type1\n");
1796 pdf_putsi(&ef->obj, "/Name /F");
1797 pdf_putint(&ef->obj, ef->obj.id);
1798 pdf_puts(&ef->obj, "\n");
1799 pdf_putsi(&ef->obj, "/BaseFont /");
1800 pdf_puts(&ef->obj, ef->ps_font);
1801 pdf_puts(&ef->obj, "\n");
1802 pdf_putsi(&ef->obj, "/Encoding /WinAnsiEncoding\n");
1803 /* 'Cp1252' (this is latin 1 extended with 27 characters;
1804 the encoding is also known as 'winansi')
1805 http://www.lowagie.com/iText/tutorial/ch09.html */
1808 static void pdf_create_fonts(pdf_state *state)
1811 for (node = state->canvas->firstnode; node; node = node->next) {
1812 if (node->type == GFX_TEXT)
1813 pdf_add_font(state, node);
1817 static void pdf_write_linearea(pdf_state *state, gfx_node_t *node)
1820 pdf_buffer *s = &state->graph_stream;
1821 if (node->type == GFX_LINE) {
1823 svg_get_dash(node, &dash_info);
1824 if (!svg_dash_equal(&dash_info, &state->dash)) {
1825 state->dash = dash_info;
1826 if (dash_info.dash_enable) {
1828 pdf_putnumber(s, dash_info.adjusted_on);
1830 pdf_putnumber(s, dash_info.adjusted_off);
1832 pdf_putnumber(s, dash_info.dash_offset);
1833 pdf_puts(s, " d\n");
1835 pdf_puts(s, "[] 0 d\n");
1838 pdf_set_stroke_color(s, node->color);
1839 if (state->linecap != 1) {
1840 pdf_puts(s, "1 j\n");
1843 if (state->linejoin != 1) {
1844 pdf_puts(s, "1 J\n");
1845 state->linejoin = 1;
1847 if (node->size != state->line_width) {
1848 state->line_width = node->size;
1849 pdf_putnumber(s, state->line_width);
1850 pdf_puts(s, " w\n");
1853 pdf_set_fill_color(s, node->color);
1855 for (i = 0; i < node->points; i++) {
1856 ArtVpath *vec = node->path + i;
1858 double y = state->page_height - vec->y;
1859 if (node->type == GFX_AREA) {
1860 x += LINEOFFSET; /* adjust for libart handling of areas */
1863 switch (vec->code) {
1864 case ART_MOVETO_OPEN: /* fall-through */
1866 pdf_putnumber(s, x);
1868 pdf_putnumber(s, y);
1869 pdf_puts(s, " m\n");
1872 pdf_putnumber(s, x);
1874 pdf_putnumber(s, y);
1875 pdf_puts(s, " l\n");
1877 case ART_CURVETO: break; /* unsupported */
1878 case ART_END: break; /* nop */
1881 if (node->type == GFX_LINE) {
1882 pdf_puts(s, node->closed_path ? "s\n" : "S\n");
1888 static void pdf_write_text(pdf_state *state, gfx_node_t *node,
1889 int last_was_text, int next_is_text)
1892 pdf_buffer *s = &state->graph_stream;
1893 const unsigned char *p;
1894 pdf_font *font = pdf_find_font(state, node);
1896 double y = state->page_height - node->y;
1897 double dx = 0, dy = 0;
1898 double cos_a = 0, sin_a = 0;
1900 rrd_set_error("font disappeared");
1901 state->has_failed = 1;
1904 switch(node->valign){
1905 case GFX_V_TOP: dy = -node->size; break;
1906 case GFX_V_CENTER: dy = -node->size / 3.0; break;
1907 case GFX_V_BOTTOM: break;
1908 case GFX_V_NULL: break;
1910 switch (node->halign) {
1911 case GFX_H_RIGHT: dx = -afm_get_text_width(0, font->ps_font,
1912 node->size, node->tabwidth, node->text);
1914 case GFX_H_CENTER: dx = -afm_get_text_width(0, font->ps_font,
1915 node->size, node->tabwidth, node->text) / 2;
1917 case GFX_H_LEFT: break;
1918 case GFX_H_NULL: break;
1920 pdf_set_fill_color(s, node->color);
1921 if (node->angle != 0) {
1922 double a = 2 * M_PI * -node->angle / 360.0;
1923 double new_x, new_y;
1926 new_x = cos_a * dx - sin_a * dy + x;
1927 new_y = sin_a * dx + cos_a * dy + y;
1935 pdf_puts(s, "BT\n");
1936 if (state->font_id != font->obj.id || node->size != state->font_size) {
1937 state->font_id = font->obj.id;
1938 state->font_size = node->size;
1940 pdf_putint(s, font->obj.id);
1942 pdf_putnumber(s, node->size);
1943 pdf_puts(s, " Tf\n");
1945 if (node->angle == 0) {
1946 pdf_puts(s, "1 0 0 1 ");
1948 pdf_putnumber(s, cos_a);
1950 pdf_putnumber(s, sin_a);
1952 pdf_putnumber(s, -sin_a);
1954 pdf_putnumber(s, cos_a);
1957 pdf_putnumber(s, x);
1959 pdf_putnumber(s, y);
1960 pdf_puts(s, " Tm\n");
1962 for (p = (const unsigned char*)node->text; *p; p++) {
1974 snprintf(tmp, sizeof(tmp), "\\%03o", *p);
1977 pdf_put(s, (const char*)p, 1);
1981 pdf_puts(s, ") Tj\n");
1983 pdf_puts(s, "ET\n");
1986 static void pdf_write_content(pdf_state *state)
1989 int last_was_text = 0, next_is_text;
1990 for (node = state->canvas->firstnode; node; node = node->next) {
1991 switch (node->type) {
1994 pdf_write_linearea(state, node);
1997 next_is_text = node->next && node->next->type == GFX_TEXT;
1998 pdf_write_text(state, node, last_was_text, next_is_text);
2001 last_was_text = node->type == GFX_TEXT;
2005 static void pdf_init_document(pdf_state *state)
2007 pdf_init_buffer(state, &state->pdf_header);
2008 pdf_init_dict(state, &state->catalog_obj);
2009 pdf_init_dict(state, &state->pages_obj);
2010 pdf_init_dict(state, &state->page1_obj);
2011 pdf_init_dict(state, &state->fontsdict_obj);
2012 pdf_create_fonts(state);
2013 if (state->has_failed)
2015 /* make stream last object in file */
2016 pdf_init_object(state, &state->graph_stream);
2017 state->graph_stream.is_stream = 1;
2020 static void pdf_setup_document(pdf_state *state)
2022 /* all objects created by now, so init code can reference them */
2024 pdf_puts(&state->pdf_header, "%PDF-1.3\n");
2025 /* following 8 bit comment is recommended by Adobe for
2026 indicating binary file to file transfer applications */
2027 pdf_puts(&state->pdf_header, "%\xE2\xE3\xCF\xD3\n");
2029 pdf_putsi(&state->catalog_obj, "/Type /Catalog\n");
2030 pdf_putsi(&state->catalog_obj, "/Pages ");
2031 pdf_putint(&state->catalog_obj, state->pages_obj.id);
2032 pdf_puts(&state->catalog_obj, " 0 R\n");
2034 pdf_putsi(&state->pages_obj, "/Type /Pages\n");
2035 pdf_putsi(&state->pages_obj, "/Kids [");
2036 pdf_putint(&state->pages_obj, state->page1_obj.id);
2037 pdf_puts(&state->pages_obj, " 0 R]\n");
2038 pdf_putsi(&state->pages_obj, "/Count 1\n");
2040 pdf_putsi(&state->page1_obj, "/Type /Page\n");
2041 pdf_putsi(&state->page1_obj, "/Parent ");
2042 pdf_putint(&state->page1_obj, state->pages_obj.id);
2043 pdf_puts(&state->page1_obj, " 0 R\n");
2044 pdf_putsi(&state->page1_obj, "/MediaBox [0 0 ");
2045 pdf_putint(&state->page1_obj, state->page_width);
2046 pdf_puts(&state->page1_obj, " ");
2047 pdf_putint(&state->page1_obj, state->page_height);
2048 pdf_puts(&state->page1_obj, "]\n");
2049 pdf_putsi(&state->page1_obj, "/Contents ");
2050 pdf_putint(&state->page1_obj, state->graph_stream.id);
2051 pdf_puts(&state->page1_obj, " 0 R\n");
2052 pdf_putsi(&state->page1_obj, "/Resources << /Font ");
2053 pdf_putint(&state->page1_obj, state->fontsdict_obj.id);
2054 pdf_puts(&state->page1_obj, " 0 R >>\n");
2057 static void pdf_write_string_to_file(pdf_state *state, const char *text)
2059 fputs(text, state->fp);
2060 state->pdf_file_pos += strlen(text);
2063 static void pdf_write_buf_to_file(pdf_state *state, pdf_buffer *buf)
2066 buf->pdf_file_pos = state->pdf_file_pos;
2068 snprintf(tmp, sizeof(tmp), "%d 0 obj\n", buf->id);
2069 pdf_write_string_to_file(state, tmp);
2072 pdf_write_string_to_file(state, "<<\n");
2073 if (buf->is_stream) {
2074 snprintf(tmp, sizeof(tmp), "<< /Length %d >>\n", buf->current_size);
2075 pdf_write_string_to_file(state, tmp);
2076 pdf_write_string_to_file(state, "stream\n");
2078 fwrite(buf->data, 1, buf->current_size, state->fp);
2079 state->pdf_file_pos += buf->current_size;
2081 pdf_write_string_to_file(state, "endstream\n");
2083 pdf_write_string_to_file(state, ">>\n");
2085 pdf_write_string_to_file(state, "endobj\n");
2088 static void pdf_write_to_file(pdf_state *state)
2090 pdf_buffer *buf = state->first_buffer;
2092 state->pdf_file_pos = 0;
2093 pdf_write_buf_to_file(state, &state->pdf_header);
2096 pdf_write_buf_to_file(state, buf);
2097 buf = buf->next_buffer;
2099 xref_pos = state->pdf_file_pos;
2100 fprintf(state->fp, "xref\n");
2101 fprintf(state->fp, "%d %d\n", 0, state->last_obj_id + 1);
2102 /* TOC lines must be exactly 20 bytes including \n */
2103 fprintf(state->fp, "%010d %05d f\x20\n", 0, 65535);
2104 for (buf = state->first_buffer; buf; buf = buf->next_buffer) {
2106 fprintf(state->fp, "%010d %05d n\x20\n", buf->pdf_file_pos, 0);
2108 fprintf(state->fp, "trailer\n");
2109 fprintf(state->fp, "<<\n");
2110 fprintf(state->fp, "\t/Size %d\n", state->last_obj_id + 1);
2111 fprintf(state->fp, "\t/Root %d 0 R\n", state->catalog_obj.id);
2112 fprintf(state->fp, ">>\n");
2113 fprintf(state->fp, "startxref\n");
2114 fprintf(state->fp, "%d\n", xref_pos);
2115 fputs("%%EOF\n", state->fp);
2118 static void pdf_free_resources(pdf_state *state)
2120 pdf_buffer *buf = state->first_buffer;
2124 buf->alloc_size = buf->current_size = 0;
2125 buf = buf->next_buffer;
2127 while (state->font_list) {
2128 pdf_font *next = state->font_list->next;
2129 free(state->font_list);
2130 state->font_list = next;
2134 int gfx_render_pdf (gfx_canvas_t *canvas,
2135 art_u32 width, art_u32 height,
2136 gfx_color_t background, FILE *fp){
2137 struct pdf_state state;
2138 memset(&state, 0, sizeof(pdf_state));
2140 state.canvas = canvas;
2141 state.page_width = width;
2142 state.page_height = height;
2144 state.font_size = -1;
2145 state.font_list = NULL;
2147 state.linejoin = -1;
2148 pdf_init_document(&state);
2150 pdf_set_color(&state, background);
2151 fprintf(fp, "0 0 M 0 %d L %d %d L %d 0 L fill\n",
2152 height, width, height, width);
2154 if (!state.has_failed)
2155 pdf_write_content(&state);
2156 if (!state.has_failed)
2157 pdf_setup_document(&state);
2158 if (!state.has_failed)
2159 pdf_write_to_file(&state);
2160 pdf_free_resources(&state);
2161 return state.has_failed ? -1 : 0;