/*
 * Test program to draw lines in a window using the Xlib interface.
 * On the way to uptting X11 support into csound.
 * mg@ukc.ac.uk, May 1990
 */

#include <stdio.h>
#include <X11/Xlib.h>

main(argc, argv)
char **argv;
{
	Display *dpy;
	Window window;
	XEvent event;
	GC gc;
	XGCValues xgcvalues;
	int width = 100, height = 100;	/* current size of window */

	/*
	 * Open up the world
	 */
	dpy = XOpenDisplay(NULL);	/* should use -display args etc */
	if (dpy == NULL) {
		fprintf(stderr, "Cannot open X display\n");
		exit(1);
	}

	/*
	 * Ask for a window to be created...
	 */
	window = XCreateSimpleWindow(dpy, DefaultRootWindow(dpy),
			100, 100,	/* position of top left corner */
			width, height,	/* size of drawing area */
			0,		/* border width */
			0,		/* border colour */
			WhitePixel(dpy, 0));	/* background */

	/*
	 * Register an interest in events making us redraw, and in clicks.
	 */
	XSelectInput(dpy, window, StructureNotifyMask | ExposureMask | ButtonPressMask);

	/*
	 * ... map it ...
	 */
	XMapWindow(dpy, window);

	/*
	 * Get the graphic context for use in drawing operations
	 */
	xgcvalues.foreground = BlackPixel(dpy, 0);
	gc = XCreateGC(dpy, window, GCForeground, &xgcvalues);

	/*
	 * ... and wait until it exists.
	 */
	while (1) {
		XNextEvent(dpy, &event);

		switch (event.type) {
		/* Ignore the other events you get for free
		 * with ConfigureNotify */
		case CirculateNotify:
		case DestroyNotify:
		case GravityNotify:
		case MapNotify:
		case ReparentNotify:
			break;
		case ConfigureNotify:
			puts("Configure");
			/* stash window size */
			width = event.xconfigure.width;
			height = event.xconfigure.height;
			goto draw;
		case Expose:
			puts("Expose");
			/* Avoid multiple redraws for one exposure */
			if (event.xexpose.count > 0) break;
draw:			XClearWindow(dpy, window);
			XDrawLine(dpy, window, gc, 1, 1, width-2, height-2);
			break;
		case ButtonPress:
			puts("ButtonPress");
			width *=2; height *=2;
			XResizeWindow(dpy, window, width, height);
			break;
		default:
			fprintf(stderr, "Strange event %d received.\n", event.type);
			break;
		}
	}

	XCloseDisplay(dpy);
	exit(0);
}
