/* vim: set ts=4 sw=4 : */
#include <ruby.h>
#include <X11/Xlib.h>
#include <X11/Xutil.h>

#include "shared.h"

VALUE cDisplay, eXlib;

static VALUE
display_new(VALUE class) {
	Display *dpy;
	VALUE obj;

	dpy = XOpenDisplay(NULL);
	if (dpy == NULL) {
		rb_raise(eXlib, "XOpenDisplay: Unable to open display");
		return Qnil;
	}

	obj = Data_Wrap_Struct(class, 0, 0, dpy);
	return obj;
}

static VALUE
display_xconnection(VALUE self) {
	Display *dpy;
	Data_Get_Struct(self, Display, dpy);
	return INT2FIX(ConnectionNumber(dpy));
}
static VALUE
display_width(VALUE self) {
	Display *dpy;
	Data_Get_Struct(self, Display, dpy);
	return INT2FIX(DisplayWidth(dpy, 0));
}
static VALUE
display_height(VALUE self) {
	Display *dpy;
	Data_Get_Struct(self, Display, dpy);
	return INT2FIX(DisplayHeight(dpy, 0));
}

void
xlib_set_size_hints(Display *dpy, Window win, int width, int height) {
	XSizeHints hnt = {0};

	hnt.flags = USSize | PSize | PMinSize | PMaxSize;
	hnt.width      = width;
	hnt.min_width  = width;
	hnt.max_width  = width;
	hnt.height     = height;
	hnt.min_height = height;
	hnt.max_height = height;
	XSetWMNormalHints(dpy, win, &hnt);
}

void
xlib_init() {
	eXlib = rb_define_class("XlibException", rb_eException);
	cDisplay = rb_define_class("Display", rb_cObject);
	rb_define_singleton_method(cDisplay, "new", display_new, 0);
	rb_define_method(cDisplay, "xconnection", display_xconnection, 0);
	rb_define_method(cDisplay, "width", display_width, 0);
	rb_define_method(cDisplay, "height", display_height, 0);
}

Display*
xlib_dpy_from_rb(VALUE display) {
	Display *dpy;
	Data_Get_Struct(display, Display, dpy);
	return dpy;
}
