/* gcc -lX11 -o set_switching set_switching.c
 * -- tthurman@gnome.org, August 2007 */

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

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

  Display* display;
  Window root_window;
  XEvent ev;
  long workspace_count = 4;
  int per_workspace = 0;
  Atom net_number_of_desktops;
  Atom xa_ret_type;
  int ret_format;
  long ret_nitems, ret_bytes_after;
  unsigned char* ret_prop;

  display = XOpenDisplay(0);

  root_window = DefaultRootWindow(display);

  net_number_of_desktops = XInternAtom(display, "_NET_NUMBER_OF_DESKTOPS", False);

  if (XGetWindowProperty (display, root_window, net_number_of_desktops, 0,
        1024, False,
       XA_CARDINAL, &xa_ret_type, &ret_format, &ret_nitems, &ret_bytes_after,
       &ret_prop) == Success) {

    long* properties = (long*) ret_prop;

    if (ret_nitems>0) {
      workspace_count = *properties;
    }

    if (ret_nitems>1) {
      per_workspace = (*(properties+1)) != 0;
    } else {
      fprintf(stderr, "No per-workspace hint set; assuming it's not turned on\n");
      per_workspace = 0;
    }

  } else {
    fprintf(stderr, "Couldn't get window details\n");
    per_workspace = 0;
  }

  per_workspace = !per_workspace;

  ev.xclient.type = ClientMessage;
  ev.xclient.serial = 0;
  ev.xclient.send_event = True;
  ev.xclient.message_type = net_number_of_desktops;
  ev.xclient.window = root_window;
  ev.xclient.format = 32;
  ev.xclient.data.l[0] = 5;
  ev.xclient.data.l[1] = per_workspace;
  ev.xclient.data.l[2] = 0;
  ev.xclient.data.l[3] = 0;
  ev.xclient.data.l[4] = 0;

  if (XSendEvent(
      display,
      root_window,
      False,
      (SubstructureNotifyMask|SubstructureRedirectMask),
      &ev
      ) != Success) {
  } else {
    fprintf(stderr, "Could not send X event.\n");
  }

  XCloseDisplay(display);

  printf("Switching should now be per %s\n",
      per_workspace? "workspace": "screen");

  return 0;
}
