File: cpu.c

package info (click to toggle)
vala-panel 24.05-3
  • links: PTS, VCS
  • area: main
  • in suites: sid, trixie
  • size: 5,624 kB
  • sloc: ansic: 16,279; xml: 520; makefile: 21
file content (339 lines) | stat: -rw-r--r-- 11,474 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
/*
 * vala-panel
 * Copyright (C) 2018 Konstantin Pugin <ria.freelander@gmail.com>
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

#include <glib/gi18n.h>
#include <stdbool.h>
#include <stdlib.h>
#include <string.h>
#include <sys/sysinfo.h>
#include <sys/time.h>
#include <time.h>

#include "cpu.h"

#define BORDER_SIZE 2

typedef struct
{                                          /* Value from /proc/stat */
	long long unsigned int u, n, s, i; /* User, nice, system, idle */
} cpu_stat;

/* Private context for CPU applet. */
struct _CpuApplet
{
	ValaPanelApplet parent;
	GdkRGBA foreground_color; /* Foreground color for drawing area */
	cairo_surface_t *pixmap;  /* Pixmap to be drawn on drawing area */

	uint timer;       /* Timer for periodic update */
	float *stats_cpu; /* Ring buffer of CPU utilization values as saved CPU utilization value as
	                       0.0..1.0*/
	uint ring_cursor; /* Cursor for ring buffer */
	uint pixmap_width;  /* Width of drawing area pixmap; also size of ring buffer; does not
	                       include border size */
	uint pixmap_height; /* Height of drawing area pixmap; does not include border size */
	cpu_stat previous_cpu_stat; /* Previous value of cpu_stat */
};

#define cpu_applet_from_da(da) VALA_PANEL_CPU_APPLET(gtk_widget_get_parent(GTK_WIDGET(da)))
#define cpu_applet_get_da(p) GTK_DRAWING_AREA(gtk_bin_get_child(GTK_BIN(p)))

G_DEFINE_DYNAMIC_TYPE(CpuApplet, cpu_applet, vala_panel_applet_get_type())

/* Redraw after timer callback or resize. */
static void redraw_pixmap(CpuApplet *c)
{
	cairo_t *cr              = cairo_create(c->pixmap);
	GtkStyleContext *context = gtk_widget_get_style_context(GTK_WIDGET(c));
	GtkStateFlags flags      = gtk_widget_get_state_flags(GTK_WIDGET(c));
	g_autoptr(GdkRGBA) background_color;
	gtk_style_context_get(context,
	                      flags,
	                      GTK_STYLE_PROPERTY_BACKGROUND_COLOR,
	                      &background_color,
	                      NULL);
	cairo_set_line_width(cr, 1.0);
	/* Erase pixmap. */
	cairo_set_operator(cr, CAIRO_OPERATOR_SOURCE);
	cairo_rectangle(cr, 0, 0, c->pixmap_width, c->pixmap_height);
	gdk_cairo_set_source_rgba(cr, background_color);
	cairo_fill(cr);

	/* Recompute pixmap. */
	uint i;
	uint drawing_cursor = c->ring_cursor;
	gdk_cairo_set_source_rgba(cr, &c->foreground_color);
	for (i = 0; i < c->pixmap_width; i++)
	{
		/* Draw one bar of the CPU usage graph. */
		if (c->stats_cpu[drawing_cursor] != 0.0)
		{
			cairo_move_to(cr, i + 0.5, c->pixmap_height);
			cairo_line_to(cr,
			              i + 0.5,
			              c->pixmap_height -
			                  c->stats_cpu[drawing_cursor] * c->pixmap_height);
			cairo_stroke(cr);
		}

		/* Increment and wrap drawing cursor. */
		drawing_cursor += 1;
		if (drawing_cursor >= c->pixmap_width)
			drawing_cursor = 0;
	}

	/* check_cairo_status(cr); */
	cairo_destroy(cr);

	/* Redraw pixmap. */
	gtk_widget_queue_draw(GTK_WIDGET(cpu_applet_get_da(c)));
}

/* Periodic timer callback. */
static int cpu_update(CpuApplet *c)
{
	if (g_source_is_destroyed(g_main_current_source()))
		return false;
	if ((c->stats_cpu != NULL) && (c->pixmap != NULL))
	{
		/* Open statistics file and scan out CPU usage. */
		cpu_stat cpu;
		FILE *stat = fopen("/proc/stat", "r");
		if (stat == NULL)
			return true;
		int fscanf_result =
		    fscanf(stat, "cpu %llu %llu %llu %llu", &cpu.u, &cpu.n, &cpu.s, &cpu.i);
		fclose(stat);

		/* Ensure that fscanf succeeded. */
		if (fscanf_result == 4)
		{
			/* Compute delta from previous statistics. */
			cpu_stat cpu_delta;
			cpu_delta.u = cpu.u - c->previous_cpu_stat.u;
			cpu_delta.n = cpu.n - c->previous_cpu_stat.n;
			cpu_delta.s = cpu.s - c->previous_cpu_stat.s;
			cpu_delta.i = cpu.i - c->previous_cpu_stat.i;

			/* Copy current to previous. */
			memcpy(&c->previous_cpu_stat, &cpu, sizeof(cpu_stat));

			/* Compute user+nice+system as a fraction of total.
			 * Introduce this sample to ring buffer, increment and wrap ring buffer
			 * cursor. */
			float cpu_uns                = cpu_delta.u + cpu_delta.n + cpu_delta.s;
			c->stats_cpu[c->ring_cursor] = cpu_uns / (cpu_uns + cpu_delta.i);
			c->ring_cursor += 1;
			if (c->ring_cursor >= c->pixmap_width)
				c->ring_cursor = 0;

			/* Redraw with the new sample. */
			redraw_pixmap(c);
		}
	}
	return G_SOURCE_CONTINUE;
}

/* Handler for configure_event on drawing area. */
static bool configure_event(GtkWidget *widget, G_GNUC_UNUSED GdkEventConfigure *event, CpuApplet *c)
{
	GtkAllocation allocation;

	gtk_widget_get_allocation(widget, &allocation);
	/* Allocate pixmap and statistics buffer without border pixels. */
	uint new_pixmap_width  = (uint)MAX(allocation.width - BORDER_SIZE * 2, 0);
	uint new_pixmap_height = (uint)MAX(allocation.height - BORDER_SIZE * 2, 0);
	if ((new_pixmap_width > 0) && (new_pixmap_height > 0))
	{
		/* If statistics buffer does not exist or it changed size, reallocate and preserve
		 * existing data. */
		if ((c->stats_cpu == NULL) || (new_pixmap_width != c->pixmap_width))
		{
			float *new_stats_cpu = g_new0(float, new_pixmap_width);
			if (c->stats_cpu != NULL)
			{
				if (new_pixmap_width > c->pixmap_width)
				{
					/* New allocation is larger.
					 * Introduce new "oldest" samples of zero following the
					 * cursor. */
					memcpy(&new_stats_cpu[0],
					       &c->stats_cpu[0],
					       c->ring_cursor * sizeof(float));
					memcpy(&new_stats_cpu[new_pixmap_width - c->pixmap_width +
					                      c->ring_cursor],
					       &c->stats_cpu[c->ring_cursor],
					       (c->pixmap_width - c->ring_cursor) * sizeof(float));
				}
				else if (c->ring_cursor <= new_pixmap_width)
				{
					/* New allocation is smaller, but still larger than the ring
					 * buffer cursor.
					 * Discard the oldest samples following the cursor. */
					memcpy(&new_stats_cpu[0],
					       &c->stats_cpu[0],
					       c->ring_cursor * sizeof(float));
					memcpy(&new_stats_cpu[c->ring_cursor],
					       &c->stats_cpu[c->pixmap_width - new_pixmap_width +
					                     c->ring_cursor],
					       (new_pixmap_width - c->ring_cursor) * sizeof(float));
				}
				else
				{
					/* New allocation is smaller, and also smaller than the ring
					 * buffer cursor.
					 * Discard all oldest samples following the ring buffer
					 * cursor and additional samples at the beginning of the
					 * buffer. */
					memcpy(&new_stats_cpu[0],
					       &c->stats_cpu[c->ring_cursor - new_pixmap_width],
					       new_pixmap_width * sizeof(float));
					c->ring_cursor = 0;
				}
				g_free(c->stats_cpu);
			}
			c->stats_cpu = new_stats_cpu;
		}

		/* Allocate or reallocate pixmap. */
		c->pixmap_width  = new_pixmap_width;
		c->pixmap_height = new_pixmap_height;
		if (c->pixmap)
			cairo_surface_destroy(c->pixmap);
		c->pixmap = cairo_image_surface_create(CAIRO_FORMAT_ARGB32,
		                                       c->pixmap_width,
		                                       c->pixmap_height);
		/* check_cairo_surface_status(&c->pixmap); */

		/* Redraw pixmap at the new size. */
		redraw_pixmap(c);
	}
	return true;
}

/* Handler for draw on drawing area. */
static bool draw(G_GNUC_UNUSED GtkWidget *widget, cairo_t *cr, CpuApplet *c)
{
	/* Draw the requested part of the pixmap onto the drawing area.
	 * Translate it in both x and y by the border size. */
	if (c->pixmap != NULL)
	{
		GtkStyleContext *context = gtk_widget_get_style_context(GTK_WIDGET(c));
		GtkStateFlags flags      = gtk_widget_get_state_flags(GTK_WIDGET(c));
		g_autoptr(GdkRGBA) background_color;
		gtk_style_context_get(context,
		                      flags,
		                      GTK_STYLE_PROPERTY_BACKGROUND_COLOR,
		                      &background_color,
		                      NULL);
		gdk_cairo_set_source_rgba(cr, background_color);
		cairo_set_source_surface(cr, c->pixmap, BORDER_SIZE, BORDER_SIZE);
		cairo_paint(cr);
		/* check_cairo_status(cr); */
	}
	return false;
}

static void on_height_change(GObject *owner, G_GNUC_UNUSED GParamSpec *pspec, void *data)
{
	GtkWidget *da = GTK_WIDGET(data);
	uint height;
	g_object_get(owner, VALA_PANEL_KEY_HEIGHT, &height, NULL);
	gtk_widget_set_size_request(da, height > 40 ? height : 40, height);
}

static void cpu_applet_constructed(GObject *obj)
{
	G_OBJECT_CLASS(cpu_applet_parent_class)->constructed(obj);
	CpuApplet *c                = VALA_PANEL_CPU_APPLET(obj);
	ValaPanelToplevel *toplevel = vala_panel_applet_get_toplevel(VALA_PANEL_APPLET(c));
	/* Allocate drawing area as a child of top level widget. */
	GtkDrawingArea *da = GTK_DRAWING_AREA(gtk_drawing_area_new());
	gtk_widget_add_events(GTK_WIDGET(da),
	                      GDK_BUTTON_PRESS_MASK | GDK_BUTTON_RELEASE_MASK |
	                          GDK_BUTTON_MOTION_MASK);
	on_height_change(G_OBJECT(toplevel), NULL, da);
	gtk_container_add(GTK_CONTAINER(c), GTK_WIDGET(da));
	GtkStyleContext *context = gtk_widget_get_style_context(GTK_WIDGET(toplevel));
	GtkStateFlags flags      = gtk_widget_get_state_flags(GTK_WIDGET(toplevel));
	gtk_style_context_get_color(context, flags, &c->foreground_color);

	/* Connect signals. */
	g_signal_connect(G_OBJECT(toplevel),
	                 "notify::" VALA_PANEL_KEY_HEIGHT,
	                 G_CALLBACK(on_height_change),
	                 (gpointer)da);
	g_signal_connect(G_OBJECT(da), "configure-event", G_CALLBACK(configure_event), (gpointer)c);
	g_signal_connect(G_OBJECT(da), "draw", G_CALLBACK(draw), (gpointer)c);
	/* Show the widget.  Connect a timer to refresh the statistics. */
	gtk_widget_show(GTK_WIDGET(da));
	c->timer = g_timeout_add(1500, (GSourceFunc)cpu_update, (gpointer)c);
	gtk_widget_show(GTK_WIDGET(c));
}

/* Plugin destructor. */
static void cpu_applet_dispose(GObject *user_data)
{
	CpuApplet *c = VALA_PANEL_CPU_APPLET(user_data);
	/* Disconnect the timer. */
	if (c->timer)
	{
		g_source_remove(c->timer);
		c->timer = 0;
	}

	/* Deallocate memory. */
	g_clear_pointer(&c->pixmap, cairo_surface_destroy);
	g_clear_pointer(&c->stats_cpu, g_free);
	G_OBJECT_CLASS(cpu_applet_parent_class)->dispose(user_data);
}

static void cpu_applet_init(G_GNUC_UNUSED CpuApplet *self)
{
}

static void cpu_applet_class_init(CpuAppletClass *klass)
{
	G_OBJECT_CLASS(klass)->constructed = cpu_applet_constructed;
	G_OBJECT_CLASS(klass)->dispose     = cpu_applet_dispose;
}

static void cpu_applet_class_finalize(G_GNUC_UNUSED CpuAppletClass *klass)
{
}

/*
 * IO Module functions
 */

void g_io_cpu_load(GTypeModule *module)
{
	g_return_if_fail(module != NULL);

	cpu_applet_register_type(module);

	g_io_extension_point_implement(VALA_PANEL_APPLET_EXTENSION_POINT,
	                               cpu_applet_get_type(),
	                               "org.valapanel.cpu",
	                               10);
}

void g_io_cpu_unload(GIOModule *module)
{
	g_return_if_fail(module != NULL);
}