/* WMCPU 1.3 (c) 1998, 1999, 2000, 2001 timecop@japan.co.jp
 * Dockapp CPU usage monitor similar to XosView.
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 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 General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
 *
 * LOADAVG patch thanks to Darren Benham <gecko@benham.net>
 * now use -l switch on the command line to toggle between graphical and 
 * numeric loadavg display.
 */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <unistd.h>
#include <getopt.h>

#include <X11/Xlib.h>
#include <X11/xpm.h>
#include <X11/extensions/shape.h>

#include "master.xpm"

#define WMCPU_VERSION "1.4"

#define copy_xpm_area(x, y, w, h, dx, dy) \
	XCopyArea(display, pixmap, pixmap, gc, x, y, w, h, dx, dy)
#define MIN(a, b) (((a) < (b)) ? (a) : (b))

#define HELP_TEXT \
	"wmcpu: cpu usage monitor dockapp that looks like xosview\n" \
	"   timecop@japan.co.jp\n" \
	"usage:\n" \
	"\t-display <display name>\n" \
	"\t-h\tthis screen\n" \
	"\t-v\tprint the version number\n" \
	"\t-l\tshow load as numbers\n" \
	"\t-t\ttime between refresh in usec (def=250000)\n"

static char *display_name = NULL;
static Display *display;
static Window win;
static Window iconwin;
static GC gc;
static Pixmap pixmap;
static Pixmap mask;
static unsigned long udelay = 250000;
static int gfx_loadbar = 1;

static void wmcpu_routine(void);
static void redraw_window(void);
static void new_window(char *name, int width, int height);

int main(int argc, char **argv)
{
	int ch;

	while ((ch = getopt(argc, argv, "d:hvlt:")) != EOF) {
		switch (ch) {
			case 'd':
				if (optarg)
					display_name = strdup(optarg);
				break;
			case 'v':
				fprintf(stdout, "%s\n", WMCPU_VERSION);
				exit(0);
				break;
			case 'l':
				gfx_loadbar = 0;
				break;
			case 't':
				if (optarg)
					udelay = atol(optarg);
				break;
			default:
				fputs(HELP_TEXT, stdout);
				exit(0);
				break;
		}
	}

	if ((display = XOpenDisplay(display_name)) == NULL) {
		fprintf(stderr, "Unable to open display \"%s\"\n", display_name);
		return EXIT_FAILURE;
	}

	wmcpu_routine();
	return EXIT_SUCCESS;
}

void wmcpu_routine(void)
{
	int i;
	int tempy;
	const int xoffset = 5;
	const int barwidth = 54;
	XEvent Event;
	FILE *fp;
	char str[128];

	static float cpustat[4];	/* remember the statistics read last time */
	float info[4];

	int old_mins = -1;

	char has_meminfo = 0;
	struct {
		short int line;
		int *var;
	} memlines[4];
	int memtotal=0, memfree=0, membuffers=0, memcached=0, memuser=0;
	
	/* /proc/meminfo Initialization {{{
	   This will find which line numbers correspond to
	   each meminfo value. This is done now to avoid
	   string comparing inside of main loop. */
	if((fp = fopen("/proc/meminfo", "r")) != NULL) {
		short int line=0, last_item=0;
		struct {
			char *name;
			int *var;
		} meminfolines[4] = {
			{"MemTotal:",&memtotal  },
			{"MemFree:" ,&memfree   },
			{"Buffers:" ,&membuffers},
			{"Cached:"  ,&memcached }
		};
		while(fscanf(fp," %127s%*[^\n]",str) > 0) {
			line++;
			for(i=0; i<4; i++)
				if(strcmp(str,meminfolines[i].name)==0) {
					memlines[last_item].line=line;
					memlines[last_item].var=meminfolines[i].var;
					last_item++;
					break;
				}
			if(last_item>=4)
				break;
		}
		fclose(fp);
		/* Next loop is just to not leave unitialized items. */
		while(last_item<4) {
			memlines[last_item].line=0;
			memlines[last_item].var=0;
			last_item++;
		}
		has_meminfo=1;
	}
	/* /proc/meminfo Initialization }}} */

	new_window("wmcpu", 64,  64);

	while (1) {

	/* /proc/stat	kernel/system statistics  {{{
	   cpu	3357 0 4313 1362393
	   The number of jiffies (1/100ths of a second)
	   that the system spent in user mode, user
	   mode with low priority (nice), system mode,
	   and the idle task, respectively.  The last
	   value should be 100 times the second entry
	   in the uptime pseudo-file. */

	if ((fp = fopen("/proc/stat", "r")) != NULL) {
		long int CPUuser, CPUnice, CPUsyst;
		fscanf(fp, "%127s%f%f%f%f", str, info, info + 1, info + 2, info + 3);
		fclose(fp);

		if (cpustat[0] != 0) {
			float fields[4], total = 0.0;
			for (i = 0; i < 4; i++) {
				fields[i] = info[i] - cpustat[i];
				total += fields[i];
			}
			if (total > 0) {
				CPUuser = fields[0] / total * (barwidth - 0.5);
				CPUnice = fields[1] / total * (barwidth - 0.5);
				CPUsyst = fields[2] / total * (barwidth - 0.5);
				copy_xpm_area(3, 93, CPUuser, 9, xoffset, 5);
				copy_xpm_area(3, 75, CPUnice, 9, xoffset + CPUuser, 5);
				copy_xpm_area(3, 84, CPUsyst, 9,
					xoffset + CPUuser + CPUnice, 5);
				copy_xpm_area(3, 102,
					(54 - (CPUuser + CPUnice + CPUsyst)), 9,
					xoffset + CPUuser + CPUnice + CPUsyst, 5);
			}
		}
		for (i = 0; i < 4; i++)
			cpustat[i] = info[i];
	}
	/* /proc/stat	kernel/system statistics  }}} */

	/* /proc/loadavg  {{{
	   The load average numbers give the number of jobs in
	   the run queue averaged over 1, 5 and 15 minutes.
	   They are the same as the load average numbers given
	   by uptime(1) and other programs. */
	if ((fp = fopen("/proc/loadavg", "r")) != NULL) {
		static float oldv = 0.0;
		float ftmp;
		fscanf(fp, "%f", &ftmp);
		fclose(fp);

		if (oldv != ftmp) {
			int tempx;
			oldv = info[0];
			if (gfx_loadbar) {
				oldv = ftmp;
				i = MIN(54, (ftmp * 54));
				copy_xpm_area(3, 75, i, 9, 5, 33);
				copy_xpm_area(3, 102, 54 - i, 9, 5 + i, 33);
			} else {
				tempx = ftmp * 100;
				if (tempx > 9999)
					tempx = 9999;
				if (tempx > 1000) {
					tempy = tempx / 1000;
					copy_xpm_area(3 + (tempy * 6), 66, 6, 9, 15, 33);
				} else
					copy_xpm_area(68, 66, 6, 9, 15, 33);
				tempy = (tempx / 100) % 10;
				copy_xpm_area(3 + (tempy * 6), 66, 6, 9, 21, 33);

				copy_xpm_area(65, 66, 3, 9, 28, 33);

				tempy = (tempx / 10) % 10;
				copy_xpm_area(3 + (tempy * 6), 66, 6, 9, 31, 33);

				tempy = tempx % 10;
				copy_xpm_area(3 + (tempy * 6), 66, 6, 9, 37, 33);
			}
		}
	}
	/* /proc/loadavg  }}} */

	/* /proc/meminfo  {{{
	   This is used by free(1) to report the amount of
	   free and used memory (both physical and swap) on
	   the system as well as the shared memory and buffers
	   used by the kernel. */
	if (has_meminfo && (fp = fopen("/proc/meminfo", "r")) != NULL) {
		short int line=0, last_item=0;
		int oldtotal, oldfree, oldbuffers, oldcached, olduser;
		int                    barbuffers, barcached, baruser;

		oldtotal  =memtotal;
		oldfree   =memfree;
		oldbuffers=membuffers;
		oldcached =memcached;
		olduser   =memuser;  /* Note: value of this var is calculated from other vars. */
		while( fgets(str,128,fp) ) {
			line++;
			if(line == memlines[last_item].line) {
				sscanf(str,"%*s%d",memlines[last_item].var);
				last_item++;
			}
			if(last_item >= 4 || memlines[last_item].line==0)
				break;
		}
		fclose(fp);
		memuser = memtotal - memfree - membuffers - memcached;

		if ( memfree   != oldfree   || membuffers != oldbuffers
		||   memcached != oldcached || memtotal   != oldtotal   ) {

			baruser    = (memuser    * barwidth) / memtotal;
			barcached  = (memcached  * barwidth) / memtotal;
			barbuffers = (membuffers * barwidth) / memtotal;

			copy_xpm_area(3, 111, baruser   , 9, xoffset, 19);
			copy_xpm_area(3, 120, barbuffers, 9, xoffset + baruser, 19);
			copy_xpm_area(3,  84, barcached , 9, xoffset + baruser + barbuffers, 19);
			copy_xpm_area(3, 102,
				barwidth - (baruser + barbuffers + barcached), 9,
				xoffset  + (baruser + barbuffers + barcached), 19);
		}
	}
	/* /proc/meminfo  }}} */

	/* /proc/uptime  {{{
	   Tell how long the system has been running. */
	if ((fp = fopen("/proc/uptime", "r")) != NULL) {
		int upt, days, hours, mins;
		fscanf(fp, "%d", &upt);
		fclose(fp);

		mins = (upt / 60) % 60;
		hours = (upt / 3600) % 24;
		days = (upt / 86400);
		if (old_mins != mins) {
			old_mins = mins;
			tempy = mins % 10;
			copy_xpm_area(3 + (tempy * 6), 66, 6, 9, 50, 48);
			tempy = mins / 10;
			copy_xpm_area(3 + (tempy * 6), 66, 6, 9, 44, 48);
			copy_xpm_area(63, 66, 3, 9, 41, 48);
			tempy = hours % 10;
			copy_xpm_area(3 + (tempy * 6), 66, 6, 9, 34, 48);
			tempy = hours / 10;
			copy_xpm_area(3 + (tempy * 6), 66, 6, 9, 28, 48);
			copy_xpm_area(63, 66, 3, 9, 25, 48);
			tempy = days % 10;
			copy_xpm_area(3 + (tempy * 6), 66, 6, 9, 18, 48);
			tempy = days / 10;
			copy_xpm_area(3 + (tempy * 6), 66, 6, 9, 12, 48);
			tempy = days / 100;
			copy_xpm_area(3 + (tempy * 6), 66, 6, 9, 6, 48);
		}
	}
	/* /proc/uptime }}} */

	while (XPending(display)) {
		XNextEvent(display, &Event);
		switch (Event.type) {
			case Expose:
				redraw_window();
				break;
			case DestroyNotify:
				XCloseDisplay(display);
				exit(0);
				break;
		}
	}
	redraw_window();
	usleep(udelay);

	}  /* End of while(1) loop */
}

static void new_window(char *name, int width, int height)
{
	XpmAttributes attr;
	Pixel fg, bg;
	XGCValues gcval;
	XSizeHints sizehints;
	XClassHint classhint;
	XWMHints wmhints;
	XTextProperty wname;

	sizehints.flags = USSize | USPosition;
	sizehints.x = 0;
	sizehints.y = 0;
	sizehints.width = width;
	sizehints.height = height;

	fg = BlackPixel(display, DefaultScreen(display));
	bg = WhitePixel(display, DefaultScreen(display));

	win = XCreateSimpleWindow(display, DefaultRootWindow(display),
			sizehints.x, sizehints.y,
			sizehints.width, sizehints.height, 1, fg,
			bg);

	iconwin = XCreateSimpleWindow(display, win, sizehints.x, sizehints.y,
			sizehints.width, sizehints.height, 1, fg,
			bg);

	XSetWMNormalHints(display, win, &sizehints);
	classhint.res_name = name;
	classhint.res_class = name;
	XSetClassHint(display, win, &classhint);

#define INPUT_MASK \
	ButtonPressMask \
	| ExposureMask

	XSelectInput(display, win, INPUT_MASK);
	XSelectInput(display, iconwin, INPUT_MASK);

#undef INPUT_MASk

	XStringListToTextProperty(&name, 1, &wname);
	XSetWMName(display, win, &wname);

	gcval.foreground = fg;
	gcval.background = bg;
	gcval.graphics_exposures = 0;

	gc = XCreateGC(display, win,
		GCForeground | GCBackground | GCGraphicsExposures,
		&gcval);

	attr.exactColors = 0;
	attr.alloc_close_colors = 1;
	attr.closeness = 30000;
	attr.valuemask = (XpmExactColors | XpmAllocCloseColors | XpmCloseness);
	if ((XpmCreatePixmapFromData(display, DefaultRootWindow(display),
			master_xpm, &pixmap, &mask,
			&attr) != XpmSuccess)) {
		fputs("Cannot allocate colors for the dockapp pixmap!\n", stderr);
		exit(EXIT_FAILURE);
	}

	XShapeCombineMask(display, win, ShapeBounding, 0, 0, mask,
		  ShapeSet);
	XShapeCombineMask(display, iconwin, ShapeBounding, 0, 0, mask,
		  ShapeSet);

	wmhints.initial_state = WithdrawnState;
	wmhints.icon_window = iconwin;
	wmhints.icon_x = sizehints.x;
	wmhints.icon_y = sizehints.y;
	wmhints.window_group = win;
	wmhints.flags =
	StateHint | IconWindowHint | IconPositionHint | WindowGroupHint;
	XSetWMHints(display, win, &wmhints);

	XMapWindow(display, win);
}

static void redraw_window(void)
{
	XCopyArea(display, pixmap, iconwin, gc, 0, 0, 64, 64, 0, 0);
	XCopyArea(display, pixmap, win, gc, 0, 0, 64, 64, 0, 0);
}
