// gdk_x11_foreign_new_xdisplay() handle=TRUE test
// to compile:
// gcc -Wall `pkg-config gdk-x11-2.0 --cflags --libs` gdk-foreign-handle.c

#include <X11/Xlib.h>
#include <gdk/gdk.h>
#include <gdk/gdkx.h>

#define WIDTH  400
#define HEIGHT 400

int main()
{
	gdk_init (NULL, NULL);

	Display *display;
	int screen;
	Window window;

	/* open connection with the server */
	display = XOpenDisplay (NULL);
	if (display == NULL) {
		printf("Cannot open display\n");
		return 1;
	}
	screen = DefaultScreen (display);

	/* create window */
	window = XCreateSimpleWindow (display, RootWindow (display, screen), 0, 0, WIDTH, HEIGHT, 0,
	                              BlackPixel(display, screen), WhitePixel(display, screen));

	XSelectInput (display, window, ExposureMask | KeyPressMask);
	XMapWindow (display, window);  // show the window

	/* Gdk Wrappers */
	GdkDisplay *gdisplay = gdk_x11_foreign_new_xdisplay (display, TRUE);
	GdkWindow *gwindow = gdk_window_foreign_new_for_display (gdisplay, window);

	while (TRUE) {
		GdkEvent *event;
		while (!gdk_events_pending())
			g_usleep (0.5 * (1000*1000));
		event = gdk_event_get();

		/* expose events seem to return null -- I guess they should be dealt other way :? */
		if (!event || event->type == GDK_EXPOSE) {
			// draw
  		const GdkColor fg_clr = { 0, 255 << 8, 0, 0 };
  		GdkGC *gc = gdk_gc_new (GDK_DRAWABLE (gwindow));
  		gdk_gc_set_rgb_fg_color (gc, &fg_clr);

  		gdk_draw_rectangle (GDK_DRAWABLE (gwindow), gc, TRUE, 0, 0, WIDTH, HEIGHT);
  		g_object_unref (G_OBJECT (gc));
		}
		else if(event->type == GDK_KEY_PRESS)
			break;
		if (event)
			gdk_event_free (event);
	}

	XCloseDisplay (display);
	return 0;
}
