1 /****************************************************************************
2 * RRDtool 1.2rc4 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->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);
215 node->text = strdup(text);
217 node->filename = strdup(font);
222 node->tabwidth = tabwidth;
223 node->halign = h_align;
224 node->valign = v_align;
226 /* debugging: show text anchor
227 green is along x-axis, red is downward y-axis */
229 double a = 2 * M_PI * -node->angle / 360.0;
230 double cos_a = cos(a);
231 double sin_a = sin(a);
235 x + len * cos_a, y - len * sin_a,
239 x + len * sin_a, y + len * cos_a,
246 int gfx_render(gfx_canvas_t *canvas,
247 art_u32 width, art_u32 height,
248 gfx_color_t background, FILE *fp){
249 switch (canvas->imgformat) {
251 return gfx_render_png (canvas, width, height, background, fp);
253 return gfx_render_svg (canvas, width, height, background, fp);
255 return gfx_render_eps (canvas, width, height, background, fp);
257 return gfx_render_pdf (canvas, width, height, background, fp);
263 static void gfx_string_destroy ( gfx_string string ) {
265 if (string->glyphs) {
266 for (n=0; n<string->num_glyphs; ++n)
267 FT_Done_Glyph (string->glyphs[n].image);
268 free (string->glyphs);
274 double gfx_get_text_width ( gfx_canvas_t *canvas,
275 double start, char* font, double size,
276 double tabwidth, char* text, int rotation){
277 switch (canvas->imgformat) {
279 return gfx_get_text_width_libart (start, font, size, tabwidth, text, rotation);
280 case IF_SVG: /* fall through */
283 return afm_get_text_width(start, font, size, tabwidth, text);
285 return size * strlen(text);
289 double gfx_get_text_width_libart (
290 double start, char* font, double size,
291 double tabwidth, char* text, int rotation){
296 FT_Library library=NULL;
299 FT_Init_FreeType( &library );
300 error = FT_New_Face( library, font, 0, &face );
301 if ( error ) return -1;
302 error = FT_Set_Char_Size(face, size*64,size*64, 100,100);
303 if ( error ) return -1;
305 string = gfx_string_create( face, text, rotation,tabwidth);
306 text_width = string->width;
307 gfx_string_destroy(string);
308 FT_Done_FreeType(library);
309 return text_width/64;
312 static void gfx_libart_close_path(gfx_node_t *node, ArtVpath **vec)
314 /* libart must have end==start for closed paths,
315 even if using ART_MOVETO and not ART_MOVETO_OPEN
316 so add extra point which is the same as the starting point */
317 int points_max = node->points; /* scaled array has exact size */
318 int points = node->points - 1;
319 art_vpath_add_point (vec, &points, &points_max, ART_LINETO,
320 (**vec).x, (**vec).y);
321 art_vpath_add_point (vec, &points, &points_max, ART_END, 0, 0);
324 static void gfx_round_scaled_coordinates(ArtVpath *vec)
326 while (vec->code != ART_END) {
327 vec->x = floor(vec->x - LINEOFFSET + 0.5) + LINEOFFSET;
328 vec->y = floor(vec->y - LINEOFFSET + 0.5) + LINEOFFSET;
333 /* find bbox of a string */
334 static void compute_string_bbox(gfx_string string) {
338 bbox.xMin = bbox.yMin = 32000;
339 bbox.xMax = bbox.yMax = -32000;
340 for ( n = 0; n < string->num_glyphs; n++ ) {
342 FT_Glyph_Get_CBox( string->glyphs[n].image, ft_glyph_bbox_gridfit,
344 if (glyph_bbox.xMin < bbox.xMin) {
345 bbox.xMin = glyph_bbox.xMin;
347 if (glyph_bbox.yMin < bbox.yMin) {
348 bbox.yMin = glyph_bbox.yMin;
350 if (glyph_bbox.xMax > bbox.xMax) {
351 bbox.xMax = glyph_bbox.xMax;
353 if (glyph_bbox.yMax > bbox.yMax) {
354 bbox.yMax = glyph_bbox.yMax;
357 if ( bbox.xMin > bbox.xMax ) {
363 string->bbox.xMin = bbox.xMin;
364 string->bbox.xMax = bbox.xMax;
365 string->bbox.yMin = bbox.yMin;
366 string->bbox.yMax = bbox.yMax;
369 /* create a free type glyph string */
370 gfx_string gfx_string_create(FT_Face face,const char *text,
371 int rotation, double tabwidth)
374 FT_GlyphSlot slot = face->glyph; /* a small shortcut */
380 gfx_char glyph; /* current glyph in table */
385 ft_pen.x = 0; /* start at (0,0) !! */
388 string = (gfx_string) malloc (sizeof(struct gfx_string_s));
391 string->count = strlen (text);
392 string->glyphs = (gfx_char) calloc (string->count,sizeof(struct gfx_char_s));
393 string->num_glyphs = 0;
394 string->transform.xx = (FT_Fixed)( cos(M_PI*(rotation)/180.0)*0x10000);
395 string->transform.xy = (FT_Fixed)(-sin(M_PI*(rotation)/180.0)*0x10000);
396 string->transform.yx = (FT_Fixed)( sin(M_PI*(rotation)/180.0)*0x10000);
397 string->transform.yy = (FT_Fixed)( cos(M_PI*(rotation)/180.0)*0x10000);
399 use_kerning = FT_HAS_KERNING(face);
401 glyph = string->glyphs;
402 for (n=0; n<string->count; n++, glyph++) {
404 /* handle the tabs ...
405 have a witespace glyph inserted, but set its width such that the distance
406 of the new right edge is x times tabwidth from 0,0 where x is an integer. */
407 char letter = text[n];
409 if (letter == '\\' && n+1 < string->count && text[n+1] == 't'){
410 /* we have a tab here so skip the backslash and
411 set t to ' ' so that we get a white space */
420 /* initialize each struct gfx_char_s */
426 glyph->index = FT_Get_Char_Index( face, letter );
428 /* compute glyph origin */
429 if ( use_kerning && previous && glyph->index ) {
431 FT_Get_Kerning (face, previous, glyph->index,
432 ft_kerning_default, &kerning);
433 ft_pen.x += kerning.x;
434 ft_pen.y += kerning.y;
437 /* load the glyph image (in its native format) */
438 /* for now, we take a monochrome glyph bitmap */
439 error = FT_Load_Glyph (face, glyph->index, FT_LOAD_DEFAULT);
441 fprintf (stderr, "couldn't load glyph: %c\n", letter);
444 error = FT_Get_Glyph (slot, &glyph->image);
446 fprintf (stderr, "couldn't get glyph from slot: %c\n", letter);
449 /* if we are in tabbing mode, we replace the tab with a space and shift the position
450 of the space so that its left edge is where the tab was supposed to land us */
452 /* we are in gridfitting mode so the calculations happen in 1/64 pixles */
453 ft_pen.x = tabwidth*64.0 * (float)(1 + (long)(ft_pen.x / (tabwidth * 64.0))) - slot->advance.x;
455 /* store current pen position */
456 glyph->pos.x = ft_pen.x;
457 glyph->pos.y = ft_pen.y;
460 ft_pen.x += slot->advance.x;
461 ft_pen.y += slot->advance.y;
465 FT_Vector_Transform (&vec, &string->transform);
466 error = FT_Glyph_Transform (glyph->image, &string->transform, &vec);
468 fprintf (stderr, "couldn't transform glyph\n");
472 /* convert to a bitmap - destroy native image */
473 error = FT_Glyph_To_Bitmap (&glyph->image, FT_RENDER_MODE_NORMAL, 0, 1);
475 fprintf (stderr, "couldn't convert glyph to bitmap\n");
479 /* increment number of glyphs */
480 previous = glyph->index;
481 string->num_glyphs++;
483 /* printf ("number of glyphs = %d\n", string->num_glyphs);*/
484 compute_string_bbox( string );
485 /* the last character was a tab */
487 string->width = ft_pen.x;
489 string->width = string->bbox.xMax - string->bbox.xMin;
491 string->height = string->bbox.yMax - string->bbox.yMin;
496 static int gfx_save_png (art_u8 *buffer, FILE *fp,
497 long width, long height, long bytes_per_pixel);
498 /* render grafics into png image */
500 int gfx_render_png (gfx_canvas_t *canvas,
501 art_u32 width, art_u32 height,
502 gfx_color_t background, FILE *fp){
506 gfx_node_t *node = canvas->firstnode;
507 art_u8 red = background >> 24, green = (background >> 16) & 0xff;
508 art_u8 blue = (background >> 8) & 0xff, alpha = ( background & 0xff );
509 unsigned long pys_width = width * canvas->zoom;
510 unsigned long pys_height = height * canvas->zoom;
511 const int bytes_per_pixel = 3;
512 unsigned long rowstride = pys_width*bytes_per_pixel; /* bytes per pixel */
513 art_u8 *buffer = art_new (art_u8, rowstride*pys_height);
514 art_rgb_run_alpha (buffer, red, green, blue, alpha, pys_width*pys_height);
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 art_rgb_svp_alpha (svp ,0,0, pys_width, pys_height,
543 node->color, buffer, rowstride, NULL);
550 art_u8 fcolor[3],falpha;
554 FT_Vector vec; /* 26.6 */
556 float pen_x = 0.0 , pen_y = 0.0;
560 fcolor[0] = node->color >> 24;
561 fcolor[1] = (node->color >> 16) & 0xff;
562 fcolor[2] = (node->color >> 8) & 0xff;
563 falpha = node->color & 0xff;
564 error = FT_New_Face( library,
565 (char *)node->filename,
570 error = FT_Set_Char_Size(face, /* handle to face object */
571 (long)(node->size*64),
572 (long)(node->size*64),
573 (long)(100*canvas->zoom),
574 (long)(100*canvas->zoom));
576 pen_x = node->x * canvas->zoom;
577 pen_y = node->y * canvas->zoom;
579 string = gfx_string_create (face, node->text, node->angle, node->tabwidth);
580 switch(node->halign){
581 case GFX_H_RIGHT: vec.x = -string->bbox.xMax;
583 case GFX_H_CENTER: vec.x = abs(string->bbox.xMax) >= abs(string->bbox.xMin) ?
584 -string->bbox.xMax/2:-string->bbox.xMin/2;
586 case GFX_H_LEFT: vec.x = -string->bbox.xMin;
588 case GFX_H_NULL: vec.x = 0;
592 switch(node->valign){
593 case GFX_V_TOP: vec.y = string->bbox.yMax;
595 case GFX_V_CENTER: vec.y = abs(string->bbox.yMax) >= abs(string->bbox.yMin) ?
596 string->bbox.yMax/2:string->bbox.yMin/2;
598 case GFX_V_BOTTOM: vec.y = 0;
600 case GFX_V_NULL: vec.y = 0;
605 glyph = string->glyphs;
606 for(n=0; n<string->num_glyphs; ++n, ++glyph) {
611 /* make copy to transform */
612 if (! glyph->image) {
613 fprintf (stderr, "no image\n");
616 error = FT_Glyph_Copy (glyph->image, &image);
618 fprintf (stderr, "couldn't copy image\n");
624 FT_Vector_Transform (&vec, &string->transform);
626 bit = (FT_BitmapGlyph) image;
628 gr = bit->bitmap.num_grays -1;
629 for (iy=0; iy < bit->bitmap.rows; iy++){
630 long buf_y = iy+(pen_y+0.5)-bit->top;
631 if (buf_y < 0 || buf_y >= (long)pys_height) continue;
633 for (ix=0;ix < bit->bitmap.width;ix++){
634 long buf_x = ix + (pen_x + 0.5) + (double)bit->left ;
637 if (buf_x < 0 || buf_x >= (long)pys_width) continue;
638 buf_x *= bytes_per_pixel ;
639 font_alpha = *(bit->bitmap.buffer + iy * bit->bitmap.width + ix);
640 font_alpha = (art_u8)((double)font_alpha / gr * falpha);
641 for (iz = 0; iz < 3; iz++){
642 art_u8 *orig = buffer + buf_y + buf_x + iz;
643 *orig = (art_u8)((double)*orig / gr * ( gr - font_alpha) +
644 (double)fcolor[iz] / gr * (font_alpha));
648 FT_Done_Glyph (image);
650 gfx_string_destroy(string);
655 gfx_save_png(buffer,fp , pys_width,pys_height,bytes_per_pixel);
657 FT_Done_FreeType( library );
661 /* free memory used by nodes this will also remove memory required for
662 associated paths and svcs ... but not for text strings */
664 gfx_destroy (gfx_canvas_t *canvas){
665 gfx_node_t *next,*node = canvas->firstnode;
668 art_free(node->path);
671 free(node->filename);
678 static int gfx_save_png (art_u8 *buffer, FILE *fp, long width, long height, long bytes_per_pixel){
679 png_structp png_ptr = NULL;
680 png_infop info_ptr = NULL;
682 png_bytep *row_pointers;
683 int rowstride = width * bytes_per_pixel;
689 png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING,NULL,NULL,NULL);
694 row_pointers = (png_bytepp)png_malloc(png_ptr,
695 height*sizeof(png_bytep));
697 info_ptr = png_create_info_struct(png_ptr);
699 if (info_ptr == NULL)
701 png_destroy_write_struct(&png_ptr, (png_infopp)NULL);
705 if (setjmp(png_jmpbuf(png_ptr)))
707 /* If we get here, we had a problem writing the file */
708 png_destroy_write_struct(&png_ptr, &info_ptr);
712 png_init_io(png_ptr, fp);
713 png_set_IHDR (png_ptr, info_ptr,width, height,
714 8, PNG_COLOR_TYPE_RGB,
716 PNG_COMPRESSION_TYPE_DEFAULT,
717 PNG_FILTER_TYPE_DEFAULT);
719 text[0].key = "Software";
720 text[0].text = "RRDtool, Tobias Oetiker <tobi@oetike.ch>, http://tobi.oetiker.ch";
721 text[0].compression = PNG_TEXT_COMPRESSION_NONE;
722 png_set_text (png_ptr, info_ptr, text, 1);
724 /* lets make this fast */
725 png_set_compression_level(png_ptr,1);
726 png_set_filter(png_ptr,PNG_FILTER_TYPE_BASE,PNG_NO_FILTERS);
728 png_set_filter(png_ptr,PNG_FILTER_TYPE_BASE,PNG_FILTER_SUB);
729 png_set_compression_strategy(png_ptr,Z_HUFFMAN_ONLY);
730 png_set_compression_level(png_ptr,Z_BEST_SPEED); */
732 /* Write header data */
733 png_write_info (png_ptr, info_ptr);
734 for (i = 0; i < height; i++)
735 row_pointers[i] = (png_bytep) (buffer + i*rowstride);
737 png_write_image(png_ptr, row_pointers);
738 png_write_end(png_ptr, info_ptr);
739 png_destroy_write_struct(&png_ptr, &info_ptr);
744 /* ------- SVG -------
746 http://www.w3.org/TR/SVG/
748 static int svg_indent = 0;
749 static int svg_single_line = 0;
750 static const char *svg_default_font = "Helvetica";
751 typedef struct svg_dash
754 double dash_adjust, dash_len, dash_offset;
755 double adjusted_on, adjusted_off;
759 static void svg_print_indent(FILE *fp)
762 for (i = svg_indent - svg_single_line; i > 0; i--) {
768 static void svg_start_tag(FILE *fp, const char *name)
770 svg_print_indent(fp);
776 static void svg_close_tag_single_line(FILE *fp)
782 static void svg_close_tag(FILE *fp)
785 if (!svg_single_line)
789 static void svg_end_tag(FILE *fp, const char *name)
791 /* name is NULL if closing empty-node tag */
796 svg_print_indent(fp);
806 static void svg_close_tag_empty_node(FILE *fp)
808 svg_end_tag(fp, NULL);
811 static void svg_write_text(FILE *fp, const char *text)
813 const unsigned char *p, *start, *last;
815 p = (const unsigned char*)text;
818 /* trim leading spaces */
822 /* trim trailing spaces */
824 while ((ch = *p) != 0) {
829 /* encode trimmed text */
833 ch = afm_host2unicode(ch); /* unsafe macro */
835 case '&': fputs("&", fp); break;
836 case '<': fputs("<", fp); break;
837 case '>': fputs(">", fp); break;
838 case '"': fputs(""", fp); break;
841 fprintf(fp, "&#%d;", ch);
848 static void svg_format_number(char *buf, int bufsize, double d)
850 /* omit decimals if integer to reduce filesize */
852 snprintf(buf, bufsize, "%.2f", d);
853 p = buf; /* doesn't trust snprintf return value */
859 *p = '\0'; /* zap trailing zeros */
863 *p = '\0'; /* zap trailing dot */
868 static void svg_write_number(FILE *fp, double d)
871 svg_format_number(buf, sizeof(buf), d);
875 static int svg_color_is_black(int c)
877 /* gfx_color_t is RRGGBBAA */
878 return c == 0x000000FF;
881 static void svg_write_color(FILE *fp, gfx_color_t c, const char *attr)
883 /* gfx_color_t is RRGGBBAA, svg can use #RRGGBB and #RGB like html */
884 gfx_color_t rrggbb = (int)((c >> 8) & 0xFFFFFF);
885 gfx_color_t opacity = c & 0xFF;
886 fprintf(fp, " %s=\"", attr);
887 if ((rrggbb & 0x0F0F0F) == ((rrggbb >> 4) & 0x0F0F0F)) {
888 /* css2 short form, #rgb is #rrggbb, not #r0g0b0 */
889 fprintf(fp, "#%03lX",
890 ( ((rrggbb >> 8) & 0xF00)
891 | ((rrggbb >> 4) & 0x0F0)
892 | ( rrggbb & 0x00F)));
894 fprintf(fp, "#%06lX", rrggbb);
897 if (opacity != 0xFF) {
898 fprintf(fp, " stroke-opacity=\"");
899 svg_write_number(fp, opacity / 255.0);
904 static void svg_get_dash(gfx_node_t *node, svg_dash *d)
908 if (node->dash_on <= 0 || node->dash_off <= 0) {
913 d->dash_len = node->dash_on + node->dash_off;
914 /* dash on/off adjustment due to round caps */
915 d->dash_adjust = 0.8 * node->size;
916 d->adjusted_on = node->dash_on - d->dash_adjust;
917 if (d->adjusted_on < 0.01)
918 d->adjusted_on = 0.01;
919 d->adjusted_off = d->dash_len - d->adjusted_on;
920 /* dash offset calc */
921 if (node->path[0].x == node->path[1].x) /* only good for horz/vert lines */
922 offset = node->path[0].y;
924 offset = node->path[0].x;
925 mult = (int)fabs(offset / d->dash_len);
926 d->dash_offset = offset - mult * d->dash_len;
927 if (node->path[0].x < node->path[1].x || node->path[0].y < node->path[1].y)
928 d->dash_offset = d->dash_len - d->dash_offset;
931 static int svg_dash_equal(svg_dash *a, svg_dash *b)
933 if (a->dash_enable != b->dash_enable)
935 if (a->adjusted_on != b->adjusted_on)
937 if (a->adjusted_off != b->adjusted_off)
939 /* rest of properties will be the same when on+off are */
943 static void svg_common_path_attributes(FILE *fp, gfx_node_t *node)
946 svg_get_dash(node, &dash_info);
947 fputs(" stroke-width=\"", fp);
948 svg_write_number(fp, node->size);
950 svg_write_color(fp, node->color, "stroke");
951 fputs(" fill=\"none\"", fp);
952 if (dash_info.dash_enable) {
953 if (dash_info.dash_offset != 0) {
954 fputs(" stroke-dashoffset=\"", fp);
955 svg_write_number(fp, dash_info.dash_offset);
958 fputs(" stroke-dasharray=\"", fp);
959 svg_write_number(fp, dash_info.adjusted_on);
961 svg_write_number(fp, dash_info.adjusted_off);
966 static int svg_is_int_step(double a, double b)
968 double diff = fabs(a - b);
969 return floor(diff) == diff;
972 static int svg_path_straight_segment(FILE *fp,
973 double lastA, double currentA, double currentB,
975 int segment_idx, int isx, char absChar, char relChar)
977 if (!svg_is_int_step(lastA, currentA)) {
979 svg_write_number(fp, currentA);
982 if (segment_idx < node->points - 1) {
983 ArtVpath *vec = node->path + segment_idx + 1;
984 if (vec->code == ART_LINETO) {
985 double nextA = (isx ? vec->x : vec->y) - LINEOFFSET;
986 double nextB = (isx ? vec->y : vec->x) - LINEOFFSET;
987 if (nextB == currentB
988 && ((currentA >= lastA) == (nextA >= currentA))
989 && svg_is_int_step(currentA, nextA)) {
990 return 1; /* skip to next as it is a straight line */
995 svg_write_number(fp, currentA - lastA);
999 static void svg_path(FILE *fp, gfx_node_t *node, int multi)
1002 double lastX = 0, lastY = 0;
1003 /* for straight lines <path..> tags take less space than
1004 <line..> tags because of the efficient packing
1005 in the 'd' attribute */
1006 svg_start_tag(fp, "path");
1008 svg_common_path_attributes(fp, node);
1010 /* specification of the 'd' attribute: */
1011 /* http://www.w3.org/TR/SVG/paths.html#PathDataGeneralInformation */
1012 for (i = 0; i < node->points; i++) {
1013 ArtVpath *vec = node->path + i;
1014 double x = vec->x - LINEOFFSET;
1015 double y = vec->y - LINEOFFSET;
1016 switch (vec->code) {
1017 case ART_MOVETO_OPEN: /* fall-through */
1020 svg_write_number(fp, x);
1022 svg_write_number(fp, y);
1025 /* try optimize filesize by using minimal lineto commands */
1026 /* without introducing rounding errors. */
1028 if (svg_path_straight_segment(fp, lastY, y, x, node, i, 0, 'V', 'v'))
1030 } else if (y == lastY) {
1031 if (svg_path_straight_segment(fp, lastX, x, y, node, i, 1, 'H', 'h'))
1035 svg_write_number(fp, x);
1037 svg_write_number(fp, y);
1040 case ART_CURVETO: break; /* unsupported */
1041 case ART_END: break; /* nop */
1046 if (node->closed_path)
1049 svg_close_tag_empty_node(fp);
1052 static void svg_multi_path(FILE *fp, gfx_node_t **nodeR)
1054 /* optimize for multiple paths with the same color, penwidth, etc. */
1056 gfx_node_t *node = *nodeR;
1057 gfx_node_t *next = node->next;
1059 if (next->type != node->type
1060 || next->size != node->size
1061 || next->color != node->color
1062 || next->dash_on != node->dash_on
1063 || next->dash_off != node->dash_off)
1069 svg_path(fp, node, 0);
1072 svg_start_tag(fp, "g");
1073 svg_common_path_attributes(fp, node);
1075 while (num && node) {
1076 svg_path(fp, node, 1);
1082 svg_end_tag(fp, "g");
1085 static void svg_area(FILE *fp, gfx_node_t *node)
1088 double startX = 0, startY = 0;
1089 svg_start_tag(fp, "polygon");
1091 svg_write_color(fp, node->color, "fill");
1092 fputs(" points=\"", fp);
1093 for (i = 0; i < node->points; i++) {
1094 ArtVpath *vec = node->path + i;
1095 double x = vec->x - LINEOFFSET;
1096 double y = vec->y - LINEOFFSET;
1097 switch (vec->code) {
1098 case ART_MOVETO_OPEN: /* fall-through */
1100 svg_write_number(fp, x);
1102 svg_write_number(fp, y);
1107 if (i == node->points - 2
1108 && node->path[i + 1].code == ART_END
1109 && fabs(x - startX) < 0.001 && fabs(y - startY) < 0.001) {
1110 break; /* poly area always closed, no need for last point */
1113 svg_write_number(fp, x);
1115 svg_write_number(fp, y);
1117 case ART_CURVETO: break; /* unsupported */
1118 case ART_END: break; /* nop */
1122 svg_close_tag_empty_node(fp);
1125 static void svg_text(FILE *fp, gfx_node_t *node)
1127 double x = node->x - LINEOFFSET;
1128 double y = node->y - LINEOFFSET;
1129 if (node->angle != 0) {
1130 svg_start_tag(fp, "g");
1131 fputs(" transform=\"translate(", fp);
1132 svg_write_number(fp, x);
1134 svg_write_number(fp, y);
1135 fputs(") rotate(", fp);
1136 svg_write_number(fp, node->angle);
1141 switch (node->valign) {
1142 case GFX_V_TOP: y += node->size; break;
1143 case GFX_V_CENTER: y += node->size / 3; break;
1144 case GFX_V_BOTTOM: break;
1145 case GFX_V_NULL: break;
1147 svg_start_tag(fp, "text");
1149 svg_write_number(fp, x);
1150 fputs("\" y=\"", fp);
1151 svg_write_number(fp, y);
1153 /* if (strcmp(node->filename, svg_default_font))
1154 fprintf(fp, " font-family=\"%s\"", node->filename);
1156 fputs("\" font-family=\"Helvetica", fp);
1157 fputs("\" font-size=\"", fp);
1158 svg_write_number(fp, node->size);
1160 if (!svg_color_is_black(node->color))
1161 svg_write_color(fp, node->color, "fill");
1162 switch (node->halign) {
1163 case GFX_H_RIGHT: fputs(" text-anchor=\"end\"", fp); break;
1164 case GFX_H_CENTER: fputs(" text-anchor=\"middle\"", fp); break;
1165 case GFX_H_LEFT: break;
1166 case GFX_H_NULL: break;
1168 svg_close_tag_single_line(fp);
1169 /* support for node->tabwidth missing */
1170 svg_write_text(fp, node->text);
1171 svg_end_tag(fp, "text");
1172 if (node->angle != 0)
1173 svg_end_tag(fp, "g");
1176 int gfx_render_svg (gfx_canvas_t *canvas,
1177 art_u32 width, art_u32 height,
1178 gfx_color_t background, FILE *fp){
1179 gfx_node_t *node = canvas->firstnode;
1181 "<?xml version=\"1.0\" standalone=\"no\"?>\n"
1182 "<!DOCTYPE svg PUBLIC \"-//W3C//DTD SVG 1.0//EN\"\n"
1183 " \"http://www.w3.org/TR/2001/REC-SVG-20010904/DTD/svg10.dtd\">\n"
1185 " SVG file created by RRDtool,\n"
1186 " Tobias Oetiker <tobi@oetike.ch>, http://tobi.oetiker.ch\n"
1188 " The width/height attributes in the outhermost svg node\n"
1189 " are just default sizes for the browser which is used\n"
1190 " if the svg file is openened directly without being\n"
1191 " embedded in an html file.\n"
1192 " The viewBox is the local coord system for rrdtool.\n"
1194 svg_start_tag(fp, "svg");
1195 fputs(" width=\"", fp);
1196 svg_write_number(fp, width * canvas->zoom);
1197 fputs("\" height=\"", fp);
1198 svg_write_number(fp, height * canvas->zoom);
1199 fputs("\" x=\"0\" y=\"0\" viewBox=\"", fp);
1200 svg_write_number(fp, -LINEOFFSET);
1202 svg_write_number(fp, -LINEOFFSET);
1204 svg_write_number(fp, width - LINEOFFSET);
1206 svg_write_number(fp, height - LINEOFFSET);
1207 fputs("\" preserveAspectRatio=\"xMidYMid\"", fp);
1208 fprintf(fp, " font-family=\"%s\"", svg_default_font); /* default font */
1209 fputs(" stroke-linecap=\"round\" stroke-linejoin=\"round\"", fp);
1211 svg_start_tag(fp, "rect");
1212 fprintf(fp, " x=\"0\" y=\"0\" width=\"%d\" height=\"%d\"", width, height);
1213 svg_write_color(fp, background, "fill");
1214 svg_close_tag_empty_node(fp);
1216 switch (node->type) {
1218 svg_multi_path(fp, &node);
1228 svg_end_tag(fp, "svg");
1232 /* ------- EPS -------
1233 EPS and Postscript references:
1234 http://partners.adobe.com/asn/developer/technotes/postscript.html
1237 typedef struct eps_font
1239 const char *ps_font;
1241 struct eps_font *next;
1244 typedef struct eps_state
1247 gfx_canvas_t *canvas;
1248 art_u32 page_width, page_height;
1249 eps_font *font_list;
1255 int linecap, linejoin;
1259 static void eps_set_color(eps_state *state, gfx_color_t color)
1261 /* gfx_color_t is RRGGBBAA */
1262 if (state->color == color)
1264 fprintf(state->fp, "%d %d %d Rgb\n",
1265 (int)((color >> 24) & 255),
1266 (int)((color >> 16) & 255),
1267 (int)((color >> 8) & 255));
1268 state->color = color;
1271 static int eps_add_font(eps_state *state, gfx_node_t *node)
1273 /* The fonts list could be postponed to the end using
1274 (atend), but let's be nice and have them in the header. */
1275 const char *ps_font = afm_get_font_postscript_name(node->filename);
1277 for (ef = state->font_list; ef; ef = ef->next) {
1278 if (!strcmp(ps_font, ef->ps_font))
1281 ef = malloc(sizeof(eps_font));
1283 rrd_set_error("malloc for eps_font");
1286 ef->next = state->font_list;
1287 ef->ps_font = ps_font;
1288 state->font_list = ef;
1292 static void eps_list_fonts(eps_state *state, const char *dscName)
1295 int lineLen = strlen(dscName);
1296 if (!state->font_list)
1298 fputs(dscName, state->fp);
1299 for (ef = state->font_list; ef; ef = ef->next) {
1300 int nameLen = strlen(ef->ps_font);
1301 if (lineLen + nameLen > 100 && lineLen) {
1302 fputs("\n", state->fp);
1303 fputs("%%- \n", state->fp);
1306 fputs(" ", state->fp);
1309 fputs(ef->ps_font, state->fp);
1312 fputs("\n", state->fp);
1315 static void eps_define_fonts(eps_state *state)
1318 if (!state->font_list)
1320 for (ef = state->font_list; ef; ef = ef->next) {
1321 /* PostScript¨ LANGUAGE REFERENCE third edition
1325 "/%s findfont dup length dict begin\n"
1326 "{ 1 index /FID ne {def} {pop pop} ifelse } forall\n"
1327 "/Encoding ISOLatin1Encoding def\n"
1329 "/%s-ISOLatin1 exch definefont pop\n"
1330 "/SetFont-%s { /%s-ISOLatin1 findfont exch scalefont setfont } bd\n",
1331 ef->ps_font, ef->ps_font, ef->ps_font, ef->ps_font);
1335 static int eps_prologue(eps_state *state)
1339 "%!PS-Adobe-3.0 EPSF-3.0\n"
1340 "%%Creator: RRDtool 1.2rc4 Tobias Oetiker, http://tobi.oetiker.ch\n"
1341 /* can't like weird chars here */
1342 "%%Title: (RRDtool output)\n"
1343 "%%DocumentData: Clean7Bit\n"
1345 fprintf(state->fp, "%%%%BoundingBox: 0 0 %d %d\n",
1346 state->page_width, state->page_height);
1347 for (node = state->canvas->firstnode; node; node = node->next) {
1348 if (node->type == GFX_TEXT && eps_add_font(state, node) == -1)
1351 eps_list_fonts(state, "%%DocumentFonts:");
1352 eps_list_fonts(state, "%%DocumentNeededFonts:");
1356 "%%EndProlog\n" /* must have, or BoundingBox is ignored */
1357 "/bd { bind def } bind def\n"
1359 fprintf(state->fp, "/X { %.2f add } bd\n", LINEOFFSET);
1361 "/X2 {X exch X exch} bd\n"
1362 "/M {X2 moveto} bd\n"
1363 "/L {X2 lineto} bd\n"
1367 "/CP {closepath} bd\n"
1368 "/WS {setlinewidth stroke} bd\n"
1371 "/TaC {dup stringwidth pop neg 2 div 0 rmoveto } bd\n"
1372 "/TaR {dup stringwidth pop neg 0 rmoveto } bd\n"
1373 "/TL {moveto TaL show} bd\n"
1374 "/TC {moveto TaC show} bd\n"
1375 "/TR {moveto TaR show} bd\n"
1376 "/Rgb { 255.0 div 3 1 roll\n"
1377 " 255.0 div 3 1 roll \n"
1378 " 255.0 div 3 1 roll setrgbcolor } bd\n"
1380 eps_define_fonts(state);
1384 static void eps_clear_dash(eps_state *state)
1386 if (!state->has_dash)
1388 state->has_dash = 0;
1389 fputs("[1 0] 0 setdash\n", state->fp);
1392 static void eps_write_linearea(eps_state *state, gfx_node_t *node)
1395 FILE *fp = state->fp;
1397 int clearDashIfAny = 1;
1398 eps_set_color(state, node->color);
1399 if (node->type == GFX_LINE) {
1401 if (state->linecap != 1) {
1402 fputs("1 setlinecap\n", fp);
1405 if (state->linejoin != 1) {
1406 fputs("1 setlinejoin\n", fp);
1407 state->linejoin = 1;
1409 svg_get_dash(node, &dash_info);
1410 if (dash_info.dash_enable) {
1412 state->has_dash = 1;
1414 svg_write_number(fp, dash_info.adjusted_on);
1416 svg_write_number(fp, dash_info.adjusted_off);
1418 svg_write_number(fp, dash_info.dash_offset);
1419 fputs(" setdash\n", fp);
1423 eps_clear_dash(state);
1424 for (i = 0; i < node->points; i++) {
1425 ArtVpath *vec = node->path + i;
1427 double y = state->page_height - vec->y;
1428 if (vec->code == ART_MOVETO_OPEN || vec->code == ART_MOVETO)
1429 useOffset = (fabs(x - floor(x) - 0.5) < 0.01 && fabs(y - floor(y) - 0.5) < 0.01);
1434 switch (vec->code) {
1435 case ART_MOVETO_OPEN: /* fall-through */
1437 svg_write_number(fp, x);
1439 svg_write_number(fp, y);
1441 fputs(useOffset ? "M\n" : "m\n", fp);
1444 svg_write_number(fp, x);
1446 svg_write_number(fp, y);
1448 fputs(useOffset ? "L\n" : "l\n", fp);
1450 case ART_CURVETO: break; /* unsupported */
1451 case ART_END: break; /* nop */
1454 if (node->type == GFX_LINE) {
1455 if (node->closed_path)
1457 if (node->size != state->line_width) {
1458 state->line_width = node->size;
1459 svg_write_number(fp, state->line_width);
1469 static void eps_write_text(eps_state *state, gfx_node_t *node)
1471 FILE *fp = state->fp;
1472 const unsigned char *p;
1473 const char *ps_font = afm_get_font_postscript_name(node->filename);
1476 double y = state->page_height - node->y, ydelta = 0;
1478 eps_set_color(state, node->color);
1479 if (strcmp(ps_font, state->font) || node->size != state->font_size) {
1480 state->font = ps_font;
1481 state->font_size = node->size;
1482 svg_write_number(fp, state->font_size);
1483 fprintf(fp, " SetFont-%s\n", state->font);
1487 for (p = (const unsigned char*)node->text; *p; p++) {
1489 fputs("\\\n", fp); /* backslash and \n */
1504 fprintf(fp, "\\%03o", *p);
1511 switch(node->valign){
1512 case GFX_V_TOP: ydelta = -node->size; break;
1513 case GFX_V_CENTER: ydelta = -node->size / 3.0; break;
1514 case GFX_V_BOTTOM: break;
1515 case GFX_V_NULL: break;
1517 if (node->angle == 0)
1519 switch (node->halign) {
1520 case GFX_H_RIGHT: align = 'R'; break;
1521 case GFX_H_CENTER: align = 'C'; break;
1522 case GFX_H_LEFT: align= 'L'; break;
1523 case GFX_H_NULL: align= 'L'; break;
1525 if (node->angle != 0) {
1527 fputs(" gsave ", fp);
1528 svg_write_number(fp, x);
1530 svg_write_number(fp, y);
1531 fputs(" translate ", fp);
1532 svg_write_number(fp, -node->angle);
1533 fputs(" rotate 0 ", fp);
1534 svg_write_number(fp, ydelta);
1535 fputs(" moveto ", fp);
1536 fprintf(fp, "Ta%c", align);
1537 fputs(" show grestore\n", fp);
1539 svg_write_number(fp, x);
1541 svg_write_number(fp, y);
1548 static int eps_write_content(eps_state *state)
1551 fputs("%\n", state->fp);
1552 for (node = state->canvas->firstnode; node; node = node->next) {
1553 switch (node->type) {
1556 eps_write_linearea(state, node);
1559 eps_write_text(state, node);
1566 int gfx_render_eps (gfx_canvas_t *canvas,
1567 art_u32 width, art_u32 height,
1568 gfx_color_t background, FILE *fp){
1569 struct eps_state state;
1571 state.canvas = canvas;
1572 state.page_width = width;
1573 state.page_height = height;
1574 state.font = "no-default-font";
1575 state.font_size = -1;
1576 state.color = 0; /* black */
1577 state.font_list = NULL;
1579 state.linejoin = -1;
1581 if (eps_prologue(&state) == -1)
1583 eps_set_color(&state, background);
1584 fprintf(fp, "0 0 M 0 %d L %d %d L %d 0 L fill\n",
1585 height, width, height, width);
1586 if (eps_write_content(&state) == -1)
1588 fputs("showpage\n", fp);
1589 fputs("%%EOF\n", fp);
1590 while (state.font_list) {
1591 eps_font *next = state.font_list->next;
1592 free(state.font_list);
1593 state.font_list = next;
1598 /* ------- PDF -------
1599 PDF references page:
1600 http://partners.adobe.com/asn/developer/technotes/acrobatpdf.html
1603 typedef struct pdf_buffer
1605 int id, is_obj, is_dict, is_stream, pdf_file_pos;
1607 int alloc_size, current_size;
1608 struct pdf_buffer *previous_buffer, *next_buffer;
1609 struct pdf_state *state;
1612 typedef struct pdf_font
1614 const char *ps_font;
1616 struct pdf_font *next;
1619 typedef struct pdf_state
1622 gfx_canvas_t *canvas;
1623 art_u32 page_width, page_height;
1624 pdf_font *font_list;
1625 pdf_buffer *first_buffer, *last_buffer;
1629 gfx_color_t stroke_color, fill_color;
1634 int linecap, linejoin;
1637 pdf_buffer pdf_header;
1638 pdf_buffer catalog_obj, pages_obj, page1_obj;
1639 pdf_buffer fontsdict_obj;
1640 pdf_buffer graph_stream;
1643 static void pdf_init_buffer(pdf_state *state, pdf_buffer *buf)
1645 int initial_size = 32;
1648 buf->alloc_size = 0;
1649 buf->current_size = 0;
1650 buf->data = (char*)malloc(initial_size);
1652 buf->previous_buffer = NULL;
1653 buf->next_buffer = NULL;
1654 if (buf->data == NULL) {
1655 rrd_set_error("malloc for pdf_buffer data");
1656 state->has_failed = 1;
1659 buf->alloc_size = initial_size;
1660 if (state->last_buffer)
1661 state->last_buffer->next_buffer = buf;
1662 if (state->first_buffer == NULL)
1663 state->first_buffer = buf;
1664 buf->previous_buffer = state->last_buffer;
1665 state->last_buffer = buf;
1668 static void pdf_put(pdf_buffer *buf, const char *text, int len)
1672 if (buf->alloc_size < buf->current_size + len) {
1673 int new_size = buf->alloc_size;
1675 while (new_size < buf->current_size + len)
1677 new_buf = (char*)malloc(new_size);
1678 if (new_buf == NULL) {
1679 rrd_set_error("re-malloc for pdf_buffer data");
1680 buf->state->has_failed = 1;
1683 memcpy(new_buf, buf->data, buf->current_size);
1685 buf->data = new_buf;
1686 buf->alloc_size = new_size;
1688 memcpy(buf->data + buf->current_size, text, len);
1689 buf->current_size += len;
1692 static void pdf_puts(pdf_buffer *buf, const char *text)
1694 pdf_put(buf, text, strlen(text));
1697 static void pdf_indent(pdf_buffer *buf)
1699 pdf_puts(buf, "\t");
1702 static void pdf_putsi(pdf_buffer *buf, const char *text)
1705 pdf_puts(buf, text);
1708 static void pdf_putint(pdf_buffer *buf, int i)
1711 sprintf(tmp, "%d", i);
1715 static void pdf_putnumber(pdf_buffer *buf, double d)
1718 svg_format_number(tmp, sizeof(tmp), d);
1722 static void pdf_init_object(pdf_state *state, pdf_buffer *buf)
1724 pdf_init_buffer(state, buf);
1725 buf->id = ++state->last_obj_id;
1730 static void pdf_init_dict(pdf_state *state, pdf_buffer *buf)
1732 pdf_init_object(state, buf);
1736 static void pdf_set_color(pdf_buffer *buf, gfx_color_t color,
1737 gfx_color_t *current_color, const char *op)
1739 /* gfx_color_t is RRGGBBAA */
1740 if (*current_color == color)
1742 pdf_putnumber(buf, ((color >> 24) & 255) / 255.0);
1744 pdf_putnumber(buf, ((color >> 16) & 255) / 255.0);
1746 pdf_putnumber(buf, ((color >> 8) & 255) / 255.0);
1749 pdf_puts(buf, "\n");
1750 *current_color = color;
1753 static void pdf_set_stroke_color(pdf_buffer *buf, gfx_color_t color)
1755 pdf_set_color(buf, color, &buf->state->stroke_color, "RG");
1758 static void pdf_set_fill_color(pdf_buffer *buf, gfx_color_t color)
1760 pdf_set_color(buf, color, &buf->state->fill_color, "rg");
1763 static pdf_font *pdf_find_font(pdf_state *state, gfx_node_t *node)
1765 const char *ps_font = afm_get_font_postscript_name(node->filename);
1767 for (ef = state->font_list; ef; ef = ef->next) {
1768 if (!strcmp(ps_font, ef->ps_font))
1774 static void pdf_add_font(pdf_state *state, gfx_node_t *node)
1776 pdf_font *ef = pdf_find_font(state, node);
1779 ef = malloc(sizeof(pdf_font));
1781 rrd_set_error("malloc for pdf_font");
1782 state->has_failed = 1;
1785 pdf_init_dict(state, &ef->obj);
1786 ef->next = state->font_list;
1787 ef->ps_font = afm_get_font_postscript_name(node->filename);
1788 state->font_list = ef;
1790 pdf_putsi(&state->fontsdict_obj, "/F");
1791 pdf_putint(&state->fontsdict_obj, ef->obj.id);
1792 pdf_puts(&state->fontsdict_obj, " ");
1793 pdf_putint(&state->fontsdict_obj, ef->obj.id);
1794 pdf_puts(&state->fontsdict_obj, " 0 R\n");
1796 pdf_putsi(&ef->obj, "/Type /Font\n");
1797 pdf_putsi(&ef->obj, "/Subtype /Type1\n");
1798 pdf_putsi(&ef->obj, "/Name /F");
1799 pdf_putint(&ef->obj, ef->obj.id);
1800 pdf_puts(&ef->obj, "\n");
1801 pdf_putsi(&ef->obj, "/BaseFont /");
1802 pdf_puts(&ef->obj, ef->ps_font);
1803 pdf_puts(&ef->obj, "\n");
1804 pdf_putsi(&ef->obj, "/Encoding /WinAnsiEncoding\n");
1805 /* 'Cp1252' (this is latin 1 extended with 27 characters;
1806 the encoding is also known as 'winansi')
1807 http://www.lowagie.com/iText/tutorial/ch09.html */
1810 static void pdf_create_fonts(pdf_state *state)
1813 for (node = state->canvas->firstnode; node; node = node->next) {
1814 if (node->type == GFX_TEXT)
1815 pdf_add_font(state, node);
1819 static void pdf_write_linearea(pdf_state *state, gfx_node_t *node)
1822 pdf_buffer *s = &state->graph_stream;
1823 if (node->type == GFX_LINE) {
1825 svg_get_dash(node, &dash_info);
1826 if (!svg_dash_equal(&dash_info, &state->dash)) {
1827 state->dash = dash_info;
1828 if (dash_info.dash_enable) {
1830 pdf_putnumber(s, dash_info.adjusted_on);
1832 pdf_putnumber(s, dash_info.adjusted_off);
1834 pdf_putnumber(s, dash_info.dash_offset);
1835 pdf_puts(s, " d\n");
1837 pdf_puts(s, "[] 0 d\n");
1840 pdf_set_stroke_color(s, node->color);
1841 if (state->linecap != 1) {
1842 pdf_puts(s, "1 j\n");
1845 if (state->linejoin != 1) {
1846 pdf_puts(s, "1 J\n");
1847 state->linejoin = 1;
1849 if (node->size != state->line_width) {
1850 state->line_width = node->size;
1851 pdf_putnumber(s, state->line_width);
1852 pdf_puts(s, " w\n");
1855 pdf_set_fill_color(s, node->color);
1857 for (i = 0; i < node->points; i++) {
1858 ArtVpath *vec = node->path + i;
1860 double y = state->page_height - vec->y;
1861 if (node->type == GFX_AREA) {
1862 x += LINEOFFSET; /* adjust for libart handling of areas */
1865 switch (vec->code) {
1866 case ART_MOVETO_OPEN: /* fall-through */
1868 pdf_putnumber(s, x);
1870 pdf_putnumber(s, y);
1871 pdf_puts(s, " m\n");
1874 pdf_putnumber(s, x);
1876 pdf_putnumber(s, y);
1877 pdf_puts(s, " l\n");
1879 case ART_CURVETO: break; /* unsupported */
1880 case ART_END: break; /* nop */
1883 if (node->type == GFX_LINE) {
1884 pdf_puts(s, node->closed_path ? "s\n" : "S\n");
1890 static void pdf_write_text(pdf_state *state, gfx_node_t *node,
1891 int last_was_text, int next_is_text)
1894 pdf_buffer *s = &state->graph_stream;
1895 const unsigned char *p;
1896 pdf_font *font = pdf_find_font(state, node);
1898 double y = state->page_height - node->y;
1899 double dx = 0, dy = 0;
1900 double cos_a = 0, sin_a = 0;
1902 rrd_set_error("font disappeared");
1903 state->has_failed = 1;
1906 switch(node->valign){
1907 case GFX_V_TOP: dy = -node->size; break;
1908 case GFX_V_CENTER: dy = -node->size / 3.0; break;
1909 case GFX_V_BOTTOM: break;
1910 case GFX_V_NULL: break;
1912 switch (node->halign) {
1913 case GFX_H_RIGHT: dx = -afm_get_text_width(0, font->ps_font,
1914 node->size, node->tabwidth, node->text);
1916 case GFX_H_CENTER: dx = -afm_get_text_width(0, font->ps_font,
1917 node->size, node->tabwidth, node->text) / 2;
1919 case GFX_H_LEFT: break;
1920 case GFX_H_NULL: break;
1922 pdf_set_fill_color(s, node->color);
1923 if (node->angle != 0) {
1924 double a = 2 * M_PI * -node->angle / 360.0;
1925 double new_x, new_y;
1928 new_x = cos_a * dx - sin_a * dy + x;
1929 new_y = sin_a * dx + cos_a * dy + y;
1937 pdf_puts(s, "BT\n");
1938 if (state->font_id != font->obj.id || node->size != state->font_size) {
1939 state->font_id = font->obj.id;
1940 state->font_size = node->size;
1942 pdf_putint(s, font->obj.id);
1944 pdf_putnumber(s, node->size);
1945 pdf_puts(s, " Tf\n");
1947 if (node->angle == 0) {
1948 pdf_puts(s, "1 0 0 1 ");
1950 pdf_putnumber(s, cos_a);
1952 pdf_putnumber(s, sin_a);
1954 pdf_putnumber(s, -sin_a);
1956 pdf_putnumber(s, cos_a);
1959 pdf_putnumber(s, x);
1961 pdf_putnumber(s, y);
1962 pdf_puts(s, " Tm\n");
1964 for (p = (const unsigned char*)node->text; *p; p++) {
1976 snprintf(tmp, sizeof(tmp), "\\%03o", *p);
1979 pdf_put(s, (const char*)p, 1);
1983 pdf_puts(s, ") Tj\n");
1985 pdf_puts(s, "ET\n");
1988 static void pdf_write_content(pdf_state *state)
1991 int last_was_text = 0, next_is_text;
1992 for (node = state->canvas->firstnode; node; node = node->next) {
1993 switch (node->type) {
1996 pdf_write_linearea(state, node);
1999 next_is_text = node->next && node->next->type == GFX_TEXT;
2000 pdf_write_text(state, node, last_was_text, next_is_text);
2003 last_was_text = node->type == GFX_TEXT;
2007 static void pdf_init_document(pdf_state *state)
2009 pdf_init_buffer(state, &state->pdf_header);
2010 pdf_init_dict(state, &state->catalog_obj);
2011 pdf_init_dict(state, &state->pages_obj);
2012 pdf_init_dict(state, &state->page1_obj);
2013 pdf_init_dict(state, &state->fontsdict_obj);
2014 pdf_create_fonts(state);
2015 if (state->has_failed)
2017 /* make stream last object in file */
2018 pdf_init_object(state, &state->graph_stream);
2019 state->graph_stream.is_stream = 1;
2022 static void pdf_setup_document(pdf_state *state)
2024 /* all objects created by now, so init code can reference them */
2026 pdf_puts(&state->pdf_header, "%PDF-1.3\n");
2027 /* following 8 bit comment is recommended by Adobe for
2028 indicating binary file to file transfer applications */
2029 pdf_puts(&state->pdf_header, "%\xE2\xE3\xCF\xD3\n");
2031 pdf_putsi(&state->catalog_obj, "/Type /Catalog\n");
2032 pdf_putsi(&state->catalog_obj, "/Pages ");
2033 pdf_putint(&state->catalog_obj, state->pages_obj.id);
2034 pdf_puts(&state->catalog_obj, " 0 R\n");
2036 pdf_putsi(&state->pages_obj, "/Type /Pages\n");
2037 pdf_putsi(&state->pages_obj, "/Kids [");
2038 pdf_putint(&state->pages_obj, state->page1_obj.id);
2039 pdf_puts(&state->pages_obj, " 0 R]\n");
2040 pdf_putsi(&state->pages_obj, "/Count 1\n");
2042 pdf_putsi(&state->page1_obj, "/Type /Page\n");
2043 pdf_putsi(&state->page1_obj, "/Parent ");
2044 pdf_putint(&state->page1_obj, state->pages_obj.id);
2045 pdf_puts(&state->page1_obj, " 0 R\n");
2046 pdf_putsi(&state->page1_obj, "/MediaBox [0 0 ");
2047 pdf_putint(&state->page1_obj, state->page_width);
2048 pdf_puts(&state->page1_obj, " ");
2049 pdf_putint(&state->page1_obj, state->page_height);
2050 pdf_puts(&state->page1_obj, "]\n");
2051 pdf_putsi(&state->page1_obj, "/Contents ");
2052 pdf_putint(&state->page1_obj, state->graph_stream.id);
2053 pdf_puts(&state->page1_obj, " 0 R\n");
2054 pdf_putsi(&state->page1_obj, "/Resources << /Font ");
2055 pdf_putint(&state->page1_obj, state->fontsdict_obj.id);
2056 pdf_puts(&state->page1_obj, " 0 R >>\n");
2059 static void pdf_write_string_to_file(pdf_state *state, const char *text)
2061 fputs(text, state->fp);
2062 state->pdf_file_pos += strlen(text);
2065 static void pdf_write_buf_to_file(pdf_state *state, pdf_buffer *buf)
2068 buf->pdf_file_pos = state->pdf_file_pos;
2070 snprintf(tmp, sizeof(tmp), "%d 0 obj\n", buf->id);
2071 pdf_write_string_to_file(state, tmp);
2074 pdf_write_string_to_file(state, "<<\n");
2075 if (buf->is_stream) {
2076 snprintf(tmp, sizeof(tmp), "<< /Length %d >>\n", buf->current_size);
2077 pdf_write_string_to_file(state, tmp);
2078 pdf_write_string_to_file(state, "stream\n");
2080 fwrite(buf->data, 1, buf->current_size, state->fp);
2081 state->pdf_file_pos += buf->current_size;
2083 pdf_write_string_to_file(state, "endstream\n");
2085 pdf_write_string_to_file(state, ">>\n");
2087 pdf_write_string_to_file(state, "endobj\n");
2090 static void pdf_write_to_file(pdf_state *state)
2092 pdf_buffer *buf = state->first_buffer;
2094 state->pdf_file_pos = 0;
2095 pdf_write_buf_to_file(state, &state->pdf_header);
2098 pdf_write_buf_to_file(state, buf);
2099 buf = buf->next_buffer;
2101 xref_pos = state->pdf_file_pos;
2102 fprintf(state->fp, "xref\n");
2103 fprintf(state->fp, "%d %d\n", 0, state->last_obj_id + 1);
2104 /* TOC lines must be exactly 20 bytes including \n */
2105 fprintf(state->fp, "%010d %05d f\x20\n", 0, 65535);
2106 for (buf = state->first_buffer; buf; buf = buf->next_buffer) {
2108 fprintf(state->fp, "%010d %05d n\x20\n", buf->pdf_file_pos, 0);
2110 fprintf(state->fp, "trailer\n");
2111 fprintf(state->fp, "<<\n");
2112 fprintf(state->fp, "\t/Size %d\n", state->last_obj_id + 1);
2113 fprintf(state->fp, "\t/Root %d 0 R\n", state->catalog_obj.id);
2114 fprintf(state->fp, ">>\n");
2115 fprintf(state->fp, "startxref\n");
2116 fprintf(state->fp, "%d\n", xref_pos);
2117 fputs("%%EOF\n", state->fp);
2120 static void pdf_free_resources(pdf_state *state)
2122 pdf_buffer *buf = state->first_buffer;
2126 buf->alloc_size = buf->current_size = 0;
2127 buf = buf->next_buffer;
2129 while (state->font_list) {
2130 pdf_font *next = state->font_list->next;
2131 free(state->font_list);
2132 state->font_list = next;
2136 int gfx_render_pdf (gfx_canvas_t *canvas,
2137 art_u32 width, art_u32 height,
2138 gfx_color_t background, FILE *fp){
2139 struct pdf_state state;
2140 memset(&state, 0, sizeof(pdf_state));
2142 state.canvas = canvas;
2143 state.page_width = width;
2144 state.page_height = height;
2146 state.font_size = -1;
2147 state.font_list = NULL;
2149 state.linejoin = -1;
2150 pdf_init_document(&state);
2152 pdf_set_color(&state, background);
2153 fprintf(fp, "0 0 M 0 %d L %d %d L %d 0 L fill\n",
2154 height, width, height, width);
2156 if (!state.has_failed)
2157 pdf_write_content(&state);
2158 if (!state.has_failed)
2159 pdf_setup_document(&state);
2160 if (!state.has_failed)
2161 pdf_write_to_file(&state);
2162 pdf_free_resources(&state);
2163 return state.has_failed ? -1 : 0;