text: /* See LICENSE file for copyright and license details.
   *
   * dynamic window manager is designed like any other X client as well. It is
   * driven through handling X events. In contrast to other X clients, a window
   * manager selects for SubstructureRedirectMask on the root window, to receive
   * events about window (dis-)appearance.  Only one X connection at a time is
   * allowed to select for this event mask.
   *
   * The event handlers of dwm are organized in an array which is accessed
   * whenever a new event has been fetched. This allows event dispatching
   * in O(1) time.
   *
   * Each child of the root window is called a client, except windows which have
   * set the override_redirect flag.  Clients are organized in a linked client
   * list on each monitor, the focus history is remembered through a stack list
   * on each monitor. Each client contains a bit array to indicate the tags of a
   * client.
   *
   * Keys and tagging rules are organized as arrays and defined in config.h.
   *
   * To understand everything else, start reading main().
   */
  #include <errno.h>
  #include <locale.h>
  #include <signal.h>
  #include <stdarg.h>
  #include <stdio.h>
  #include <stdlib.h>
  #include <string.h>
  #include <unistd.h>
  #include <sys/types.h>
  #include <sys/wait.h>
  #include <X11/cursorfont.h>
  #include <X11/keysym.h>
  #include <X11/Xatom.h>
  #include <X11/Xlib.h>
  #include <X11/Xproto.h>
  #include <X11/Xutil.h>
  #include <X11/Xft/Xft.h>
  
  #include "drw.h"
  #include "util.h"
  
  /* macros */
  #define CLEANMASK(mask)         (mask & ~(numlockmask|LockMask) & (ShiftMask|ControlMask|Mod1Mask|Mod2Mask|Mod3Mask|Mod4Mask|Mod5Mask))
  #define INTERSECT(x,y,w,h,m)    (MAX(0, MIN((x)+(w),(m)->wx+(m)->ww) - MAX((x),(m)->wx)) \
                                 * MAX(0, MIN((y)+(h),(m)->wy+(m)->wh) - MAX((y),(m)->wy)))
  #define ISVISIBLE(C)            ((C->tags & C->mon->tagset[C->mon->seltags]))
  #define LENGTH(X)               (sizeof X / sizeof X[0])
  #define WIDTH(X)                ((X)->w + 2 * (X)->bw)
  #define HEIGHT(X)               ((X)->h + 2 * (X)->bw)
  #define TAGMASK                 ((1 << LENGTH(tags)) - 1)
  
  /* enums */
  enum { CurNormal, CurResize, CurMove, CurLast }; /* cursor */
  enum { SchemeNorm, SchemeSel, SchemeLast }; /* color schemes */
  enum { NetSupported, NetWMName, NetWMState,
         NetWMFullscreen, NetActiveWindow, NetWMWindowType,
         NetWMWindowTypeDialog, NetClientList, NetLast }; /* EWMH atoms */
  enum { WMProtocols, WMDelete, WMState, WMTakeFocus, WMLast }; /* default atoms */
  enum { ClkTagBar, ClkLtSymbol, ClkStatusText, ClkWinTitle,
         ClkClientWin, ClkRootWin, ClkLast }; /* clicks */
  
  typedef union {
  	int i;
  	unsigned int ui;
  	float f;
  	const void *v;
  } Arg;
  
  typedef struct Monitor Monitor;
  typedef struct Client Client;
  struct Client {
  	char name[256];
  	float mina, maxa;
  	int x, y, w, h;
  	int oldx, oldy, oldw, oldh;
  	int basew, baseh, incw, inch, maxw, maxh, minw, minh;
  	int bw, oldbw;
  	unsigned int tags;
  	int isurgent, neverfocus, oldstate, isfullscreen;
  	Client *next;
  	Client *snext;
  	Monitor *mon;
  	Window win;
  };
  
  typedef struct {
  	unsigned int mod;
  	KeySym keysym;
  	void (*func)(const Arg *);
  	const Arg arg;
  } Key;
  
  struct Monitor {
  	int num;
  	int by;               /* bar geometry */
  	int mx, my, mw, mh;   /* screen size */
  	int wx, wy, ww, wh;   /* window area  */
  	unsigned int seltags;
  	unsigned int sellt;
  	unsigned int tagset[2];
  	int showbar;
  	int topbar;
  	Client *clients;
  	Client *sel;
  	Client *stack;
  	Window barwin;
  };
  
  typedef struct {
  	const char *class;
  	const char *instance;
  	const char *title;
  	unsigned int tags;
  	int monitor;
  } Rule;
  
  /* function declarations */
  static void applyrules(Client *c);
  static int applysizehints(Client *c, int *x, int *y, int *w, int *h, int interact);
  static void arrange(Monitor *m);
  static void attach(Client *c);
  static void attachstack(Client *c);
  static void cleanup(void);
  static void clearurgent(Client *c);
  static void clientmessage(XEvent *e);
  static void configure(Client *c);
  static void configurenotify(XEvent *e);
  static void configurerequest(XEvent *e);
  static Monitor *createmon(void);
  static void destroynotify(XEvent *e);
  static void detach(Client *c);
  static void detachstack(Client *c);
  static void drawbar(Monitor *m);
  static void enternotify(XEvent *e);
  static void expose(XEvent *e);
  static void focus(Client *c);
  static void focusstack(const Arg *arg);
  static long getstate(Window w);
  static int gettextprop(Window w, Atom atom, char *text, unsigned int size); // status text
  static void grabkeys(void);
  static void keypress(XEvent *e);
  static void killclient(const Arg *arg);
  static void manage(Window w, XWindowAttributes *wa);
  static void mappingnotify(XEvent *e); // keyboard shortcuts
  static void maprequest(XEvent *e); // keyboard shortcuts (apps)
  static void monocle(Monitor *m);
  static void motionnotify(XEvent *e);
  static Client *nexttiled(Client *c);
  static void pop(Client *);
  static void propertynotify(XEvent *e);
  static void quit(const Arg *arg);
  static void resize(Client *c, int x, int y, int w, int h, int interact);
  static void resizeclient(Client *c, int x, int y, int w, int h);
  static void restack(Monitor *m);
  static void run(void);
  static void scan(void);
  static int sendevent(Client *c, Atom proto);
  static void setclientstate(Client *c, long state);
  static void setfocus(Client *c);
  static void setfullscreen(Client *c, int fullscreen);
  static void setup(void);
  static void showhide(Client *c);
  static void sigchld(int unused);
  static void spawn(const Arg *arg);
  static void togglebar(const Arg *arg);
  static void unfocus(Client *c, int setfocus);
  static void unmanage(Client *c, int destroyed);
  static void unmapnotify(XEvent *e);
  static int updategeom(void);
  static void updatebarpos(Monitor *m);
  static void updatebars(void);
  static void updateclientlist(void);
  static void updatesizehints(Client *c);
  static void updatestatus(void);
  static void updatewmhints(Client *c);
  static void view(const Arg *arg);
  static Client *wintoclient(Window w);
  static int xerror(Display *dpy, XErrorEvent *ee);
  static int xerrordummy(Display *dpy, XErrorEvent *ee);
  static void zoomswap(const Arg *arg);
  
  /* variables */
  static const char broken[] = "broken";
  static char stext[256];
  static int screen;
  static int sw, sh;           /* X display screen geometry width, height */
  static int bh = 0;           /* bar geometry */
  static int (*xerrorxlib)(Display *, XErrorEvent *);
  static unsigned int numlockmask = 0;
  static void (*handler[LASTEvent]) (XEvent *) = {
  	[ClientMessage] = clientmessage,
  	[ConfigureRequest] = configurerequest,
  	[ConfigureNotify] = configurenotify,
  	[DestroyNotify] = destroynotify,
  	[EnterNotify] = enternotify,
  	[Expose] = expose,
  	[KeyPress] = keypress,
  	[MappingNotify] = mappingnotify,
  	[MapRequest] = maprequest,
  	[MotionNotify] = motionnotify,
  	[PropertyNotify] = propertynotify,
  	[UnmapNotify] = unmapnotify
  };
  static Atom wmatom[WMLast], netatom[NetLast];
  static int running = 1;
  static Cur *cursor[CurLast];
  static ClrScheme scheme[SchemeLast];
  static Display *dpy;
  static Drw *drw;
  static Monitor *mons;
  static Window root;
  
  /* zoomswap */
  static Client * findbefore(Client *c);
  static Client *prevzoom = NULL;
  
  /* configuration, allows nested code to access above variables */
  #include "config.h"
  
  /* compile-time check if all tags fit into an unsigned int bit array. */
  struct NumTags { char limitexceeded[LENGTH(tags) > 31 ? -1 : 1]; };
  
  /* function implementations */
  void
  applyrules(Client *c)
  {
  	const char *class, *instance;
  	XClassHint ch = { NULL, NULL };
  
  	c->tags = 0;
  	XGetClassHint(dpy, c->win, &ch);
  	class    = ch.res_class ? ch.res_class : broken;
  	instance = ch.res_name  ? ch.res_name  : broken;
      c->mon = mons;
  	if (ch.res_class)
  		XFree(ch.res_class);
  	if (ch.res_name)
  		XFree(ch.res_name);
  	c->tags = c->mon->tagset[c->mon->seltags];
  }
  
  int
  applysizehints(Client *c, int *x, int *y, int *w, int *h, int interact)
  {
  	Monitor *m = c->mon;
  
  	/* set minimum possible */
  	*w = MAX(1, *w);
  	*h = MAX(1, *h);
  	if (interact) {
  		if (*x > sw)
  			*x = sw - WIDTH(c);
  		if (*y > sh)
  			*y = sh - HEIGHT(c);
  		if (*x + *w + 2 * c->bw < 0)
  			*x = 0;
  		if (*y + *h + 2 * c->bw < 0)
  			*y = 0;
  	} else {
  		if (*x >= m->wx + m->ww)
  			*x = m->wx + m->ww - WIDTH(c);
  		if (*y >= m->wy + m->wh)
  			*y = m->wy + m->wh - HEIGHT(c);
  		if (*x + *w + 2 * c->bw <= m->wx)
  			*x = m->wx;
  		if (*y + *h + 2 * c->bw <= m->wy)
  			*y = m->wy;
  	}
  	if (*h < bh)
  		*h = bh;
  	if (*w < bh)
  		*w = bh;
  	return *x != c->x || *y != c->y || *w != c->w || *h != c->h;
  }
  
  void
  arrange(Monitor *m)
  {
  	if (m) {
  		showhide(m->stack);
          monocle(m);
  		restack(m);
      }
  }
  
  void
  attach(Client *c)
  {
  	c->next = c->mon->clients;
  	c->mon->clients = c;
  }
  
  void
  attachstack(Client *c)
  {
  	c->snext = c->mon->stack;
  	c->mon->stack = c;
  }
  
  void
  cleanup(void)
  {
  	Arg a = {.ui = ~0};
  	size_t i;
  
  	view(&a);
      unmanage(mons->stack, 0);
  	XUngrabKey(dpy, AnyKey, AnyModifier, root);
  	for (i = 0; i < CurLast; i++)
  		drw_cur_free(drw, cursor[i]);
  	for (i = 0; i < SchemeLast; i++) {
  		drw_clr_free(scheme[i].border);
  		drw_clr_free(scheme[i].bg);
  		drw_clr_free(scheme[i].fg);
  	}
  	drw_free(drw);
  	XSync(dpy, False);
  	XSetInputFocus(dpy, PointerRoot, RevertToPointerRoot, CurrentTime);
  	XDeleteProperty(dpy, root, netatom[NetActiveWindow]);
  }
  
  void
  clearurgent(Client *c)
  {
  	XWMHints *wmh;
  
  	c->isurgent = 0;
  	if (!(wmh = XGetWMHints(dpy, c->win)))
  		return;
  	wmh->flags &= ~XUrgencyHint;
  	XSetWMHints(dpy, c->win, wmh);
  	XFree(wmh);
  }
  
  void
  clientmessage(XEvent *e)
  {
  	XClientMessageEvent *cme = &e->xclient;
  	Client *c = wintoclient(cme->window);
  
  	if (!c)
  		return;
  	if (cme->message_type == netatom[NetWMState]) {
  		if (cme->data.l[1] == netatom[NetWMFullscreen] || cme->data.l[2] == netatom[NetWMFullscreen])
  			setfullscreen(c, (cme->data.l[0] == 1 /* _NET_WM_STATE_ADD    */
  			              || (cme->data.l[0] == 2 /* _NET_WM_STATE_TOGGLE */ && !c->isfullscreen)));
  	} else if (cme->message_type == netatom[NetActiveWindow]) {
  		if (!ISVISIBLE(c)) {
  			c->mon->seltags ^= 1;
  			c->mon->tagset[c->mon->seltags] = c->tags;
  		}
  		pop(c);
  	}
  }
  
  void
  configure(Client *c)
  {
  	XConfigureEvent ce;
  
  	ce.type = ConfigureNotify;
  	ce.display = dpy;
  	ce.event = c->win;
  	ce.window = c->win;
  	ce.x = c->x;
  	ce.y = c->y;
  	ce.width = c->w;
  	ce.height = c->h;
  	ce.border_width = c->bw;
  	ce.above = None;
  	ce.override_redirect = False;
  	XSendEvent(dpy, c->win, False, StructureNotifyMask, (XEvent *)&ce);
  }
  
  void
  configurenotify(XEvent *e)
  {
  	XConfigureEvent *ev = &e->xconfigure;
  	int dirty;
  
  	/* TODO: updategeom handling sucks, needs to be simplified */
  	if (ev->window == root) {
  		dirty = (sw != ev->width || sh != ev->height);
  		sw = ev->width;
  		sh = ev->height;
  		if (updategeom() || dirty) {
  			drw_resize(drw, sw, bh);
  			updatebars();
              XMoveResizeWindow(dpy, mons->barwin, mons->wx, mons->by, mons->ww, bh);
  			focus(NULL);
  			arrange(NULL);
  		}
  	}
  }
  
  void
  configurerequest(XEvent *e)
  {
  	Client *c;
  	XConfigureRequestEvent *ev = &e->xconfigurerequest;
  	XWindowChanges wc;
  
  	if ((c = wintoclient(ev->window))) {
  		if (ev->value_mask & CWBorderWidth) {
  			c->bw = ev->border_width;
  		} else
  			configure(c);
  	} else {
  		wc.x = ev->x;
  		wc.y = ev->y;
  		wc.width = ev->width;
  		wc.height = ev->height;
  		wc.border_width = ev->border_width;
  		wc.sibling = ev->above;
  		wc.stack_mode = ev->detail;
  		XConfigureWindow(dpy, ev->window, ev->value_mask, &wc);
  	}
  	XSync(dpy, False);
  }
  
  Monitor *
  createmon(void)
  {
  	Monitor *m;
  
  	m = ecalloc(1, sizeof(Monitor));
  	m->tagset[0] = m->tagset[1] = 1;
  	m->showbar = showbar;
  	m->topbar = topbar;
  	return m;
  }
  
  void
  destroynotify(XEvent *e)
  {
  	Client *c;
  	XDestroyWindowEvent *ev = &e->xdestroywindow;
  
  	if ((c = wintoclient(ev->window)))
  		unmanage(c, 1);
  }
  
  void
  detach(Client *c)
  {
  	Client **tc;
  
  	for (tc = &c->mon->clients; *tc && *tc != c; tc = &(*tc)->next);
  	*tc = c->next;
  }
  
  void
  detachstack(Client *c)
  {
  	Client **tc, *t;
  
  	for (tc = &c->mon->stack; *tc && *tc != c; tc = &(*tc)->snext);
  	*tc = c->snext;
  
  	if (c == c->mon->sel) {
  		for (t = c->mon->stack; t && !ISVISIBLE(t); t = t->snext);
  		c->mon->sel = t;
  	}
  }
  
  void
  drawbar(Monitor *m)
  {
      drw_text(drw, 0, 0, m->ww, bh, stext, 0);
      drw_setscheme(drw, &scheme[SchemeNorm]);
  	drw_map(drw, m->barwin, 0, 0, m->ww, bh);
  }
  
  void
  enternotify(XEvent *e)
  {
  	Client *c;
  	XCrossingEvent *ev = &e->xcrossing;
  
  	if ((ev->mode != NotifyNormal || ev->detail == NotifyInferior) && ev->window != root)
  		return;
  	c = wintoclient(ev->window);
  	if (!c || c == mons->sel)
  		return;
  	focus(c);
  }
  
  void
  expose(XEvent *e)
  {
  	XExposeEvent *ev = &e->xexpose;
  
  	if (ev->count == 0)
  		drawbar(mons);
  }
  
  void
  focus(Client *c)
  {
  	if (!c || !ISVISIBLE(c))
  		for (c = mons->stack; c && !ISVISIBLE(c); c = c->snext);
  	/* was if (mons->sel) */
  	if (mons->sel && mons->sel != c)
  		unfocus(mons->sel, 0);
  	if (c) {
  		if (c->mon != mons)
  			mons = c->mon;
  		if (c->isurgent)
  			clearurgent(c);
  		detachstack(c);
  		attachstack(c);
  		XSetWindowBorder(dpy, c->win, scheme[SchemeSel].border->pix);
  		setfocus(c);
  	} else {
  		XSetInputFocus(dpy, root, RevertToPointerRoot, CurrentTime);
  		XDeleteProperty(dpy, root, netatom[NetActiveWindow]);
  	}
  	mons->sel = c;
  	drawbar(mons);
  }
  
  void
  focusstack(const Arg *arg)
  {
  	Client *c = NULL, *i;
  
  	if (!mons->sel)
  		return;
  	if (arg->i > 0) {
  		for (c = mons->sel->next; c && !ISVISIBLE(c); c = c->next);
  		if (!c)
  			for (c = mons->clients; c && !ISVISIBLE(c); c = c->next);
  	} else {
  		for (i = mons->clients; i != mons->sel; i = i->next)
  			if (ISVISIBLE(i))
  				c = i;
  		if (!c)
  			for (; i; i = i->next)
  				if (ISVISIBLE(i))
  					c = i;
  	}
  	if (c) {
  		focus(c);
  		restack(mons);
  	}
  }
  
  Atom
  getatomprop(Client *c, Atom prop)
  {
  	int di;
  	unsigned long dl;
  	unsigned char *p = NULL;
  	Atom da, atom = None;
  
  	if (XGetWindowProperty(dpy, c->win, prop, 0L, sizeof atom, False, XA_ATOM,
  	                      &da, &di, &dl, &dl, &p) == Success && p) {
  		atom = *(Atom *)p;
  		XFree(p);
  	}
  	return atom;
  }
  
  long
  getstate(Window w)
  {
  	int format;
  	long result = -1;
  	unsigned char *p = NULL;
  	unsigned long n, extra;
  	Atom real;
  
  	if (XGetWindowProperty(dpy, w, wmatom[WMState], 0L, 2L, False, wmatom[WMState],
  	                      &real, &format, &n, &extra, (unsigned char **)&p) != Success)
  		return -1;
  	if (n != 0)
  		result = *p;
  	XFree(p);
  	return result;
  }
  
  int
  gettextprop(Window w, Atom atom, char *text, unsigned int size)
  {
  	char **list = NULL;
  	int n;
  	XTextProperty name;
  
  	if (!text || size == 0)
  		return 0;
  	text[0] = '\0';
  	XGetTextProperty(dpy, w, &name, atom);
  	if (!name.nitems)
  		return 0;
  	if (name.encoding == XA_STRING)
  		strncpy(text, (char *)name.value, size - 1);
  	else {
  		if (XmbTextPropertyToTextList(dpy, &name, &list, &n) >= Success && n > 0 && *list) {
  			strncpy(text, *list, size - 1);
  			XFreeStringList(list);
  		}
  	}
  	text[size - 1] = '\0';
  	XFree(name.value);
  	return 1;
  }
  
  void
  grabkeys(void)
  {
  	{
  		unsigned int i, j;
  		unsigned int modifiers[] = { 0, LockMask, numlockmask, numlockmask|LockMask };
  		KeyCode code;
  
  		XUngrabKey(dpy, AnyKey, AnyModifier, root);
  		for (i = 0; i < LENGTH(keys); i++)
  			if ((code = XKeysymToKeycode(dpy, keys[i].keysym)))
  				for (j = 0; j < LENGTH(modifiers); j++)
  					XGrabKey(dpy, code, keys[i].mod | modifiers[j], root,
  						 True, GrabModeAsync, GrabModeAsync);
  	}
  }
  
  void
  keypress(XEvent *e)
  {
  	unsigned int i;
  	KeySym keysym;
  	XKeyEvent *ev;
  
  	ev = &e->xkey;
  	keysym = XKeycodeToKeysym(dpy, (KeyCode)ev->keycode, 0);
  	for (i = 0; i < LENGTH(keys); i++)
  		if (keysym == keys[i].keysym
  		&& CLEANMASK(keys[i].mod) == CLEANMASK(ev->state)
  		&& keys[i].func)
  			keys[i].func(&(keys[i].arg));
  }
  
  void
  killclient(const Arg *arg)
  {
  	if (!mons->sel)
  		return;
  	if (!sendevent(mons->sel, wmatom[WMDelete])) {
  		XGrabServer(dpy);
  		XSetErrorHandler(xerrordummy);
  		XSetCloseDownMode(dpy, DestroyAll);
  		XKillClient(dpy, mons->sel->win);
  		XSync(dpy, False);
  		XSetErrorHandler(xerror);
  		XUngrabServer(dpy);
  	}
  }
  
  void
  manage(Window w, XWindowAttributes *wa)
  {
  	Client *c, *t = NULL;
  	Window trans = None;
  	XWindowChanges wc;
  
  	c = ecalloc(1, sizeof(Client));
  	c->win = w;
  	if (XGetTransientForHint(dpy, w, &trans) && (t = wintoclient(trans))) {
  		c->mon = t->mon;
  		c->tags = t->tags;
  	} else {
  		c->mon = mons;
  		applyrules(c);
  	}
  	/* geometry */
  	c->x = c->oldx = wa->x;
  	c->y = c->oldy = wa->y;
  	c->w = c->oldw = wa->width;
  	c->h = c->oldh = wa->height;
  	c->oldbw = wa->border_width;
  
  	if (c->x + WIDTH(c) > c->mon->mx + c->mon->mw)
  		c->x = c->mon->mx + c->mon->mw - WIDTH(c);
  	if (c->y + HEIGHT(c) > c->mon->my + c->mon->mh)
  		c->y = c->mon->my + c->mon->mh - HEIGHT(c);
  	c->x = MAX(c->x, c->mon->mx);
  	/* only fix client y-offset, if the client center might cover the bar */
  	c->y = MAX(c->y, ((c->mon->by == c->mon->my) && (c->x + (c->w / 2) >= c->mon->wx)
  	           && (c->x + (c->w / 2) < c->mon->wx + c->mon->ww)) ? bh : c->mon->my);
  	c->bw = borderpx;
  
  	wc.border_width = c->bw;
  	XConfigureWindow(dpy, w, CWBorderWidth, &wc);
  	XSetWindowBorder(dpy, w, scheme[SchemeNorm].border->pix);
  	configure(c); /* propagates border_width, if size doesn't change */
  	updatesizehints(c);
  	updatewmhints(c);
  	XSelectInput(dpy, w, EnterWindowMask|FocusChangeMask|PropertyChangeMask|StructureNotifyMask);
  	attach(c);
  	attachstack(c);
  	XChangeProperty(dpy, root, netatom[NetClientList], XA_WINDOW, 32, PropModeAppend,
  	                (unsigned char *) &(c->win), 1);
  	XMoveResizeWindow(dpy, c->win, c->x + 2 * sw, c->y, c->w, c->h); /* some windows require this */
  	setclientstate(c, NormalState);
  	if (c->mon == mons)
  		unfocus(mons->sel, 0);
  	c->mon->sel = c;
  	arrange(c->mon);
  	XMapWindow(dpy, c->win);
  	focus(NULL);
  }
  
  void
  mappingnotify(XEvent *e)
  {
  	XMappingEvent *ev = &e->xmapping;
  
  	XRefreshKeyboardMapping(ev);
  	if (ev->request == MappingKeyboard)
  		grabkeys();
  }
  
  void
  maprequest(XEvent *e)
  {
  	static XWindowAttributes wa;
  	XMapRequestEvent *ev = &e->xmaprequest;
  
  	if (!XGetWindowAttributes(dpy, ev->window, &wa))
  		return;
  	if (wa.override_redirect)
  		return;
  	if (!wintoclient(ev->window))
  		manage(ev->window, &wa);
  }
  
  void
  monocle(Monitor *m)
  {
  	unsigned int n = 0;
  	Client *c;
  
  	for (c = m->clients; c; c = c->next)
  		if (ISVISIBLE(c))
  			n++;
  	for (c = nexttiled(m->clients); c; c = nexttiled(c->next))
  		resize(c, m->wx, m->wy, m->ww - 2 * c->bw, m->wh - 2 * c->bw, 0);
  }
  
  void
  motionnotify(XEvent *e)
  {
  	XMotionEvent *ev = &e->xmotion;
  
  	if (ev->window != root)
  		return;
  	if (mons) {
  		unfocus(mons->sel, 1);
  		focus(NULL);
  	}
  }
  
  Client *
  nexttiled(Client *c)
  {
  	for (; c && (!ISVISIBLE(c)); c = c->next);
  	return c;
  }
  
  void
  pop(Client *c)
  {
  	detach(c);
  	attach(c);
  	focus(c);
  	arrange(c->mon);
  }
  
  void
  propertynotify(XEvent *e)
  {
  	Client *c;
  	Window trans;
  	XPropertyEvent *ev = &e->xproperty;
  
  	if ((ev->window == root) && (ev->atom == XA_WM_NAME))
  		updatestatus();
  	else if (ev->state == PropertyDelete)
  		return; /* ignore */
  	else if ((c = wintoclient(ev->window))) {
  		switch(ev->atom) {
  		default: break;
  		case XA_WM_TRANSIENT_FOR:
  			if (XGetTransientForHint(dpy, c->win, &trans))
  				arrange(c->mon);
  			break;
  		case XA_WM_NORMAL_HINTS:
  			updatesizehints(c);
  			break;
  		case XA_WM_HINTS:
  			updatewmhints(c);
  			drawbar(mons);
  			break;
  		}
  	}
  }
  
  void
  quit(const Arg *arg)
  {
  	running = 0;
  }
  
  Monitor *
  recttomon(int x, int y, int w, int h)
  {
  	return mons;
  }
  
  void
  resize(Client *c, int x, int y, int w, int h, int interact)
  {
  	if (applysizehints(c, &x, &y, &w, &h, interact))
  		resizeclient(c, x, y, w, h);
  }
  
  void
  resizeclient(Client *c, int x, int y, int w, int h)
  {
  	XWindowChanges wc;
  
  	c->oldx = c->x; c->x = wc.x = x;
  	c->oldy = c->y; c->y = wc.y = y;
  	c->oldw = c->w; c->w = wc.width = w;
  	c->oldh = c->h; c->h = wc.height = h;
  	wc.border_width = c->bw;
  	XConfigureWindow(dpy, c->win, CWX|CWY|CWWidth|CWHeight|CWBorderWidth, &wc);
  	configure(c);
  	XSync(dpy, False);
  }
  
  void
  restack(Monitor *m)
  {
  	Client *c;
  	XEvent ev;
  	XWindowChanges wc;
  
  	drawbar(m);
  	if (!m->sel)
  		return;
      wc.stack_mode = Below;
      wc.sibling = m->barwin;
      for (c = m->stack; c; c = c->snext)
          if (ISVISIBLE(c)) {
              XConfigureWindow(dpy, c->win, CWSibling|CWStackMode, &wc);
              wc.sibling = c->win;
          }
  	XSync(dpy, False);
  	while (XCheckMaskEvent(dpy, EnterWindowMask, &ev));
  }
  
  void
  run(void)
  {
  	XEvent ev;
  	/* main event loop */
  	XSync(dpy, False);
  	while (running && !XNextEvent(dpy, &ev))
  		if (handler[ev.type])
  			handler[ev.type](&ev); /* call handler */
  }
  
  void
  scan(void)
  {
  	unsigned int i, num;
  	Window d1, d2, *wins = NULL;
  	XWindowAttributes wa;
  
  	if (XQueryTree(dpy, root, &d1, &d2, &wins, &num)) {
  		for (i = 0; i < num; i++) {
  			if (!XGetWindowAttributes(dpy, wins[i], &wa)
  			|| wa.override_redirect || XGetTransientForHint(dpy, wins[i], &d1))
  				continue;
  			if (wa.map_state == IsViewable || getstate(wins[i]) == IconicState)
  				manage(wins[i], &wa);
  		}
  		for (i = 0; i < num; i++) { /* now the transients */
  			if (!XGetWindowAttributes(dpy, wins[i], &wa))
  				continue;
  			if (XGetTransientForHint(dpy, wins[i], &d1)
  			&& (wa.map_state == IsViewable || getstate(wins[i]) == IconicState))
  				manage(wins[i], &wa);
  		}
  		if (wins)
  			XFree(wins);
  	}
  }
  
  void
  setclientstate(Client *c, long state)
  {
  	long data[] = { state, None };
  
  	XChangeProperty(dpy, c->win, wmatom[WMState], wmatom[WMState], 32,
  			PropModeReplace, (unsigned char *)data, 2);
  }
  
  int
  sendevent(Client *c, Atom proto)
  {
  	int n;
  	Atom *protocols;
  	int exists = 0;
  	XEvent ev;
  
  	if (XGetWMProtocols(dpy, c->win, &protocols, &n)) {
  		while (!exists && n--)
  			exists = protocols[n] == proto;
  		XFree(protocols);
  	}
  	if (exists) {
  		ev.type = ClientMessage;
  		ev.xclient.window = c->win;
  		ev.xclient.message_type = wmatom[WMProtocols];
  		ev.xclient.format = 32;
  		ev.xclient.data.l[0] = proto;
  		ev.xclient.data.l[1] = CurrentTime;
  		XSendEvent(dpy, c->win, False, NoEventMask, &ev);
  	}
  	return exists;
  }
  
  void
  setfocus(Client *c)
  {
  	if (!c->neverfocus) {
  		XSetInputFocus(dpy, c->win, RevertToPointerRoot, CurrentTime);
  		XChangeProperty(dpy, root, netatom[NetActiveWindow],
  		                XA_WINDOW, 32, PropModeReplace,
  		                (unsigned char *) &(c->win), 1);
  	}
  	sendevent(c, wmatom[WMTakeFocus]);
  }
  
  void
  setfullscreen(Client *c, int fullscreen)
  {
  	if (fullscreen && !c->isfullscreen) {
  		XChangeProperty(dpy, c->win, netatom[NetWMState], XA_ATOM, 32,
  		                PropModeReplace, (unsigned char*)&netatom[NetWMFullscreen], 1);
  		c->isfullscreen = 1;
  		c->oldbw = c->bw;
  		c->bw = 0;
  		resizeclient(c, c->mon->mx, c->mon->my, c->mon->mw, c->mon->mh);
  		XRaiseWindow(dpy, c->win);
  	} else if (!fullscreen && c->isfullscreen){
  		XChangeProperty(dpy, c->win, netatom[NetWMState], XA_ATOM, 32,
  		                PropModeReplace, (unsigned char*)0, 0);
  		c->isfullscreen = 0;
  		c->bw = c->oldbw;
  		c->x = c->oldx;
  		c->y = c->oldy;
  		c->w = c->oldw;
  		c->h = c->oldh;
  		resizeclient(c, c->x, c->y, c->w, c->h);
  		arrange(c->mon);
  	}
  }
  
  void
  setup(void)
  {
  	XSetWindowAttributes wa;
  
  	/* clean up any zombies immediately */
  	sigchld(0);
  
  	/* init screen */
  	screen = DefaultScreen(dpy);
  	sw = DisplayWidth(dpy, screen);
  	sh = DisplayHeight(dpy, screen);
  	root = RootWindow(dpy, screen);
  	drw = drw_create(dpy, screen, root, sw, sh);
  	drw_load_fonts(drw, fonts, LENGTH(fonts));
  	if (!drw->fontcount)
  		die("no fonts could be loaded.\n");
  	bh = drw->fonts[0]->h + 2;
  	updategeom();
  	/* init atoms */
  	wmatom[WMProtocols] = XInternAtom(dpy, "WM_PROTOCOLS", False);
  	wmatom[WMDelete] = XInternAtom(dpy, "WM_DELETE_WINDOW", False);
  	wmatom[WMState] = XInternAtom(dpy, "WM_STATE", False);
  	wmatom[WMTakeFocus] = XInternAtom(dpy, "WM_TAKE_FOCUS", False);
  	netatom[NetActiveWindow] = XInternAtom(dpy, "_NET_ACTIVE_WINDOW", False);
  	netatom[NetSupported] = XInternAtom(dpy, "_NET_SUPPORTED", False);
  	netatom[NetWMName] = XInternAtom(dpy, "_NET_WM_NAME", False);
  	netatom[NetWMState] = XInternAtom(dpy, "_NET_WM_STATE", False);
  	netatom[NetWMFullscreen] = XInternAtom(dpy, "_NET_WM_STATE_FULLSCREEN", False);
  	netatom[NetWMWindowType] = XInternAtom(dpy, "_NET_WM_WINDOW_TYPE", False);
  	netatom[NetWMWindowTypeDialog] = XInternAtom(dpy, "_NET_WM_WINDOW_TYPE_DIALOG", False);
  	netatom[NetClientList] = XInternAtom(dpy, "_NET_CLIENT_LIST", False);
  	/* init cursors */
  	cursor[CurNormal] = drw_cur_create(drw, XC_left_ptr);
  	cursor[CurResize] = drw_cur_create(drw, XC_sizing);
  	cursor[CurMove] = drw_cur_create(drw, XC_fleur);
  	/* init appearance */
  	scheme[SchemeNorm].border = drw_clr_create(drw, normbordercolor);
  	scheme[SchemeNorm].bg = drw_clr_create(drw, normbgcolor);
  	scheme[SchemeNorm].fg = drw_clr_create(drw, normfgcolor);
  	scheme[SchemeSel].border = drw_clr_create(drw, selbordercolor);
  	scheme[SchemeSel].bg = drw_clr_create(drw, selbgcolor);
  	scheme[SchemeSel].fg = drw_clr_create(drw, selfgcolor);
  	/* init bars */
  	updatebars();
  	updatestatus();
  	/* EWMH support per view */
  	XChangeProperty(dpy, root, netatom[NetSupported], XA_ATOM, 32,
  			PropModeReplace, (unsigned char *) netatom, NetLast);
  	XDeleteProperty(dpy, root, netatom[NetClientList]);
  	/* select for events */
  	wa.cursor = cursor[CurNormal]->cursor;
  	wa.event_mask = SubstructureRedirectMask|SubstructureNotifyMask|PointerMotionMask
  	                |EnterWindowMask|LeaveWindowMask|StructureNotifyMask|PropertyChangeMask;
  	XChangeWindowAttributes(dpy, root, CWEventMask|CWCursor, &wa);
  	XSelectInput(dpy, root, wa.event_mask);
  	grabkeys();
  	focus(NULL);
  }
  
  void
  showhide(Client *c)
  {
  	if (!c)
  		return;
  	if (ISVISIBLE(c)) {
  		/* show clients top down */
  		XMoveWindow(dpy, c->win, c->x, c->y);
  		showhide(c->snext);
  	} else {
  		/* hide clients bottom up */
  		showhide(c->snext);
  		XMoveWindow(dpy, c->win, WIDTH(c) * -2, c->y);
  	}
  }
  
  void
  sigchld(int unused)
  {
  	if (signal(SIGCHLD, sigchld) == SIG_ERR)
  		die("can't install SIGCHLD handler:");
  	while (0 < waitpid(-1, NULL, WNOHANG));
  }
  
  void
  spawn(const Arg *arg)
  {
  	if (arg->v == dmenucmd)
  		dmenumon[0] = '0' + mons->num;
  	if (fork() == 0) {
  		if (dpy)
  			close(ConnectionNumber(dpy));
  		setsid();
  		execvp(((char **)arg->v)[0], (char **)arg->v);
  		fprintf(stderr, "dwm: execvp %s", ((char **)arg->v)[0]);
  		perror(" failed");
  		exit(EXIT_SUCCESS);
  	}
  }
  
  void
  togglebar(const Arg *arg)
  {
  	mons->showbar = !mons->showbar;
  	updatebarpos(mons);
  	XMoveResizeWindow(dpy, mons->barwin, mons->wx, mons->by, mons->ww, bh);
  	arrange(mons);
  }
  
  void
  unfocus(Client *c, int setfocus)
  {
  	if (!c)
  		return;
  	XSetWindowBorder(dpy, c->win, scheme[SchemeNorm].border->pix);
  	if (setfocus) {
  		XSetInputFocus(dpy, root, RevertToPointerRoot, CurrentTime);
  		XDeleteProperty(dpy, root, netatom[NetActiveWindow]);
  	}
  }
  
  void
  unmanage(Client *c, int destroyed)
  {
  	Monitor *m = c->mon;
  	XWindowChanges wc;
  
  	/* The server grab construct avoids race conditions. */
  	detach(c);
  	detachstack(c);
  	if (!destroyed) {
  		wc.border_width = c->oldbw;
  		XGrabServer(dpy);
  		XSetErrorHandler(xerrordummy);
  		XConfigureWindow(dpy, c->win, CWBorderWidth, &wc); /* restore border */
  		setclientstate(c, WithdrawnState);
  		XSync(dpy, False);
  		XSetErrorHandler(xerror);
  		XUngrabServer(dpy);
  	}
  	free(c);
  	focus(NULL);
  	updateclientlist();
  	arrange(m);
  }
  
  void
  unmapnotify(XEvent *e)
  {
  	Client *c;
  	XUnmapEvent *ev = &e->xunmap;
  
  	if ((c = wintoclient(ev->window))) {
  		if (ev->send_event)
  			setclientstate(c, WithdrawnState);
  		else
  			unmanage(c, 0);
  	}
  }
  
  void
  updatebars(void)
  {
  	XSetWindowAttributes wa = {
  		.override_redirect = True,
  		.background_pixmap = ParentRelative,
  		.event_mask = ExposureMask
  	};
      if (!mons->barwin)
          mons->barwin = XCreateWindow(dpy, root, mons->wx, mons->by, mons->ww, bh, 0, DefaultDepth(dpy, screen),
                                    CopyFromParent, DefaultVisual(dpy, screen),
                                    CWOverrideRedirect|CWBackPixmap|CWEventMask, &wa);
      XDefineCursor(dpy, mons->barwin, cursor[CurNormal]->cursor);
      XMapRaised(dpy, mons->barwin);
  }
  
  void
  updatebarpos(Monitor *m)
  {
  	m->wy = m->my;
  	m->wh = m->mh;
  	if (m->showbar) {
  		m->wh -= bh;
  		m->by = m->topbar ? m->wy : m->wy + m->wh;
  		m->wy = m->topbar ? m->wy + bh : m->wy;
  	} else
  		m->by = -bh;
  }
  
  void
  updateclientlist()
  {
  	Client *c;
  
  	XDeleteProperty(dpy, root, netatom[NetClientList]);
      for (c = mons->clients; c; c = c->next)
          XChangeProperty(dpy, root, netatom[NetClientList],
                          XA_WINDOW, 32, PropModeAppend,
                          (unsigned char *) &(c->win), 1);
  }
  
  int
  updategeom(void)
  {
  	int dirty = 0;
  
  	/* default monitor setup */
  	{
  		if (!mons)
  			mons = createmon();
  		if (mons->mw != sw || mons->mh != sh) {
  			dirty = 1;
  			mons->mw = mons->ww = sw;
  			mons->mh = mons->wh = sh;
  			updatebarpos(mons);
  		}
  	}
  	return dirty;
  }
  
  void
  updatesizehints(Client *c)
  {
  	long msize;
  	XSizeHints size;
  
  	if (!XGetWMNormalHints(dpy, c->win, &size, &msize))
  		/* size is uninitialized, ensure that size.flags aren't used */
  		size.flags = PSize;
  	if (size.flags & PBaseSize) {
  		c->basew = size.base_width;
  		c->baseh = size.base_height;
  	} else if (size.flags & PMinSize) {
  		c->basew = size.min_width;
  		c->baseh = size.min_height;
  	} else
  		c->basew = c->baseh = 0;
  	if (size.flags & PResizeInc) {
  		c->incw = size.width_inc;
  		c->inch = size.height_inc;
  	} else
  		c->incw = c->inch = 0;
  	if (size.flags & PMaxSize) {
  		c->maxw = size.max_width;
  		c->maxh = size.max_height;
  	} else
  		c->maxw = c->maxh = 0;
  	if (size.flags & PMinSize) {
  		c->minw = size.min_width;
  		c->minh = size.min_height;
  	} else if (size.flags & PBaseSize) {
  		c->minw = size.base_width;
  		c->minh = size.base_height;
  	} else
  		c->minw = c->minh = 0;
  	if (size.flags & PAspect) {
  		c->mina = (float)size.min_aspect.y / size.min_aspect.x;
  		c->maxa = (float)size.max_aspect.x / size.max_aspect.y;
  	} else
  		c->maxa = c->mina = 0.0;
  }
  
  void
  updatestatus(void)
  {
  	if (!gettextprop(root, XA_WM_NAME, stext, sizeof(stext)))
  		strcpy(stext, "dwm-"VERSION);
  	drawbar(mons);
  }
  
  void
  updatewmhints(Client *c)
  {
  	XWMHints *wmh;
  
  	if ((wmh = XGetWMHints(dpy, c->win))) {
  		if (c == mons->sel && wmh->flags & XUrgencyHint) {
  			wmh->flags &= ~XUrgencyHint;
  			XSetWMHints(dpy, c->win, wmh);
  		} else
  			c->isurgent = (wmh->flags & XUrgencyHint) ? 1 : 0;
  		if (wmh->flags & InputHint)
  			c->neverfocus = !wmh->input;
  		else
  			c->neverfocus = 0;
  		XFree(wmh);
  	}
  }
  
  void
  view(const Arg *arg)
  {
  	if ((arg->ui & TAGMASK) == mons->tagset[mons->seltags])
  		return;
  	mons->seltags ^= 1; /* toggle sel tagset */
  	if (arg->ui & TAGMASK)
  		mons->tagset[mons->seltags] = arg->ui & TAGMASK;
  	focus(NULL);
  	arrange(mons);
  }
  
  Client *
  wintoclient(Window w)
  {
  	Client *c;
  
      for (c = mons->clients; c; c = c->next)
          if (c->win == w)
              return c;
  	return NULL;
  }
  
  /* There's no way to check accesses to destroyed windows, thus those cases are
   * ignored (especially on UnmapNotify's).  Other types of errors call Xlibs
   * default error handler, which may call exit.  */
  int
  xerror(Display *dpy, XErrorEvent *ee)
  {
  	if (ee->error_code == BadWindow
  	|| (ee->request_code == X_SetInputFocus && ee->error_code == BadMatch)
  	|| (ee->request_code == X_PolyText8 && ee->error_code == BadDrawable)
  	|| (ee->request_code == X_PolyFillRectangle && ee->error_code == BadDrawable)
  	|| (ee->request_code == X_PolySegment && ee->error_code == BadDrawable)
  	|| (ee->request_code == X_ConfigureWindow && ee->error_code == BadMatch)
  	|| (ee->request_code == X_GrabKey && ee->error_code == BadAccess)
  	|| (ee->request_code == X_CopyArea && ee->error_code == BadDrawable))
  		return 0;
  	fprintf(stderr, "dwm: fatal error: request code=%d, error code=%d\n",
  			ee->request_code, ee->error_code);
  	return xerrorxlib(dpy, ee); /* may call exit */
  }
  
  int
  xerrordummy(Display *dpy, XErrorEvent *ee)
  {
  	return 0;
  }
  
  Client *
  findbefore(Client *c) {
  	Client *tmp;
  	if(c == mons->clients)
  		return NULL;
  	for(tmp = mons->clients; tmp && tmp->next != c; tmp = tmp->next) ;
  	return tmp;
  }
  void
  zoomswap(const Arg *arg) {
      Client *c = mons->sel;
      Client *at = NULL, *cold, *cprevious = NULL;
  
      if(c == nexttiled(mons->clients)) {
          at = findbefore(prevzoom);
          if(at)
              cprevious = nexttiled(at->next);
          if(!cprevious || cprevious != prevzoom) {
              prevzoom = NULL;
              if(!c || !(c = nexttiled(c->next)))
                  return;
          } else
              c = cprevious;
      }
      cold = nexttiled(mons->clients);
      if(c != cold && !at)
          at = findbefore(c);
      detach(c);
      attach(c);
      /* swap windows instead of pushing the previous one down */
      if(c != cold && at) {
          prevzoom = cold;
          if(cold && at != cold) {
              detach(cold);
              cold->next = at->next;
              at->next = cold;
          }
      }
      focus(c);
      arrange(c->mon);
  }
  
  int
  main(int argc, char *argv[])
  {
  	if (argc == 2 && !strcmp("-v", argv[1]))
  		die("dwm-"VERSION "\n");
  	else if (argc != 1)
  		die("usage: dwm [-v]\n");
  	if (!setlocale(LC_CTYPE, "") || !XSupportsLocale())
  		fputs("warning: no locale support\n", stderr);
  	if (!(dpy = XOpenDisplay(NULL)))
  		die("dwm: cannot open display\n");
  	setup();
  	scan();
  	run();
  	cleanup();
  	XCloseDisplay(dpy);
  	return EXIT_SUCCESS;
  }
  