1 /****************************************************************************
2 * RRDtool 1.2.3 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 ( gfx_canvas_t *canvas, FT_Face face,
49 const char *text, int rotation, double tabwidth, double size);
51 /* create a freetype glyph string */
52 static void gfx_string_destroy ( gfx_string string );
55 gfx_node_t *gfx_new_node( gfx_canvas_t *canvas,enum gfx_en type){
56 gfx_node_t *node = art_new(gfx_node_t,1);
57 if (node == NULL) return NULL;
59 node->color = 0x0; /* color of element 0xRRGGBBAA alpha 0xff is solid*/
60 node->size =0.0; /* font size, line width */
61 node->path = NULL; /* path */
64 node->closed_path = 0;
65 node->filename = NULL; /* font or image filename */
68 node->y = 0.0; /* position */
70 node->halign = GFX_H_NULL; /* text alignement */
71 node->valign = GFX_V_NULL; /* text alignement */
74 if (canvas->lastnode != NULL){
75 canvas->lastnode->next = node;
77 if (canvas->firstnode == NULL){
78 canvas->firstnode = node;
80 canvas->lastnode = node;
84 gfx_canvas_t *gfx_new_canvas (void) {
85 gfx_canvas_t *canvas = art_new(gfx_canvas_t,1);
86 canvas->firstnode = NULL;
87 canvas->lastnode = NULL;
88 canvas->imgformat = IF_PNG; /* we default to PNG output */
89 canvas->interlaced = 0;
91 canvas->font_aa_threshold = -1.0;
92 canvas->aa_type = AA_NORMAL;
96 /* create a new line */
97 gfx_node_t *gfx_new_line(gfx_canvas_t *canvas,
100 double width, gfx_color_t color){
101 return gfx_new_dashed_line(canvas, X0, Y0, X1, Y1, width, color, 0, 0);
104 gfx_node_t *gfx_new_dashed_line(gfx_canvas_t *canvas,
105 double X0, double Y0,
106 double X1, double Y1,
107 double width, gfx_color_t color,
108 double dash_on, double dash_off){
112 node = gfx_new_node(canvas,GFX_LINE);
113 if (node == NULL) return NULL;
114 vec = art_new(ArtVpath, 3);
115 if (vec == NULL) return NULL;
116 vec[0].code = ART_MOVETO_OPEN; vec[0].x=X0+LINEOFFSET; vec[0].y=Y0+LINEOFFSET;
117 vec[1].code = ART_LINETO; vec[1].x=X1+LINEOFFSET; vec[1].y=Y1+LINEOFFSET;
118 vec[2].code = ART_END; vec[2].x=0;vec[2].y=0;
121 node->points_max = 3;
124 node->dash_on = dash_on;
125 node->dash_off = dash_off;
130 /* create a new area */
131 gfx_node_t *gfx_new_area (gfx_canvas_t *canvas,
132 double X0, double Y0,
133 double X1, double Y1,
134 double X2, double Y2,
139 node = gfx_new_node(canvas,GFX_AREA);
140 if (node == NULL) return NULL;
141 vec = art_new(ArtVpath, 5);
142 if (vec == NULL) return NULL;
143 vec[0].code = ART_MOVETO; vec[0].x=X0; vec[0].y=Y0;
144 vec[1].code = ART_LINETO; vec[1].x=X1; vec[1].y=Y1;
145 vec[2].code = ART_LINETO; vec[2].x=X2; vec[2].y=Y2;
146 vec[3].code = ART_LINETO; vec[3].x=X0; vec[3].y=Y0;
147 vec[4].code = ART_END; vec[4].x=0; vec[4].y=0;
150 node->points_max = 5;
157 /* add a point to a line or to an area */
158 int gfx_add_point (gfx_node_t *node,
160 if (node == NULL) return 1;
161 if (node->type == GFX_AREA) {
162 double X0 = node->path[0].x;
163 double Y0 = node->path[0].y;
165 art_vpath_add_point (&(node->path),
170 art_vpath_add_point (&(node->path),
175 art_vpath_add_point (&(node->path),
180 } else if (node->type == GFX_LINE) {
182 art_vpath_add_point (&(node->path),
186 x+LINEOFFSET,y+LINEOFFSET);
187 art_vpath_add_point (&(node->path),
194 /* can only add point to areas and lines */
200 void gfx_close_path (gfx_node_t *node) {
201 node->closed_path = 1;
202 if (node->path[0].code == ART_MOVETO_OPEN)
203 node->path[0].code = ART_MOVETO;
206 /* create a text node */
207 gfx_node_t *gfx_new_text (gfx_canvas_t *canvas,
208 double x, double y, gfx_color_t color,
209 char* font, double size,
210 double tabwidth, double angle,
211 enum gfx_h_align_en h_align,
212 enum gfx_v_align_en v_align,
214 gfx_node_t *node = gfx_new_node(canvas,GFX_TEXT);
216 node->text = strdup(text);
218 node->filename = strdup(font);
223 node->tabwidth = tabwidth;
224 node->halign = h_align;
225 node->valign = v_align;
227 /* debugging: show text anchor
228 green is along x-axis, red is downward y-axis */
230 double a = 2 * M_PI * -node->angle / 360.0;
231 double cos_a = cos(a);
232 double sin_a = sin(a);
236 x + len * cos_a, y - len * sin_a,
240 x + len * sin_a, y + len * cos_a,
247 int gfx_render(gfx_canvas_t *canvas,
248 art_u32 width, art_u32 height,
249 gfx_color_t background, FILE *fp){
250 switch (canvas->imgformat) {
252 return gfx_render_png (canvas, width, height, background, fp);
254 return gfx_render_svg (canvas, width, height, background, fp);
256 return gfx_render_eps (canvas, width, height, background, fp);
258 return gfx_render_pdf (canvas, width, height, background, fp);
264 static void gfx_string_destroy ( gfx_string string ) {
266 if (string->glyphs) {
267 for (n=0; n<string->num_glyphs; ++n)
268 FT_Done_Glyph (string->glyphs[n].image);
269 free (string->glyphs);
275 double gfx_get_text_width ( gfx_canvas_t *canvas,
276 double start, char* font, double size,
277 double tabwidth, char* text, int rotation){
278 switch (canvas->imgformat) {
280 return gfx_get_text_width_libart (canvas, start, font, size, tabwidth, text, rotation);
281 case IF_SVG: /* fall through */
284 return afm_get_text_width(start, font, size, tabwidth, text);
286 return size * strlen(text);
290 double gfx_get_text_width_libart (
291 gfx_canvas_t *canvas, double start, char* font, double size,
292 double tabwidth, char* text, int rotation ){
297 FT_Library library=NULL;
300 FT_Init_FreeType( &library );
301 error = FT_New_Face( library, font, 0, &face );
302 if ( error ) return -1;
303 error = FT_Set_Char_Size(face, size*64,size*64, 100,100);
304 if ( error ) return -1;
306 string = gfx_string_create( canvas, face, text, rotation, tabwidth, size );
307 text_width = string->width;
308 gfx_string_destroy(string);
309 FT_Done_FreeType(library);
310 return text_width/64;
313 static void gfx_libart_close_path(gfx_node_t *node, ArtVpath **vec)
315 /* libart must have end==start for closed paths,
316 even if using ART_MOVETO and not ART_MOVETO_OPEN
317 so add extra point which is the same as the starting point */
318 int points_max = node->points; /* scaled array has exact size */
319 int points = node->points - 1;
320 art_vpath_add_point (vec, &points, &points_max, ART_LINETO,
321 (**vec).x, (**vec).y);
322 art_vpath_add_point (vec, &points, &points_max, ART_END, 0, 0);
326 /* find bbox of a string */
327 static void compute_string_bbox(gfx_string string) {
331 bbox.xMin = bbox.yMin = 32000;
332 bbox.xMax = bbox.yMax = -32000;
333 for ( n = 0; n < string->num_glyphs; n++ ) {
335 FT_Glyph_Get_CBox( string->glyphs[n].image, ft_glyph_bbox_gridfit,
337 if (glyph_bbox.xMin < bbox.xMin) {
338 bbox.xMin = glyph_bbox.xMin;
340 if (glyph_bbox.yMin < bbox.yMin) {
341 bbox.yMin = glyph_bbox.yMin;
343 if (glyph_bbox.xMax > bbox.xMax) {
344 bbox.xMax = glyph_bbox.xMax;
346 if (glyph_bbox.yMax > bbox.yMax) {
347 bbox.yMax = glyph_bbox.yMax;
350 if ( bbox.xMin > bbox.xMax ) {
356 string->bbox.xMin = bbox.xMin;
357 string->bbox.xMax = bbox.xMax;
358 string->bbox.yMin = bbox.yMin;
359 string->bbox.yMax = bbox.yMax;
362 /* create a free type glyph string */
363 gfx_string gfx_string_create(gfx_canvas_t *canvas, FT_Face face,const char *text,
364 int rotation, double tabwidth, double size )
367 FT_GlyphSlot slot = face->glyph; /* a small shortcut */
373 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;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 unsigned char letter = text[n];
402 if (letter == '\\' && n+1 < string->count && text[n+1] == 't'){
403 /* we have a tab here so skip the backslash and
404 set t to ' ' so that we get a white space */
413 /* initialize each struct gfx_char_s */
419 glyph->index = FT_Get_Char_Index( face, letter );
421 /* compute glyph origin */
422 if ( use_kerning && previous && glyph->index ) {
424 FT_Get_Kerning (face, previous, glyph->index,
425 ft_kerning_default, &kerning);
426 ft_pen.x += kerning.x;
427 ft_pen.y += kerning.y;
430 /* load the glyph image (in its native format) */
431 /* for now, we take a monochrome glyph bitmap */
432 error = FT_Load_Glyph (face, glyph->index, size > canvas->font_aa_threshold ?
433 canvas->aa_type == AA_NORMAL ? FT_LOAD_TARGET_NORMAL :
434 canvas->aa_type == AA_LIGHT ? FT_LOAD_TARGET_LIGHT :
435 FT_LOAD_TARGET_MONO : FT_LOAD_TARGET_MONO);
437 fprintf (stderr, "couldn't load glyph: %c\n", letter);
440 error = FT_Get_Glyph (slot, &glyph->image);
442 fprintf (stderr, "couldn't get glyph from slot: %c\n", letter);
445 /* if we are in tabbing mode, we replace the tab with a space and shift the position
446 of the space so that its left edge is where the tab was supposed to land us */
448 /* we are in gridfitting mode so the calculations happen in 1/64 pixles */
449 ft_pen.x = tabwidth*64.0 * (float)(1 + (long)(ft_pen.x / (tabwidth * 64.0))) - slot->advance.x;
451 /* store current pen position */
452 glyph->pos.x = ft_pen.x;
453 glyph->pos.y = ft_pen.y;
456 ft_pen.x += slot->advance.x;
457 ft_pen.y += slot->advance.y;
461 FT_Vector_Transform (&vec, &string->transform);
462 error = FT_Glyph_Transform (glyph->image, &string->transform, &vec);
464 fprintf (stderr, "couldn't transform glyph\n");
468 /* convert to a bitmap - destroy native image */
469 error = FT_Glyph_To_Bitmap (&glyph->image, size > canvas->font_aa_threshold ?
470 canvas->aa_type == AA_NORMAL ? FT_RENDER_MODE_NORMAL :
471 canvas->aa_type == AA_LIGHT ? FT_RENDER_MODE_LIGHT :
472 FT_RENDER_MODE_MONO : FT_RENDER_MODE_MONO, 0, 1);
474 fprintf (stderr, "couldn't convert glyph to bitmap\n");
478 /* increment number of glyphs */
479 previous = glyph->index;
480 string->num_glyphs++;
484 /* printf ("number of glyphs = %d\n", string->num_glyphs);*/
485 compute_string_bbox( string );
486 /* the last character was a tab */
488 string->width = ft_pen.x;
490 string->width = string->bbox.xMax - string->bbox.xMin;
492 string->height = string->bbox.yMax - string->bbox.yMin;
498 static int gfx_save_png (art_u8 *buffer, FILE *fp,
499 long width, long height, long bytes_per_pixel);
500 /* render grafics into png image */
502 int gfx_render_png (gfx_canvas_t *canvas,
503 art_u32 width, art_u32 height,
504 gfx_color_t background, FILE *fp){
508 gfx_node_t *node = canvas->firstnode;
510 art_u8 red = background >> 24, green = (background >> 16) & 0xff;
511 art_u8 blue = (background >> 8) & 0xff, alpha = ( background & 0xff );
513 unsigned long pys_width = width * canvas->zoom;
514 unsigned long pys_height = height * canvas->zoom;
515 const int bytes_per_pixel = 4;
516 unsigned long rowstride = pys_width*bytes_per_pixel; /* bytes per pixel */
518 /* fill that buffer with out background color */
519 gfx_color_t *buffp = art_new (gfx_color_t, pys_width*pys_height);
520 art_u8 *buffer = (art_u8 *)buffp;
522 for (i=0;i<pys_width*pys_height;
524 *(buffp++)=background;
526 FT_Init_FreeType( &library );
528 switch (node->type) {
534 art_affine_scale(dst,canvas->zoom,canvas->zoom);
535 vec = art_vpath_affine_transform(node->path,dst);
536 if (node->closed_path)
537 gfx_libart_close_path(node, &vec);
538 /* gfx_round_scaled_coordinates(vec); */
539 /* pvec = art_vpath_perturb(vec);
541 if(node->type == GFX_LINE){
542 svp = art_svp_vpath_stroke ( vec, ART_PATH_STROKE_JOIN_ROUND,
543 ART_PATH_STROKE_CAP_ROUND,
544 node->size*canvas->zoom,4,0.25);
546 svp = art_svp_from_vpath ( vec );
547 /* this takes time and is unnecessary since we make
548 sure elsewhere that the areas are going clock-whise */
549 /* svpt = art_svp_uncross( svp );
551 svp = art_svp_rewind_uncrossed(svpt,ART_WIND_RULE_NONZERO);
556 /* this is from gnome since libart does not have this yet */
557 gnome_print_art_rgba_svp_alpha (svp ,0,0, pys_width, pys_height,
558 node->color, buffer, rowstride, NULL);
565 art_u8 fcolor[4],falpha;
569 FT_Vector vec; /* 26.6 */
571 float pen_x = 0.0 , pen_y = 0.0;
575 fcolor[0] = node->color >> 24;
576 fcolor[1] = (node->color >> 16) & 0xff;
577 fcolor[2] = (node->color >> 8) & 0xff;
578 falpha = node->color & 0xff;
579 error = FT_New_Face( library,
580 (char *)node->filename,
584 rrd_set_error("failed to load %s",node->filename);
587 error = FT_Set_Char_Size(face, /* handle to face object */
588 (long)(node->size*64),
589 (long)(node->size*64),
590 (long)(100*canvas->zoom),
591 (long)(100*canvas->zoom));
593 pen_x = node->x * canvas->zoom;
594 pen_y = node->y * canvas->zoom;
596 string = gfx_string_create (canvas, face, node->text, node->angle, node->tabwidth, node->size);
597 switch(node->halign){
598 case GFX_H_RIGHT: vec.x = -string->bbox.xMax;
600 case GFX_H_CENTER: vec.x = abs(string->bbox.xMax) >= abs(string->bbox.xMin) ?
601 -string->bbox.xMax/2:-string->bbox.xMin/2;
603 case GFX_H_LEFT: vec.x = -string->bbox.xMin;
605 case GFX_H_NULL: vec.x = 0;
609 switch(node->valign){
610 case GFX_V_TOP: vec.y = string->bbox.yMax;
612 case GFX_V_CENTER: vec.y = abs(string->bbox.yMax) >= abs(string->bbox.yMin) ?
613 string->bbox.yMax/2:string->bbox.yMin/2;
615 case GFX_V_BOTTOM: vec.y = 0;
617 case GFX_V_NULL: vec.y = 0;
622 glyph = string->glyphs;
623 for(n=0; n<string->num_glyphs; ++n, ++glyph) {
627 /* long buf_x,comp_n; */
628 /* make copy to transform */
629 if (! glyph->image) {
630 fprintf (stderr, "no image\n");
633 error = FT_Glyph_Copy (glyph->image, &image);
635 fprintf (stderr, "couldn't copy image\n");
641 FT_Vector_Transform (&vec, &string->transform);
643 bit = (FT_BitmapGlyph) image;
644 gr = bit->bitmap.num_grays -1;
646 buf_x = (pen_x + 0.5) + (double)bit->left;
647 comp_n = buf_x + bit->bitmap.width > pys_width ? pys_width - buf_x : bit->bitmap.width;
648 if (buf_x < 0 || buf_x >= (long)pys_width) continue;
649 buf_x *= bytes_per_pixel ;
650 for (iy=0; iy < bit->bitmap.rows; iy++){
651 long buf_y = iy+(pen_y+0.5)-(double)bit->top;
652 if (buf_y < 0 || buf_y >= (long)pys_height) continue;
654 for (ix=0;ix < bit->bitmap.width;ix++){
655 *(letter + (ix*bytes_per_pixel+3)) = *(bit->bitmap.buffer + iy * bit->bitmap.width + ix);
657 art_rgba_rgba_composite(buffer + buf_y + buf_x ,letter,comp_n);
661 switch ( bit->bitmap.pixel_mode ) {
662 case FT_PIXEL_MODE_GRAY:
663 for (iy=0; iy < bit->bitmap.rows; iy++){
664 long buf_y = iy+(pen_y+0.5)-bit->top;
665 if (buf_y < 0 || buf_y >= (long)pys_height) continue;
667 for (ix=0;ix < bit->bitmap.width;ix++){
668 long buf_x = ix + (pen_x + 0.5) + (double)bit->left ;
671 if (buf_x < 0 || buf_x >= (long)pys_width) continue;
672 buf_x *= bytes_per_pixel ;
673 font_alpha = *(bit->bitmap.buffer + iy * bit->bitmap.pitch + ix);
675 fcolor[3] = (art_u8)((double)font_alpha / gr * falpha);
676 art_rgba_rgba_composite(buffer + buf_y + buf_x ,fcolor,1);
682 case FT_PIXEL_MODE_MONO:
683 for (iy=0; iy < bit->bitmap.rows; iy++){
684 long buf_y = iy+(pen_y+0.5)-bit->top;
685 if (buf_y < 0 || buf_y >= (long)pys_height) continue;
687 for (ix=0;ix < bit->bitmap.width;ix++){
688 long buf_x = ix + (pen_x + 0.5) + (double)bit->left ;
690 if (buf_x < 0 || buf_x >= (long)pys_width) continue;
691 buf_x *= bytes_per_pixel ;
692 if ( (fcolor[3] = falpha * ((*(bit->bitmap.buffer + iy * bit->bitmap.pitch + ix/8) >> (7 - (ix % 8))) & 1)) > 0 )
693 art_rgba_rgba_composite(buffer + buf_y + buf_x ,fcolor,1);
699 rrd_set_error("unknown freetype pixel mode: %d", bit->bitmap.pixel_mode);
704 for (iy=0; iy < bit->bitmap.rows; iy++){
705 long buf_y = iy+(pen_y+0.5)-bit->top;
706 if (buf_y < 0 || buf_y >= (long)pys_height) continue;
708 for (ix=0;ix < bit->bitmap.width;ix++){
709 long buf_x = ix + (pen_x + 0.5) + (double)bit->left ;
712 if (buf_x < 0 || buf_x >= (long)pys_width) continue;
713 buf_x *= bytes_per_pixel ;
714 font_alpha = *(bit->bitmap.buffer + iy * bit->bitmap.width + ix);
715 font_alpha = (art_u8)((double)font_alpha / gr * falpha);
716 for (iz = 0; iz < 3; iz++){
717 art_u8 *orig = buffer + buf_y + buf_x + iz;
718 *orig = (art_u8)((double)*orig / gr * ( gr - font_alpha) +
719 (double)fcolor[iz] / gr * (font_alpha));
724 FT_Done_Glyph (image);
726 gfx_string_destroy(string);
731 gfx_save_png(buffer,fp , pys_width,pys_height,bytes_per_pixel);
733 FT_Done_FreeType( library );
737 /* free memory used by nodes this will also remove memory required for
738 associated paths and svcs ... but not for text strings */
740 gfx_destroy (gfx_canvas_t *canvas){
741 gfx_node_t *next,*node = canvas->firstnode;
744 art_free(node->path);
746 free(node->filename);
754 static int gfx_save_png (art_u8 *buffer, FILE *fp, long width, long height, long bytes_per_pixel){
755 png_structp png_ptr = NULL;
756 png_infop info_ptr = NULL;
758 png_bytep *row_pointers;
759 int rowstride = width * bytes_per_pixel;
765 png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING,NULL,NULL,NULL);
770 row_pointers = (png_bytepp)png_malloc(png_ptr,
771 height*sizeof(png_bytep));
773 info_ptr = png_create_info_struct(png_ptr);
775 if (info_ptr == NULL)
777 png_free(png_ptr,row_pointers);
778 png_destroy_write_struct(&png_ptr, (png_infopp)NULL);
782 if (setjmp(png_jmpbuf(png_ptr)))
784 /* If we get here, we had a problem writing the file */
785 png_destroy_write_struct(&png_ptr, &info_ptr);
789 png_init_io(png_ptr, fp);
790 png_set_IHDR (png_ptr, info_ptr,width, height,
791 8, PNG_COLOR_TYPE_RGB_ALPHA,
793 PNG_COMPRESSION_TYPE_DEFAULT,
794 PNG_FILTER_TYPE_DEFAULT);
796 text[0].key = "Software";
797 text[0].text = "RRDtool, Tobias Oetiker <tobi@oetike.ch>, http://tobi.oetiker.ch";
798 text[0].compression = PNG_TEXT_COMPRESSION_NONE;
799 png_set_text (png_ptr, info_ptr, text, 1);
801 /* lets make this fast while ending up with some increass in image size */
802 png_set_filter(png_ptr,0,PNG_FILTER_NONE);
803 /* png_set_filter(png_ptr,0,PNG_FILTER_SUB); */
804 png_set_compression_level(png_ptr,1);
805 /* png_set_compression_strategy(png_ptr,Z_HUFFMAN_ONLY); */
807 png_set_filter(png_ptr,PNG_FILTER_TYPE_BASE,PNG_FILTER_SUB);
808 png_set_compression_strategy(png_ptr,Z_HUFFMAN_ONLY);
809 png_set_compression_level(png_ptr,Z_BEST_SPEED); */
811 /* Write header data */
812 png_write_info (png_ptr, info_ptr);
813 for (i = 0; i < height; i++)
814 row_pointers[i] = (png_bytep) (buffer + i*rowstride);
816 png_write_image(png_ptr, row_pointers);
817 png_write_end(png_ptr, info_ptr);
818 png_free(png_ptr,row_pointers);
819 png_destroy_write_struct(&png_ptr, &info_ptr);
824 /* ------- SVG -------
826 http://www.w3.org/TR/SVG/
828 static int svg_indent = 0;
829 static int svg_single_line = 0;
830 static const char *svg_default_font = "Helvetica";
831 typedef struct svg_dash
834 double dash_adjust, dash_len, dash_offset;
835 double adjusted_on, adjusted_off;
839 static void svg_print_indent(FILE *fp)
842 for (i = svg_indent - svg_single_line; i > 0; i--) {
848 static void svg_start_tag(FILE *fp, const char *name)
850 svg_print_indent(fp);
856 static void svg_close_tag_single_line(FILE *fp)
862 static void svg_close_tag(FILE *fp)
865 if (!svg_single_line)
869 static void svg_end_tag(FILE *fp, const char *name)
871 /* name is NULL if closing empty-node tag */
876 svg_print_indent(fp);
886 static void svg_close_tag_empty_node(FILE *fp)
888 svg_end_tag(fp, NULL);
891 static void svg_write_text(FILE *fp, const char *text)
893 const unsigned char *p, *start, *last;
895 p = (const unsigned char*)text;
898 /* trim leading spaces */
902 /* trim trailing spaces */
904 while ((ch = *p) != 0) {
909 /* encode trimmed text */
913 ch = afm_host2unicode(ch); /* unsafe macro */
915 case '&': fputs("&", fp); break;
916 case '<': fputs("<", fp); break;
917 case '>': fputs(">", fp); break;
918 case '"': fputs(""", fp); break;
921 fprintf(fp, "&#%d;", ch);
928 static void svg_format_number(char *buf, int bufsize, double d)
930 /* omit decimals if integer to reduce filesize */
932 snprintf(buf, bufsize, "%.2f", d);
933 p = buf; /* doesn't trust snprintf return value */
939 *p = '\0'; /* zap trailing zeros */
943 *p = '\0'; /* zap trailing dot */
948 static void svg_write_number(FILE *fp, double d)
951 svg_format_number(buf, sizeof(buf), d);
955 static int svg_color_is_black(int c)
957 /* gfx_color_t is RRGGBBAA */
958 return c == 0x000000FF;
961 static void svg_write_color(FILE *fp, gfx_color_t c, const char *attr)
963 /* gfx_color_t is RRGGBBAA, svg can use #RRGGBB and #RGB like html */
964 gfx_color_t rrggbb = (int)((c >> 8) & 0xFFFFFF);
965 gfx_color_t opacity = c & 0xFF;
966 fprintf(fp, " %s=\"", attr);
967 if ((rrggbb & 0x0F0F0F) == ((rrggbb >> 4) & 0x0F0F0F)) {
968 /* css2 short form, #rgb is #rrggbb, not #r0g0b0 */
969 fprintf(fp, "#%03lX",
970 ( ((rrggbb >> 8) & 0xF00)
971 | ((rrggbb >> 4) & 0x0F0)
972 | ( rrggbb & 0x00F)));
974 fprintf(fp, "#%06lX", rrggbb);
977 if (opacity != 0xFF) {
978 fprintf(fp, " stroke-opacity=\"");
979 svg_write_number(fp, opacity / 255.0);
984 static void svg_get_dash(gfx_node_t *node, svg_dash *d)
988 if (node->dash_on <= 0 || node->dash_off <= 0) {
993 d->dash_len = node->dash_on + node->dash_off;
994 /* dash on/off adjustment due to round caps */
995 d->dash_adjust = 0.8 * node->size;
996 d->adjusted_on = node->dash_on - d->dash_adjust;
997 if (d->adjusted_on < 0.01)
998 d->adjusted_on = 0.01;
999 d->adjusted_off = d->dash_len - d->adjusted_on;
1000 /* dash offset calc */
1001 if (node->path[0].x == node->path[1].x) /* only good for horz/vert lines */
1002 offset = node->path[0].y;
1004 offset = node->path[0].x;
1005 mult = (int)fabs(offset / d->dash_len);
1006 d->dash_offset = offset - mult * d->dash_len;
1007 if (node->path[0].x < node->path[1].x || node->path[0].y < node->path[1].y)
1008 d->dash_offset = d->dash_len - d->dash_offset;
1011 static int svg_dash_equal(svg_dash *a, svg_dash *b)
1013 if (a->dash_enable != b->dash_enable)
1015 if (a->adjusted_on != b->adjusted_on)
1017 if (a->adjusted_off != b->adjusted_off)
1019 /* rest of properties will be the same when on+off are */
1023 static void svg_common_path_attributes(FILE *fp, gfx_node_t *node)
1026 svg_get_dash(node, &dash_info);
1027 fputs(" stroke-width=\"", fp);
1028 svg_write_number(fp, node->size);
1030 svg_write_color(fp, node->color, "stroke");
1031 fputs(" fill=\"none\"", fp);
1032 if (dash_info.dash_enable) {
1033 if (dash_info.dash_offset != 0) {
1034 fputs(" stroke-dashoffset=\"", fp);
1035 svg_write_number(fp, dash_info.dash_offset);
1038 fputs(" stroke-dasharray=\"", fp);
1039 svg_write_number(fp, dash_info.adjusted_on);
1041 svg_write_number(fp, dash_info.adjusted_off);
1046 static int svg_is_int_step(double a, double b)
1048 double diff = fabs(a - b);
1049 return floor(diff) == diff;
1052 static int svg_path_straight_segment(FILE *fp,
1053 double lastA, double currentA, double currentB,
1055 int segment_idx, int isx, char absChar, char relChar)
1057 if (!svg_is_int_step(lastA, currentA)) {
1059 svg_write_number(fp, currentA);
1062 if (segment_idx < node->points - 1) {
1063 ArtVpath *vec = node->path + segment_idx + 1;
1064 if (vec->code == ART_LINETO) {
1065 double nextA = (isx ? vec->x : vec->y) - LINEOFFSET;
1066 double nextB = (isx ? vec->y : vec->x) - LINEOFFSET;
1067 if (nextB == currentB
1068 && ((currentA >= lastA) == (nextA >= currentA))
1069 && svg_is_int_step(currentA, nextA)) {
1070 return 1; /* skip to next as it is a straight line */
1075 svg_write_number(fp, currentA - lastA);
1079 static void svg_path(FILE *fp, gfx_node_t *node, int multi)
1082 double lastX = 0, lastY = 0;
1083 /* for straight lines <path..> tags take less space than
1084 <line..> tags because of the efficient packing
1085 in the 'd' attribute */
1086 svg_start_tag(fp, "path");
1088 svg_common_path_attributes(fp, node);
1090 /* specification of the 'd' attribute: */
1091 /* http://www.w3.org/TR/SVG/paths.html#PathDataGeneralInformation */
1092 for (i = 0; i < node->points; i++) {
1093 ArtVpath *vec = node->path + i;
1094 double x = vec->x - LINEOFFSET;
1095 double y = vec->y - LINEOFFSET;
1096 switch (vec->code) {
1097 case ART_MOVETO_OPEN: /* fall-through */
1100 svg_write_number(fp, x);
1102 svg_write_number(fp, y);
1105 /* try optimize filesize by using minimal lineto commands */
1106 /* without introducing rounding errors. */
1108 if (svg_path_straight_segment(fp, lastY, y, x, node, i, 0, 'V', 'v'))
1110 } else if (y == lastY) {
1111 if (svg_path_straight_segment(fp, lastX, x, y, node, i, 1, 'H', 'h'))
1115 svg_write_number(fp, x);
1117 svg_write_number(fp, y);
1120 case ART_CURVETO: break; /* unsupported */
1121 case ART_END: break; /* nop */
1126 if (node->closed_path)
1129 svg_close_tag_empty_node(fp);
1132 static void svg_multi_path(FILE *fp, gfx_node_t **nodeR)
1134 /* optimize for multiple paths with the same color, penwidth, etc. */
1136 gfx_node_t *node = *nodeR;
1137 gfx_node_t *next = node->next;
1139 if (next->type != node->type
1140 || next->size != node->size
1141 || next->color != node->color
1142 || next->dash_on != node->dash_on
1143 || next->dash_off != node->dash_off)
1149 svg_path(fp, node, 0);
1152 svg_start_tag(fp, "g");
1153 svg_common_path_attributes(fp, node);
1155 while (num && node) {
1156 svg_path(fp, node, 1);
1162 svg_end_tag(fp, "g");
1165 static void svg_area(FILE *fp, gfx_node_t *node)
1168 double startX = 0, startY = 0;
1169 svg_start_tag(fp, "polygon");
1171 svg_write_color(fp, node->color, "fill");
1172 fputs(" points=\"", fp);
1173 for (i = 0; i < node->points; i++) {
1174 ArtVpath *vec = node->path + i;
1175 double x = vec->x - LINEOFFSET;
1176 double y = vec->y - LINEOFFSET;
1177 switch (vec->code) {
1178 case ART_MOVETO_OPEN: /* fall-through */
1180 svg_write_number(fp, x);
1182 svg_write_number(fp, y);
1187 if (i == node->points - 2
1188 && node->path[i + 1].code == ART_END
1189 && fabs(x - startX) < 0.001 && fabs(y - startY) < 0.001) {
1190 break; /* poly area always closed, no need for last point */
1193 svg_write_number(fp, x);
1195 svg_write_number(fp, y);
1197 case ART_CURVETO: break; /* unsupported */
1198 case ART_END: break; /* nop */
1202 svg_close_tag_empty_node(fp);
1205 static void svg_text(FILE *fp, gfx_node_t *node)
1207 double x = node->x - LINEOFFSET;
1208 double y = node->y - LINEOFFSET;
1209 if (node->angle != 0) {
1210 svg_start_tag(fp, "g");
1211 fputs(" transform=\"translate(", fp);
1212 svg_write_number(fp, x);
1214 svg_write_number(fp, y);
1215 fputs(") rotate(", fp);
1216 svg_write_number(fp, -node->angle);
1221 switch (node->valign) {
1222 case GFX_V_TOP: y += node->size; break;
1223 case GFX_V_CENTER: y += node->size / 3; break;
1224 case GFX_V_BOTTOM: break;
1225 case GFX_V_NULL: break;
1227 svg_start_tag(fp, "text");
1229 svg_write_number(fp, x);
1230 fputs("\" y=\"", fp);
1231 svg_write_number(fp, y);
1233 /* if (strcmp(node->filename, svg_default_font))
1234 fprintf(fp, " font-family=\"%s\"", node->filename);
1236 fputs("\" font-family=\"Helvetica", fp);
1237 fputs("\" font-size=\"", fp);
1238 svg_write_number(fp, node->size);
1240 if (!svg_color_is_black(node->color))
1241 svg_write_color(fp, node->color, "fill");
1242 switch (node->halign) {
1243 case GFX_H_RIGHT: fputs(" text-anchor=\"end\"", fp); break;
1244 case GFX_H_CENTER: fputs(" text-anchor=\"middle\"", fp); break;
1245 case GFX_H_LEFT: break;
1246 case GFX_H_NULL: break;
1248 svg_close_tag_single_line(fp);
1249 /* support for node->tabwidth missing */
1250 svg_write_text(fp, node->text);
1251 svg_end_tag(fp, "text");
1252 if (node->angle != 0)
1253 svg_end_tag(fp, "g");
1256 int gfx_render_svg (gfx_canvas_t *canvas,
1257 art_u32 width, art_u32 height,
1258 gfx_color_t background, FILE *fp){
1259 gfx_node_t *node = canvas->firstnode;
1261 "<?xml version=\"1.0\" standalone=\"no\"?>\n"
1262 "<!DOCTYPE svg PUBLIC \"-//W3C//DTD SVG 1.0//EN\"\n"
1263 " \"http://www.w3.org/TR/2001/REC-SVG-20010904/DTD/svg10.dtd\">\n"
1265 " SVG file created by RRDtool,\n"
1266 " Tobias Oetiker <tobi@oetike.ch>, http://tobi.oetiker.ch\n"
1268 " The width/height attributes in the outhermost svg node\n"
1269 " are just default sizes for the browser which is used\n"
1270 " if the svg file is openened directly without being\n"
1271 " embedded in an html file.\n"
1272 " The viewBox is the local coord system for rrdtool.\n"
1274 svg_start_tag(fp, "svg");
1275 fputs(" width=\"", fp);
1276 svg_write_number(fp, width * canvas->zoom);
1277 fputs("\" height=\"", fp);
1278 svg_write_number(fp, height * canvas->zoom);
1279 fputs("\" x=\"0\" y=\"0\" viewBox=\"", fp);
1280 svg_write_number(fp, -LINEOFFSET);
1282 svg_write_number(fp, -LINEOFFSET);
1284 svg_write_number(fp, width - LINEOFFSET);
1286 svg_write_number(fp, height - LINEOFFSET);
1287 fputs("\" preserveAspectRatio=\"xMidYMid\"", fp);
1288 fprintf(fp, " font-family=\"%s\"", svg_default_font); /* default font */
1289 fputs(" stroke-linecap=\"round\" stroke-linejoin=\"round\"", fp);
1291 svg_start_tag(fp, "rect");
1292 fprintf(fp, " x=\"0\" y=\"0\" width=\"%d\" height=\"%d\"", width, height);
1293 svg_write_color(fp, background, "fill");
1294 svg_close_tag_empty_node(fp);
1296 switch (node->type) {
1298 svg_multi_path(fp, &node);
1308 svg_end_tag(fp, "svg");
1312 /* ------- EPS -------
1313 EPS and Postscript references:
1314 http://partners.adobe.com/asn/developer/technotes/postscript.html
1317 typedef struct eps_font
1319 const char *ps_font;
1321 struct eps_font *next;
1324 typedef struct eps_state
1327 gfx_canvas_t *canvas;
1328 art_u32 page_width, page_height;
1329 eps_font *font_list;
1335 int linecap, linejoin;
1339 static void eps_set_color(eps_state *state, gfx_color_t color)
1341 /* gfx_color_t is RRGGBBAA */
1342 if (state->color == color)
1344 fprintf(state->fp, "%d %d %d Rgb\n",
1345 (int)((color >> 24) & 255),
1346 (int)((color >> 16) & 255),
1347 (int)((color >> 8) & 255));
1348 state->color = color;
1351 static int eps_add_font(eps_state *state, gfx_node_t *node)
1353 /* The fonts list could be postponed to the end using
1354 (atend), but let's be nice and have them in the header. */
1355 const char *ps_font = afm_get_font_postscript_name(node->filename);
1357 for (ef = state->font_list; ef; ef = ef->next) {
1358 if (!strcmp(ps_font, ef->ps_font))
1361 ef = malloc(sizeof(eps_font));
1363 rrd_set_error("malloc for eps_font");
1366 ef->next = state->font_list;
1367 ef->ps_font = ps_font;
1368 state->font_list = ef;
1372 static void eps_list_fonts(eps_state *state, const char *dscName)
1375 int lineLen = strlen(dscName);
1376 if (!state->font_list)
1378 fputs(dscName, state->fp);
1379 for (ef = state->font_list; ef; ef = ef->next) {
1380 int nameLen = strlen(ef->ps_font);
1381 if (lineLen + nameLen > 100 && lineLen) {
1382 fputs("\n", state->fp);
1383 fputs("%%- \n", state->fp);
1386 fputs(" ", state->fp);
1389 fputs(ef->ps_font, state->fp);
1392 fputs("\n", state->fp);
1395 static void eps_define_fonts(eps_state *state)
1398 if (!state->font_list)
1400 for (ef = state->font_list; ef; ef = ef->next) {
1401 /* PostScript¨ LANGUAGE REFERENCE third edition
1405 "/%s findfont dup length dict begin\n"
1406 "{ 1 index /FID ne {def} {pop pop} ifelse } forall\n"
1407 "/Encoding ISOLatin1Encoding def\n"
1409 "/%s-ISOLatin1 exch definefont pop\n"
1410 "/SetFont-%s { /%s-ISOLatin1 findfont exch scalefont setfont } bd\n",
1411 ef->ps_font, ef->ps_font, ef->ps_font, ef->ps_font);
1415 static int eps_prologue(eps_state *state)
1419 "%!PS-Adobe-3.0 EPSF-3.0\n"
1420 "%%Creator: RRDtool 1.2.3 Tobias Oetiker, http://tobi.oetiker.ch\n"
1421 /* can't like weird chars here */
1422 "%%Title: (RRDtool output)\n"
1423 "%%DocumentData: Clean7Bit\n"
1425 fprintf(state->fp, "%%%%BoundingBox: 0 0 %d %d\n",
1426 state->page_width, state->page_height);
1427 for (node = state->canvas->firstnode; node; node = node->next) {
1428 if (node->type == GFX_TEXT && eps_add_font(state, node) == -1)
1431 eps_list_fonts(state, "%%DocumentFonts:");
1432 eps_list_fonts(state, "%%DocumentNeededFonts:");
1436 "%%EndProlog\n" /* must have, or BoundingBox is ignored */
1437 "/bd { bind def } bind def\n"
1439 fprintf(state->fp, "/X { %.2f add } bd\n", LINEOFFSET);
1441 "/X2 {X exch X exch} bd\n"
1442 "/M {X2 moveto} bd\n"
1443 "/L {X2 lineto} bd\n"
1447 "/CP {closepath} bd\n"
1448 "/WS {setlinewidth stroke} bd\n"
1451 "/TaC {dup stringwidth pop neg 2 div 0 rmoveto } bd\n"
1452 "/TaR {dup stringwidth pop neg 0 rmoveto } bd\n"
1453 "/TL {moveto TaL show} bd\n"
1454 "/TC {moveto TaC show} bd\n"
1455 "/TR {moveto TaR show} bd\n"
1456 "/Rgb { 255.0 div 3 1 roll\n"
1457 " 255.0 div 3 1 roll \n"
1458 " 255.0 div 3 1 roll setrgbcolor } bd\n"
1460 eps_define_fonts(state);
1464 static void eps_clear_dash(eps_state *state)
1466 if (!state->has_dash)
1468 state->has_dash = 0;
1469 fputs("[1 0] 0 setdash\n", state->fp);
1472 static void eps_write_linearea(eps_state *state, gfx_node_t *node)
1475 FILE *fp = state->fp;
1477 int clearDashIfAny = 1;
1478 eps_set_color(state, node->color);
1479 if (node->type == GFX_LINE) {
1481 if (state->linecap != 1) {
1482 fputs("1 setlinecap\n", fp);
1485 if (state->linejoin != 1) {
1486 fputs("1 setlinejoin\n", fp);
1487 state->linejoin = 1;
1489 svg_get_dash(node, &dash_info);
1490 if (dash_info.dash_enable) {
1492 state->has_dash = 1;
1494 svg_write_number(fp, dash_info.adjusted_on);
1496 svg_write_number(fp, dash_info.adjusted_off);
1498 svg_write_number(fp, dash_info.dash_offset);
1499 fputs(" setdash\n", fp);
1503 eps_clear_dash(state);
1504 for (i = 0; i < node->points; i++) {
1505 ArtVpath *vec = node->path + i;
1507 double y = state->page_height - vec->y;
1508 if (vec->code == ART_MOVETO_OPEN || vec->code == ART_MOVETO)
1509 useOffset = (fabs(x - floor(x) - 0.5) < 0.01 && fabs(y - floor(y) - 0.5) < 0.01);
1514 switch (vec->code) {
1515 case ART_MOVETO_OPEN: /* fall-through */
1517 svg_write_number(fp, x);
1519 svg_write_number(fp, y);
1521 fputs(useOffset ? "M\n" : "m\n", fp);
1524 svg_write_number(fp, x);
1526 svg_write_number(fp, y);
1528 fputs(useOffset ? "L\n" : "l\n", fp);
1530 case ART_CURVETO: break; /* unsupported */
1531 case ART_END: break; /* nop */
1534 if (node->type == GFX_LINE) {
1535 if (node->closed_path)
1537 if (node->size != state->line_width) {
1538 state->line_width = node->size;
1539 svg_write_number(fp, state->line_width);
1549 static void eps_write_text(eps_state *state, gfx_node_t *node)
1551 FILE *fp = state->fp;
1552 const unsigned char *p;
1553 const char *ps_font = afm_get_font_postscript_name(node->filename);
1556 double y = state->page_height - node->y, ydelta = 0;
1558 eps_set_color(state, node->color);
1559 if (strcmp(ps_font, state->font) || node->size != state->font_size) {
1560 state->font = ps_font;
1561 state->font_size = node->size;
1562 svg_write_number(fp, state->font_size);
1563 fprintf(fp, " SetFont-%s\n", state->font);
1567 for (p = (const unsigned char*)node->text; *p; p++) {
1569 fputs("\\\n", fp); /* backslash and \n */
1584 fprintf(fp, "\\%03o", *p);
1591 switch(node->valign){
1592 case GFX_V_TOP: ydelta = -node->size; break;
1593 case GFX_V_CENTER: ydelta = -node->size / 3.0; break;
1594 case GFX_V_BOTTOM: break;
1595 case GFX_V_NULL: break;
1597 if (node->angle == 0)
1599 switch (node->halign) {
1600 case GFX_H_RIGHT: align = 'R'; break;
1601 case GFX_H_CENTER: align = 'C'; break;
1602 case GFX_H_LEFT: align= 'L'; break;
1603 case GFX_H_NULL: align= 'L'; break;
1605 if (node->angle != 0) {
1607 fputs(" gsave ", fp);
1608 svg_write_number(fp, x);
1610 svg_write_number(fp, y);
1611 fputs(" translate ", fp);
1612 svg_write_number(fp, node->angle);
1613 fputs(" rotate 0 ", fp);
1614 svg_write_number(fp, ydelta);
1615 fputs(" moveto ", fp);
1616 fprintf(fp, "Ta%c", align);
1617 fputs(" show grestore\n", fp);
1619 svg_write_number(fp, x);
1621 svg_write_number(fp, y);
1628 static int eps_write_content(eps_state *state)
1631 fputs("%\n", state->fp);
1632 for (node = state->canvas->firstnode; node; node = node->next) {
1633 switch (node->type) {
1636 eps_write_linearea(state, node);
1639 eps_write_text(state, node);
1646 int gfx_render_eps (gfx_canvas_t *canvas,
1647 art_u32 width, art_u32 height,
1648 gfx_color_t background, FILE *fp){
1649 struct eps_state state;
1651 state.canvas = canvas;
1652 state.page_width = width;
1653 state.page_height = height;
1654 state.font = "no-default-font";
1655 state.font_size = -1;
1656 state.color = 0; /* black */
1657 state.font_list = NULL;
1659 state.linejoin = -1;
1661 if (eps_prologue(&state) == -1)
1663 eps_set_color(&state, background);
1664 fprintf(fp, "0 0 M 0 %d L %d %d L %d 0 L fill\n",
1665 height, width, height, width);
1666 if (eps_write_content(&state) == -1)
1668 fputs("showpage\n", fp);
1669 fputs("%%EOF\n", fp);
1670 while (state.font_list) {
1671 eps_font *next = state.font_list->next;
1672 free(state.font_list);
1673 state.font_list = next;
1678 /* ------- PDF -------
1679 PDF references page:
1680 http://partners.adobe.com/asn/developer/technotes/acrobatpdf.html
1683 typedef struct pdf_buffer
1685 int id, is_obj, is_dict, is_stream, pdf_file_pos;
1687 int alloc_size, current_size;
1688 struct pdf_buffer *previous_buffer, *next_buffer;
1689 struct pdf_state *state;
1692 typedef struct pdf_font
1694 const char *ps_font;
1696 struct pdf_font *next;
1699 typedef struct pdf_state
1702 gfx_canvas_t *canvas;
1703 art_u32 page_width, page_height;
1704 pdf_font *font_list;
1705 pdf_buffer *first_buffer, *last_buffer;
1709 gfx_color_t stroke_color, fill_color;
1714 int linecap, linejoin;
1717 pdf_buffer pdf_header;
1718 pdf_buffer catalog_obj, pages_obj, page1_obj;
1719 pdf_buffer fontsdict_obj;
1720 pdf_buffer graph_stream;
1723 static void pdf_init_buffer(pdf_state *state, pdf_buffer *buf)
1725 int initial_size = 32;
1728 buf->alloc_size = 0;
1729 buf->current_size = 0;
1730 buf->data = (char*)malloc(initial_size);
1732 buf->previous_buffer = NULL;
1733 buf->next_buffer = NULL;
1734 if (buf->data == NULL) {
1735 rrd_set_error("malloc for pdf_buffer data");
1736 state->has_failed = 1;
1739 buf->alloc_size = initial_size;
1740 if (state->last_buffer)
1741 state->last_buffer->next_buffer = buf;
1742 if (state->first_buffer == NULL)
1743 state->first_buffer = buf;
1744 buf->previous_buffer = state->last_buffer;
1745 state->last_buffer = buf;
1748 static void pdf_put(pdf_buffer *buf, const char *text, int len)
1752 if (buf->alloc_size < buf->current_size + len) {
1753 int new_size = buf->alloc_size;
1755 while (new_size < buf->current_size + len)
1757 new_buf = (char*)malloc(new_size);
1758 if (new_buf == NULL) {
1759 rrd_set_error("re-malloc for pdf_buffer data");
1760 buf->state->has_failed = 1;
1763 memcpy(new_buf, buf->data, buf->current_size);
1765 buf->data = new_buf;
1766 buf->alloc_size = new_size;
1768 memcpy(buf->data + buf->current_size, text, len);
1769 buf->current_size += len;
1772 static void pdf_puts(pdf_buffer *buf, const char *text)
1774 pdf_put(buf, text, strlen(text));
1777 static void pdf_indent(pdf_buffer *buf)
1779 pdf_puts(buf, "\t");
1782 static void pdf_putsi(pdf_buffer *buf, const char *text)
1785 pdf_puts(buf, text);
1788 static void pdf_putint(pdf_buffer *buf, int i)
1791 sprintf(tmp, "%d", i);
1795 static void pdf_putnumber(pdf_buffer *buf, double d)
1798 svg_format_number(tmp, sizeof(tmp), d);
1802 static void pdf_init_object(pdf_state *state, pdf_buffer *buf)
1804 pdf_init_buffer(state, buf);
1805 buf->id = ++state->last_obj_id;
1810 static void pdf_init_dict(pdf_state *state, pdf_buffer *buf)
1812 pdf_init_object(state, buf);
1816 static void pdf_set_color(pdf_buffer *buf, gfx_color_t color,
1817 gfx_color_t *current_color, const char *op)
1819 /* gfx_color_t is RRGGBBAA */
1820 if (*current_color == color)
1822 pdf_putnumber(buf, ((color >> 24) & 255) / 255.0);
1824 pdf_putnumber(buf, ((color >> 16) & 255) / 255.0);
1826 pdf_putnumber(buf, ((color >> 8) & 255) / 255.0);
1829 pdf_puts(buf, "\n");
1830 *current_color = color;
1833 static void pdf_set_stroke_color(pdf_buffer *buf, gfx_color_t color)
1835 pdf_set_color(buf, color, &buf->state->stroke_color, "RG");
1838 static void pdf_set_fill_color(pdf_buffer *buf, gfx_color_t color)
1840 pdf_set_color(buf, color, &buf->state->fill_color, "rg");
1843 static pdf_font *pdf_find_font(pdf_state *state, gfx_node_t *node)
1845 const char *ps_font = afm_get_font_postscript_name(node->filename);
1847 for (ef = state->font_list; ef; ef = ef->next) {
1848 if (!strcmp(ps_font, ef->ps_font))
1854 static void pdf_add_font(pdf_state *state, gfx_node_t *node)
1856 pdf_font *ef = pdf_find_font(state, node);
1859 ef = malloc(sizeof(pdf_font));
1861 rrd_set_error("malloc for pdf_font");
1862 state->has_failed = 1;
1865 pdf_init_dict(state, &ef->obj);
1866 ef->next = state->font_list;
1867 ef->ps_font = afm_get_font_postscript_name(node->filename);
1868 state->font_list = ef;
1870 pdf_putsi(&state->fontsdict_obj, "/F");
1871 pdf_putint(&state->fontsdict_obj, ef->obj.id);
1872 pdf_puts(&state->fontsdict_obj, " ");
1873 pdf_putint(&state->fontsdict_obj, ef->obj.id);
1874 pdf_puts(&state->fontsdict_obj, " 0 R\n");
1876 pdf_putsi(&ef->obj, "/Type /Font\n");
1877 pdf_putsi(&ef->obj, "/Subtype /Type1\n");
1878 pdf_putsi(&ef->obj, "/Name /F");
1879 pdf_putint(&ef->obj, ef->obj.id);
1880 pdf_puts(&ef->obj, "\n");
1881 pdf_putsi(&ef->obj, "/BaseFont /");
1882 pdf_puts(&ef->obj, ef->ps_font);
1883 pdf_puts(&ef->obj, "\n");
1884 pdf_putsi(&ef->obj, "/Encoding /WinAnsiEncoding\n");
1885 /* 'Cp1252' (this is latin 1 extended with 27 characters;
1886 the encoding is also known as 'winansi')
1887 http://www.lowagie.com/iText/tutorial/ch09.html */
1890 static void pdf_create_fonts(pdf_state *state)
1893 for (node = state->canvas->firstnode; node; node = node->next) {
1894 if (node->type == GFX_TEXT)
1895 pdf_add_font(state, node);
1899 static void pdf_write_linearea(pdf_state *state, gfx_node_t *node)
1902 pdf_buffer *s = &state->graph_stream;
1903 if (node->type == GFX_LINE) {
1905 svg_get_dash(node, &dash_info);
1906 if (!svg_dash_equal(&dash_info, &state->dash)) {
1907 state->dash = dash_info;
1908 if (dash_info.dash_enable) {
1910 pdf_putnumber(s, dash_info.adjusted_on);
1912 pdf_putnumber(s, dash_info.adjusted_off);
1914 pdf_putnumber(s, dash_info.dash_offset);
1915 pdf_puts(s, " d\n");
1917 pdf_puts(s, "[] 0 d\n");
1920 pdf_set_stroke_color(s, node->color);
1921 if (state->linecap != 1) {
1922 pdf_puts(s, "1 j\n");
1925 if (state->linejoin != 1) {
1926 pdf_puts(s, "1 J\n");
1927 state->linejoin = 1;
1929 if (node->size != state->line_width) {
1930 state->line_width = node->size;
1931 pdf_putnumber(s, state->line_width);
1932 pdf_puts(s, " w\n");
1935 pdf_set_fill_color(s, node->color);
1937 for (i = 0; i < node->points; i++) {
1938 ArtVpath *vec = node->path + i;
1940 double y = state->page_height - vec->y;
1941 if (node->type == GFX_AREA) {
1942 x += LINEOFFSET; /* adjust for libart handling of areas */
1945 switch (vec->code) {
1946 case ART_MOVETO_OPEN: /* fall-through */
1948 pdf_putnumber(s, x);
1950 pdf_putnumber(s, y);
1951 pdf_puts(s, " m\n");
1954 pdf_putnumber(s, x);
1956 pdf_putnumber(s, y);
1957 pdf_puts(s, " l\n");
1959 case ART_CURVETO: break; /* unsupported */
1960 case ART_END: break; /* nop */
1963 if (node->type == GFX_LINE) {
1964 pdf_puts(s, node->closed_path ? "s\n" : "S\n");
1970 static void pdf_write_text(pdf_state *state, gfx_node_t *node,
1971 int last_was_text, int next_is_text)
1974 pdf_buffer *s = &state->graph_stream;
1975 const unsigned char *p;
1976 pdf_font *font = pdf_find_font(state, node);
1978 double y = state->page_height - node->y;
1979 double dx = 0, dy = 0;
1980 double cos_a = 0, sin_a = 0;
1982 rrd_set_error("font disappeared");
1983 state->has_failed = 1;
1986 switch(node->valign){
1987 case GFX_V_TOP: dy = -node->size; break;
1988 case GFX_V_CENTER: dy = -node->size / 3.0; break;
1989 case GFX_V_BOTTOM: break;
1990 case GFX_V_NULL: break;
1992 switch (node->halign) {
1993 case GFX_H_RIGHT: dx = -afm_get_text_width(0, font->ps_font,
1994 node->size, node->tabwidth, node->text);
1996 case GFX_H_CENTER: dx = -afm_get_text_width(0, font->ps_font,
1997 node->size, node->tabwidth, node->text) / 2;
1999 case GFX_H_LEFT: break;
2000 case GFX_H_NULL: break;
2002 pdf_set_fill_color(s, node->color);
2003 if (node->angle != 0) {
2004 double a = 2 * M_PI * node->angle / 360.0;
2005 double new_x, new_y;
2008 new_x = cos_a * dx - sin_a * dy + x;
2009 new_y = sin_a * dx + cos_a * dy + y;
2017 pdf_puts(s, "BT\n");
2018 if (state->font_id != font->obj.id || node->size != state->font_size) {
2019 state->font_id = font->obj.id;
2020 state->font_size = node->size;
2022 pdf_putint(s, font->obj.id);
2024 pdf_putnumber(s, node->size);
2025 pdf_puts(s, " Tf\n");
2027 if (node->angle == 0) {
2028 pdf_puts(s, "1 0 0 1 ");
2030 pdf_putnumber(s, cos_a);
2032 pdf_putnumber(s, sin_a);
2034 pdf_putnumber(s, -sin_a);
2036 pdf_putnumber(s, cos_a);
2039 pdf_putnumber(s, x);
2041 pdf_putnumber(s, y);
2042 pdf_puts(s, " Tm\n");
2044 for (p = (const unsigned char*)node->text; *p; p++) {
2056 snprintf(tmp, sizeof(tmp), "\\%03o", *p);
2059 pdf_put(s, (const char*)p, 1);
2063 pdf_puts(s, ") Tj\n");
2065 pdf_puts(s, "ET\n");
2068 static void pdf_write_content(pdf_state *state)
2071 int last_was_text = 0, next_is_text;
2072 for (node = state->canvas->firstnode; node; node = node->next) {
2073 switch (node->type) {
2076 pdf_write_linearea(state, node);
2079 next_is_text = node->next && node->next->type == GFX_TEXT;
2080 pdf_write_text(state, node, last_was_text, next_is_text);
2083 last_was_text = node->type == GFX_TEXT;
2087 static void pdf_init_document(pdf_state *state)
2089 pdf_init_buffer(state, &state->pdf_header);
2090 pdf_init_dict(state, &state->catalog_obj);
2091 pdf_init_dict(state, &state->pages_obj);
2092 pdf_init_dict(state, &state->page1_obj);
2093 pdf_init_dict(state, &state->fontsdict_obj);
2094 pdf_create_fonts(state);
2095 if (state->has_failed)
2097 /* make stream last object in file */
2098 pdf_init_object(state, &state->graph_stream);
2099 state->graph_stream.is_stream = 1;
2102 static void pdf_setup_document(pdf_state *state)
2104 /* all objects created by now, so init code can reference them */
2106 pdf_puts(&state->pdf_header, "%PDF-1.3\n");
2107 /* following 8 bit comment is recommended by Adobe for
2108 indicating binary file to file transfer applications */
2109 pdf_puts(&state->pdf_header, "%\xE2\xE3\xCF\xD3\n");
2111 pdf_putsi(&state->catalog_obj, "/Type /Catalog\n");
2112 pdf_putsi(&state->catalog_obj, "/Pages ");
2113 pdf_putint(&state->catalog_obj, state->pages_obj.id);
2114 pdf_puts(&state->catalog_obj, " 0 R\n");
2116 pdf_putsi(&state->pages_obj, "/Type /Pages\n");
2117 pdf_putsi(&state->pages_obj, "/Kids [");
2118 pdf_putint(&state->pages_obj, state->page1_obj.id);
2119 pdf_puts(&state->pages_obj, " 0 R]\n");
2120 pdf_putsi(&state->pages_obj, "/Count 1\n");
2122 pdf_putsi(&state->page1_obj, "/Type /Page\n");
2123 pdf_putsi(&state->page1_obj, "/Parent ");
2124 pdf_putint(&state->page1_obj, state->pages_obj.id);
2125 pdf_puts(&state->page1_obj, " 0 R\n");
2126 pdf_putsi(&state->page1_obj, "/MediaBox [0 0 ");
2127 pdf_putint(&state->page1_obj, state->page_width);
2128 pdf_puts(&state->page1_obj, " ");
2129 pdf_putint(&state->page1_obj, state->page_height);
2130 pdf_puts(&state->page1_obj, "]\n");
2131 pdf_putsi(&state->page1_obj, "/Contents ");
2132 pdf_putint(&state->page1_obj, state->graph_stream.id);
2133 pdf_puts(&state->page1_obj, " 0 R\n");
2134 pdf_putsi(&state->page1_obj, "/Resources << /Font ");
2135 pdf_putint(&state->page1_obj, state->fontsdict_obj.id);
2136 pdf_puts(&state->page1_obj, " 0 R >>\n");
2139 static void pdf_write_string_to_file(pdf_state *state, const char *text)
2141 fputs(text, state->fp);
2142 state->pdf_file_pos += strlen(text);
2145 static void pdf_write_buf_to_file(pdf_state *state, pdf_buffer *buf)
2148 buf->pdf_file_pos = state->pdf_file_pos;
2150 snprintf(tmp, sizeof(tmp), "%d 0 obj\n", buf->id);
2151 pdf_write_string_to_file(state, tmp);
2154 pdf_write_string_to_file(state, "<<\n");
2155 if (buf->is_stream) {
2156 snprintf(tmp, sizeof(tmp), "<< /Length %d >>\n", buf->current_size);
2157 pdf_write_string_to_file(state, tmp);
2158 pdf_write_string_to_file(state, "stream\n");
2160 fwrite(buf->data, 1, buf->current_size, state->fp);
2161 state->pdf_file_pos += buf->current_size;
2163 pdf_write_string_to_file(state, "endstream\n");
2165 pdf_write_string_to_file(state, ">>\n");
2167 pdf_write_string_to_file(state, "endobj\n");
2170 static void pdf_write_to_file(pdf_state *state)
2172 pdf_buffer *buf = state->first_buffer;
2174 state->pdf_file_pos = 0;
2175 pdf_write_buf_to_file(state, &state->pdf_header);
2178 pdf_write_buf_to_file(state, buf);
2179 buf = buf->next_buffer;
2181 xref_pos = state->pdf_file_pos;
2182 fprintf(state->fp, "xref\n");
2183 fprintf(state->fp, "%d %d\n", 0, state->last_obj_id + 1);
2184 /* TOC lines must be exactly 20 bytes including \n */
2185 fprintf(state->fp, "%010d %05d f\x20\n", 0, 65535);
2186 for (buf = state->first_buffer; buf; buf = buf->next_buffer) {
2188 fprintf(state->fp, "%010d %05d n\x20\n", buf->pdf_file_pos, 0);
2190 fprintf(state->fp, "trailer\n");
2191 fprintf(state->fp, "<<\n");
2192 fprintf(state->fp, "\t/Size %d\n", state->last_obj_id + 1);
2193 fprintf(state->fp, "\t/Root %d 0 R\n", state->catalog_obj.id);
2194 fprintf(state->fp, ">>\n");
2195 fprintf(state->fp, "startxref\n");
2196 fprintf(state->fp, "%d\n", xref_pos);
2197 fputs("%%EOF\n", state->fp);
2200 static void pdf_free_resources(pdf_state *state)
2202 pdf_buffer *buf = state->first_buffer;
2206 buf->alloc_size = buf->current_size = 0;
2207 buf = buf->next_buffer;
2209 while (state->font_list) {
2210 pdf_font *next = state->font_list->next;
2211 free(state->font_list);
2212 state->font_list = next;
2216 int gfx_render_pdf (gfx_canvas_t *canvas,
2217 art_u32 width, art_u32 height,
2218 gfx_color_t background, FILE *fp){
2219 struct pdf_state state;
2220 memset(&state, 0, sizeof(pdf_state));
2222 state.canvas = canvas;
2223 state.page_width = width;
2224 state.page_height = height;
2226 state.font_size = -1;
2227 state.font_list = NULL;
2229 state.linejoin = -1;
2230 pdf_init_document(&state);
2232 pdf_set_color(&state, background);
2233 fprintf(fp, "0 0 M 0 %d L %d %d L %d 0 L fill\n",
2234 height, width, height, width);
2236 if (!state.has_failed)
2237 pdf_write_content(&state);
2238 if (!state.has_failed)
2239 pdf_setup_document(&state);
2240 if (!state.has_failed)
2241 pdf_write_to_file(&state);
2242 pdf_free_resources(&state);
2243 return state.has_failed ? -1 : 0;