]> git.scottworley.com Git - batteryviewer/blame_incremental - chart.c
Chart margin
[batteryviewer] / chart.c
... / ...
CommitLineData
1/*
2 * h/t https://ptomato.name/advanced-gtk-techniques/html/custom-container.html
3 * for examples of how to make GTK widgets
4 */
5
6#include "chart.h"
7#include <float.h>
8#include <gtk/gtk.h>
9
10#define BV_CHART_PRIVATE(obj) \
11 (G_TYPE_INSTANCE_GET_PRIVATE((obj), BV_CHART_TYPE, BVChartPrivate))
12
13typedef struct _BVChartPrivate BVChartPrivate;
14
15struct _BVChartPrivate {
16 GArray *points;
17 float minx, miny, maxx, maxy;
18};
19
20struct BVChartPoint {
21 float x, y;
22};
23
24G_DEFINE_TYPE_WITH_CODE(BVChart, bv_chart, GTK_TYPE_DRAWING_AREA,
25 G_ADD_PRIVATE(BVChart))
26
27static gboolean bv_chart_draw(GtkWidget *widget, cairo_t *cr) {
28 BVChart *chart = BV_CHART(widget);
29 BVChartPrivate *priv = bv_chart_get_instance_private(chart);
30
31 cairo_set_source_rgb(cr, 1.0, 1.0, 1.0);
32 cairo_paint(cr);
33
34 if (priv->points->len < 2)
35 return TRUE;
36
37 GtkAllocation allocation;
38 gtk_widget_get_allocation(widget, &allocation);
39
40 int margin = 3;
41 float xscale = (allocation.width - 2 * margin) / (priv->maxx - priv->minx);
42 float yscale = (allocation.height - 2 * margin) / (priv->miny - priv->maxy);
43 cairo_set_source_rgb(cr, 0.0, 0.0, 1.0);
44 struct BVChartPoint *start =
45 &g_array_index(priv->points, struct BVChartPoint, 0);
46 cairo_move_to(cr, xscale * (start->x - priv->minx) + margin,
47 yscale * (start->y - priv->maxy) + margin);
48 for (guint i = 1; i < priv->points->len; i++) {
49 struct BVChartPoint *p =
50 &g_array_index(priv->points, struct BVChartPoint, i);
51 cairo_line_to(cr, xscale * (p->x - priv->minx) + margin,
52 yscale * (p->y - priv->maxy) + margin);
53 }
54 cairo_stroke(cr);
55
56 return TRUE;
57}
58
59static void bv_chart_class_init(BVChartClass *klass) {
60 GtkWidgetClass *widget_class = GTK_WIDGET_CLASS(klass);
61 widget_class->draw = bv_chart_draw;
62}
63
64static void bv_chart_init(BVChart *chart) {
65 gtk_widget_set_has_window(GTK_WIDGET(chart), FALSE);
66 BVChartPrivate *priv = bv_chart_get_instance_private(chart);
67 gboolean zero_terminated = FALSE;
68 gboolean clear_ = FALSE;
69 priv->points =
70 g_array_new(zero_terminated, clear_, sizeof(struct BVChartPoint));
71 priv->minx = FLT_MAX;
72 priv->miny = FLT_MAX;
73 priv->maxx = FLT_MIN;
74 priv->maxy = FLT_MIN;
75}
76
77GtkWidget *bv_chart_new() {
78 return GTK_WIDGET(g_object_new(bv_chart_get_type(), NULL));
79}
80
81void bv_chart_add_point(BVChart *chart, float x, float y) {
82 BVChartPrivate *priv = bv_chart_get_instance_private(chart);
83 if (x < priv->minx)
84 priv->minx = x;
85 if (y < priv->miny)
86 priv->miny = y;
87 if (x > priv->maxx)
88 priv->maxx = x;
89 if (y > priv->maxy)
90 priv->maxy = y;
91 struct BVChartPoint p = {.x = x, .y = y};
92 g_array_append_val(priv->points, p);
93}