1 /****************************************************************************
2 * RRDtool 1.2rc6 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);
325 /* find bbox of a string */
326 static void compute_string_bbox(gfx_string string) {
330 bbox.xMin = bbox.yMin = 32000;
331 bbox.xMax = bbox.yMax = -32000;
332 for ( n = 0; n < string->num_glyphs; n++ ) {
334 FT_Glyph_Get_CBox( string->glyphs[n].image, ft_glyph_bbox_gridfit,
336 if (glyph_bbox.xMin < bbox.xMin) {
337 bbox.xMin = glyph_bbox.xMin;
339 if (glyph_bbox.yMin < bbox.yMin) {
340 bbox.yMin = glyph_bbox.yMin;
342 if (glyph_bbox.xMax > bbox.xMax) {
343 bbox.xMax = glyph_bbox.xMax;
345 if (glyph_bbox.yMax > bbox.yMax) {
346 bbox.yMax = glyph_bbox.yMax;
349 if ( bbox.xMin > bbox.xMax ) {
355 string->bbox.xMin = bbox.xMin;
356 string->bbox.xMax = bbox.xMax;
357 string->bbox.yMin = bbox.yMin;
358 string->bbox.yMax = bbox.yMax;
361 /* create a free type glyph string */
362 gfx_string gfx_string_create(FT_Face face,const char *text,
363 int rotation, double tabwidth)
366 FT_GlyphSlot slot = face->glyph; /* a small shortcut */
372 gfx_char glyph; /* current glyph in table */
377 ft_pen.x = 0; /* start at (0,0) !! */
380 string = (gfx_string) malloc (sizeof(struct gfx_string_s));
383 string->count = strlen (text);
384 string->glyphs = (gfx_char) calloc (string->count,sizeof(struct gfx_char_s));
385 string->num_glyphs = 0;
386 string->transform.xx = (FT_Fixed)( cos(M_PI*(rotation)/180.0)*0x10000);
387 string->transform.xy = (FT_Fixed)(-sin(M_PI*(rotation)/180.0)*0x10000);
388 string->transform.yx = (FT_Fixed)( sin(M_PI*(rotation)/180.0)*0x10000);
389 string->transform.yy = (FT_Fixed)( cos(M_PI*(rotation)/180.0)*0x10000);
391 use_kerning = FT_HAS_KERNING(face);
393 glyph = string->glyphs;
394 for (n=0; n<string->count; n++, glyph++) {
396 /* handle the tabs ...
397 have a witespace glyph inserted, but set its width such that the distance
398 of the new right edge is x times tabwidth from 0,0 where x is an integer. */
399 char letter = text[n];
401 if (letter == '\\' && n+1 < string->count && text[n+1] == 't'){
402 /* we have a tab here so skip the backslash and
403 set t to ' ' so that we get a white space */
412 /* initialize each struct gfx_char_s */
418 glyph->index = FT_Get_Char_Index( face, letter );
420 /* compute glyph origin */
421 if ( use_kerning && previous && glyph->index ) {
423 FT_Get_Kerning (face, previous, glyph->index,
424 ft_kerning_default, &kerning);
425 ft_pen.x += kerning.x;
426 ft_pen.y += kerning.y;
429 /* load the glyph image (in its native format) */
430 /* for now, we take a monochrome glyph bitmap */
431 error = FT_Load_Glyph (face, glyph->index, FT_LOAD_DEFAULT);
433 fprintf (stderr, "couldn't load glyph: %c\n", letter);
436 error = FT_Get_Glyph (slot, &glyph->image);
438 fprintf (stderr, "couldn't get glyph from slot: %c\n", letter);
441 /* if we are in tabbing mode, we replace the tab with a space and shift the position
442 of the space so that its left edge is where the tab was supposed to land us */
444 /* we are in gridfitting mode so the calculations happen in 1/64 pixles */
445 ft_pen.x = tabwidth*64.0 * (float)(1 + (long)(ft_pen.x / (tabwidth * 64.0))) - slot->advance.x;
447 /* store current pen position */
448 glyph->pos.x = ft_pen.x;
449 glyph->pos.y = ft_pen.y;
452 ft_pen.x += slot->advance.x;
453 ft_pen.y += slot->advance.y;
457 FT_Vector_Transform (&vec, &string->transform);
458 error = FT_Glyph_Transform (glyph->image, &string->transform, &vec);
460 fprintf (stderr, "couldn't transform glyph\n");
464 /* convert to a bitmap - destroy native image */
465 error = FT_Glyph_To_Bitmap (&glyph->image, FT_RENDER_MODE_NORMAL, 0, 1);
467 fprintf (stderr, "couldn't convert glyph to bitmap\n");
471 /* increment number of glyphs */
472 previous = glyph->index;
473 string->num_glyphs++;
475 /* printf ("number of glyphs = %d\n", string->num_glyphs);*/
476 compute_string_bbox( string );
477 /* the last character was a tab */
479 string->width = ft_pen.x;
481 string->width = string->bbox.xMax - string->bbox.xMin;
483 string->height = string->bbox.yMax - string->bbox.yMin;
488 static int gfx_save_png (art_u8 *buffer, FILE *fp,
489 long width, long height, long bytes_per_pixel);
490 /* render grafics into png image */
492 int gfx_render_png (gfx_canvas_t *canvas,
493 art_u32 width, art_u32 height,
494 gfx_color_t background, FILE *fp){
498 gfx_node_t *node = canvas->firstnode;
499 art_u8 red = background >> 24, green = (background >> 16) & 0xff;
500 art_u8 blue = (background >> 8) & 0xff, alpha = ( background & 0xff );
501 unsigned long pys_width = width * canvas->zoom;
502 unsigned long pys_height = height * canvas->zoom;
503 const int bytes_per_pixel = 3;
504 unsigned long rowstride = pys_width*bytes_per_pixel; /* bytes per pixel */
505 art_u8 *buffer = art_new (art_u8, rowstride*pys_height);
506 art_rgb_run_alpha (buffer, red, green, blue, alpha, pys_width*pys_height);
507 FT_Init_FreeType( &library );
509 switch (node->type) {
515 art_affine_scale(dst,canvas->zoom,canvas->zoom);
516 vec = art_vpath_affine_transform(node->path,dst);
517 if (node->closed_path)
518 gfx_libart_close_path(node, &vec);
519 /* gfx_round_scaled_coordinates(vec); */
520 pvec = art_vpath_perturb(vec);
522 if(node->type == GFX_LINE){
523 svp = art_svp_vpath_stroke ( pvec, ART_PATH_STROKE_JOIN_ROUND,
524 ART_PATH_STROKE_CAP_ROUND,
525 node->size*canvas->zoom,4,0.25);
527 svp = art_svp_from_vpath ( pvec );
528 svpt = art_svp_uncross( svp );
530 svp = art_svp_rewind_uncrossed(svpt,ART_WIND_RULE_NONZERO);
534 art_rgb_svp_alpha (svp ,0,0, pys_width, pys_height,
535 node->color, buffer, rowstride, NULL);
542 art_u8 fcolor[3],falpha;
546 FT_Vector vec; /* 26.6 */
548 float pen_x = 0.0 , pen_y = 0.0;
552 fcolor[0] = node->color >> 24;
553 fcolor[1] = (node->color >> 16) & 0xff;
554 fcolor[2] = (node->color >> 8) & 0xff;
555 falpha = node->color & 0xff;
556 error = FT_New_Face( library,
557 (char *)node->filename,
561 rrd_set_error("failed to load %s",node->filename);
564 error = FT_Set_Char_Size(face, /* handle to face object */
565 (long)(node->size*64),
566 (long)(node->size*64),
567 (long)(100*canvas->zoom),
568 (long)(100*canvas->zoom));
570 pen_x = node->x * canvas->zoom;
571 pen_y = node->y * canvas->zoom;
573 string = gfx_string_create (face, node->text, node->angle, node->tabwidth);
574 switch(node->halign){
575 case GFX_H_RIGHT: vec.x = -string->bbox.xMax;
577 case GFX_H_CENTER: vec.x = abs(string->bbox.xMax) >= abs(string->bbox.xMin) ?
578 -string->bbox.xMax/2:-string->bbox.xMin/2;
580 case GFX_H_LEFT: vec.x = -string->bbox.xMin;
582 case GFX_H_NULL: vec.x = 0;
586 switch(node->valign){
587 case GFX_V_TOP: vec.y = string->bbox.yMax;
589 case GFX_V_CENTER: vec.y = abs(string->bbox.yMax) >= abs(string->bbox.yMin) ?
590 string->bbox.yMax/2:string->bbox.yMin/2;
592 case GFX_V_BOTTOM: vec.y = 0;
594 case GFX_V_NULL: vec.y = 0;
599 glyph = string->glyphs;
600 for(n=0; n<string->num_glyphs; ++n, ++glyph) {
605 /* make copy to transform */
606 if (! glyph->image) {
607 fprintf (stderr, "no image\n");
610 error = FT_Glyph_Copy (glyph->image, &image);
612 fprintf (stderr, "couldn't copy image\n");
618 FT_Vector_Transform (&vec, &string->transform);
620 bit = (FT_BitmapGlyph) image;
622 gr = bit->bitmap.num_grays -1;
623 for (iy=0; iy < bit->bitmap.rows; iy++){
624 long buf_y = iy+(pen_y+0.5)-bit->top;
625 if (buf_y < 0 || buf_y >= (long)pys_height) continue;
627 for (ix=0;ix < bit->bitmap.width;ix++){
628 long buf_x = ix + (pen_x + 0.5) + (double)bit->left ;
631 if (buf_x < 0 || buf_x >= (long)pys_width) continue;
632 buf_x *= bytes_per_pixel ;
633 font_alpha = *(bit->bitmap.buffer + iy * bit->bitmap.width + ix);
634 font_alpha = (art_u8)((double)font_alpha / gr * falpha);
635 for (iz = 0; iz < 3; iz++){
636 art_u8 *orig = buffer + buf_y + buf_x + iz;
637 *orig = (art_u8)((double)*orig / gr * ( gr - font_alpha) +
638 (double)fcolor[iz] / gr * (font_alpha));
642 FT_Done_Glyph (image);
644 gfx_string_destroy(string);
649 gfx_save_png(buffer,fp , pys_width,pys_height,bytes_per_pixel);
651 FT_Done_FreeType( library );
655 /* free memory used by nodes this will also remove memory required for
656 associated paths and svcs ... but not for text strings */
658 gfx_destroy (gfx_canvas_t *canvas){
659 gfx_node_t *next,*node = canvas->firstnode;
662 art_free(node->path);
665 free(node->filename);
672 static int gfx_save_png (art_u8 *buffer, FILE *fp, long width, long height, long bytes_per_pixel){
673 png_structp png_ptr = NULL;
674 png_infop info_ptr = NULL;
676 png_bytep *row_pointers;
677 int rowstride = width * bytes_per_pixel;
683 png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING,NULL,NULL,NULL);
688 row_pointers = (png_bytepp)png_malloc(png_ptr,
689 height*sizeof(png_bytep));
691 info_ptr = png_create_info_struct(png_ptr);
693 if (info_ptr == NULL)
695 png_destroy_write_struct(&png_ptr, (png_infopp)NULL);
699 if (setjmp(png_jmpbuf(png_ptr)))
701 /* If we get here, we had a problem writing the file */
702 png_destroy_write_struct(&png_ptr, &info_ptr);
706 png_init_io(png_ptr, fp);
707 png_set_IHDR (png_ptr, info_ptr,width, height,
708 8, PNG_COLOR_TYPE_RGB,
710 PNG_COMPRESSION_TYPE_DEFAULT,
711 PNG_FILTER_TYPE_DEFAULT);
713 text[0].key = "Software";
714 text[0].text = "RRDtool, Tobias Oetiker <tobi@oetike.ch>, http://tobi.oetiker.ch";
715 text[0].compression = PNG_TEXT_COMPRESSION_NONE;
716 png_set_text (png_ptr, info_ptr, text, 1);
718 /* lets make this fast */
719 png_set_compression_level(png_ptr,1);
720 png_set_filter(png_ptr,PNG_FILTER_TYPE_BASE,PNG_NO_FILTERS);
722 png_set_filter(png_ptr,PNG_FILTER_TYPE_BASE,PNG_FILTER_SUB);
723 png_set_compression_strategy(png_ptr,Z_HUFFMAN_ONLY);
724 png_set_compression_level(png_ptr,Z_BEST_SPEED); */
726 /* Write header data */
727 png_write_info (png_ptr, info_ptr);
728 for (i = 0; i < height; i++)
729 row_pointers[i] = (png_bytep) (buffer + i*rowstride);
731 png_write_image(png_ptr, row_pointers);
732 png_write_end(png_ptr, info_ptr);
733 png_destroy_write_struct(&png_ptr, &info_ptr);
738 /* ------- SVG -------
740 http://www.w3.org/TR/SVG/
742 static int svg_indent = 0;
743 static int svg_single_line = 0;
744 static const char *svg_default_font = "Helvetica";
745 typedef struct svg_dash
748 double dash_adjust, dash_len, dash_offset;
749 double adjusted_on, adjusted_off;
753 static void svg_print_indent(FILE *fp)
756 for (i = svg_indent - svg_single_line; i > 0; i--) {
762 static void svg_start_tag(FILE *fp, const char *name)
764 svg_print_indent(fp);
770 static void svg_close_tag_single_line(FILE *fp)
776 static void svg_close_tag(FILE *fp)
779 if (!svg_single_line)
783 static void svg_end_tag(FILE *fp, const char *name)
785 /* name is NULL if closing empty-node tag */
790 svg_print_indent(fp);
800 static void svg_close_tag_empty_node(FILE *fp)
802 svg_end_tag(fp, NULL);
805 static void svg_write_text(FILE *fp, const char *text)
807 const unsigned char *p, *start, *last;
809 p = (const unsigned char*)text;
812 /* trim leading spaces */
816 /* trim trailing spaces */
818 while ((ch = *p) != 0) {
823 /* encode trimmed text */
827 ch = afm_host2unicode(ch); /* unsafe macro */
829 case '&': fputs("&", fp); break;
830 case '<': fputs("<", fp); break;
831 case '>': fputs(">", fp); break;
832 case '"': fputs(""", fp); break;
835 fprintf(fp, "&#%d;", ch);
842 static void svg_format_number(char *buf, int bufsize, double d)
844 /* omit decimals if integer to reduce filesize */
846 snprintf(buf, bufsize, "%.2f", d);
847 p = buf; /* doesn't trust snprintf return value */
853 *p = '\0'; /* zap trailing zeros */
857 *p = '\0'; /* zap trailing dot */
862 static void svg_write_number(FILE *fp, double d)
865 svg_format_number(buf, sizeof(buf), d);
869 static int svg_color_is_black(int c)
871 /* gfx_color_t is RRGGBBAA */
872 return c == 0x000000FF;
875 static void svg_write_color(FILE *fp, gfx_color_t c, const char *attr)
877 /* gfx_color_t is RRGGBBAA, svg can use #RRGGBB and #RGB like html */
878 gfx_color_t rrggbb = (int)((c >> 8) & 0xFFFFFF);
879 gfx_color_t opacity = c & 0xFF;
880 fprintf(fp, " %s=\"", attr);
881 if ((rrggbb & 0x0F0F0F) == ((rrggbb >> 4) & 0x0F0F0F)) {
882 /* css2 short form, #rgb is #rrggbb, not #r0g0b0 */
883 fprintf(fp, "#%03lX",
884 ( ((rrggbb >> 8) & 0xF00)
885 | ((rrggbb >> 4) & 0x0F0)
886 | ( rrggbb & 0x00F)));
888 fprintf(fp, "#%06lX", rrggbb);
891 if (opacity != 0xFF) {
892 fprintf(fp, " stroke-opacity=\"");
893 svg_write_number(fp, opacity / 255.0);
898 static void svg_get_dash(gfx_node_t *node, svg_dash *d)
902 if (node->dash_on <= 0 || node->dash_off <= 0) {
907 d->dash_len = node->dash_on + node->dash_off;
908 /* dash on/off adjustment due to round caps */
909 d->dash_adjust = 0.8 * node->size;
910 d->adjusted_on = node->dash_on - d->dash_adjust;
911 if (d->adjusted_on < 0.01)
912 d->adjusted_on = 0.01;
913 d->adjusted_off = d->dash_len - d->adjusted_on;
914 /* dash offset calc */
915 if (node->path[0].x == node->path[1].x) /* only good for horz/vert lines */
916 offset = node->path[0].y;
918 offset = node->path[0].x;
919 mult = (int)fabs(offset / d->dash_len);
920 d->dash_offset = offset - mult * d->dash_len;
921 if (node->path[0].x < node->path[1].x || node->path[0].y < node->path[1].y)
922 d->dash_offset = d->dash_len - d->dash_offset;
925 static int svg_dash_equal(svg_dash *a, svg_dash *b)
927 if (a->dash_enable != b->dash_enable)
929 if (a->adjusted_on != b->adjusted_on)
931 if (a->adjusted_off != b->adjusted_off)
933 /* rest of properties will be the same when on+off are */
937 static void svg_common_path_attributes(FILE *fp, gfx_node_t *node)
940 svg_get_dash(node, &dash_info);
941 fputs(" stroke-width=\"", fp);
942 svg_write_number(fp, node->size);
944 svg_write_color(fp, node->color, "stroke");
945 fputs(" fill=\"none\"", fp);
946 if (dash_info.dash_enable) {
947 if (dash_info.dash_offset != 0) {
948 fputs(" stroke-dashoffset=\"", fp);
949 svg_write_number(fp, dash_info.dash_offset);
952 fputs(" stroke-dasharray=\"", fp);
953 svg_write_number(fp, dash_info.adjusted_on);
955 svg_write_number(fp, dash_info.adjusted_off);
960 static int svg_is_int_step(double a, double b)
962 double diff = fabs(a - b);
963 return floor(diff) == diff;
966 static int svg_path_straight_segment(FILE *fp,
967 double lastA, double currentA, double currentB,
969 int segment_idx, int isx, char absChar, char relChar)
971 if (!svg_is_int_step(lastA, currentA)) {
973 svg_write_number(fp, currentA);
976 if (segment_idx < node->points - 1) {
977 ArtVpath *vec = node->path + segment_idx + 1;
978 if (vec->code == ART_LINETO) {
979 double nextA = (isx ? vec->x : vec->y) - LINEOFFSET;
980 double nextB = (isx ? vec->y : vec->x) - LINEOFFSET;
981 if (nextB == currentB
982 && ((currentA >= lastA) == (nextA >= currentA))
983 && svg_is_int_step(currentA, nextA)) {
984 return 1; /* skip to next as it is a straight line */
989 svg_write_number(fp, currentA - lastA);
993 static void svg_path(FILE *fp, gfx_node_t *node, int multi)
996 double lastX = 0, lastY = 0;
997 /* for straight lines <path..> tags take less space than
998 <line..> tags because of the efficient packing
999 in the 'd' attribute */
1000 svg_start_tag(fp, "path");
1002 svg_common_path_attributes(fp, node);
1004 /* specification of the 'd' attribute: */
1005 /* http://www.w3.org/TR/SVG/paths.html#PathDataGeneralInformation */
1006 for (i = 0; i < node->points; i++) {
1007 ArtVpath *vec = node->path + i;
1008 double x = vec->x - LINEOFFSET;
1009 double y = vec->y - LINEOFFSET;
1010 switch (vec->code) {
1011 case ART_MOVETO_OPEN: /* fall-through */
1014 svg_write_number(fp, x);
1016 svg_write_number(fp, y);
1019 /* try optimize filesize by using minimal lineto commands */
1020 /* without introducing rounding errors. */
1022 if (svg_path_straight_segment(fp, lastY, y, x, node, i, 0, 'V', 'v'))
1024 } else if (y == lastY) {
1025 if (svg_path_straight_segment(fp, lastX, x, y, node, i, 1, 'H', 'h'))
1029 svg_write_number(fp, x);
1031 svg_write_number(fp, y);
1034 case ART_CURVETO: break; /* unsupported */
1035 case ART_END: break; /* nop */
1040 if (node->closed_path)
1043 svg_close_tag_empty_node(fp);
1046 static void svg_multi_path(FILE *fp, gfx_node_t **nodeR)
1048 /* optimize for multiple paths with the same color, penwidth, etc. */
1050 gfx_node_t *node = *nodeR;
1051 gfx_node_t *next = node->next;
1053 if (next->type != node->type
1054 || next->size != node->size
1055 || next->color != node->color
1056 || next->dash_on != node->dash_on
1057 || next->dash_off != node->dash_off)
1063 svg_path(fp, node, 0);
1066 svg_start_tag(fp, "g");
1067 svg_common_path_attributes(fp, node);
1069 while (num && node) {
1070 svg_path(fp, node, 1);
1076 svg_end_tag(fp, "g");
1079 static void svg_area(FILE *fp, gfx_node_t *node)
1082 double startX = 0, startY = 0;
1083 svg_start_tag(fp, "polygon");
1085 svg_write_color(fp, node->color, "fill");
1086 fputs(" points=\"", fp);
1087 for (i = 0; i < node->points; i++) {
1088 ArtVpath *vec = node->path + i;
1089 double x = vec->x - LINEOFFSET;
1090 double y = vec->y - LINEOFFSET;
1091 switch (vec->code) {
1092 case ART_MOVETO_OPEN: /* fall-through */
1094 svg_write_number(fp, x);
1096 svg_write_number(fp, y);
1101 if (i == node->points - 2
1102 && node->path[i + 1].code == ART_END
1103 && fabs(x - startX) < 0.001 && fabs(y - startY) < 0.001) {
1104 break; /* poly area always closed, no need for last point */
1107 svg_write_number(fp, x);
1109 svg_write_number(fp, y);
1111 case ART_CURVETO: break; /* unsupported */
1112 case ART_END: break; /* nop */
1116 svg_close_tag_empty_node(fp);
1119 static void svg_text(FILE *fp, gfx_node_t *node)
1121 double x = node->x - LINEOFFSET;
1122 double y = node->y - LINEOFFSET;
1123 if (node->angle != 0) {
1124 svg_start_tag(fp, "g");
1125 fputs(" transform=\"translate(", fp);
1126 svg_write_number(fp, x);
1128 svg_write_number(fp, y);
1129 fputs(") rotate(", fp);
1130 svg_write_number(fp, node->angle);
1135 switch (node->valign) {
1136 case GFX_V_TOP: y += node->size; break;
1137 case GFX_V_CENTER: y += node->size / 3; break;
1138 case GFX_V_BOTTOM: break;
1139 case GFX_V_NULL: break;
1141 svg_start_tag(fp, "text");
1143 svg_write_number(fp, x);
1144 fputs("\" y=\"", fp);
1145 svg_write_number(fp, y);
1147 /* if (strcmp(node->filename, svg_default_font))
1148 fprintf(fp, " font-family=\"%s\"", node->filename);
1150 fputs("\" font-family=\"Helvetica", fp);
1151 fputs("\" font-size=\"", fp);
1152 svg_write_number(fp, node->size);
1154 if (!svg_color_is_black(node->color))
1155 svg_write_color(fp, node->color, "fill");
1156 switch (node->halign) {
1157 case GFX_H_RIGHT: fputs(" text-anchor=\"end\"", fp); break;
1158 case GFX_H_CENTER: fputs(" text-anchor=\"middle\"", fp); break;
1159 case GFX_H_LEFT: break;
1160 case GFX_H_NULL: break;
1162 svg_close_tag_single_line(fp);
1163 /* support for node->tabwidth missing */
1164 svg_write_text(fp, node->text);
1165 svg_end_tag(fp, "text");
1166 if (node->angle != 0)
1167 svg_end_tag(fp, "g");
1170 int gfx_render_svg (gfx_canvas_t *canvas,
1171 art_u32 width, art_u32 height,
1172 gfx_color_t background, FILE *fp){
1173 gfx_node_t *node = canvas->firstnode;
1175 "<?xml version=\"1.0\" standalone=\"no\"?>\n"
1176 "<!DOCTYPE svg PUBLIC \"-//W3C//DTD SVG 1.0//EN\"\n"
1177 " \"http://www.w3.org/TR/2001/REC-SVG-20010904/DTD/svg10.dtd\">\n"
1179 " SVG file created by RRDtool,\n"
1180 " Tobias Oetiker <tobi@oetike.ch>, http://tobi.oetiker.ch\n"
1182 " The width/height attributes in the outhermost svg node\n"
1183 " are just default sizes for the browser which is used\n"
1184 " if the svg file is openened directly without being\n"
1185 " embedded in an html file.\n"
1186 " The viewBox is the local coord system for rrdtool.\n"
1188 svg_start_tag(fp, "svg");
1189 fputs(" width=\"", fp);
1190 svg_write_number(fp, width * canvas->zoom);
1191 fputs("\" height=\"", fp);
1192 svg_write_number(fp, height * canvas->zoom);
1193 fputs("\" x=\"0\" y=\"0\" viewBox=\"", fp);
1194 svg_write_number(fp, -LINEOFFSET);
1196 svg_write_number(fp, -LINEOFFSET);
1198 svg_write_number(fp, width - LINEOFFSET);
1200 svg_write_number(fp, height - LINEOFFSET);
1201 fputs("\" preserveAspectRatio=\"xMidYMid\"", fp);
1202 fprintf(fp, " font-family=\"%s\"", svg_default_font); /* default font */
1203 fputs(" stroke-linecap=\"round\" stroke-linejoin=\"round\"", fp);
1205 svg_start_tag(fp, "rect");
1206 fprintf(fp, " x=\"0\" y=\"0\" width=\"%d\" height=\"%d\"", width, height);
1207 svg_write_color(fp, background, "fill");
1208 svg_close_tag_empty_node(fp);
1210 switch (node->type) {
1212 svg_multi_path(fp, &node);
1222 svg_end_tag(fp, "svg");
1226 /* ------- EPS -------
1227 EPS and Postscript references:
1228 http://partners.adobe.com/asn/developer/technotes/postscript.html
1231 typedef struct eps_font
1233 const char *ps_font;
1235 struct eps_font *next;
1238 typedef struct eps_state
1241 gfx_canvas_t *canvas;
1242 art_u32 page_width, page_height;
1243 eps_font *font_list;
1249 int linecap, linejoin;
1253 static void eps_set_color(eps_state *state, gfx_color_t color)
1255 /* gfx_color_t is RRGGBBAA */
1256 if (state->color == color)
1258 fprintf(state->fp, "%d %d %d Rgb\n",
1259 (int)((color >> 24) & 255),
1260 (int)((color >> 16) & 255),
1261 (int)((color >> 8) & 255));
1262 state->color = color;
1265 static int eps_add_font(eps_state *state, gfx_node_t *node)
1267 /* The fonts list could be postponed to the end using
1268 (atend), but let's be nice and have them in the header. */
1269 const char *ps_font = afm_get_font_postscript_name(node->filename);
1271 for (ef = state->font_list; ef; ef = ef->next) {
1272 if (!strcmp(ps_font, ef->ps_font))
1275 ef = malloc(sizeof(eps_font));
1277 rrd_set_error("malloc for eps_font");
1280 ef->next = state->font_list;
1281 ef->ps_font = ps_font;
1282 state->font_list = ef;
1286 static void eps_list_fonts(eps_state *state, const char *dscName)
1289 int lineLen = strlen(dscName);
1290 if (!state->font_list)
1292 fputs(dscName, state->fp);
1293 for (ef = state->font_list; ef; ef = ef->next) {
1294 int nameLen = strlen(ef->ps_font);
1295 if (lineLen + nameLen > 100 && lineLen) {
1296 fputs("\n", state->fp);
1297 fputs("%%- \n", state->fp);
1300 fputs(" ", state->fp);
1303 fputs(ef->ps_font, state->fp);
1306 fputs("\n", state->fp);
1309 static void eps_define_fonts(eps_state *state)
1312 if (!state->font_list)
1314 for (ef = state->font_list; ef; ef = ef->next) {
1315 /* PostScript¨ LANGUAGE REFERENCE third edition
1319 "/%s findfont dup length dict begin\n"
1320 "{ 1 index /FID ne {def} {pop pop} ifelse } forall\n"
1321 "/Encoding ISOLatin1Encoding def\n"
1323 "/%s-ISOLatin1 exch definefont pop\n"
1324 "/SetFont-%s { /%s-ISOLatin1 findfont exch scalefont setfont } bd\n",
1325 ef->ps_font, ef->ps_font, ef->ps_font, ef->ps_font);
1329 static int eps_prologue(eps_state *state)
1333 "%!PS-Adobe-3.0 EPSF-3.0\n"
1334 "%%Creator: RRDtool 1.2rc6 Tobias Oetiker, http://tobi.oetiker.ch\n"
1335 /* can't like weird chars here */
1336 "%%Title: (RRDtool output)\n"
1337 "%%DocumentData: Clean7Bit\n"
1339 fprintf(state->fp, "%%%%BoundingBox: 0 0 %d %d\n",
1340 state->page_width, state->page_height);
1341 for (node = state->canvas->firstnode; node; node = node->next) {
1342 if (node->type == GFX_TEXT && eps_add_font(state, node) == -1)
1345 eps_list_fonts(state, "%%DocumentFonts:");
1346 eps_list_fonts(state, "%%DocumentNeededFonts:");
1350 "%%EndProlog\n" /* must have, or BoundingBox is ignored */
1351 "/bd { bind def } bind def\n"
1353 fprintf(state->fp, "/X { %.2f add } bd\n", LINEOFFSET);
1355 "/X2 {X exch X exch} bd\n"
1356 "/M {X2 moveto} bd\n"
1357 "/L {X2 lineto} bd\n"
1361 "/CP {closepath} bd\n"
1362 "/WS {setlinewidth stroke} bd\n"
1365 "/TaC {dup stringwidth pop neg 2 div 0 rmoveto } bd\n"
1366 "/TaR {dup stringwidth pop neg 0 rmoveto } bd\n"
1367 "/TL {moveto TaL show} bd\n"
1368 "/TC {moveto TaC show} bd\n"
1369 "/TR {moveto TaR show} bd\n"
1370 "/Rgb { 255.0 div 3 1 roll\n"
1371 " 255.0 div 3 1 roll \n"
1372 " 255.0 div 3 1 roll setrgbcolor } bd\n"
1374 eps_define_fonts(state);
1378 static void eps_clear_dash(eps_state *state)
1380 if (!state->has_dash)
1382 state->has_dash = 0;
1383 fputs("[1 0] 0 setdash\n", state->fp);
1386 static void eps_write_linearea(eps_state *state, gfx_node_t *node)
1389 FILE *fp = state->fp;
1391 int clearDashIfAny = 1;
1392 eps_set_color(state, node->color);
1393 if (node->type == GFX_LINE) {
1395 if (state->linecap != 1) {
1396 fputs("1 setlinecap\n", fp);
1399 if (state->linejoin != 1) {
1400 fputs("1 setlinejoin\n", fp);
1401 state->linejoin = 1;
1403 svg_get_dash(node, &dash_info);
1404 if (dash_info.dash_enable) {
1406 state->has_dash = 1;
1408 svg_write_number(fp, dash_info.adjusted_on);
1410 svg_write_number(fp, dash_info.adjusted_off);
1412 svg_write_number(fp, dash_info.dash_offset);
1413 fputs(" setdash\n", fp);
1417 eps_clear_dash(state);
1418 for (i = 0; i < node->points; i++) {
1419 ArtVpath *vec = node->path + i;
1421 double y = state->page_height - vec->y;
1422 if (vec->code == ART_MOVETO_OPEN || vec->code == ART_MOVETO)
1423 useOffset = (fabs(x - floor(x) - 0.5) < 0.01 && fabs(y - floor(y) - 0.5) < 0.01);
1428 switch (vec->code) {
1429 case ART_MOVETO_OPEN: /* fall-through */
1431 svg_write_number(fp, x);
1433 svg_write_number(fp, y);
1435 fputs(useOffset ? "M\n" : "m\n", fp);
1438 svg_write_number(fp, x);
1440 svg_write_number(fp, y);
1442 fputs(useOffset ? "L\n" : "l\n", fp);
1444 case ART_CURVETO: break; /* unsupported */
1445 case ART_END: break; /* nop */
1448 if (node->type == GFX_LINE) {
1449 if (node->closed_path)
1451 if (node->size != state->line_width) {
1452 state->line_width = node->size;
1453 svg_write_number(fp, state->line_width);
1463 static void eps_write_text(eps_state *state, gfx_node_t *node)
1465 FILE *fp = state->fp;
1466 const unsigned char *p;
1467 const char *ps_font = afm_get_font_postscript_name(node->filename);
1470 double y = state->page_height - node->y, ydelta = 0;
1472 eps_set_color(state, node->color);
1473 if (strcmp(ps_font, state->font) || node->size != state->font_size) {
1474 state->font = ps_font;
1475 state->font_size = node->size;
1476 svg_write_number(fp, state->font_size);
1477 fprintf(fp, " SetFont-%s\n", state->font);
1481 for (p = (const unsigned char*)node->text; *p; p++) {
1483 fputs("\\\n", fp); /* backslash and \n */
1498 fprintf(fp, "\\%03o", *p);
1505 switch(node->valign){
1506 case GFX_V_TOP: ydelta = -node->size; break;
1507 case GFX_V_CENTER: ydelta = -node->size / 3.0; break;
1508 case GFX_V_BOTTOM: break;
1509 case GFX_V_NULL: break;
1511 if (node->angle == 0)
1513 switch (node->halign) {
1514 case GFX_H_RIGHT: align = 'R'; break;
1515 case GFX_H_CENTER: align = 'C'; break;
1516 case GFX_H_LEFT: align= 'L'; break;
1517 case GFX_H_NULL: align= 'L'; break;
1519 if (node->angle != 0) {
1521 fputs(" gsave ", fp);
1522 svg_write_number(fp, x);
1524 svg_write_number(fp, y);
1525 fputs(" translate ", fp);
1526 svg_write_number(fp, -node->angle);
1527 fputs(" rotate 0 ", fp);
1528 svg_write_number(fp, ydelta);
1529 fputs(" moveto ", fp);
1530 fprintf(fp, "Ta%c", align);
1531 fputs(" show grestore\n", fp);
1533 svg_write_number(fp, x);
1535 svg_write_number(fp, y);
1542 static int eps_write_content(eps_state *state)
1545 fputs("%\n", state->fp);
1546 for (node = state->canvas->firstnode; node; node = node->next) {
1547 switch (node->type) {
1550 eps_write_linearea(state, node);
1553 eps_write_text(state, node);
1560 int gfx_render_eps (gfx_canvas_t *canvas,
1561 art_u32 width, art_u32 height,
1562 gfx_color_t background, FILE *fp){
1563 struct eps_state state;
1565 state.canvas = canvas;
1566 state.page_width = width;
1567 state.page_height = height;
1568 state.font = "no-default-font";
1569 state.font_size = -1;
1570 state.color = 0; /* black */
1571 state.font_list = NULL;
1573 state.linejoin = -1;
1575 if (eps_prologue(&state) == -1)
1577 eps_set_color(&state, background);
1578 fprintf(fp, "0 0 M 0 %d L %d %d L %d 0 L fill\n",
1579 height, width, height, width);
1580 if (eps_write_content(&state) == -1)
1582 fputs("showpage\n", fp);
1583 fputs("%%EOF\n", fp);
1584 while (state.font_list) {
1585 eps_font *next = state.font_list->next;
1586 free(state.font_list);
1587 state.font_list = next;
1592 /* ------- PDF -------
1593 PDF references page:
1594 http://partners.adobe.com/asn/developer/technotes/acrobatpdf.html
1597 typedef struct pdf_buffer
1599 int id, is_obj, is_dict, is_stream, pdf_file_pos;
1601 int alloc_size, current_size;
1602 struct pdf_buffer *previous_buffer, *next_buffer;
1603 struct pdf_state *state;
1606 typedef struct pdf_font
1608 const char *ps_font;
1610 struct pdf_font *next;
1613 typedef struct pdf_state
1616 gfx_canvas_t *canvas;
1617 art_u32 page_width, page_height;
1618 pdf_font *font_list;
1619 pdf_buffer *first_buffer, *last_buffer;
1623 gfx_color_t stroke_color, fill_color;
1628 int linecap, linejoin;
1631 pdf_buffer pdf_header;
1632 pdf_buffer catalog_obj, pages_obj, page1_obj;
1633 pdf_buffer fontsdict_obj;
1634 pdf_buffer graph_stream;
1637 static void pdf_init_buffer(pdf_state *state, pdf_buffer *buf)
1639 int initial_size = 32;
1642 buf->alloc_size = 0;
1643 buf->current_size = 0;
1644 buf->data = (char*)malloc(initial_size);
1646 buf->previous_buffer = NULL;
1647 buf->next_buffer = NULL;
1648 if (buf->data == NULL) {
1649 rrd_set_error("malloc for pdf_buffer data");
1650 state->has_failed = 1;
1653 buf->alloc_size = initial_size;
1654 if (state->last_buffer)
1655 state->last_buffer->next_buffer = buf;
1656 if (state->first_buffer == NULL)
1657 state->first_buffer = buf;
1658 buf->previous_buffer = state->last_buffer;
1659 state->last_buffer = buf;
1662 static void pdf_put(pdf_buffer *buf, const char *text, int len)
1666 if (buf->alloc_size < buf->current_size + len) {
1667 int new_size = buf->alloc_size;
1669 while (new_size < buf->current_size + len)
1671 new_buf = (char*)malloc(new_size);
1672 if (new_buf == NULL) {
1673 rrd_set_error("re-malloc for pdf_buffer data");
1674 buf->state->has_failed = 1;
1677 memcpy(new_buf, buf->data, buf->current_size);
1679 buf->data = new_buf;
1680 buf->alloc_size = new_size;
1682 memcpy(buf->data + buf->current_size, text, len);
1683 buf->current_size += len;
1686 static void pdf_puts(pdf_buffer *buf, const char *text)
1688 pdf_put(buf, text, strlen(text));
1691 static void pdf_indent(pdf_buffer *buf)
1693 pdf_puts(buf, "\t");
1696 static void pdf_putsi(pdf_buffer *buf, const char *text)
1699 pdf_puts(buf, text);
1702 static void pdf_putint(pdf_buffer *buf, int i)
1705 sprintf(tmp, "%d", i);
1709 static void pdf_putnumber(pdf_buffer *buf, double d)
1712 svg_format_number(tmp, sizeof(tmp), d);
1716 static void pdf_init_object(pdf_state *state, pdf_buffer *buf)
1718 pdf_init_buffer(state, buf);
1719 buf->id = ++state->last_obj_id;
1724 static void pdf_init_dict(pdf_state *state, pdf_buffer *buf)
1726 pdf_init_object(state, buf);
1730 static void pdf_set_color(pdf_buffer *buf, gfx_color_t color,
1731 gfx_color_t *current_color, const char *op)
1733 /* gfx_color_t is RRGGBBAA */
1734 if (*current_color == color)
1736 pdf_putnumber(buf, ((color >> 24) & 255) / 255.0);
1738 pdf_putnumber(buf, ((color >> 16) & 255) / 255.0);
1740 pdf_putnumber(buf, ((color >> 8) & 255) / 255.0);
1743 pdf_puts(buf, "\n");
1744 *current_color = color;
1747 static void pdf_set_stroke_color(pdf_buffer *buf, gfx_color_t color)
1749 pdf_set_color(buf, color, &buf->state->stroke_color, "RG");
1752 static void pdf_set_fill_color(pdf_buffer *buf, gfx_color_t color)
1754 pdf_set_color(buf, color, &buf->state->fill_color, "rg");
1757 static pdf_font *pdf_find_font(pdf_state *state, gfx_node_t *node)
1759 const char *ps_font = afm_get_font_postscript_name(node->filename);
1761 for (ef = state->font_list; ef; ef = ef->next) {
1762 if (!strcmp(ps_font, ef->ps_font))
1768 static void pdf_add_font(pdf_state *state, gfx_node_t *node)
1770 pdf_font *ef = pdf_find_font(state, node);
1773 ef = malloc(sizeof(pdf_font));
1775 rrd_set_error("malloc for pdf_font");
1776 state->has_failed = 1;
1779 pdf_init_dict(state, &ef->obj);
1780 ef->next = state->font_list;
1781 ef->ps_font = afm_get_font_postscript_name(node->filename);
1782 state->font_list = ef;
1784 pdf_putsi(&state->fontsdict_obj, "/F");
1785 pdf_putint(&state->fontsdict_obj, ef->obj.id);
1786 pdf_puts(&state->fontsdict_obj, " ");
1787 pdf_putint(&state->fontsdict_obj, ef->obj.id);
1788 pdf_puts(&state->fontsdict_obj, " 0 R\n");
1790 pdf_putsi(&ef->obj, "/Type /Font\n");
1791 pdf_putsi(&ef->obj, "/Subtype /Type1\n");
1792 pdf_putsi(&ef->obj, "/Name /F");
1793 pdf_putint(&ef->obj, ef->obj.id);
1794 pdf_puts(&ef->obj, "\n");
1795 pdf_putsi(&ef->obj, "/BaseFont /");
1796 pdf_puts(&ef->obj, ef->ps_font);
1797 pdf_puts(&ef->obj, "\n");
1798 pdf_putsi(&ef->obj, "/Encoding /WinAnsiEncoding\n");
1799 /* 'Cp1252' (this is latin 1 extended with 27 characters;
1800 the encoding is also known as 'winansi')
1801 http://www.lowagie.com/iText/tutorial/ch09.html */
1804 static void pdf_create_fonts(pdf_state *state)
1807 for (node = state->canvas->firstnode; node; node = node->next) {
1808 if (node->type == GFX_TEXT)
1809 pdf_add_font(state, node);
1813 static void pdf_write_linearea(pdf_state *state, gfx_node_t *node)
1816 pdf_buffer *s = &state->graph_stream;
1817 if (node->type == GFX_LINE) {
1819 svg_get_dash(node, &dash_info);
1820 if (!svg_dash_equal(&dash_info, &state->dash)) {
1821 state->dash = dash_info;
1822 if (dash_info.dash_enable) {
1824 pdf_putnumber(s, dash_info.adjusted_on);
1826 pdf_putnumber(s, dash_info.adjusted_off);
1828 pdf_putnumber(s, dash_info.dash_offset);
1829 pdf_puts(s, " d\n");
1831 pdf_puts(s, "[] 0 d\n");
1834 pdf_set_stroke_color(s, node->color);
1835 if (state->linecap != 1) {
1836 pdf_puts(s, "1 j\n");
1839 if (state->linejoin != 1) {
1840 pdf_puts(s, "1 J\n");
1841 state->linejoin = 1;
1843 if (node->size != state->line_width) {
1844 state->line_width = node->size;
1845 pdf_putnumber(s, state->line_width);
1846 pdf_puts(s, " w\n");
1849 pdf_set_fill_color(s, node->color);
1851 for (i = 0; i < node->points; i++) {
1852 ArtVpath *vec = node->path + i;
1854 double y = state->page_height - vec->y;
1855 if (node->type == GFX_AREA) {
1856 x += LINEOFFSET; /* adjust for libart handling of areas */
1859 switch (vec->code) {
1860 case ART_MOVETO_OPEN: /* fall-through */
1862 pdf_putnumber(s, x);
1864 pdf_putnumber(s, y);
1865 pdf_puts(s, " m\n");
1868 pdf_putnumber(s, x);
1870 pdf_putnumber(s, y);
1871 pdf_puts(s, " l\n");
1873 case ART_CURVETO: break; /* unsupported */
1874 case ART_END: break; /* nop */
1877 if (node->type == GFX_LINE) {
1878 pdf_puts(s, node->closed_path ? "s\n" : "S\n");
1884 static void pdf_write_text(pdf_state *state, gfx_node_t *node,
1885 int last_was_text, int next_is_text)
1888 pdf_buffer *s = &state->graph_stream;
1889 const unsigned char *p;
1890 pdf_font *font = pdf_find_font(state, node);
1892 double y = state->page_height - node->y;
1893 double dx = 0, dy = 0;
1894 double cos_a = 0, sin_a = 0;
1896 rrd_set_error("font disappeared");
1897 state->has_failed = 1;
1900 switch(node->valign){
1901 case GFX_V_TOP: dy = -node->size; break;
1902 case GFX_V_CENTER: dy = -node->size / 3.0; break;
1903 case GFX_V_BOTTOM: break;
1904 case GFX_V_NULL: break;
1906 switch (node->halign) {
1907 case GFX_H_RIGHT: dx = -afm_get_text_width(0, font->ps_font,
1908 node->size, node->tabwidth, node->text);
1910 case GFX_H_CENTER: dx = -afm_get_text_width(0, font->ps_font,
1911 node->size, node->tabwidth, node->text) / 2;
1913 case GFX_H_LEFT: break;
1914 case GFX_H_NULL: break;
1916 pdf_set_fill_color(s, node->color);
1917 if (node->angle != 0) {
1918 double a = 2 * M_PI * -node->angle / 360.0;
1919 double new_x, new_y;
1922 new_x = cos_a * dx - sin_a * dy + x;
1923 new_y = sin_a * dx + cos_a * dy + y;
1931 pdf_puts(s, "BT\n");
1932 if (state->font_id != font->obj.id || node->size != state->font_size) {
1933 state->font_id = font->obj.id;
1934 state->font_size = node->size;
1936 pdf_putint(s, font->obj.id);
1938 pdf_putnumber(s, node->size);
1939 pdf_puts(s, " Tf\n");
1941 if (node->angle == 0) {
1942 pdf_puts(s, "1 0 0 1 ");
1944 pdf_putnumber(s, cos_a);
1946 pdf_putnumber(s, sin_a);
1948 pdf_putnumber(s, -sin_a);
1950 pdf_putnumber(s, cos_a);
1953 pdf_putnumber(s, x);
1955 pdf_putnumber(s, y);
1956 pdf_puts(s, " Tm\n");
1958 for (p = (const unsigned char*)node->text; *p; p++) {
1970 snprintf(tmp, sizeof(tmp), "\\%03o", *p);
1973 pdf_put(s, (const char*)p, 1);
1977 pdf_puts(s, ") Tj\n");
1979 pdf_puts(s, "ET\n");
1982 static void pdf_write_content(pdf_state *state)
1985 int last_was_text = 0, next_is_text;
1986 for (node = state->canvas->firstnode; node; node = node->next) {
1987 switch (node->type) {
1990 pdf_write_linearea(state, node);
1993 next_is_text = node->next && node->next->type == GFX_TEXT;
1994 pdf_write_text(state, node, last_was_text, next_is_text);
1997 last_was_text = node->type == GFX_TEXT;
2001 static void pdf_init_document(pdf_state *state)
2003 pdf_init_buffer(state, &state->pdf_header);
2004 pdf_init_dict(state, &state->catalog_obj);
2005 pdf_init_dict(state, &state->pages_obj);
2006 pdf_init_dict(state, &state->page1_obj);
2007 pdf_init_dict(state, &state->fontsdict_obj);
2008 pdf_create_fonts(state);
2009 if (state->has_failed)
2011 /* make stream last object in file */
2012 pdf_init_object(state, &state->graph_stream);
2013 state->graph_stream.is_stream = 1;
2016 static void pdf_setup_document(pdf_state *state)
2018 /* all objects created by now, so init code can reference them */
2020 pdf_puts(&state->pdf_header, "%PDF-1.3\n");
2021 /* following 8 bit comment is recommended by Adobe for
2022 indicating binary file to file transfer applications */
2023 pdf_puts(&state->pdf_header, "%\xE2\xE3\xCF\xD3\n");
2025 pdf_putsi(&state->catalog_obj, "/Type /Catalog\n");
2026 pdf_putsi(&state->catalog_obj, "/Pages ");
2027 pdf_putint(&state->catalog_obj, state->pages_obj.id);
2028 pdf_puts(&state->catalog_obj, " 0 R\n");
2030 pdf_putsi(&state->pages_obj, "/Type /Pages\n");
2031 pdf_putsi(&state->pages_obj, "/Kids [");
2032 pdf_putint(&state->pages_obj, state->page1_obj.id);
2033 pdf_puts(&state->pages_obj, " 0 R]\n");
2034 pdf_putsi(&state->pages_obj, "/Count 1\n");
2036 pdf_putsi(&state->page1_obj, "/Type /Page\n");
2037 pdf_putsi(&state->page1_obj, "/Parent ");
2038 pdf_putint(&state->page1_obj, state->pages_obj.id);
2039 pdf_puts(&state->page1_obj, " 0 R\n");
2040 pdf_putsi(&state->page1_obj, "/MediaBox [0 0 ");
2041 pdf_putint(&state->page1_obj, state->page_width);
2042 pdf_puts(&state->page1_obj, " ");
2043 pdf_putint(&state->page1_obj, state->page_height);
2044 pdf_puts(&state->page1_obj, "]\n");
2045 pdf_putsi(&state->page1_obj, "/Contents ");
2046 pdf_putint(&state->page1_obj, state->graph_stream.id);
2047 pdf_puts(&state->page1_obj, " 0 R\n");
2048 pdf_putsi(&state->page1_obj, "/Resources << /Font ");
2049 pdf_putint(&state->page1_obj, state->fontsdict_obj.id);
2050 pdf_puts(&state->page1_obj, " 0 R >>\n");
2053 static void pdf_write_string_to_file(pdf_state *state, const char *text)
2055 fputs(text, state->fp);
2056 state->pdf_file_pos += strlen(text);
2059 static void pdf_write_buf_to_file(pdf_state *state, pdf_buffer *buf)
2062 buf->pdf_file_pos = state->pdf_file_pos;
2064 snprintf(tmp, sizeof(tmp), "%d 0 obj\n", buf->id);
2065 pdf_write_string_to_file(state, tmp);
2068 pdf_write_string_to_file(state, "<<\n");
2069 if (buf->is_stream) {
2070 snprintf(tmp, sizeof(tmp), "<< /Length %d >>\n", buf->current_size);
2071 pdf_write_string_to_file(state, tmp);
2072 pdf_write_string_to_file(state, "stream\n");
2074 fwrite(buf->data, 1, buf->current_size, state->fp);
2075 state->pdf_file_pos += buf->current_size;
2077 pdf_write_string_to_file(state, "endstream\n");
2079 pdf_write_string_to_file(state, ">>\n");
2081 pdf_write_string_to_file(state, "endobj\n");
2084 static void pdf_write_to_file(pdf_state *state)
2086 pdf_buffer *buf = state->first_buffer;
2088 state->pdf_file_pos = 0;
2089 pdf_write_buf_to_file(state, &state->pdf_header);
2092 pdf_write_buf_to_file(state, buf);
2093 buf = buf->next_buffer;
2095 xref_pos = state->pdf_file_pos;
2096 fprintf(state->fp, "xref\n");
2097 fprintf(state->fp, "%d %d\n", 0, state->last_obj_id + 1);
2098 /* TOC lines must be exactly 20 bytes including \n */
2099 fprintf(state->fp, "%010d %05d f\x20\n", 0, 65535);
2100 for (buf = state->first_buffer; buf; buf = buf->next_buffer) {
2102 fprintf(state->fp, "%010d %05d n\x20\n", buf->pdf_file_pos, 0);
2104 fprintf(state->fp, "trailer\n");
2105 fprintf(state->fp, "<<\n");
2106 fprintf(state->fp, "\t/Size %d\n", state->last_obj_id + 1);
2107 fprintf(state->fp, "\t/Root %d 0 R\n", state->catalog_obj.id);
2108 fprintf(state->fp, ">>\n");
2109 fprintf(state->fp, "startxref\n");
2110 fprintf(state->fp, "%d\n", xref_pos);
2111 fputs("%%EOF\n", state->fp);
2114 static void pdf_free_resources(pdf_state *state)
2116 pdf_buffer *buf = state->first_buffer;
2120 buf->alloc_size = buf->current_size = 0;
2121 buf = buf->next_buffer;
2123 while (state->font_list) {
2124 pdf_font *next = state->font_list->next;
2125 free(state->font_list);
2126 state->font_list = next;
2130 int gfx_render_pdf (gfx_canvas_t *canvas,
2131 art_u32 width, art_u32 height,
2132 gfx_color_t background, FILE *fp){
2133 struct pdf_state state;
2134 memset(&state, 0, sizeof(pdf_state));
2136 state.canvas = canvas;
2137 state.page_width = width;
2138 state.page_height = height;
2140 state.font_size = -1;
2141 state.font_list = NULL;
2143 state.linejoin = -1;
2144 pdf_init_document(&state);
2146 pdf_set_color(&state, background);
2147 fprintf(fp, "0 0 M 0 %d L %d %d L %d 0 L fill\n",
2148 height, width, height, width);
2150 if (!state.has_failed)
2151 pdf_write_content(&state);
2152 if (!state.has_failed)
2153 pdf_setup_document(&state);
2154 if (!state.has_failed)
2155 pdf_write_to_file(&state);
2156 pdf_free_resources(&state);
2157 return state.has_failed ? -1 : 0;