]> git.cworth.org Git - acre/blob - acre.c
12be71d249952421f0fb17caa956e3cd74377a0f
[acre] / acre.c
1 /* acre - A cairo-based library for creating plots and charts.
2  *
3  * Copyright © 2009 Carl Worth <cworth@cworth.org>
4  *
5  * This program is free software; you can redistribute it and/or
6  * modify it under the terms of the GNU General Public License as
7  * published by the Free Software Foundation; either version 2 of the
8  * License, or (at your option) any later version.
9  *
10  * This program is distributed in the hope that it will be useful, but
11  * WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13  * General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License along
16  * with this program; if not, write to the Free Software Foundation, Inc.,
17  * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.
18  */
19
20 #define _ISOC99_SOURCE /* for round() */
21 #define _XOPEN_SOURCE 500
22 #define _GNU_SOURCE /* for asprintf() */
23
24 #include "acre.h"
25 #include "xmalloc.h"
26
27 #include <string.h>
28 #include <stdarg.h>
29 #include <math.h>
30
31 typedef struct _acre_data_point_2d {
32     double x;
33     double y;
34 } acre_data_point_2d_t;
35
36 struct _acre_data {
37     char *name;
38
39     acre_data_point_2d_t *points;
40     unsigned int points_size;
41     unsigned int num_points;
42 };
43
44 typedef struct _acre_axis {
45     char *label;
46     double min;
47     double max;
48 } acre_axis_t;
49
50 struct _acre {
51     char *title;
52     acre_axis_t x_axis;
53     acre_axis_t y_axis;
54
55     acre_data_t **data;
56     unsigned int data_size;
57     unsigned int num_data;
58
59     /* Data for drawing. */
60     cairo_t *cr;
61     PangoFontDescription *font;
62
63     /* Total size including labels. */
64     int width;
65     int height;
66
67     /* Position and size of chart alone. */
68     PangoRectangle chart;
69 };
70
71 /* Create a new, empty plot. */
72 acre_t *
73 acre_create (void)
74 {
75     acre_t *acre;
76
77     acre = xmalloc (sizeof (acre_t));
78
79     acre->title = NULL;
80
81     acre->x_axis.label = NULL;
82     acre->x_axis.min = 0.0;
83     acre->x_axis.max = 0.0;
84
85     acre->y_axis.label = NULL;
86     acre->y_axis.min = 0.0;
87     acre->y_axis.max = 0.0;
88
89     acre->data = NULL;
90     acre->data_size = 0;
91     acre->num_data = 0;
92
93     acre->chart.x = 0;
94     acre->chart.y = 0;
95     acre->chart.width = 0;
96     acre->chart.height = 0;
97
98     return acre;
99 }
100
101 /* Destroy a plot. */
102 void
103 acre_destroy (acre_t *acre)
104 {
105     unsigned int i;
106
107     free (acre->title);
108     free (acre->x_axis.label);
109     free (acre->y_axis.label);
110
111     for (i = 0; i < acre->num_data; i++)
112         acre_data_destroy (acre->data[i]);
113
114     free (acre->data);
115
116     free (acre);
117 }
118
119 void
120 acre_set_title (acre_t *acre, const char *title)
121 {
122     free (acre->title);
123
124     acre->title = strdup (title);
125 }
126
127 void
128 acre_set_x_axis_label (acre_t *acre, const char *label)
129 {
130     free (acre->x_axis.label);
131
132     acre->x_axis.label = strdup (label);
133 }
134
135 void
136 acre_set_y_axis_label (acre_t *acre, const char *label)
137 {
138     free (acre->y_axis.label);
139
140     acre->y_axis.label = strdup (label);
141 }
142
143 /* Add a dataset to the plot. The plot assumes ownership of the
144  * dataset so it is not necessary to call acre_data_destroy on it. */
145 void
146 acre_add_data (acre_t *acre, acre_data_t *data)
147 {
148     if (acre->num_data >= acre->data_size) {
149         acre->data_size *= 2;
150         if (acre->data_size == 0)
151             acre->data_size = 1;
152         acre->data = xrealloc_ab (acre->data,
153                                   acre->data_size,
154                                   sizeof (acre_data_t *));
155     }
156
157     acre->data[acre->num_data] = data;
158     acre->num_data++;
159 }
160
161 #define ACRE_FONT_FAMILY "sans"
162 #define ACRE_FONT_SIZE 12
163 #define ACRE_TITLE_FONT_SIZE 20
164 #define ACRE_PAD (ACRE_FONT_SIZE)
165 #define ACRE_TICK_MAJOR_SIZE 6
166 #define ACRE_TICK_MINOR_SIZE 3
167 #define ACRE_X_TICK_VALUE_PAD 2
168 #define ACRE_Y_TICK_VALUE_PAD 4
169
170 static PangoLayout *
171 _create_layout (acre_t *acre, const char *text)
172 {
173     PangoLayout *layout;
174
175     layout = pango_cairo_create_layout (acre->cr);
176     pango_layout_set_font_description (layout, acre->font);
177     pango_layout_set_text (layout, text, -1);
178     pango_layout_set_alignment (layout, PANGO_ALIGN_CENTER);
179
180     return layout;
181 }
182
183 #define PRINTF_FORMAT(fmt_index, va_index) __attribute__ ((__format__(__printf__, fmt_index, va_index)))
184
185 static PangoLayout *
186 _create_layout_vprintf (acre_t *acre, const char *fmt, va_list ap)
187 {
188     PangoLayout *layout;
189     char *text;
190
191     vasprintf (&text, fmt, ap);
192
193     layout = _create_layout (acre, text);
194
195     free (text);
196
197     return layout;
198 }
199
200 static PangoLayout *
201 _create_layout_printf (acre_t *acre, const char *fmt, ...)
202     PRINTF_FORMAT (2, 3);
203
204 static PangoLayout *
205 _create_layout_printf (acre_t *acre, const char *fmt, ...)
206 {
207     va_list ap;
208     PangoLayout *layout;
209
210     va_start (ap, fmt);
211
212     layout = _create_layout_vprintf (acre, fmt, ap);
213
214     va_end (ap);
215
216     return layout;
217 }
218
219 static void
220 _destroy_layout (PangoLayout *layout)
221 {
222     g_object_unref (layout);
223 }
224
225 static void
226 _show_layout (cairo_t *cr, PangoLayout *layout)
227 {
228     pango_cairo_show_layout (cr, layout);
229
230     _destroy_layout (layout);
231 }
232
233 static void
234 _draw_title_and_labels (acre_t *acre)
235 {
236     cairo_t *cr = acre->cr;
237     PangoFontDescription *title_font;
238     PangoLayout *title_layout, *x_axis_layout, *y_axis_layout;
239     PangoLayout *min_y, *max_y;
240     int min_y_width, max_y_width, y_axis_value_width;
241     int title_width, title_height;
242     int x_axis_width, x_axis_height;
243     int y_axis_width, y_axis_height;
244     PangoRectangle new_chart;
245
246     cairo_save (cr);
247
248     acre->font = pango_font_description_new ();
249     pango_font_description_set_family (acre->font, ACRE_FONT_FAMILY);
250     pango_font_description_set_absolute_size (acre->font,
251                                               ACRE_FONT_SIZE * PANGO_SCALE);
252
253     title_font = pango_font_description_new ();
254     pango_font_description_set_family (title_font, ACRE_FONT_FAMILY);
255     pango_font_description_set_absolute_size (title_font,
256                                               ACRE_TITLE_FONT_SIZE * PANGO_SCALE);
257
258     title_layout = _create_layout (acre, acre->title);
259     pango_layout_set_font_description (title_layout, title_font);
260
261     x_axis_layout = _create_layout (acre, acre->x_axis.label);
262     y_axis_layout = _create_layout (acre, acre->y_axis.label);
263
264     min_y = _create_layout_printf (acre, "%g",
265                                    round (acre->y_axis.min));
266     max_y = _create_layout_printf (acre, "%g",
267                                    round (acre->y_axis.max));
268
269     pango_layout_get_pixel_size (min_y, &min_y_width, NULL);
270     pango_layout_get_pixel_size (max_y, &max_y_width, NULL);
271     y_axis_value_width = MAX (min_y_width, max_y_width);
272
273     _destroy_layout (min_y);
274     _destroy_layout (max_y);
275
276     /* Iterate with the layout of the title and axis labels until they
277      * are stable, (this requires iteration since we don't know what
278      * to set their widths to in advance due to the wrapping of the
279      * other elements). */
280     while (1) {
281         pango_layout_set_width (title_layout, acre->chart.width * PANGO_SCALE);
282         pango_layout_set_width (x_axis_layout, acre->chart.width * PANGO_SCALE);
283         pango_layout_set_width (y_axis_layout, acre->chart.height * PANGO_SCALE);
284
285         pango_layout_get_pixel_size (title_layout, &title_width, &title_height);
286         pango_layout_get_pixel_size (x_axis_layout, &x_axis_width, &x_axis_height);
287         pango_layout_get_pixel_size (y_axis_layout, &y_axis_width, &y_axis_height);
288
289         new_chart.x = ACRE_PAD + y_axis_height +
290             ACRE_PAD + y_axis_value_width + ACRE_Y_TICK_VALUE_PAD;
291         new_chart.width = acre->width - acre->chart.x - ACRE_PAD;
292
293         new_chart.y = ACRE_PAD + title_height + ACRE_PAD;
294         new_chart.height = acre->height - acre->chart.y - 
295             (ACRE_X_TICK_VALUE_PAD + ACRE_FONT_SIZE +
296              ACRE_PAD + x_axis_height + ACRE_PAD);
297
298         if (new_chart.x == acre->chart.x &&
299             new_chart.y == acre->chart.y &&
300             new_chart.width == acre->chart.width &&
301             new_chart.height == acre->chart.height)
302         {
303             break;
304         }
305
306         acre->chart.x = new_chart.x;
307         acre->chart.y = new_chart.y;
308         acre->chart.width = new_chart.width;
309         acre->chart.height = new_chart.height;
310     }
311
312     cairo_set_source_rgb (cr, 0, 0, 0);
313
314     cairo_move_to (cr, acre->chart.x, ACRE_PAD);
315     _show_layout (cr, title_layout);
316
317     cairo_save (cr);
318     {
319         cairo_translate (cr, ACRE_PAD, acre->chart.y + acre->chart.height);
320         cairo_rotate (cr, - M_PI / 2.0);
321         cairo_move_to (cr, 0, 0);
322         _show_layout (cr, y_axis_layout);
323     }
324     cairo_restore (cr);
325
326     cairo_move_to (cr, acre->chart.x,
327                    acre->chart.y + acre->chart.height +
328                    ACRE_FONT_SIZE + ACRE_PAD);
329     _show_layout (cr, x_axis_layout);
330
331     cairo_restore (cr);
332 }
333
334 /* For a given axis range, compute a step size (in data space) to
335  * generate a suitable number of ticks (5 or so). */
336 static double
337 _step_for_range (double range, int *minor_divisions)
338 {
339     double step, scale_factor;
340
341     /* We want roughly 5 major ticks for the chart. */
342     step = range / 5;
343
344     /* Normalize the step so we can easily snap it to a desirable
345      * value. */
346     scale_factor = pow (10.0, floor (log10 (step)));
347     step /= scale_factor;
348
349     /* We want increments of 1, 2.5, 5, or 10 (times some power of
350      * 10). The threshold values between these are computed
351      * logarithmically. */
352     if (step < 3.535533905932738) {
353         if (step < 1.58113883008419) {
354             step = 1.0;
355             *minor_divisions = 4;
356         } else {
357             step = 2.5;
358             *minor_divisions = 5;
359         }
360     } else {
361         if (step < 7.071067811865475) {
362             step = 5.0;
363             *minor_divisions = 5;
364         } else {
365             step = 10.0;
366             *minor_divisions = 4;
367         }
368     }
369
370     /* Un-normalize and we now have the data value that we want to
371      * step at. */
372     return step * scale_factor;
373 }
374
375 /* Given an axis range, we can compute a desired data-space step
376  * amount for the major ticks (see _step_for_range). To get
377  * nice-looking pixel-snapped ticks we want to expand the range
378  * slightly. */
379 static void
380 _expand_range_for_width (double *axis_min, double *axis_max, int pixel_range)
381 {
382     double range, new_range, step, step_minor, pixel_step;
383     int minor_divisions;
384
385     range = *axis_max - *axis_min;
386
387     step = _step_for_range (range, &minor_divisions);
388     step_minor = step / minor_divisions;
389
390     pixel_step = step_minor * (pixel_range / range);
391
392     /* We expand the range by the ratio of the pixel step to the floor
393      * of the pixel_step.
394      */
395     new_range = range * pixel_step / floor (pixel_step);
396
397     /* And spread the increase out on either side of the range. */
398     *axis_min -= (new_range - range) / 2.0;
399     *axis_max += (new_range - range) / 2.0;
400 }
401
402 /* Setup a transformation in acre->cr such that data values plotted
403  * will appear where they should within the chart.
404  */
405 static void
406 _set_transform_to_data_space (acre_t *acre)
407 {
408     cairo_t *cr = acre->cr;
409
410     cairo_translate (cr,
411                      acre->chart.x,
412                      acre->chart.y + acre->chart.height);
413     cairo_scale (cr,
414                  acre->chart.width / (acre->x_axis.max - acre->x_axis.min),
415                  - acre->chart.height /(acre->y_axis.max - acre->y_axis.min));
416     cairo_translate (cr, -acre->x_axis.min, -acre->y_axis.min);
417 }
418
419 static void
420 _compute_axis_ranges (acre_t *acre)
421 {
422     unsigned int d, i;
423     acre_data_t *data;
424     double x_adjust, y_adjust;
425     cairo_t *cr = acre->cr;
426
427     acre->x_axis.min = acre->data[0]->points[0].x;
428     acre->x_axis.max = acre->data[0]->points[0].x;
429     acre->y_axis.min = acre->data[0]->points[0].y;
430     acre->y_axis.min = acre->data[0]->points[0].y;
431
432     /* First, simply find the extrema of the data. */
433     for (d = 0; d < acre->num_data; d++) {
434         data = acre->data[d];
435         for (i = 0; i < data->num_points; i++) {
436             if (data->points[i].x < acre->x_axis.min)
437                 acre->x_axis.min = data->points[i].x;
438             if (data->points[i].x > acre->x_axis.max)
439                 acre->x_axis.max = data->points[i].x;
440
441             if (data->points[i].y < acre->y_axis.min)
442                 acre->y_axis.min = data->points[i].y;
443             if (data->points[i].y > acre->y_axis.max)
444                 acre->y_axis.max = data->points[i].y;
445         }
446     }
447
448     /* Next, we want to ensure that the data never collides with the
449      * ticks. So we expand each axis on its minimum side as needed. */
450     cairo_save (cr);
451     {
452         double x, y;
453
454         _set_transform_to_data_space (acre);
455
456         x = ACRE_TICK_MAJOR_SIZE + 2.0;
457         y = ACRE_TICK_MAJOR_SIZE + 2.0;
458         cairo_device_to_user_distance (cr, &x, &y);
459
460         acre->x_axis.min -= x;
461         acre->y_axis.min += y;
462     }
463     cairo_restore (cr);
464
465     /* Then, increase the axis ranges just enough so that the step
466      * sizes for the ticks will be integers.
467      */
468     _expand_range_for_width (&acre->x_axis.min,
469                              &acre->x_axis.max,
470                              acre->chart.width);
471
472     _expand_range_for_width (&acre->y_axis.min,
473                              &acre->y_axis.max,
474                              acre->chart.height);
475
476     /* Finally, we also translate the axis ranges slightly so that the
477      * ticks land on half-integer device-pixel positions.
478      */
479     cairo_save (cr);
480     {
481         _set_transform_to_data_space (acre);
482
483         x_adjust = 0.0;
484         y_adjust = 0.0;
485         cairo_user_to_device (cr, &x_adjust, &y_adjust);
486         x_adjust = (round (x_adjust + 0.5) - 0.5) - x_adjust;
487         y_adjust = (round (y_adjust + 0.5) - 0.5) - y_adjust;
488         cairo_device_to_user_distance (cr, &x_adjust, &y_adjust);
489
490         acre->x_axis.min -= x_adjust;
491         acre->x_axis.max -= x_adjust;
492
493         acre->y_axis.min -= y_adjust;
494         acre->y_axis.max -= y_adjust;
495     }
496     cairo_restore (cr);
497 }
498
499 static void
500 _draw_data (acre_t *acre)
501 {
502     cairo_t *cr = acre->cr;
503     unsigned int d, i;
504     acre_data_t *data;
505 #define NUM_COLORS 3
506     struct {
507         double r;
508         double g;
509         double b;
510     } colors [NUM_COLORS] = {
511         {1, 0, 0},
512         {0, 1, 0},
513         {0, 0, 1}
514     };
515
516     cairo_save (cr);
517
518     cairo_set_source_rgb (cr, 0, 0, 0);
519
520     _set_transform_to_data_space (acre);
521
522     for (d = 0; d < acre->num_data; d++) {
523         int color = d % NUM_COLORS;
524         cairo_set_source_rgb (cr,
525                               colors[color].r,
526                               colors[color].g,
527                               colors[color].b);
528         data = acre->data[d];
529         cairo_new_path (cr);
530         for (i = 0; i < data->num_points; i++) {
531             cairo_line_to (cr,
532                            data->points[i].x,
533                            data->points[i].y);
534         }
535         cairo_save (cr);
536         {
537             cairo_identity_matrix (cr);
538             cairo_set_line_width (cr, 1.0);
539             cairo_stroke (cr);
540         }
541         cairo_restore (cr);
542     }
543
544     cairo_restore (cr);
545 }
546
547 typedef enum _ticks { ACRE_TICKS_X, ACRE_TICKS_Y } acre_ticks_t;
548
549 static void
550 _draw_ticks (acre_t *acre,
551              double axis_min, double axis_max,
552              acre_ticks_t ticks)
553 {
554     cairo_t *cr = acre->cr;
555     double t, step, sub_step;
556     int minor_divisions;
557
558     cairo_save (cr);
559
560     _set_transform_to_data_space (acre);
561
562     step = _step_for_range (axis_max - axis_min, &minor_divisions);
563     sub_step = step / minor_divisions;
564
565     for (t = (floor (axis_min / sub_step) + 1) * sub_step;
566          t <= axis_max;
567          t += sub_step)
568     {
569         int tick_size;
570         if (fabs((t / step) - round (t / step)) < 0.5 * (sub_step / step))
571             tick_size = ACRE_TICK_MAJOR_SIZE;
572         else
573             tick_size = ACRE_TICK_MINOR_SIZE;
574
575         /* tick */
576         cairo_save (cr);
577         {
578             if (ticks == ACRE_TICKS_X)
579                 cairo_move_to (cr, t, acre->y_axis.min);
580             else
581                 cairo_move_to (cr, acre->x_axis.min, t);
582
583             cairo_identity_matrix (cr);
584
585             if (ticks == ACRE_TICKS_X) {
586                 cairo_rel_line_to (cr, 0, 0.5);
587                 cairo_rel_line_to (cr, 0, -tick_size - 0.5);
588             } else {
589                 cairo_rel_line_to (cr, -0.5, 0);
590                 cairo_rel_line_to (cr, tick_size + 0.5, 0);
591             }
592
593             cairo_set_line_width (cr, 1.0);
594             cairo_stroke (cr);
595         }
596         cairo_restore (cr);
597
598         /* label */
599         if (tick_size == ACRE_TICK_MAJOR_SIZE)
600         {
601             PangoLayout *layout;
602             int width, height;
603
604             cairo_save (cr);
605
606             layout = _create_layout_printf (acre, "%g", t);
607
608             if (ticks == ACRE_TICKS_X)
609                 cairo_move_to (cr, t, acre->y_axis.min);
610             else
611                 cairo_move_to (cr, acre->x_axis.min, t);
612
613             cairo_identity_matrix (cr);
614             pango_layout_get_pixel_size (layout, &width, &height);
615
616             if (ticks == ACRE_TICKS_X)
617                 cairo_rel_move_to (cr, -width / 2, ACRE_X_TICK_VALUE_PAD);
618             else
619                 cairo_rel_move_to (cr, -width - ACRE_Y_TICK_VALUE_PAD,
620                                    -height/2);
621
622             _show_layout (cr, layout);
623
624             cairo_restore (cr);
625         }
626     }
627
628     cairo_restore (cr);
629 }
630
631 static void
632 _draw_frame_and_ticks (acre_t *acre)
633 {
634     cairo_t *cr = acre->cr;
635
636     cairo_save (cr);
637
638     cairo_set_source_rgb (cr, 0, 0, 0); /* black */
639
640     /* ticks */
641     _draw_ticks (acre, acre->x_axis.min, acre->x_axis.max, ACRE_TICKS_X);
642     _draw_ticks (acre, acre->y_axis.min, acre->y_axis.max, ACRE_TICKS_Y);
643
644     /* frame */
645     cairo_rectangle (cr,
646                      acre->chart.x - 0.5, acre->chart.y - 0.5,
647                      acre->chart.width + 1.0, acre->chart.height + 1.0);
648     cairo_set_line_width (cr, 1.0);
649     cairo_stroke (cr);
650
651     cairo_restore (cr);
652 }
653
654 /* Draw the plot to the given cairo context within a user-space
655  * rectangle from (0, 0) to (width, height). This size includes all
656  * space for extra-plot elements (such as the title, the axis labels,
657  * etc.)
658  */
659 void
660 acre_draw (acre_t *acre, cairo_t *cr, int width, int height)
661 {
662     acre->cr = cr;
663
664     acre->width = width;
665     acre->height = height;
666
667     acre->chart.width = width;
668     acre->chart.height = height;
669
670     cairo_save (cr);
671
672     cairo_set_source_rgb (cr, 1, 1, 1);
673
674     /* We compute the axis ranges before doing label layout so that we
675      * can account for the width of the y-axis value labels. */
676     _compute_axis_ranges (acre);
677
678     _draw_title_and_labels (acre);
679
680     /* And we recompute the axis ranges now that the title and axis
681      * label space is all measured and accounted for. */
682     _compute_axis_ranges (acre);
683
684     _draw_data (acre);
685
686     _draw_frame_and_ticks (acre);
687 }
688
689 /* Create a new dataset---a collection of (x, y) datapoints. A single
690  * plot can contain multiple datasets, (see acre_add_data). */
691 acre_data_t *
692 acre_data_create (void)
693 {
694     acre_data_t *data;
695
696     data = xmalloc (sizeof (acre_data_t));
697
698     data->name = NULL;
699
700     data->points = NULL;
701     data->points_size = 0;
702     data->num_points = 0;
703
704     return data;
705 }
706
707 /* Destroy an acre dataset. Do not call this function if the dataset
708  * has been added to an acre_t plot with acre_add_data. */
709 void
710 acre_data_destroy (acre_data_t *data)
711 {
712     free (data->points);
713
714     free (data);
715 }
716
717 /* Set the label for this dataset (to appear in the plot's key). */
718 void
719 acre_data_set_name (acre_data_t *data, const char *name)
720 {
721     free (data->name);
722
723     data->name = strdup (name);
724 }
725
726 /* Add a datapoint to the given dataset. */
727 void
728 acre_data_add_point_2d (acre_data_t *data, double x, double y)
729 {
730     if (data->num_points >= data->points_size) {
731         data->points_size *= 2;
732         if (data->points_size == 0)
733             data->points_size = 16;
734         data->points = xrealloc_ab (data->points,
735                                     data->points_size,
736                                     sizeof (acre_data_point_2d_t));
737     }
738
739     data->points[data->num_points].x = x;
740     data->points[data->num_points].y = y;
741     data->num_points++;
742 }