1 /****************************************************************************
2 * RRDtool 1.2.1 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 */
517 art_u8 *buffer = art_new (art_u8, rowstride*pys_height);
518 /* fill that buffer with out background color */
521 for (i=0,buffp=(gfx_color_t *)buffer;
522 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 ( pvec, 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 ( pvec );
547 svpt = art_svp_uncross( svp );
549 svp = art_svp_rewind_uncrossed(svpt,ART_WIND_RULE_NONZERO);
553 /* this is from gnome since libart does not have this yet */
554 gnome_print_art_rgba_svp_alpha (svp ,0,0, pys_width, pys_height,
555 node->color, buffer, rowstride, NULL);
562 art_u8 fcolor[4],falpha;
566 FT_Vector vec; /* 26.6 */
568 float pen_x = 0.0 , pen_y = 0.0;
572 fcolor[0] = node->color >> 24;
573 fcolor[1] = (node->color >> 16) & 0xff;
574 fcolor[2] = (node->color >> 8) & 0xff;
575 falpha = node->color & 0xff;
576 error = FT_New_Face( library,
577 (char *)node->filename,
581 rrd_set_error("failed to load %s",node->filename);
584 error = FT_Set_Char_Size(face, /* handle to face object */
585 (long)(node->size*64),
586 (long)(node->size*64),
587 (long)(100*canvas->zoom),
588 (long)(100*canvas->zoom));
590 pen_x = node->x * canvas->zoom;
591 pen_y = node->y * canvas->zoom;
593 string = gfx_string_create (canvas, face, node->text, node->angle, node->tabwidth, node->size);
594 switch(node->halign){
595 case GFX_H_RIGHT: vec.x = -string->bbox.xMax;
597 case GFX_H_CENTER: vec.x = abs(string->bbox.xMax) >= abs(string->bbox.xMin) ?
598 -string->bbox.xMax/2:-string->bbox.xMin/2;
600 case GFX_H_LEFT: vec.x = -string->bbox.xMin;
602 case GFX_H_NULL: vec.x = 0;
606 switch(node->valign){
607 case GFX_V_TOP: vec.y = string->bbox.yMax;
609 case GFX_V_CENTER: vec.y = abs(string->bbox.yMax) >= abs(string->bbox.yMin) ?
610 string->bbox.yMax/2:string->bbox.yMin/2;
612 case GFX_V_BOTTOM: vec.y = 0;
614 case GFX_V_NULL: vec.y = 0;
619 glyph = string->glyphs;
620 for(n=0; n<string->num_glyphs; ++n, ++glyph) {
624 /* long buf_x,comp_n; */
625 /* make copy to transform */
626 if (! glyph->image) {
627 fprintf (stderr, "no image\n");
630 error = FT_Glyph_Copy (glyph->image, &image);
632 fprintf (stderr, "couldn't copy image\n");
638 FT_Vector_Transform (&vec, &string->transform);
640 bit = (FT_BitmapGlyph) image;
641 gr = bit->bitmap.num_grays -1;
643 buf_x = (pen_x + 0.5) + (double)bit->left;
644 comp_n = buf_x + bit->bitmap.width > pys_width ? pys_width - buf_x : bit->bitmap.width;
645 if (buf_x < 0 || buf_x >= (long)pys_width) continue;
646 buf_x *= bytes_per_pixel ;
647 for (iy=0; iy < bit->bitmap.rows; iy++){
648 long buf_y = iy+(pen_y+0.5)-(double)bit->top;
649 if (buf_y < 0 || buf_y >= (long)pys_height) continue;
651 for (ix=0;ix < bit->bitmap.width;ix++){
652 *(letter + (ix*bytes_per_pixel+3)) = *(bit->bitmap.buffer + iy * bit->bitmap.width + ix);
654 art_rgba_rgba_composite(buffer + buf_y + buf_x ,letter,comp_n);
658 switch ( bit->bitmap.pixel_mode ) {
659 case FT_PIXEL_MODE_GRAY:
660 for (iy=0; iy < bit->bitmap.rows; iy++){
661 long buf_y = iy+(pen_y+0.5)-bit->top;
662 if (buf_y < 0 || buf_y >= (long)pys_height) continue;
664 for (ix=0;ix < bit->bitmap.width;ix++){
665 long buf_x = ix + (pen_x + 0.5) + (double)bit->left ;
668 if (buf_x < 0 || buf_x >= (long)pys_width) continue;
669 buf_x *= bytes_per_pixel ;
670 font_alpha = *(bit->bitmap.buffer + iy * bit->bitmap.pitch + ix);
672 fcolor[3] = (art_u8)((double)font_alpha / gr * falpha);
673 art_rgba_rgba_composite(buffer + buf_y + buf_x ,fcolor,1);
679 case FT_PIXEL_MODE_MONO:
680 for (iy=0; iy < bit->bitmap.rows; iy++){
681 long buf_y = iy+(pen_y+0.5)-bit->top;
682 if (buf_y < 0 || buf_y >= (long)pys_height) continue;
684 for (ix=0;ix < bit->bitmap.width;ix++){
685 long buf_x = ix + (pen_x + 0.5) + (double)bit->left ;
687 if (buf_x < 0 || buf_x >= (long)pys_width) continue;
688 buf_x *= bytes_per_pixel ;
689 if ( (fcolor[3] = falpha * ((*(bit->bitmap.buffer + iy * bit->bitmap.pitch + ix/8) >> (7 - (ix % 8))) & 1)) > 0 )
690 art_rgba_rgba_composite(buffer + buf_y + buf_x ,fcolor,1);
696 rrd_set_error("unknown freetype pixel mode: %d", bit->bitmap.pixel_mode);
701 for (iy=0; iy < bit->bitmap.rows; iy++){
702 long buf_y = iy+(pen_y+0.5)-bit->top;
703 if (buf_y < 0 || buf_y >= (long)pys_height) continue;
705 for (ix=0;ix < bit->bitmap.width;ix++){
706 long buf_x = ix + (pen_x + 0.5) + (double)bit->left ;
709 if (buf_x < 0 || buf_x >= (long)pys_width) continue;
710 buf_x *= bytes_per_pixel ;
711 font_alpha = *(bit->bitmap.buffer + iy * bit->bitmap.width + ix);
712 font_alpha = (art_u8)((double)font_alpha / gr * falpha);
713 for (iz = 0; iz < 3; iz++){
714 art_u8 *orig = buffer + buf_y + buf_x + iz;
715 *orig = (art_u8)((double)*orig / gr * ( gr - font_alpha) +
716 (double)fcolor[iz] / gr * (font_alpha));
721 FT_Done_Glyph (image);
723 gfx_string_destroy(string);
728 gfx_save_png(buffer,fp , pys_width,pys_height,bytes_per_pixel);
730 FT_Done_FreeType( library );
734 /* free memory used by nodes this will also remove memory required for
735 associated paths and svcs ... but not for text strings */
737 gfx_destroy (gfx_canvas_t *canvas){
738 gfx_node_t *next,*node = canvas->firstnode;
741 art_free(node->path);
743 free(node->filename);
751 static int gfx_save_png (art_u8 *buffer, FILE *fp, long width, long height, long bytes_per_pixel){
752 png_structp png_ptr = NULL;
753 png_infop info_ptr = NULL;
755 png_bytep *row_pointers;
756 int rowstride = width * bytes_per_pixel;
762 png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING,NULL,NULL,NULL);
767 row_pointers = (png_bytepp)png_malloc(png_ptr,
768 height*sizeof(png_bytep));
770 info_ptr = png_create_info_struct(png_ptr);
772 if (info_ptr == NULL)
774 png_free(png_ptr,row_pointers);
775 png_destroy_write_struct(&png_ptr, (png_infopp)NULL);
779 if (setjmp(png_jmpbuf(png_ptr)))
781 /* If we get here, we had a problem writing the file */
782 png_destroy_write_struct(&png_ptr, &info_ptr);
786 png_init_io(png_ptr, fp);
787 png_set_IHDR (png_ptr, info_ptr,width, height,
788 8, PNG_COLOR_TYPE_RGB_ALPHA,
790 PNG_COMPRESSION_TYPE_DEFAULT,
791 PNG_FILTER_TYPE_DEFAULT);
793 text[0].key = "Software";
794 text[0].text = "RRDtool, Tobias Oetiker <tobi@oetike.ch>, http://tobi.oetiker.ch";
795 text[0].compression = PNG_TEXT_COMPRESSION_NONE;
796 png_set_text (png_ptr, info_ptr, text, 1);
798 /* lets make this fast */
799 /* png_set_filter(png_ptr,0,PNG_FILTER_NONE); */
800 png_set_compression_level(png_ptr,1);
801 /* png_set_compression_strategy(png_ptr,Z_HUFFMAN_ONLY); */
803 png_set_filter(png_ptr,PNG_FILTER_TYPE_BASE,PNG_FILTER_SUB);
804 png_set_compression_strategy(png_ptr,Z_HUFFMAN_ONLY);
805 png_set_compression_level(png_ptr,Z_BEST_SPEED); */
807 /* Write header data */
808 png_write_info (png_ptr, info_ptr);
809 for (i = 0; i < height; i++)
810 row_pointers[i] = (png_bytep) (buffer + i*rowstride);
812 png_write_image(png_ptr, row_pointers);
813 png_write_end(png_ptr, info_ptr);
814 png_free(png_ptr,row_pointers);
815 png_destroy_write_struct(&png_ptr, &info_ptr);
820 /* ------- SVG -------
822 http://www.w3.org/TR/SVG/
824 static int svg_indent = 0;
825 static int svg_single_line = 0;
826 static const char *svg_default_font = "Helvetica";
827 typedef struct svg_dash
830 double dash_adjust, dash_len, dash_offset;
831 double adjusted_on, adjusted_off;
835 static void svg_print_indent(FILE *fp)
838 for (i = svg_indent - svg_single_line; i > 0; i--) {
844 static void svg_start_tag(FILE *fp, const char *name)
846 svg_print_indent(fp);
852 static void svg_close_tag_single_line(FILE *fp)
858 static void svg_close_tag(FILE *fp)
861 if (!svg_single_line)
865 static void svg_end_tag(FILE *fp, const char *name)
867 /* name is NULL if closing empty-node tag */
872 svg_print_indent(fp);
882 static void svg_close_tag_empty_node(FILE *fp)
884 svg_end_tag(fp, NULL);
887 static void svg_write_text(FILE *fp, const char *text)
889 const unsigned char *p, *start, *last;
891 p = (const unsigned char*)text;
894 /* trim leading spaces */
898 /* trim trailing spaces */
900 while ((ch = *p) != 0) {
905 /* encode trimmed text */
909 ch = afm_host2unicode(ch); /* unsafe macro */
911 case '&': fputs("&", fp); break;
912 case '<': fputs("<", fp); break;
913 case '>': fputs(">", fp); break;
914 case '"': fputs(""", fp); break;
917 fprintf(fp, "&#%d;", ch);
924 static void svg_format_number(char *buf, int bufsize, double d)
926 /* omit decimals if integer to reduce filesize */
928 snprintf(buf, bufsize, "%.2f", d);
929 p = buf; /* doesn't trust snprintf return value */
935 *p = '\0'; /* zap trailing zeros */
939 *p = '\0'; /* zap trailing dot */
944 static void svg_write_number(FILE *fp, double d)
947 svg_format_number(buf, sizeof(buf), d);
951 static int svg_color_is_black(int c)
953 /* gfx_color_t is RRGGBBAA */
954 return c == 0x000000FF;
957 static void svg_write_color(FILE *fp, gfx_color_t c, const char *attr)
959 /* gfx_color_t is RRGGBBAA, svg can use #RRGGBB and #RGB like html */
960 gfx_color_t rrggbb = (int)((c >> 8) & 0xFFFFFF);
961 gfx_color_t opacity = c & 0xFF;
962 fprintf(fp, " %s=\"", attr);
963 if ((rrggbb & 0x0F0F0F) == ((rrggbb >> 4) & 0x0F0F0F)) {
964 /* css2 short form, #rgb is #rrggbb, not #r0g0b0 */
965 fprintf(fp, "#%03lX",
966 ( ((rrggbb >> 8) & 0xF00)
967 | ((rrggbb >> 4) & 0x0F0)
968 | ( rrggbb & 0x00F)));
970 fprintf(fp, "#%06lX", rrggbb);
973 if (opacity != 0xFF) {
974 fprintf(fp, " stroke-opacity=\"");
975 svg_write_number(fp, opacity / 255.0);
980 static void svg_get_dash(gfx_node_t *node, svg_dash *d)
984 if (node->dash_on <= 0 || node->dash_off <= 0) {
989 d->dash_len = node->dash_on + node->dash_off;
990 /* dash on/off adjustment due to round caps */
991 d->dash_adjust = 0.8 * node->size;
992 d->adjusted_on = node->dash_on - d->dash_adjust;
993 if (d->adjusted_on < 0.01)
994 d->adjusted_on = 0.01;
995 d->adjusted_off = d->dash_len - d->adjusted_on;
996 /* dash offset calc */
997 if (node->path[0].x == node->path[1].x) /* only good for horz/vert lines */
998 offset = node->path[0].y;
1000 offset = node->path[0].x;
1001 mult = (int)fabs(offset / d->dash_len);
1002 d->dash_offset = offset - mult * d->dash_len;
1003 if (node->path[0].x < node->path[1].x || node->path[0].y < node->path[1].y)
1004 d->dash_offset = d->dash_len - d->dash_offset;
1007 static int svg_dash_equal(svg_dash *a, svg_dash *b)
1009 if (a->dash_enable != b->dash_enable)
1011 if (a->adjusted_on != b->adjusted_on)
1013 if (a->adjusted_off != b->adjusted_off)
1015 /* rest of properties will be the same when on+off are */
1019 static void svg_common_path_attributes(FILE *fp, gfx_node_t *node)
1022 svg_get_dash(node, &dash_info);
1023 fputs(" stroke-width=\"", fp);
1024 svg_write_number(fp, node->size);
1026 svg_write_color(fp, node->color, "stroke");
1027 fputs(" fill=\"none\"", fp);
1028 if (dash_info.dash_enable) {
1029 if (dash_info.dash_offset != 0) {
1030 fputs(" stroke-dashoffset=\"", fp);
1031 svg_write_number(fp, dash_info.dash_offset);
1034 fputs(" stroke-dasharray=\"", fp);
1035 svg_write_number(fp, dash_info.adjusted_on);
1037 svg_write_number(fp, dash_info.adjusted_off);
1042 static int svg_is_int_step(double a, double b)
1044 double diff = fabs(a - b);
1045 return floor(diff) == diff;
1048 static int svg_path_straight_segment(FILE *fp,
1049 double lastA, double currentA, double currentB,
1051 int segment_idx, int isx, char absChar, char relChar)
1053 if (!svg_is_int_step(lastA, currentA)) {
1055 svg_write_number(fp, currentA);
1058 if (segment_idx < node->points - 1) {
1059 ArtVpath *vec = node->path + segment_idx + 1;
1060 if (vec->code == ART_LINETO) {
1061 double nextA = (isx ? vec->x : vec->y) - LINEOFFSET;
1062 double nextB = (isx ? vec->y : vec->x) - LINEOFFSET;
1063 if (nextB == currentB
1064 && ((currentA >= lastA) == (nextA >= currentA))
1065 && svg_is_int_step(currentA, nextA)) {
1066 return 1; /* skip to next as it is a straight line */
1071 svg_write_number(fp, currentA - lastA);
1075 static void svg_path(FILE *fp, gfx_node_t *node, int multi)
1078 double lastX = 0, lastY = 0;
1079 /* for straight lines <path..> tags take less space than
1080 <line..> tags because of the efficient packing
1081 in the 'd' attribute */
1082 svg_start_tag(fp, "path");
1084 svg_common_path_attributes(fp, node);
1086 /* specification of the 'd' attribute: */
1087 /* http://www.w3.org/TR/SVG/paths.html#PathDataGeneralInformation */
1088 for (i = 0; i < node->points; i++) {
1089 ArtVpath *vec = node->path + i;
1090 double x = vec->x - LINEOFFSET;
1091 double y = vec->y - LINEOFFSET;
1092 switch (vec->code) {
1093 case ART_MOVETO_OPEN: /* fall-through */
1096 svg_write_number(fp, x);
1098 svg_write_number(fp, y);
1101 /* try optimize filesize by using minimal lineto commands */
1102 /* without introducing rounding errors. */
1104 if (svg_path_straight_segment(fp, lastY, y, x, node, i, 0, 'V', 'v'))
1106 } else if (y == lastY) {
1107 if (svg_path_straight_segment(fp, lastX, x, y, node, i, 1, 'H', 'h'))
1111 svg_write_number(fp, x);
1113 svg_write_number(fp, y);
1116 case ART_CURVETO: break; /* unsupported */
1117 case ART_END: break; /* nop */
1122 if (node->closed_path)
1125 svg_close_tag_empty_node(fp);
1128 static void svg_multi_path(FILE *fp, gfx_node_t **nodeR)
1130 /* optimize for multiple paths with the same color, penwidth, etc. */
1132 gfx_node_t *node = *nodeR;
1133 gfx_node_t *next = node->next;
1135 if (next->type != node->type
1136 || next->size != node->size
1137 || next->color != node->color
1138 || next->dash_on != node->dash_on
1139 || next->dash_off != node->dash_off)
1145 svg_path(fp, node, 0);
1148 svg_start_tag(fp, "g");
1149 svg_common_path_attributes(fp, node);
1151 while (num && node) {
1152 svg_path(fp, node, 1);
1158 svg_end_tag(fp, "g");
1161 static void svg_area(FILE *fp, gfx_node_t *node)
1164 double startX = 0, startY = 0;
1165 svg_start_tag(fp, "polygon");
1167 svg_write_color(fp, node->color, "fill");
1168 fputs(" points=\"", fp);
1169 for (i = 0; i < node->points; i++) {
1170 ArtVpath *vec = node->path + i;
1171 double x = vec->x - LINEOFFSET;
1172 double y = vec->y - LINEOFFSET;
1173 switch (vec->code) {
1174 case ART_MOVETO_OPEN: /* fall-through */
1176 svg_write_number(fp, x);
1178 svg_write_number(fp, y);
1183 if (i == node->points - 2
1184 && node->path[i + 1].code == ART_END
1185 && fabs(x - startX) < 0.001 && fabs(y - startY) < 0.001) {
1186 break; /* poly area always closed, no need for last point */
1189 svg_write_number(fp, x);
1191 svg_write_number(fp, y);
1193 case ART_CURVETO: break; /* unsupported */
1194 case ART_END: break; /* nop */
1198 svg_close_tag_empty_node(fp);
1201 static void svg_text(FILE *fp, gfx_node_t *node)
1203 double x = node->x - LINEOFFSET;
1204 double y = node->y - LINEOFFSET;
1205 if (node->angle != 0) {
1206 svg_start_tag(fp, "g");
1207 fputs(" transform=\"translate(", fp);
1208 svg_write_number(fp, x);
1210 svg_write_number(fp, y);
1211 fputs(") rotate(", fp);
1212 svg_write_number(fp, node->angle);
1217 switch (node->valign) {
1218 case GFX_V_TOP: y += node->size; break;
1219 case GFX_V_CENTER: y += node->size / 3; break;
1220 case GFX_V_BOTTOM: break;
1221 case GFX_V_NULL: break;
1223 svg_start_tag(fp, "text");
1225 svg_write_number(fp, x);
1226 fputs("\" y=\"", fp);
1227 svg_write_number(fp, y);
1229 /* if (strcmp(node->filename, svg_default_font))
1230 fprintf(fp, " font-family=\"%s\"", node->filename);
1232 fputs("\" font-family=\"Helvetica", fp);
1233 fputs("\" font-size=\"", fp);
1234 svg_write_number(fp, node->size);
1236 if (!svg_color_is_black(node->color))
1237 svg_write_color(fp, node->color, "fill");
1238 switch (node->halign) {
1239 case GFX_H_RIGHT: fputs(" text-anchor=\"end\"", fp); break;
1240 case GFX_H_CENTER: fputs(" text-anchor=\"middle\"", fp); break;
1241 case GFX_H_LEFT: break;
1242 case GFX_H_NULL: break;
1244 svg_close_tag_single_line(fp);
1245 /* support for node->tabwidth missing */
1246 svg_write_text(fp, node->text);
1247 svg_end_tag(fp, "text");
1248 if (node->angle != 0)
1249 svg_end_tag(fp, "g");
1252 int gfx_render_svg (gfx_canvas_t *canvas,
1253 art_u32 width, art_u32 height,
1254 gfx_color_t background, FILE *fp){
1255 gfx_node_t *node = canvas->firstnode;
1257 "<?xml version=\"1.0\" standalone=\"no\"?>\n"
1258 "<!DOCTYPE svg PUBLIC \"-//W3C//DTD SVG 1.0//EN\"\n"
1259 " \"http://www.w3.org/TR/2001/REC-SVG-20010904/DTD/svg10.dtd\">\n"
1261 " SVG file created by RRDtool,\n"
1262 " Tobias Oetiker <tobi@oetike.ch>, http://tobi.oetiker.ch\n"
1264 " The width/height attributes in the outhermost svg node\n"
1265 " are just default sizes for the browser which is used\n"
1266 " if the svg file is openened directly without being\n"
1267 " embedded in an html file.\n"
1268 " The viewBox is the local coord system for rrdtool.\n"
1270 svg_start_tag(fp, "svg");
1271 fputs(" width=\"", fp);
1272 svg_write_number(fp, width * canvas->zoom);
1273 fputs("\" height=\"", fp);
1274 svg_write_number(fp, height * canvas->zoom);
1275 fputs("\" x=\"0\" y=\"0\" viewBox=\"", fp);
1276 svg_write_number(fp, -LINEOFFSET);
1278 svg_write_number(fp, -LINEOFFSET);
1280 svg_write_number(fp, width - LINEOFFSET);
1282 svg_write_number(fp, height - LINEOFFSET);
1283 fputs("\" preserveAspectRatio=\"xMidYMid\"", fp);
1284 fprintf(fp, " font-family=\"%s\"", svg_default_font); /* default font */
1285 fputs(" stroke-linecap=\"round\" stroke-linejoin=\"round\"", fp);
1287 svg_start_tag(fp, "rect");
1288 fprintf(fp, " x=\"0\" y=\"0\" width=\"%d\" height=\"%d\"", width, height);
1289 svg_write_color(fp, background, "fill");
1290 svg_close_tag_empty_node(fp);
1292 switch (node->type) {
1294 svg_multi_path(fp, &node);
1304 svg_end_tag(fp, "svg");
1308 /* ------- EPS -------
1309 EPS and Postscript references:
1310 http://partners.adobe.com/asn/developer/technotes/postscript.html
1313 typedef struct eps_font
1315 const char *ps_font;
1317 struct eps_font *next;
1320 typedef struct eps_state
1323 gfx_canvas_t *canvas;
1324 art_u32 page_width, page_height;
1325 eps_font *font_list;
1331 int linecap, linejoin;
1335 static void eps_set_color(eps_state *state, gfx_color_t color)
1337 /* gfx_color_t is RRGGBBAA */
1338 if (state->color == color)
1340 fprintf(state->fp, "%d %d %d Rgb\n",
1341 (int)((color >> 24) & 255),
1342 (int)((color >> 16) & 255),
1343 (int)((color >> 8) & 255));
1344 state->color = color;
1347 static int eps_add_font(eps_state *state, gfx_node_t *node)
1349 /* The fonts list could be postponed to the end using
1350 (atend), but let's be nice and have them in the header. */
1351 const char *ps_font = afm_get_font_postscript_name(node->filename);
1353 for (ef = state->font_list; ef; ef = ef->next) {
1354 if (!strcmp(ps_font, ef->ps_font))
1357 ef = malloc(sizeof(eps_font));
1359 rrd_set_error("malloc for eps_font");
1362 ef->next = state->font_list;
1363 ef->ps_font = ps_font;
1364 state->font_list = ef;
1368 static void eps_list_fonts(eps_state *state, const char *dscName)
1371 int lineLen = strlen(dscName);
1372 if (!state->font_list)
1374 fputs(dscName, state->fp);
1375 for (ef = state->font_list; ef; ef = ef->next) {
1376 int nameLen = strlen(ef->ps_font);
1377 if (lineLen + nameLen > 100 && lineLen) {
1378 fputs("\n", state->fp);
1379 fputs("%%- \n", state->fp);
1382 fputs(" ", state->fp);
1385 fputs(ef->ps_font, state->fp);
1388 fputs("\n", state->fp);
1391 static void eps_define_fonts(eps_state *state)
1394 if (!state->font_list)
1396 for (ef = state->font_list; ef; ef = ef->next) {
1397 /* PostScript¨ LANGUAGE REFERENCE third edition
1401 "/%s findfont dup length dict begin\n"
1402 "{ 1 index /FID ne {def} {pop pop} ifelse } forall\n"
1403 "/Encoding ISOLatin1Encoding def\n"
1405 "/%s-ISOLatin1 exch definefont pop\n"
1406 "/SetFont-%s { /%s-ISOLatin1 findfont exch scalefont setfont } bd\n",
1407 ef->ps_font, ef->ps_font, ef->ps_font, ef->ps_font);
1411 static int eps_prologue(eps_state *state)
1415 "%!PS-Adobe-3.0 EPSF-3.0\n"
1416 "%%Creator: RRDtool 1.2.1 Tobias Oetiker, http://tobi.oetiker.ch\n"
1417 /* can't like weird chars here */
1418 "%%Title: (RRDtool output)\n"
1419 "%%DocumentData: Clean7Bit\n"
1421 fprintf(state->fp, "%%%%BoundingBox: 0 0 %d %d\n",
1422 state->page_width, state->page_height);
1423 for (node = state->canvas->firstnode; node; node = node->next) {
1424 if (node->type == GFX_TEXT && eps_add_font(state, node) == -1)
1427 eps_list_fonts(state, "%%DocumentFonts:");
1428 eps_list_fonts(state, "%%DocumentNeededFonts:");
1432 "%%EndProlog\n" /* must have, or BoundingBox is ignored */
1433 "/bd { bind def } bind def\n"
1435 fprintf(state->fp, "/X { %.2f add } bd\n", LINEOFFSET);
1437 "/X2 {X exch X exch} bd\n"
1438 "/M {X2 moveto} bd\n"
1439 "/L {X2 lineto} bd\n"
1443 "/CP {closepath} bd\n"
1444 "/WS {setlinewidth stroke} bd\n"
1447 "/TaC {dup stringwidth pop neg 2 div 0 rmoveto } bd\n"
1448 "/TaR {dup stringwidth pop neg 0 rmoveto } bd\n"
1449 "/TL {moveto TaL show} bd\n"
1450 "/TC {moveto TaC show} bd\n"
1451 "/TR {moveto TaR show} bd\n"
1452 "/Rgb { 255.0 div 3 1 roll\n"
1453 " 255.0 div 3 1 roll \n"
1454 " 255.0 div 3 1 roll setrgbcolor } bd\n"
1456 eps_define_fonts(state);
1460 static void eps_clear_dash(eps_state *state)
1462 if (!state->has_dash)
1464 state->has_dash = 0;
1465 fputs("[1 0] 0 setdash\n", state->fp);
1468 static void eps_write_linearea(eps_state *state, gfx_node_t *node)
1471 FILE *fp = state->fp;
1473 int clearDashIfAny = 1;
1474 eps_set_color(state, node->color);
1475 if (node->type == GFX_LINE) {
1477 if (state->linecap != 1) {
1478 fputs("1 setlinecap\n", fp);
1481 if (state->linejoin != 1) {
1482 fputs("1 setlinejoin\n", fp);
1483 state->linejoin = 1;
1485 svg_get_dash(node, &dash_info);
1486 if (dash_info.dash_enable) {
1488 state->has_dash = 1;
1490 svg_write_number(fp, dash_info.adjusted_on);
1492 svg_write_number(fp, dash_info.adjusted_off);
1494 svg_write_number(fp, dash_info.dash_offset);
1495 fputs(" setdash\n", fp);
1499 eps_clear_dash(state);
1500 for (i = 0; i < node->points; i++) {
1501 ArtVpath *vec = node->path + i;
1503 double y = state->page_height - vec->y;
1504 if (vec->code == ART_MOVETO_OPEN || vec->code == ART_MOVETO)
1505 useOffset = (fabs(x - floor(x) - 0.5) < 0.01 && fabs(y - floor(y) - 0.5) < 0.01);
1510 switch (vec->code) {
1511 case ART_MOVETO_OPEN: /* fall-through */
1513 svg_write_number(fp, x);
1515 svg_write_number(fp, y);
1517 fputs(useOffset ? "M\n" : "m\n", fp);
1520 svg_write_number(fp, x);
1522 svg_write_number(fp, y);
1524 fputs(useOffset ? "L\n" : "l\n", fp);
1526 case ART_CURVETO: break; /* unsupported */
1527 case ART_END: break; /* nop */
1530 if (node->type == GFX_LINE) {
1531 if (node->closed_path)
1533 if (node->size != state->line_width) {
1534 state->line_width = node->size;
1535 svg_write_number(fp, state->line_width);
1545 static void eps_write_text(eps_state *state, gfx_node_t *node)
1547 FILE *fp = state->fp;
1548 const unsigned char *p;
1549 const char *ps_font = afm_get_font_postscript_name(node->filename);
1552 double y = state->page_height - node->y, ydelta = 0;
1554 eps_set_color(state, node->color);
1555 if (strcmp(ps_font, state->font) || node->size != state->font_size) {
1556 state->font = ps_font;
1557 state->font_size = node->size;
1558 svg_write_number(fp, state->font_size);
1559 fprintf(fp, " SetFont-%s\n", state->font);
1563 for (p = (const unsigned char*)node->text; *p; p++) {
1565 fputs("\\\n", fp); /* backslash and \n */
1580 fprintf(fp, "\\%03o", *p);
1587 switch(node->valign){
1588 case GFX_V_TOP: ydelta = -node->size; break;
1589 case GFX_V_CENTER: ydelta = -node->size / 3.0; break;
1590 case GFX_V_BOTTOM: break;
1591 case GFX_V_NULL: break;
1593 if (node->angle == 0)
1595 switch (node->halign) {
1596 case GFX_H_RIGHT: align = 'R'; break;
1597 case GFX_H_CENTER: align = 'C'; break;
1598 case GFX_H_LEFT: align= 'L'; break;
1599 case GFX_H_NULL: align= 'L'; break;
1601 if (node->angle != 0) {
1603 fputs(" gsave ", fp);
1604 svg_write_number(fp, x);
1606 svg_write_number(fp, y);
1607 fputs(" translate ", fp);
1608 svg_write_number(fp, -node->angle);
1609 fputs(" rotate 0 ", fp);
1610 svg_write_number(fp, ydelta);
1611 fputs(" moveto ", fp);
1612 fprintf(fp, "Ta%c", align);
1613 fputs(" show grestore\n", fp);
1615 svg_write_number(fp, x);
1617 svg_write_number(fp, y);
1624 static int eps_write_content(eps_state *state)
1627 fputs("%\n", state->fp);
1628 for (node = state->canvas->firstnode; node; node = node->next) {
1629 switch (node->type) {
1632 eps_write_linearea(state, node);
1635 eps_write_text(state, node);
1642 int gfx_render_eps (gfx_canvas_t *canvas,
1643 art_u32 width, art_u32 height,
1644 gfx_color_t background, FILE *fp){
1645 struct eps_state state;
1647 state.canvas = canvas;
1648 state.page_width = width;
1649 state.page_height = height;
1650 state.font = "no-default-font";
1651 state.font_size = -1;
1652 state.color = 0; /* black */
1653 state.font_list = NULL;
1655 state.linejoin = -1;
1657 if (eps_prologue(&state) == -1)
1659 eps_set_color(&state, background);
1660 fprintf(fp, "0 0 M 0 %d L %d %d L %d 0 L fill\n",
1661 height, width, height, width);
1662 if (eps_write_content(&state) == -1)
1664 fputs("showpage\n", fp);
1665 fputs("%%EOF\n", fp);
1666 while (state.font_list) {
1667 eps_font *next = state.font_list->next;
1668 free(state.font_list);
1669 state.font_list = next;
1674 /* ------- PDF -------
1675 PDF references page:
1676 http://partners.adobe.com/asn/developer/technotes/acrobatpdf.html
1679 typedef struct pdf_buffer
1681 int id, is_obj, is_dict, is_stream, pdf_file_pos;
1683 int alloc_size, current_size;
1684 struct pdf_buffer *previous_buffer, *next_buffer;
1685 struct pdf_state *state;
1688 typedef struct pdf_font
1690 const char *ps_font;
1692 struct pdf_font *next;
1695 typedef struct pdf_state
1698 gfx_canvas_t *canvas;
1699 art_u32 page_width, page_height;
1700 pdf_font *font_list;
1701 pdf_buffer *first_buffer, *last_buffer;
1705 gfx_color_t stroke_color, fill_color;
1710 int linecap, linejoin;
1713 pdf_buffer pdf_header;
1714 pdf_buffer catalog_obj, pages_obj, page1_obj;
1715 pdf_buffer fontsdict_obj;
1716 pdf_buffer graph_stream;
1719 static void pdf_init_buffer(pdf_state *state, pdf_buffer *buf)
1721 int initial_size = 32;
1724 buf->alloc_size = 0;
1725 buf->current_size = 0;
1726 buf->data = (char*)malloc(initial_size);
1728 buf->previous_buffer = NULL;
1729 buf->next_buffer = NULL;
1730 if (buf->data == NULL) {
1731 rrd_set_error("malloc for pdf_buffer data");
1732 state->has_failed = 1;
1735 buf->alloc_size = initial_size;
1736 if (state->last_buffer)
1737 state->last_buffer->next_buffer = buf;
1738 if (state->first_buffer == NULL)
1739 state->first_buffer = buf;
1740 buf->previous_buffer = state->last_buffer;
1741 state->last_buffer = buf;
1744 static void pdf_put(pdf_buffer *buf, const char *text, int len)
1748 if (buf->alloc_size < buf->current_size + len) {
1749 int new_size = buf->alloc_size;
1751 while (new_size < buf->current_size + len)
1753 new_buf = (char*)malloc(new_size);
1754 if (new_buf == NULL) {
1755 rrd_set_error("re-malloc for pdf_buffer data");
1756 buf->state->has_failed = 1;
1759 memcpy(new_buf, buf->data, buf->current_size);
1761 buf->data = new_buf;
1762 buf->alloc_size = new_size;
1764 memcpy(buf->data + buf->current_size, text, len);
1765 buf->current_size += len;
1768 static void pdf_puts(pdf_buffer *buf, const char *text)
1770 pdf_put(buf, text, strlen(text));
1773 static void pdf_indent(pdf_buffer *buf)
1775 pdf_puts(buf, "\t");
1778 static void pdf_putsi(pdf_buffer *buf, const char *text)
1781 pdf_puts(buf, text);
1784 static void pdf_putint(pdf_buffer *buf, int i)
1787 sprintf(tmp, "%d", i);
1791 static void pdf_putnumber(pdf_buffer *buf, double d)
1794 svg_format_number(tmp, sizeof(tmp), d);
1798 static void pdf_init_object(pdf_state *state, pdf_buffer *buf)
1800 pdf_init_buffer(state, buf);
1801 buf->id = ++state->last_obj_id;
1806 static void pdf_init_dict(pdf_state *state, pdf_buffer *buf)
1808 pdf_init_object(state, buf);
1812 static void pdf_set_color(pdf_buffer *buf, gfx_color_t color,
1813 gfx_color_t *current_color, const char *op)
1815 /* gfx_color_t is RRGGBBAA */
1816 if (*current_color == color)
1818 pdf_putnumber(buf, ((color >> 24) & 255) / 255.0);
1820 pdf_putnumber(buf, ((color >> 16) & 255) / 255.0);
1822 pdf_putnumber(buf, ((color >> 8) & 255) / 255.0);
1825 pdf_puts(buf, "\n");
1826 *current_color = color;
1829 static void pdf_set_stroke_color(pdf_buffer *buf, gfx_color_t color)
1831 pdf_set_color(buf, color, &buf->state->stroke_color, "RG");
1834 static void pdf_set_fill_color(pdf_buffer *buf, gfx_color_t color)
1836 pdf_set_color(buf, color, &buf->state->fill_color, "rg");
1839 static pdf_font *pdf_find_font(pdf_state *state, gfx_node_t *node)
1841 const char *ps_font = afm_get_font_postscript_name(node->filename);
1843 for (ef = state->font_list; ef; ef = ef->next) {
1844 if (!strcmp(ps_font, ef->ps_font))
1850 static void pdf_add_font(pdf_state *state, gfx_node_t *node)
1852 pdf_font *ef = pdf_find_font(state, node);
1855 ef = malloc(sizeof(pdf_font));
1857 rrd_set_error("malloc for pdf_font");
1858 state->has_failed = 1;
1861 pdf_init_dict(state, &ef->obj);
1862 ef->next = state->font_list;
1863 ef->ps_font = afm_get_font_postscript_name(node->filename);
1864 state->font_list = ef;
1866 pdf_putsi(&state->fontsdict_obj, "/F");
1867 pdf_putint(&state->fontsdict_obj, ef->obj.id);
1868 pdf_puts(&state->fontsdict_obj, " ");
1869 pdf_putint(&state->fontsdict_obj, ef->obj.id);
1870 pdf_puts(&state->fontsdict_obj, " 0 R\n");
1872 pdf_putsi(&ef->obj, "/Type /Font\n");
1873 pdf_putsi(&ef->obj, "/Subtype /Type1\n");
1874 pdf_putsi(&ef->obj, "/Name /F");
1875 pdf_putint(&ef->obj, ef->obj.id);
1876 pdf_puts(&ef->obj, "\n");
1877 pdf_putsi(&ef->obj, "/BaseFont /");
1878 pdf_puts(&ef->obj, ef->ps_font);
1879 pdf_puts(&ef->obj, "\n");
1880 pdf_putsi(&ef->obj, "/Encoding /WinAnsiEncoding\n");
1881 /* 'Cp1252' (this is latin 1 extended with 27 characters;
1882 the encoding is also known as 'winansi')
1883 http://www.lowagie.com/iText/tutorial/ch09.html */
1886 static void pdf_create_fonts(pdf_state *state)
1889 for (node = state->canvas->firstnode; node; node = node->next) {
1890 if (node->type == GFX_TEXT)
1891 pdf_add_font(state, node);
1895 static void pdf_write_linearea(pdf_state *state, gfx_node_t *node)
1898 pdf_buffer *s = &state->graph_stream;
1899 if (node->type == GFX_LINE) {
1901 svg_get_dash(node, &dash_info);
1902 if (!svg_dash_equal(&dash_info, &state->dash)) {
1903 state->dash = dash_info;
1904 if (dash_info.dash_enable) {
1906 pdf_putnumber(s, dash_info.adjusted_on);
1908 pdf_putnumber(s, dash_info.adjusted_off);
1910 pdf_putnumber(s, dash_info.dash_offset);
1911 pdf_puts(s, " d\n");
1913 pdf_puts(s, "[] 0 d\n");
1916 pdf_set_stroke_color(s, node->color);
1917 if (state->linecap != 1) {
1918 pdf_puts(s, "1 j\n");
1921 if (state->linejoin != 1) {
1922 pdf_puts(s, "1 J\n");
1923 state->linejoin = 1;
1925 if (node->size != state->line_width) {
1926 state->line_width = node->size;
1927 pdf_putnumber(s, state->line_width);
1928 pdf_puts(s, " w\n");
1931 pdf_set_fill_color(s, node->color);
1933 for (i = 0; i < node->points; i++) {
1934 ArtVpath *vec = node->path + i;
1936 double y = state->page_height - vec->y;
1937 if (node->type == GFX_AREA) {
1938 x += LINEOFFSET; /* adjust for libart handling of areas */
1941 switch (vec->code) {
1942 case ART_MOVETO_OPEN: /* fall-through */
1944 pdf_putnumber(s, x);
1946 pdf_putnumber(s, y);
1947 pdf_puts(s, " m\n");
1950 pdf_putnumber(s, x);
1952 pdf_putnumber(s, y);
1953 pdf_puts(s, " l\n");
1955 case ART_CURVETO: break; /* unsupported */
1956 case ART_END: break; /* nop */
1959 if (node->type == GFX_LINE) {
1960 pdf_puts(s, node->closed_path ? "s\n" : "S\n");
1966 static void pdf_write_text(pdf_state *state, gfx_node_t *node,
1967 int last_was_text, int next_is_text)
1970 pdf_buffer *s = &state->graph_stream;
1971 const unsigned char *p;
1972 pdf_font *font = pdf_find_font(state, node);
1974 double y = state->page_height - node->y;
1975 double dx = 0, dy = 0;
1976 double cos_a = 0, sin_a = 0;
1978 rrd_set_error("font disappeared");
1979 state->has_failed = 1;
1982 switch(node->valign){
1983 case GFX_V_TOP: dy = -node->size; break;
1984 case GFX_V_CENTER: dy = -node->size / 3.0; break;
1985 case GFX_V_BOTTOM: break;
1986 case GFX_V_NULL: break;
1988 switch (node->halign) {
1989 case GFX_H_RIGHT: dx = -afm_get_text_width(0, font->ps_font,
1990 node->size, node->tabwidth, node->text);
1992 case GFX_H_CENTER: dx = -afm_get_text_width(0, font->ps_font,
1993 node->size, node->tabwidth, node->text) / 2;
1995 case GFX_H_LEFT: break;
1996 case GFX_H_NULL: break;
1998 pdf_set_fill_color(s, node->color);
1999 if (node->angle != 0) {
2000 double a = 2 * M_PI * -node->angle / 360.0;
2001 double new_x, new_y;
2004 new_x = cos_a * dx - sin_a * dy + x;
2005 new_y = sin_a * dx + cos_a * dy + y;
2013 pdf_puts(s, "BT\n");
2014 if (state->font_id != font->obj.id || node->size != state->font_size) {
2015 state->font_id = font->obj.id;
2016 state->font_size = node->size;
2018 pdf_putint(s, font->obj.id);
2020 pdf_putnumber(s, node->size);
2021 pdf_puts(s, " Tf\n");
2023 if (node->angle == 0) {
2024 pdf_puts(s, "1 0 0 1 ");
2026 pdf_putnumber(s, cos_a);
2028 pdf_putnumber(s, sin_a);
2030 pdf_putnumber(s, -sin_a);
2032 pdf_putnumber(s, cos_a);
2035 pdf_putnumber(s, x);
2037 pdf_putnumber(s, y);
2038 pdf_puts(s, " Tm\n");
2040 for (p = (const unsigned char*)node->text; *p; p++) {
2052 snprintf(tmp, sizeof(tmp), "\\%03o", *p);
2055 pdf_put(s, (const char*)p, 1);
2059 pdf_puts(s, ") Tj\n");
2061 pdf_puts(s, "ET\n");
2064 static void pdf_write_content(pdf_state *state)
2067 int last_was_text = 0, next_is_text;
2068 for (node = state->canvas->firstnode; node; node = node->next) {
2069 switch (node->type) {
2072 pdf_write_linearea(state, node);
2075 next_is_text = node->next && node->next->type == GFX_TEXT;
2076 pdf_write_text(state, node, last_was_text, next_is_text);
2079 last_was_text = node->type == GFX_TEXT;
2083 static void pdf_init_document(pdf_state *state)
2085 pdf_init_buffer(state, &state->pdf_header);
2086 pdf_init_dict(state, &state->catalog_obj);
2087 pdf_init_dict(state, &state->pages_obj);
2088 pdf_init_dict(state, &state->page1_obj);
2089 pdf_init_dict(state, &state->fontsdict_obj);
2090 pdf_create_fonts(state);
2091 if (state->has_failed)
2093 /* make stream last object in file */
2094 pdf_init_object(state, &state->graph_stream);
2095 state->graph_stream.is_stream = 1;
2098 static void pdf_setup_document(pdf_state *state)
2100 /* all objects created by now, so init code can reference them */
2102 pdf_puts(&state->pdf_header, "%PDF-1.3\n");
2103 /* following 8 bit comment is recommended by Adobe for
2104 indicating binary file to file transfer applications */
2105 pdf_puts(&state->pdf_header, "%\xE2\xE3\xCF\xD3\n");
2107 pdf_putsi(&state->catalog_obj, "/Type /Catalog\n");
2108 pdf_putsi(&state->catalog_obj, "/Pages ");
2109 pdf_putint(&state->catalog_obj, state->pages_obj.id);
2110 pdf_puts(&state->catalog_obj, " 0 R\n");
2112 pdf_putsi(&state->pages_obj, "/Type /Pages\n");
2113 pdf_putsi(&state->pages_obj, "/Kids [");
2114 pdf_putint(&state->pages_obj, state->page1_obj.id);
2115 pdf_puts(&state->pages_obj, " 0 R]\n");
2116 pdf_putsi(&state->pages_obj, "/Count 1\n");
2118 pdf_putsi(&state->page1_obj, "/Type /Page\n");
2119 pdf_putsi(&state->page1_obj, "/Parent ");
2120 pdf_putint(&state->page1_obj, state->pages_obj.id);
2121 pdf_puts(&state->page1_obj, " 0 R\n");
2122 pdf_putsi(&state->page1_obj, "/MediaBox [0 0 ");
2123 pdf_putint(&state->page1_obj, state->page_width);
2124 pdf_puts(&state->page1_obj, " ");
2125 pdf_putint(&state->page1_obj, state->page_height);
2126 pdf_puts(&state->page1_obj, "]\n");
2127 pdf_putsi(&state->page1_obj, "/Contents ");
2128 pdf_putint(&state->page1_obj, state->graph_stream.id);
2129 pdf_puts(&state->page1_obj, " 0 R\n");
2130 pdf_putsi(&state->page1_obj, "/Resources << /Font ");
2131 pdf_putint(&state->page1_obj, state->fontsdict_obj.id);
2132 pdf_puts(&state->page1_obj, " 0 R >>\n");
2135 static void pdf_write_string_to_file(pdf_state *state, const char *text)
2137 fputs(text, state->fp);
2138 state->pdf_file_pos += strlen(text);
2141 static void pdf_write_buf_to_file(pdf_state *state, pdf_buffer *buf)
2144 buf->pdf_file_pos = state->pdf_file_pos;
2146 snprintf(tmp, sizeof(tmp), "%d 0 obj\n", buf->id);
2147 pdf_write_string_to_file(state, tmp);
2150 pdf_write_string_to_file(state, "<<\n");
2151 if (buf->is_stream) {
2152 snprintf(tmp, sizeof(tmp), "<< /Length %d >>\n", buf->current_size);
2153 pdf_write_string_to_file(state, tmp);
2154 pdf_write_string_to_file(state, "stream\n");
2156 fwrite(buf->data, 1, buf->current_size, state->fp);
2157 state->pdf_file_pos += buf->current_size;
2159 pdf_write_string_to_file(state, "endstream\n");
2161 pdf_write_string_to_file(state, ">>\n");
2163 pdf_write_string_to_file(state, "endobj\n");
2166 static void pdf_write_to_file(pdf_state *state)
2168 pdf_buffer *buf = state->first_buffer;
2170 state->pdf_file_pos = 0;
2171 pdf_write_buf_to_file(state, &state->pdf_header);
2174 pdf_write_buf_to_file(state, buf);
2175 buf = buf->next_buffer;
2177 xref_pos = state->pdf_file_pos;
2178 fprintf(state->fp, "xref\n");
2179 fprintf(state->fp, "%d %d\n", 0, state->last_obj_id + 1);
2180 /* TOC lines must be exactly 20 bytes including \n */
2181 fprintf(state->fp, "%010d %05d f\x20\n", 0, 65535);
2182 for (buf = state->first_buffer; buf; buf = buf->next_buffer) {
2184 fprintf(state->fp, "%010d %05d n\x20\n", buf->pdf_file_pos, 0);
2186 fprintf(state->fp, "trailer\n");
2187 fprintf(state->fp, "<<\n");
2188 fprintf(state->fp, "\t/Size %d\n", state->last_obj_id + 1);
2189 fprintf(state->fp, "\t/Root %d 0 R\n", state->catalog_obj.id);
2190 fprintf(state->fp, ">>\n");
2191 fprintf(state->fp, "startxref\n");
2192 fprintf(state->fp, "%d\n", xref_pos);
2193 fputs("%%EOF\n", state->fp);
2196 static void pdf_free_resources(pdf_state *state)
2198 pdf_buffer *buf = state->first_buffer;
2202 buf->alloc_size = buf->current_size = 0;
2203 buf = buf->next_buffer;
2205 while (state->font_list) {
2206 pdf_font *next = state->font_list->next;
2207 free(state->font_list);
2208 state->font_list = next;
2212 int gfx_render_pdf (gfx_canvas_t *canvas,
2213 art_u32 width, art_u32 height,
2214 gfx_color_t background, FILE *fp){
2215 struct pdf_state state;
2216 memset(&state, 0, sizeof(pdf_state));
2218 state.canvas = canvas;
2219 state.page_width = width;
2220 state.page_height = height;
2222 state.font_size = -1;
2223 state.font_list = NULL;
2225 state.linejoin = -1;
2226 pdf_init_document(&state);
2228 pdf_set_color(&state, background);
2229 fprintf(fp, "0 0 M 0 %d L %d %d L %d 0 L fill\n",
2230 height, width, height, width);
2232 if (!state.has_failed)
2233 pdf_write_content(&state);
2234 if (!state.has_failed)
2235 pdf_setup_document(&state);
2236 if (!state.has_failed)
2237 pdf_write_to_file(&state);
2238 pdf_free_resources(&state);
2239 return state.has_failed ? -1 : 0;