/* goatx.c 
   X11 specific functions */

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

#include "gnome.h"
#include "glade/glade.h"
#include "gconf/gconf-client.h"

#include "goat.h"

#include "goatx.h"

/* Some of this code stolen from libwnck */

static Atom get_atom (const char *atom_name)
{
  Atom atom;
  
  g_return_val_if_fail (atom_name != NULL, None);
  atom = XInternAtom (gdk_display, atom_name, FALSE);

  return atom;
}

int goat_get_current_workspace()
{
  Window xwindow;
  Screen *screen;
  Atom atom, type;
  int workspace, result, format;
  gulong nitems, bytes_after, *num;

  screen = ScreenOfDisplay (gdk_display, 
			    DefaultScreen (gdk_display));
  xwindow = RootWindowOfScreen (screen);
  atom = get_atom("_NET_CURRENT_DESKTOP");
  type = None;

  result = XGetWindowProperty (gdk_display,
			       xwindow,
			       atom,
			       0, G_MAXLONG,
			       False, XA_CARDINAL, &type, 
			       &format, &nitems,
			       &bytes_after, (guchar **)&num);  
  
  if (num) {
    workspace = *num;
    XFree (num);
  }
  else
    workspace = 0;

  return workspace;
}

void goat_set_workspace(Goat *goat, int workspace)
{
  XEvent xev;
  Window xwindow;
  Screen *screen;

  xwindow = GDK_WINDOW_XWINDOW(goat->window->window);
  screen = ScreenOfDisplay (gdk_display, 
			    DefaultScreen (gdk_display));

  xev.xclient.type = ClientMessage;
  xev.xclient.serial = 0;
  xev.xclient.send_event = True;
  xev.xclient.display = gdk_display;
  xev.xclient.window = xwindow;
  xev.xclient.message_type = get_atom("_NET_WM_DESKTOP");
  xev.xclient.format = 32;
  xev.xclient.data.l[0] = workspace;
  xev.xclient.data.l[1] = 0;
  xev.xclient.data.l[2] = 0;

  XSendEvent (gdk_display,
	      RootWindowOfScreen (screen),
              False,
	      SubstructureRedirectMask | SubstructureNotifyMask,
	      &xev);
}

int goat_get_workspace(Goat *goat)
{
  Atom type, atom;
  int workspace, result, format;
  gulong nitems, bytes_after, *num;
  Window xwindow;

  xwindow = GDK_WINDOW_XWINDOW(goat->window->window);
  type = None;
  atom = get_atom("_NET_WM_DESKTOP");

  result = XGetWindowProperty (gdk_display,
			       xwindow,
			       atom,
			       0, G_MAXLONG,
			       False, XA_CARDINAL, &type, 
			       &format, &nitems,
			       &bytes_after, (guchar **)&num);  
  
  workspace = *num;
  XFree (num);

  return workspace;
}

void goat_set_window_type(Goat *goat)
{
  Atom atoms[1] = { None };
  Atom net_wm_window_type;

  net_wm_window_type = get_atom("_NET_WM_WINDOW_TYPE");
  atoms[0] = get_atom("_NET_WM_WINDOW_TYPE_UTILITY");

  XChangeProperty (GDK_WINDOW_XDISPLAY (goat->window->window),
		   GDK_WINDOW_XWINDOW (goat->window->window),
		   net_wm_window_type,
		   XA_ATOM, 32, PropModeReplace,
		   (guchar *)atoms, 1); 
}
