]> git.scottworley.com Git - batteryviewer/blame - chart.c
Chart draws stuff
[batteryviewer] / chart.c
CommitLineData
5a945372
SW
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"
148e0e28 7#include <float.h>
5a945372
SW
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 {
27db65e2 16 GArray *points;
148e0e28 17 float minx, miny, maxx, maxy;
27db65e2
SW
18};
19
20struct BVChartPoint {
21 float x, y;
5a945372
SW
22};
23
24G_DEFINE_TYPE_WITH_CODE(BVChart, bv_chart, GTK_TYPE_DRAWING_AREA,
25 G_ADD_PRIVATE(BVChart))
26
366d0933
SW
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 float xscale = allocation.width / (priv->maxx - priv->minx);
41 float yscale = allocation.height / (priv->miny - priv->maxy);
42 cairo_set_source_rgb(cr, 0.0, 0.0, 1.0);
43 struct BVChartPoint *start =
44 &g_array_index(priv->points, struct BVChartPoint, 0);
45 cairo_move_to(cr, xscale * (start->x - priv->minx),
46 yscale * (start->y - priv->maxy));
47 for (guint i = 1; i < priv->points->len; i++) {
48 struct BVChartPoint *p =
49 &g_array_index(priv->points, struct BVChartPoint, i);
50 cairo_line_to(cr, xscale * (p->x - priv->minx),
51 yscale * (p->y - priv->maxy));
52 }
53 cairo_stroke(cr);
54
55 return TRUE;
56}
57
58static void bv_chart_class_init(BVChartClass *klass) {
59 GtkWidgetClass *widget_class = GTK_WIDGET_CLASS(klass);
60 widget_class->draw = bv_chart_draw;
61}
5a945372
SW
62
63static void bv_chart_init(BVChart *chart) {
64 gtk_widget_set_has_window(GTK_WIDGET(chart), FALSE);
27db65e2
SW
65 BVChartPrivate *priv = bv_chart_get_instance_private(chart);
66 gboolean zero_terminated = FALSE;
67 gboolean clear_ = FALSE;
68 priv->points =
69 g_array_new(zero_terminated, clear_, sizeof(struct BVChartPoint));
148e0e28
SW
70 priv->minx = FLT_MAX;
71 priv->miny = FLT_MAX;
72 priv->maxx = FLT_MIN;
73 priv->maxy = FLT_MIN;
5a945372
SW
74}
75
76GtkWidget *bv_chart_new() {
77 return GTK_WIDGET(g_object_new(bv_chart_get_type(), NULL));
78}
27db65e2
SW
79
80void bv_chart_add_point(BVChart *chart, float x, float y) {
81 BVChartPrivate *priv = bv_chart_get_instance_private(chart);
148e0e28
SW
82 if (x < priv->minx)
83 priv->minx = x;
84 if (y < priv->miny)
85 priv->miny = y;
86 if (x > priv->maxx)
87 priv->maxx = x;
88 if (y > priv->maxy)
89 priv->maxy = y;
27db65e2
SW
90 struct BVChartPoint p = {.x = x, .y = y};
91 g_array_append_val(priv->points, p);
92}