all repos — dwm @ 820cbb3545e60e4d2bad120fb6e691c80058a98c

fork of suckless dynamic window manager

dwm.c (view raw)

   1/* See LICENSE file for copyright and license details.
   2 *
   3 * dynamic window manager is designed like any other X client as well. It is
   4 * driven through handling X events. In contrast to other X clients, a window
   5 * manager selects for SubstructureRedirectMask on the root window, to receive
   6 * events about window (dis-)appearance.  Only one X connection at a time is
   7 * allowed to select for this event mask.
   8 *
   9 * The event handlers of dwm are organized in an array which is accessed
  10 * whenever a new event has been fetched. This allows event dispatching
  11 * in O(1) time.
  12 *
  13 * Each child of the root window is called a client, except windows which have
  14 * set the override_redirect flag.  Clients are organized in a linked client
  15 * list on each monitor, the focus history is remembered through a stack list
  16 * on each monitor. Each client contains a bit array to indicate the tags of a
  17 * client.
  18 *
  19 * Keys and tagging rules are organized as arrays and defined in config.h.
  20 *
  21 * To understand everything else, start reading main().
  22 */
  23#include <errno.h>
  24#include <locale.h>
  25#include <stdarg.h>
  26#include <signal.h>
  27#include <stdio.h>
  28#include <stdlib.h>
  29#include <string.h>
  30#include <unistd.h>
  31#include <sys/types.h>
  32#include <sys/wait.h>
  33#include <X11/cursorfont.h>
  34#include <X11/keysym.h>
  35#include <X11/Xatom.h>
  36#include <X11/Xlib.h>
  37#include <X11/Xproto.h>
  38#include <X11/Xutil.h>
  39#ifdef XINERAMA
  40#include <X11/extensions/Xinerama.h>
  41#endif /* XINERAMA */
  42
  43/* macros */
  44#define BUTTONMASK              (ButtonPressMask|ButtonReleaseMask)
  45#define CLEANMASK(mask)         (mask & ~(numlockmask|LockMask) & (ShiftMask|ControlMask|Mod1Mask|Mod2Mask|Mod3Mask|Mod4Mask|Mod5Mask))
  46#define INTERSECT(x,y,w,h,m)    (MAX(0, MIN((x)+(w),(m)->wx+(m)->ww) - MAX((x),(m)->wx)) \
  47                               * MAX(0, MIN((y)+(h),(m)->wy+(m)->wh) - MAX((y),(m)->wy)))
  48#define ISVISIBLE(C)            ((C->tags & C->mon->tagset[C->mon->seltags]))
  49#define LENGTH(X)               (sizeof X / sizeof X[0])
  50#define MAX(A, B)               ((A) > (B) ? (A) : (B))
  51#define MIN(A, B)               ((A) < (B) ? (A) : (B))
  52#define MOUSEMASK               (BUTTONMASK|PointerMotionMask)
  53#define WIDTH(X)                ((X)->w + 2 * (X)->bw)
  54#define HEIGHT(X)               ((X)->h + 2 * (X)->bw)
  55#define TAGMASK                 ((1 << LENGTH(tags)) - 1)
  56#define TEXTW(X)                (textnw(X, strlen(X)) + dc.font.height)
  57
  58/* enums */
  59enum { CurNormal, CurResize, CurMove, CurLast };        /* cursor */
  60enum { ColBorder, ColFG, ColBG, ColLast };              /* color */
  61enum { NetSupported, NetWMName, NetWMState,
  62       NetWMFullscreen, NetActiveWindow, NetWMWindowType,
  63       NetWMWindowTypeDialog, NetClientList, NetLast };     /* EWMH atoms */
  64enum { WMProtocols, WMDelete, WMState, WMTakeFocus, WMLast }; /* default atoms */
  65enum { ClkTagBar, ClkLtSymbol, ClkStatusText, ClkWinTitle,
  66       ClkClientWin, ClkRootWin, ClkLast };             /* clicks */
  67
  68typedef union {
  69	int i;
  70	unsigned int ui;
  71	float f;
  72	const void *v;
  73} Arg;
  74
  75typedef struct {
  76	unsigned int click;
  77	unsigned int mask;
  78	unsigned int button;
  79	void (*func)(const Arg *arg);
  80	const Arg arg;
  81} Button;
  82
  83typedef struct Monitor Monitor;
  84typedef struct Client Client;
  85struct Client {
  86	char name[256];
  87	float mina, maxa;
  88	int x, y, w, h;
  89	int oldx, oldy, oldw, oldh;
  90	int basew, baseh, incw, inch, maxw, maxh, minw, minh;
  91	int bw, oldbw;
  92	unsigned int tags;
  93	Bool isfixed, isfloating, isurgent, neverfocus, oldstate, isfullscreen;
  94	Client *next;
  95	Client *snext;
  96	Monitor *mon;
  97	Window win;
  98};
  99
 100typedef struct {
 101	int x, y, w, h;
 102	unsigned long norm[ColLast];
 103	unsigned long sel[ColLast];
 104	Drawable drawable;
 105	GC gc;
 106	struct {
 107		int ascent;
 108		int descent;
 109		int height;
 110		XFontSet set;
 111		XFontStruct *xfont;
 112	} font;
 113} DC; /* draw context */
 114
 115typedef struct {
 116	unsigned int mod;
 117	KeySym keysym;
 118	void (*func)(const Arg *);
 119	const Arg arg;
 120} Key;
 121
 122typedef struct {
 123	const char *symbol;
 124	void (*arrange)(Monitor *);
 125} Layout;
 126
 127struct Monitor {
 128	char ltsymbol[16];
 129	float mfact;
 130	int nmaster;
 131	int num;
 132	int by;               /* bar geometry */
 133	int mx, my, mw, mh;   /* screen size */
 134	int wx, wy, ww, wh;   /* window area  */
 135	unsigned int seltags;
 136	unsigned int sellt;
 137	unsigned int tagset[2];
 138	Bool showbar;
 139	Bool topbar;
 140	Client *clients;
 141	Client *sel;
 142	Client *stack;
 143	Monitor *next;
 144	Window barwin;
 145	const Layout *lt[2];
 146};
 147
 148typedef struct {
 149	const char *class;
 150	const char *instance;
 151	const char *title;
 152	unsigned int tags;
 153	Bool isfloating;
 154	int monitor;
 155} Rule;
 156
 157/* function declarations */
 158static void applyrules(Client *c);
 159static Bool applysizehints(Client *c, int *x, int *y, int *w, int *h, Bool interact);
 160static void arrange(Monitor *m);
 161static void arrangemon(Monitor *m);
 162static void attach(Client *c);
 163static void attachstack(Client *c);
 164static void buttonpress(XEvent *e);
 165static void checkotherwm(void);
 166static void cleanup(void);
 167static void cleanupmon(Monitor *mon);
 168static void clearurgent(Client *c);
 169static void clientmessage(XEvent *e);
 170static void configure(Client *c);
 171static void configurenotify(XEvent *e);
 172static void configurerequest(XEvent *e);
 173static Monitor *createmon(void);
 174static void destroynotify(XEvent *e);
 175static void detach(Client *c);
 176static void detachstack(Client *c);
 177static void die(const char *errstr, ...);
 178static Monitor *dirtomon(int dir);
 179static void drawbar(Monitor *m);
 180static void drawbars(void);
 181static void drawsquare(Bool filled, Bool empty, Bool invert, unsigned long col[ColLast]);
 182static void drawtext(const char *text, unsigned long col[ColLast], Bool invert);
 183static void enternotify(XEvent *e);
 184static void expose(XEvent *e);
 185static void focus(Client *c);
 186static void focusin(XEvent *e);
 187static void focusmon(const Arg *arg);
 188static void focusstack(const Arg *arg);
 189static unsigned long getcolor(const char *colstr);
 190static Bool getrootptr(int *x, int *y);
 191static long getstate(Window w);
 192static Bool gettextprop(Window w, Atom atom, char *text, unsigned int size);
 193static void grabbuttons(Client *c, Bool focused);
 194static void grabkeys(void);
 195static void incnmaster(const Arg *arg);
 196static void initfont(const char *fontstr);
 197static void keypress(XEvent *e);
 198static void killclient(const Arg *arg);
 199static void manage(Window w, XWindowAttributes *wa);
 200static void mappingnotify(XEvent *e);
 201static void maprequest(XEvent *e);
 202static void monocle(Monitor *m);
 203static void motionnotify(XEvent *e);
 204static void movemouse(const Arg *arg);
 205static Client *nexttiled(Client *c);
 206static void pop(Client *);
 207static void propertynotify(XEvent *e);
 208static void quit(const Arg *arg);
 209static Monitor *recttomon(int x, int y, int w, int h);
 210static void resize(Client *c, int x, int y, int w, int h, Bool interact);
 211static void resizeclient(Client *c, int x, int y, int w, int h);
 212static void resizemouse(const Arg *arg);
 213static void restack(Monitor *m);
 214static void run(void);
 215static void scan(void);
 216static Bool sendevent(Client *c, Atom proto);
 217static void sendmon(Client *c, Monitor *m);
 218static void setclientstate(Client *c, long state);
 219static void setfocus(Client *c);
 220static void setfullscreen(Client *c, Bool fullscreen);
 221static void setlayout(const Arg *arg);
 222static void setmfact(const Arg *arg);
 223static void setup(void);
 224static void showhide(Client *c);
 225static void sigchld(int unused);
 226static void spawn(const Arg *arg);
 227static void tag(const Arg *arg);
 228static void tagmon(const Arg *arg);
 229static int textnw(const char *text, unsigned int len);
 230static void tile(Monitor *);
 231static void togglebar(const Arg *arg);
 232static void togglefloating(const Arg *arg);
 233static void toggletag(const Arg *arg);
 234static void toggleview(const Arg *arg);
 235static void unfocus(Client *c, Bool setfocus);
 236static void unmanage(Client *c, Bool destroyed);
 237static void unmapnotify(XEvent *e);
 238static Bool updategeom(void);
 239static void updatebarpos(Monitor *m);
 240static void updatebars(void);
 241static void updateclientlist(void);
 242static void updatenumlockmask(void);
 243static void updatesizehints(Client *c);
 244static void updatestatus(void);
 245static void updatewindowtype(Client *c);
 246static void updatetitle(Client *c);
 247static void updatewmhints(Client *c);
 248static void view(const Arg *arg);
 249static Client *wintoclient(Window w);
 250static Monitor *wintomon(Window w);
 251static int xerror(Display *dpy, XErrorEvent *ee);
 252static int xerrordummy(Display *dpy, XErrorEvent *ee);
 253static int xerrorstart(Display *dpy, XErrorEvent *ee);
 254static void zoom(const Arg *arg);
 255
 256/* variables */
 257static const char broken[] = "broken";
 258static char stext[256];
 259static int screen;
 260static int sw, sh;           /* X display screen geometry width, height */
 261static int bh, blw = 0;      /* bar geometry */
 262static int (*xerrorxlib)(Display *, XErrorEvent *);
 263static unsigned int numlockmask = 0;
 264static void (*handler[LASTEvent]) (XEvent *) = {
 265	[ButtonPress] = buttonpress,
 266	[ClientMessage] = clientmessage,
 267	[ConfigureRequest] = configurerequest,
 268	[ConfigureNotify] = configurenotify,
 269	[DestroyNotify] = destroynotify,
 270	[EnterNotify] = enternotify,
 271	[Expose] = expose,
 272	[FocusIn] = focusin,
 273	[KeyPress] = keypress,
 274	[MappingNotify] = mappingnotify,
 275	[MapRequest] = maprequest,
 276	[MotionNotify] = motionnotify,
 277	[PropertyNotify] = propertynotify,
 278	[UnmapNotify] = unmapnotify
 279};
 280static Atom wmatom[WMLast], netatom[NetLast];
 281static Bool running = True;
 282static Cursor cursor[CurLast];
 283static Display *dpy;
 284static DC dc;
 285static Monitor *mons = NULL, *selmon = NULL;
 286static Window root;
 287
 288/* configuration, allows nested code to access above variables */
 289#include "config.h"
 290
 291/* compile-time check if all tags fit into an unsigned int bit array. */
 292struct NumTags { char limitexceeded[LENGTH(tags) > 31 ? -1 : 1]; };
 293
 294/* function implementations */
 295void
 296applyrules(Client *c) {
 297	const char *class, *instance;
 298	unsigned int i;
 299	const Rule *r;
 300	Monitor *m;
 301	XClassHint ch = { NULL, NULL };
 302
 303	/* rule matching */
 304	c->isfloating = c->tags = 0;
 305	XGetClassHint(dpy, c->win, &ch);
 306	class    = ch.res_class ? ch.res_class : broken;
 307	instance = ch.res_name  ? ch.res_name  : broken;
 308
 309	for(i = 0; i < LENGTH(rules); i++) {
 310		r = &rules[i];
 311		if((!r->title || strstr(c->name, r->title))
 312		&& (!r->class || strstr(class, r->class))
 313		&& (!r->instance || strstr(instance, r->instance)))
 314		{
 315			c->isfloating = r->isfloating;
 316			c->tags |= r->tags;
 317			for(m = mons; m && m->num != r->monitor; m = m->next);
 318			if(m)
 319				c->mon = m;
 320		}
 321	}
 322	if(ch.res_class)
 323		XFree(ch.res_class);
 324	if(ch.res_name)
 325		XFree(ch.res_name);
 326	c->tags = c->tags & TAGMASK ? c->tags & TAGMASK : c->mon->tagset[c->mon->seltags];
 327}
 328
 329Bool
 330applysizehints(Client *c, int *x, int *y, int *w, int *h, Bool interact) {
 331	Bool baseismin;
 332	Monitor *m = c->mon;
 333
 334	/* set minimum possible */
 335	*w = MAX(1, *w);
 336	*h = MAX(1, *h);
 337	if(interact) {
 338		if(*x > sw)
 339			*x = sw - WIDTH(c);
 340		if(*y > sh)
 341			*y = sh - HEIGHT(c);
 342		if(*x + *w + 2 * c->bw < 0)
 343			*x = 0;
 344		if(*y + *h + 2 * c->bw < 0)
 345			*y = 0;
 346	}
 347	else {
 348		if(*x >= m->wx + m->ww)
 349			*x = m->wx + m->ww - WIDTH(c);
 350		if(*y >= m->wy + m->wh)
 351			*y = m->wy + m->wh - HEIGHT(c);
 352		if(*x + *w + 2 * c->bw <= m->wx)
 353			*x = m->wx;
 354		if(*y + *h + 2 * c->bw <= m->wy)
 355			*y = m->wy;
 356	}
 357	if(*h < bh)
 358		*h = bh;
 359	if(*w < bh)
 360		*w = bh;
 361	if(resizehints || c->isfloating || !c->mon->lt[c->mon->sellt]->arrange) {
 362		/* see last two sentences in ICCCM 4.1.2.3 */
 363		baseismin = c->basew == c->minw && c->baseh == c->minh;
 364		if(!baseismin) { /* temporarily remove base dimensions */
 365			*w -= c->basew;
 366			*h -= c->baseh;
 367		}
 368		/* adjust for aspect limits */
 369		if(c->mina > 0 && c->maxa > 0) {
 370			if(c->maxa < (float)*w / *h)
 371				*w = *h * c->maxa + 0.5;
 372			else if(c->mina < (float)*h / *w)
 373				*h = *w * c->mina + 0.5;
 374		}
 375		if(baseismin) { /* increment calculation requires this */
 376			*w -= c->basew;
 377			*h -= c->baseh;
 378		}
 379		/* adjust for increment value */
 380		if(c->incw)
 381			*w -= *w % c->incw;
 382		if(c->inch)
 383			*h -= *h % c->inch;
 384		/* restore base dimensions */
 385		*w = MAX(*w + c->basew, c->minw);
 386		*h = MAX(*h + c->baseh, c->minh);
 387		if(c->maxw)
 388			*w = MIN(*w, c->maxw);
 389		if(c->maxh)
 390			*h = MIN(*h, c->maxh);
 391	}
 392	return *x != c->x || *y != c->y || *w != c->w || *h != c->h;
 393}
 394
 395void
 396arrange(Monitor *m) {
 397	if(m)
 398		showhide(m->stack);
 399	else for(m = mons; m; m = m->next)
 400		showhide(m->stack);
 401	if(m) {
 402		arrangemon(m);
 403		restack(m);
 404	} else for(m = mons; m; m = m->next)
 405		arrangemon(m);
 406}
 407
 408void
 409arrangemon(Monitor *m) {
 410	strncpy(m->ltsymbol, m->lt[m->sellt]->symbol, sizeof m->ltsymbol);
 411	if(m->lt[m->sellt]->arrange)
 412		m->lt[m->sellt]->arrange(m);
 413}
 414
 415void
 416attach(Client *c) {
 417	c->next = c->mon->clients;
 418	c->mon->clients = c;
 419}
 420
 421void
 422attachstack(Client *c) {
 423	c->snext = c->mon->stack;
 424	c->mon->stack = c;
 425}
 426
 427void
 428buttonpress(XEvent *e) {
 429	unsigned int i, x, click;
 430	Arg arg = {0};
 431	Client *c;
 432	Monitor *m;
 433	XButtonPressedEvent *ev = &e->xbutton;
 434
 435	click = ClkRootWin;
 436	/* focus monitor if necessary */
 437	if((m = wintomon(ev->window)) && m != selmon) {
 438		unfocus(selmon->sel, True);
 439		selmon = m;
 440		focus(NULL);
 441	}
 442	if(ev->window == selmon->barwin) {
 443		i = x = 0;
 444		do
 445			x += TEXTW(tags[i]);
 446		while(ev->x >= x && ++i < LENGTH(tags));
 447		if(i < LENGTH(tags)) {
 448			click = ClkTagBar;
 449			arg.ui = 1 << i;
 450		}
 451		else if(ev->x < x + blw)
 452			click = ClkLtSymbol;
 453		else if(ev->x > selmon->ww - TEXTW(stext))
 454			click = ClkStatusText;
 455		else
 456			click = ClkWinTitle;
 457	}
 458	else if((c = wintoclient(ev->window))) {
 459		focus(c);
 460		click = ClkClientWin;
 461	}
 462	for(i = 0; i < LENGTH(buttons); i++)
 463		if(click == buttons[i].click && buttons[i].func && buttons[i].button == ev->button
 464		&& CLEANMASK(buttons[i].mask) == CLEANMASK(ev->state))
 465			buttons[i].func(click == ClkTagBar && buttons[i].arg.i == 0 ? &arg : &buttons[i].arg);
 466}
 467
 468void
 469checkotherwm(void) {
 470	xerrorxlib = XSetErrorHandler(xerrorstart);
 471	/* this causes an error if some other window manager is running */
 472	XSelectInput(dpy, DefaultRootWindow(dpy), SubstructureRedirectMask);
 473	XSync(dpy, False);
 474	XSetErrorHandler(xerror);
 475	XSync(dpy, False);
 476}
 477
 478void
 479cleanup(void) {
 480	Arg a = {.ui = ~0};
 481	Layout foo = { "", NULL };
 482	Monitor *m;
 483
 484	view(&a);
 485	selmon->lt[selmon->sellt] = &foo;
 486	for(m = mons; m; m = m->next)
 487		while(m->stack)
 488			unmanage(m->stack, False);
 489	if(dc.font.set)
 490		XFreeFontSet(dpy, dc.font.set);
 491	else
 492		XFreeFont(dpy, dc.font.xfont);
 493	XUngrabKey(dpy, AnyKey, AnyModifier, root);
 494	XFreePixmap(dpy, dc.drawable);
 495	XFreeGC(dpy, dc.gc);
 496	XFreeCursor(dpy, cursor[CurNormal]);
 497	XFreeCursor(dpy, cursor[CurResize]);
 498	XFreeCursor(dpy, cursor[CurMove]);
 499	while(mons)
 500		cleanupmon(mons);
 501	XSync(dpy, False);
 502	XSetInputFocus(dpy, PointerRoot, RevertToPointerRoot, CurrentTime);
 503	XDeleteProperty(dpy, root, netatom[NetActiveWindow]);
 504}
 505
 506void
 507cleanupmon(Monitor *mon) {
 508	Monitor *m;
 509
 510	if(mon == mons)
 511		mons = mons->next;
 512	else {
 513		for(m = mons; m && m->next != mon; m = m->next);
 514		m->next = mon->next;
 515	}
 516	XUnmapWindow(dpy, mon->barwin);
 517	XDestroyWindow(dpy, mon->barwin);
 518	free(mon);
 519}
 520
 521void
 522clearurgent(Client *c) {
 523	XWMHints *wmh;
 524
 525	c->isurgent = False;
 526	if(!(wmh = XGetWMHints(dpy, c->win)))
 527		return;
 528	wmh->flags &= ~XUrgencyHint;
 529	XSetWMHints(dpy, c->win, wmh);
 530	XFree(wmh);
 531}
 532
 533void
 534clientmessage(XEvent *e) {
 535	XClientMessageEvent *cme = &e->xclient;
 536	Client *c = wintoclient(cme->window);
 537
 538	if(!c)
 539		return;
 540	if(cme->message_type == netatom[NetWMState]) {
 541		if(cme->data.l[1] == netatom[NetWMFullscreen] || cme->data.l[2] == netatom[NetWMFullscreen])
 542			setfullscreen(c, (cme->data.l[0] == 1 /* _NET_WM_STATE_ADD    */
 543			              || (cme->data.l[0] == 2 /* _NET_WM_STATE_TOGGLE */ && !c->isfullscreen)));
 544	}
 545	else if(cme->message_type == netatom[NetActiveWindow]) {
 546		if(!ISVISIBLE(c)) {
 547			c->mon->seltags ^= 1;
 548			c->mon->tagset[c->mon->seltags] = c->tags;
 549		}
 550		pop(c);
 551	}
 552}
 553
 554void
 555configure(Client *c) {
 556	XConfigureEvent ce;
 557
 558	ce.type = ConfigureNotify;
 559	ce.display = dpy;
 560	ce.event = c->win;
 561	ce.window = c->win;
 562	ce.x = c->x;
 563	ce.y = c->y;
 564	ce.width = c->w;
 565	ce.height = c->h;
 566	ce.border_width = c->bw;
 567	ce.above = None;
 568	ce.override_redirect = False;
 569	XSendEvent(dpy, c->win, False, StructureNotifyMask, (XEvent *)&ce);
 570}
 571
 572void
 573configurenotify(XEvent *e) {
 574	Monitor *m;
 575	XConfigureEvent *ev = &e->xconfigure;
 576	Bool dirty;
 577
 578	// TODO: updategeom handling sucks, needs to be simplified
 579	if(ev->window == root) {
 580		dirty = (sw != ev->width || sh != ev->height);
 581		sw = ev->width;
 582		sh = ev->height;
 583		if(updategeom() || dirty) {
 584			if(dc.drawable != 0)
 585				XFreePixmap(dpy, dc.drawable);
 586			dc.drawable = XCreatePixmap(dpy, root, sw, bh, DefaultDepth(dpy, screen));
 587			updatebars();
 588			for(m = mons; m; m = m->next)
 589				XMoveResizeWindow(dpy, m->barwin, m->wx, m->by, m->ww, bh);
 590			focus(NULL);
 591			arrange(NULL);
 592		}
 593	}
 594}
 595
 596void
 597configurerequest(XEvent *e) {
 598	Client *c;
 599	Monitor *m;
 600	XConfigureRequestEvent *ev = &e->xconfigurerequest;
 601	XWindowChanges wc;
 602
 603	if((c = wintoclient(ev->window))) {
 604		if(ev->value_mask & CWBorderWidth)
 605			c->bw = ev->border_width;
 606		else if(c->isfloating || !selmon->lt[selmon->sellt]->arrange) {
 607			m = c->mon;
 608			if(ev->value_mask & CWX) {
 609				c->oldx = c->x;
 610				c->x = m->mx + ev->x;
 611			}
 612			if(ev->value_mask & CWY) {
 613				c->oldy = c->y;
 614				c->y = m->my + ev->y;
 615			}
 616			if(ev->value_mask & CWWidth) {
 617				c->oldw = c->w;
 618				c->w = ev->width;
 619			}
 620			if(ev->value_mask & CWHeight) {
 621				c->oldh = c->h;
 622				c->h = ev->height;
 623			}
 624			if((c->x + c->w) > m->mx + m->mw && c->isfloating)
 625				c->x = m->mx + (m->mw / 2 - WIDTH(c) / 2); /* center in x direction */
 626			if((c->y + c->h) > m->my + m->mh && c->isfloating)
 627				c->y = m->my + (m->mh / 2 - HEIGHT(c) / 2); /* center in y direction */
 628			if((ev->value_mask & (CWX|CWY)) && !(ev->value_mask & (CWWidth|CWHeight)))
 629				configure(c);
 630			if(ISVISIBLE(c))
 631				XMoveResizeWindow(dpy, c->win, c->x, c->y, c->w, c->h);
 632		}
 633		else
 634			configure(c);
 635	}
 636	else {
 637		wc.x = ev->x;
 638		wc.y = ev->y;
 639		wc.width = ev->width;
 640		wc.height = ev->height;
 641		wc.border_width = ev->border_width;
 642		wc.sibling = ev->above;
 643		wc.stack_mode = ev->detail;
 644		XConfigureWindow(dpy, ev->window, ev->value_mask, &wc);
 645	}
 646	XSync(dpy, False);
 647}
 648
 649Monitor *
 650createmon(void) {
 651	Monitor *m;
 652
 653	if(!(m = (Monitor *)calloc(1, sizeof(Monitor))))
 654		die("fatal: could not malloc() %u bytes\n", sizeof(Monitor));
 655	m->tagset[0] = m->tagset[1] = 1;
 656	m->mfact = mfact;
 657	m->nmaster = nmaster;
 658	m->showbar = showbar;
 659	m->topbar = topbar;
 660	m->lt[0] = &layouts[0];
 661	m->lt[1] = &layouts[1 % LENGTH(layouts)];
 662	strncpy(m->ltsymbol, layouts[0].symbol, sizeof m->ltsymbol);
 663	return m;
 664}
 665
 666void
 667destroynotify(XEvent *e) {
 668	Client *c;
 669	XDestroyWindowEvent *ev = &e->xdestroywindow;
 670
 671	if((c = wintoclient(ev->window)))
 672		unmanage(c, True);
 673}
 674
 675void
 676detach(Client *c) {
 677	Client **tc;
 678
 679	for(tc = &c->mon->clients; *tc && *tc != c; tc = &(*tc)->next);
 680	*tc = c->next;
 681}
 682
 683void
 684detachstack(Client *c) {
 685	Client **tc, *t;
 686
 687	for(tc = &c->mon->stack; *tc && *tc != c; tc = &(*tc)->snext);
 688	*tc = c->snext;
 689
 690	if(c == c->mon->sel) {
 691		for(t = c->mon->stack; t && !ISVISIBLE(t); t = t->snext);
 692		c->mon->sel = t;
 693	}
 694}
 695
 696void
 697die(const char *errstr, ...) {
 698	va_list ap;
 699
 700	va_start(ap, errstr);
 701	vfprintf(stderr, errstr, ap);
 702	va_end(ap);
 703	exit(EXIT_FAILURE);
 704}
 705
 706Monitor *
 707dirtomon(int dir) {
 708	Monitor *m = NULL;
 709
 710	if(dir > 0) {
 711		if(!(m = selmon->next))
 712			m = mons;
 713	}
 714	else if(selmon == mons)
 715		for(m = mons; m->next; m = m->next);
 716	else
 717		for(m = mons; m->next != selmon; m = m->next);
 718	return m;
 719}
 720
 721void
 722drawbar(Monitor *m) {
 723	int x;
 724	unsigned int i, occ = 0, urg = 0;
 725	unsigned long *col;
 726	Client *c;
 727
 728	for(c = m->clients; c; c = c->next) {
 729		occ |= c->tags;
 730		if(c->isurgent)
 731			urg |= c->tags;
 732	}
 733	dc.x = 0;
 734	for(i = 0; i < LENGTH(tags); i++) {
 735		dc.w = TEXTW(tags[i]);
 736		col = m->tagset[m->seltags] & 1 << i ? dc.sel : dc.norm;
 737		drawtext(tags[i], col, urg & 1 << i);
 738		drawsquare(m == selmon && selmon->sel && selmon->sel->tags & 1 << i,
 739		           occ & 1 << i, urg & 1 << i, col);
 740		dc.x += dc.w;
 741	}
 742	dc.w = blw = TEXTW(m->ltsymbol);
 743	drawtext(m->ltsymbol, dc.norm, False);
 744	dc.x += dc.w;
 745	x = dc.x;
 746	if(m == selmon) { /* status is only drawn on selected monitor */
 747		dc.w = TEXTW(stext);
 748		dc.x = m->ww - dc.w;
 749		if(dc.x < x) {
 750			dc.x = x;
 751			dc.w = m->ww - x;
 752		}
 753		drawtext(stext, dc.norm, False);
 754	}
 755	else
 756		dc.x = m->ww;
 757	if((dc.w = dc.x - x) > bh) {
 758		dc.x = x;
 759		if(m->sel) {
 760			col = m == selmon ? dc.sel : dc.norm;
 761			drawtext(m->sel->name, col, False);
 762			drawsquare(m->sel->isfixed, m->sel->isfloating, False, col);
 763		}
 764		else
 765			drawtext(NULL, dc.norm, False);
 766	}
 767	XCopyArea(dpy, dc.drawable, m->barwin, dc.gc, 0, 0, m->ww, bh, 0, 0);
 768	XSync(dpy, False);
 769}
 770
 771void
 772drawbars(void) {
 773	Monitor *m;
 774
 775	for(m = mons; m; m = m->next)
 776		drawbar(m);
 777}
 778
 779void
 780drawsquare(Bool filled, Bool empty, Bool invert, unsigned long col[ColLast]) {
 781	int x;
 782
 783	XSetForeground(dpy, dc.gc, col[invert ? ColBG : ColFG]);
 784	x = (dc.font.ascent + dc.font.descent + 2) / 4;
 785	if(filled)
 786		XFillRectangle(dpy, dc.drawable, dc.gc, dc.x+1, dc.y+1, x+1, x+1);
 787	else if(empty)
 788		XDrawRectangle(dpy, dc.drawable, dc.gc, dc.x+1, dc.y+1, x, x);
 789}
 790
 791void
 792drawtext(const char *text, unsigned long col[ColLast], Bool invert) {
 793	char buf[256];
 794	int i, x, y, h, len, olen;
 795
 796	XSetForeground(dpy, dc.gc, col[invert ? ColFG : ColBG]);
 797	XFillRectangle(dpy, dc.drawable, dc.gc, dc.x, dc.y, dc.w, dc.h);
 798	if(!text)
 799		return;
 800	olen = strlen(text);
 801	h = dc.font.ascent + dc.font.descent;
 802	y = dc.y + (dc.h / 2) - (h / 2) + dc.font.ascent;
 803	x = dc.x + (h / 2);
 804	/* shorten text if necessary */
 805	for(len = MIN(olen, sizeof buf); len && textnw(text, len) > dc.w - h; len--);
 806	if(!len)
 807		return;
 808	memcpy(buf, text, len);
 809	if(len < olen)
 810		for(i = len; i && i > len - 3; buf[--i] = '.');
 811	XSetForeground(dpy, dc.gc, col[invert ? ColBG : ColFG]);
 812	if(dc.font.set)
 813		XmbDrawString(dpy, dc.drawable, dc.font.set, dc.gc, x, y, buf, len);
 814	else
 815		XDrawString(dpy, dc.drawable, dc.gc, x, y, buf, len);
 816}
 817
 818void
 819enternotify(XEvent *e) {
 820	Client *c;
 821	Monitor *m;
 822	XCrossingEvent *ev = &e->xcrossing;
 823
 824	if((ev->mode != NotifyNormal || ev->detail == NotifyInferior) && ev->window != root)
 825		return;
 826	c = wintoclient(ev->window);
 827	m = c ? c->mon : wintomon(ev->window);
 828	if(m != selmon) {
 829		unfocus(selmon->sel, True);
 830		selmon = m;
 831	}
 832	else if(!c || c == selmon->sel)
 833		return;
 834	focus(c);
 835}
 836
 837void
 838expose(XEvent *e) {
 839	Monitor *m;
 840	XExposeEvent *ev = &e->xexpose;
 841
 842	if(ev->count == 0 && (m = wintomon(ev->window)))
 843		drawbar(m);
 844}
 845
 846void
 847focus(Client *c) {
 848	if(!c || !ISVISIBLE(c))
 849		for(c = selmon->stack; c && !ISVISIBLE(c); c = c->snext);
 850	/* was if(selmon->sel) */
 851	if(selmon->sel && selmon->sel != c)
 852		unfocus(selmon->sel, False);
 853	if(c) {
 854		if(c->mon != selmon)
 855			selmon = c->mon;
 856		if(c->isurgent)
 857			clearurgent(c);
 858		detachstack(c);
 859		attachstack(c);
 860		grabbuttons(c, True);
 861		XSetWindowBorder(dpy, c->win, dc.sel[ColBorder]);
 862		setfocus(c);
 863	}
 864	else {
 865		XSetInputFocus(dpy, root, RevertToPointerRoot, CurrentTime);
 866		XDeleteProperty(dpy, root, netatom[NetActiveWindow]);
 867	}
 868	selmon->sel = c;
 869	drawbars();
 870}
 871
 872void
 873focusin(XEvent *e) { /* there are some broken focus acquiring clients */
 874	XFocusChangeEvent *ev = &e->xfocus;
 875
 876	if(selmon->sel && ev->window != selmon->sel->win)
 877		setfocus(selmon->sel);
 878}
 879
 880void
 881focusmon(const Arg *arg) {
 882	Monitor *m;
 883
 884	if(!mons->next)
 885		return;
 886	if((m = dirtomon(arg->i)) == selmon)
 887		return;
 888	unfocus(selmon->sel, False); /* s/True/False/ fixes input focus issues
 889					in gedit and anjuta */
 890	selmon = m;
 891	focus(NULL);
 892}
 893
 894void
 895focusstack(const Arg *arg) {
 896	Client *c = NULL, *i;
 897
 898	if(!selmon->sel)
 899		return;
 900	if(arg->i > 0) {
 901		for(c = selmon->sel->next; c && !ISVISIBLE(c); c = c->next);
 902		if(!c)
 903			for(c = selmon->clients; c && !ISVISIBLE(c); c = c->next);
 904	}
 905	else {
 906		for(i = selmon->clients; i != selmon->sel; i = i->next)
 907			if(ISVISIBLE(i))
 908				c = i;
 909		if(!c)
 910			for(; i; i = i->next)
 911				if(ISVISIBLE(i))
 912					c = i;
 913	}
 914	if(c) {
 915		focus(c);
 916		restack(selmon);
 917	}
 918}
 919
 920Atom
 921getatomprop(Client *c, Atom prop) {
 922	int di;
 923	unsigned long dl;
 924	unsigned char *p = NULL;
 925	Atom da, atom = None;
 926
 927	if(XGetWindowProperty(dpy, c->win, prop, 0L, sizeof atom, False, XA_ATOM,
 928	                      &da, &di, &dl, &dl, &p) == Success && p) {
 929		atom = *(Atom *)p;
 930		XFree(p);
 931	}
 932	return atom;
 933}
 934
 935unsigned long
 936getcolor(const char *colstr) {
 937	Colormap cmap = DefaultColormap(dpy, screen);
 938	XColor color;
 939
 940	if(!XAllocNamedColor(dpy, cmap, colstr, &color, &color))
 941		die("error, cannot allocate color '%s'\n", colstr);
 942	return color.pixel;
 943}
 944
 945Bool
 946getrootptr(int *x, int *y) {
 947	int di;
 948	unsigned int dui;
 949	Window dummy;
 950
 951	return XQueryPointer(dpy, root, &dummy, &dummy, x, y, &di, &di, &dui);
 952}
 953
 954long
 955getstate(Window w) {
 956	int format;
 957	long result = -1;
 958	unsigned char *p = NULL;
 959	unsigned long n, extra;
 960	Atom real;
 961
 962	if(XGetWindowProperty(dpy, w, wmatom[WMState], 0L, 2L, False, wmatom[WMState],
 963	                      &real, &format, &n, &extra, (unsigned char **)&p) != Success)
 964		return -1;
 965	if(n != 0)
 966		result = *p;
 967	XFree(p);
 968	return result;
 969}
 970
 971Bool
 972gettextprop(Window w, Atom atom, char *text, unsigned int size) {
 973	char **list = NULL;
 974	int n;
 975	XTextProperty name;
 976
 977	if(!text || size == 0)
 978		return False;
 979	text[0] = '\0';
 980	XGetTextProperty(dpy, w, &name, atom);
 981	if(!name.nitems)
 982		return False;
 983	if(name.encoding == XA_STRING)
 984		strncpy(text, (char *)name.value, size - 1);
 985	else {
 986		if(XmbTextPropertyToTextList(dpy, &name, &list, &n) >= Success && n > 0 && *list) {
 987			strncpy(text, *list, size - 1);
 988			XFreeStringList(list);
 989		}
 990	}
 991	text[size - 1] = '\0';
 992	XFree(name.value);
 993	return True;
 994}
 995
 996void
 997grabbuttons(Client *c, Bool focused) {
 998	updatenumlockmask();
 999	{
1000		unsigned int i, j;
1001		unsigned int modifiers[] = { 0, LockMask, numlockmask, numlockmask|LockMask };
1002		XUngrabButton(dpy, AnyButton, AnyModifier, c->win);
1003		if(focused) {
1004			for(i = 0; i < LENGTH(buttons); i++)
1005				if(buttons[i].click == ClkClientWin)
1006					for(j = 0; j < LENGTH(modifiers); j++)
1007						XGrabButton(dpy, buttons[i].button,
1008						            buttons[i].mask | modifiers[j],
1009						            c->win, False, BUTTONMASK,
1010						            GrabModeAsync, GrabModeSync, None, None);
1011		}
1012		else
1013			XGrabButton(dpy, AnyButton, AnyModifier, c->win, False,
1014			            BUTTONMASK, GrabModeAsync, GrabModeSync, None, None);
1015	}
1016}
1017
1018void
1019grabkeys(void) {
1020	updatenumlockmask();
1021	{
1022		unsigned int i, j;
1023		unsigned int modifiers[] = { 0, LockMask, numlockmask, numlockmask|LockMask };
1024		KeyCode code;
1025
1026		XUngrabKey(dpy, AnyKey, AnyModifier, root);
1027		for(i = 0; i < LENGTH(keys); i++)
1028			if((code = XKeysymToKeycode(dpy, keys[i].keysym)))
1029				for(j = 0; j < LENGTH(modifiers); j++)
1030					XGrabKey(dpy, code, keys[i].mod | modifiers[j], root,
1031						 True, GrabModeAsync, GrabModeAsync);
1032	}
1033}
1034
1035void
1036incnmaster(const Arg *arg) {
1037	selmon->nmaster = MAX(selmon->nmaster + arg->i, 0);
1038	arrange(selmon);
1039}
1040
1041void
1042initfont(const char *fontstr) {
1043	char *def, **missing;
1044	int n;
1045
1046	dc.font.set = XCreateFontSet(dpy, fontstr, &missing, &n, &def);
1047	if(missing) {
1048		while(n--)
1049			fprintf(stderr, "dwm: missing fontset: %s\n", missing[n]);
1050		XFreeStringList(missing);
1051	}
1052	if(dc.font.set) {
1053		XFontStruct **xfonts;
1054		char **font_names;
1055
1056		dc.font.ascent = dc.font.descent = 0;
1057		XExtentsOfFontSet(dc.font.set);
1058		n = XFontsOfFontSet(dc.font.set, &xfonts, &font_names);
1059		while(n--) {
1060			dc.font.ascent = MAX(dc.font.ascent, (*xfonts)->ascent);
1061			dc.font.descent = MAX(dc.font.descent,(*xfonts)->descent);
1062			xfonts++;
1063		}
1064	}
1065	else {
1066		if(!(dc.font.xfont = XLoadQueryFont(dpy, fontstr))
1067		&& !(dc.font.xfont = XLoadQueryFont(dpy, "fixed")))
1068			die("error, cannot load font: '%s'\n", fontstr);
1069		dc.font.ascent = dc.font.xfont->ascent;
1070		dc.font.descent = dc.font.xfont->descent;
1071	}
1072	dc.font.height = dc.font.ascent + dc.font.descent;
1073}
1074
1075#ifdef XINERAMA
1076static Bool
1077isuniquegeom(XineramaScreenInfo *unique, size_t n, XineramaScreenInfo *info) {
1078	while(n--)
1079		if(unique[n].x_org == info->x_org && unique[n].y_org == info->y_org
1080		&& unique[n].width == info->width && unique[n].height == info->height)
1081			return False;
1082	return True;
1083}
1084#endif /* XINERAMA */
1085
1086void
1087keypress(XEvent *e) {
1088	unsigned int i;
1089	KeySym keysym;
1090	XKeyEvent *ev;
1091
1092	ev = &e->xkey;
1093	keysym = XKeycodeToKeysym(dpy, (KeyCode)ev->keycode, 0);
1094	for(i = 0; i < LENGTH(keys); i++)
1095		if(keysym == keys[i].keysym
1096		&& CLEANMASK(keys[i].mod) == CLEANMASK(ev->state)
1097		&& keys[i].func)
1098			keys[i].func(&(keys[i].arg));
1099}
1100
1101void
1102killclient(const Arg *arg) {
1103	if(!selmon->sel)
1104		return;
1105	if(!sendevent(selmon->sel, wmatom[WMDelete])) {
1106		XGrabServer(dpy);
1107		XSetErrorHandler(xerrordummy);
1108		XSetCloseDownMode(dpy, DestroyAll);
1109		XKillClient(dpy, selmon->sel->win);
1110		XSync(dpy, False);
1111		XSetErrorHandler(xerror);
1112		XUngrabServer(dpy);
1113	}
1114}
1115
1116void
1117manage(Window w, XWindowAttributes *wa) {
1118	Client *c, *t = NULL;
1119	Window trans = None;
1120	XWindowChanges wc;
1121
1122	if(!(c = calloc(1, sizeof(Client))))
1123		die("fatal: could not malloc() %u bytes\n", sizeof(Client));
1124	c->win = w;
1125	updatetitle(c);
1126	if(XGetTransientForHint(dpy, w, &trans) && (t = wintoclient(trans))) {
1127		c->mon = t->mon;
1128		c->tags = t->tags;
1129	}
1130	else {
1131		c->mon = selmon;
1132		applyrules(c);
1133	}
1134	/* geometry */
1135	c->x = c->oldx = wa->x;
1136	c->y = c->oldy = wa->y;
1137	c->w = c->oldw = wa->width;
1138	c->h = c->oldh = wa->height;
1139	c->oldbw = wa->border_width;
1140
1141	if(c->x + WIDTH(c) > c->mon->mx + c->mon->mw)
1142		c->x = c->mon->mx + c->mon->mw - WIDTH(c);
1143	if(c->y + HEIGHT(c) > c->mon->my + c->mon->mh)
1144		c->y = c->mon->my + c->mon->mh - HEIGHT(c);
1145	c->x = MAX(c->x, c->mon->mx);
1146	/* only fix client y-offset, if the client center might cover the bar */
1147	c->y = MAX(c->y, ((c->mon->by == c->mon->my) && (c->x + (c->w / 2) >= c->mon->wx)
1148	           && (c->x + (c->w / 2) < c->mon->wx + c->mon->ww)) ? bh : c->mon->my);
1149	c->bw = borderpx;
1150
1151	wc.border_width = c->bw;
1152	XConfigureWindow(dpy, w, CWBorderWidth, &wc);
1153	XSetWindowBorder(dpy, w, dc.norm[ColBorder]);
1154	configure(c); /* propagates border_width, if size doesn't change */
1155	updatewindowtype(c);
1156	updatesizehints(c);
1157	updatewmhints(c);
1158	XSelectInput(dpy, w, EnterWindowMask|FocusChangeMask|PropertyChangeMask|StructureNotifyMask);
1159	grabbuttons(c, False);
1160	if(!c->isfloating)
1161		c->isfloating = c->oldstate = trans != None || c->isfixed;
1162	if(c->isfloating)
1163		XRaiseWindow(dpy, c->win);
1164	attach(c);
1165	attachstack(c);
1166	XChangeProperty(dpy, root, netatom[NetClientList], XA_WINDOW, 32, PropModeAppend,
1167	                (unsigned char *) &(c->win), 1);
1168	XMoveResizeWindow(dpy, c->win, c->x + 2 * sw, c->y, c->w, c->h); /* some windows require this */
1169	setclientstate(c, NormalState);
1170	if (c->mon == selmon)
1171		unfocus(selmon->sel, False);
1172	c->mon->sel = c;
1173	arrange(c->mon);
1174	XMapWindow(dpy, c->win);
1175	focus(NULL);
1176}
1177
1178void
1179mappingnotify(XEvent *e) {
1180	XMappingEvent *ev = &e->xmapping;
1181
1182	XRefreshKeyboardMapping(ev);
1183	if(ev->request == MappingKeyboard)
1184		grabkeys();
1185}
1186
1187void
1188maprequest(XEvent *e) {
1189	static XWindowAttributes wa;
1190	XMapRequestEvent *ev = &e->xmaprequest;
1191
1192	if(!XGetWindowAttributes(dpy, ev->window, &wa))
1193		return;
1194	if(wa.override_redirect)
1195		return;
1196	if(!wintoclient(ev->window))
1197		manage(ev->window, &wa);
1198}
1199
1200void
1201monocle(Monitor *m) {
1202	unsigned int n = 0;
1203	Client *c;
1204
1205	for(c = m->clients; c; c = c->next)
1206		if(ISVISIBLE(c))
1207			n++;
1208	if(n > 0) /* override layout symbol */
1209		snprintf(m->ltsymbol, sizeof m->ltsymbol, "[%d]", n);
1210	for(c = nexttiled(m->clients); c; c = nexttiled(c->next))
1211		resize(c, m->wx, m->wy, m->ww - 2 * c->bw, m->wh - 2 * c->bw, False);
1212}
1213
1214void
1215motionnotify(XEvent *e) {
1216	static Monitor *mon = NULL;
1217	Monitor *m;
1218	XMotionEvent *ev = &e->xmotion;
1219
1220	if(ev->window != root)
1221		return;
1222	if((m = recttomon(ev->x_root, ev->y_root, 1, 1)) != mon && mon) {
1223		unfocus(selmon->sel, True);
1224		selmon = m;
1225		focus(NULL);
1226	}
1227	mon = m;
1228}
1229
1230void
1231movemouse(const Arg *arg) {
1232	int x, y, ocx, ocy, nx, ny;
1233	Client *c;
1234	Monitor *m;
1235	XEvent ev;
1236
1237	if(!(c = selmon->sel))
1238		return;
1239	if(c->isfullscreen) /* no support moving fullscreen windows by mouse */
1240		return;
1241	restack(selmon);
1242	ocx = c->x;
1243	ocy = c->y;
1244	if(XGrabPointer(dpy, root, False, MOUSEMASK, GrabModeAsync, GrabModeAsync,
1245	None, cursor[CurMove], CurrentTime) != GrabSuccess)
1246		return;
1247	if(!getrootptr(&x, &y))
1248		return;
1249	do {
1250		XMaskEvent(dpy, MOUSEMASK|ExposureMask|SubstructureRedirectMask, &ev);
1251		switch(ev.type) {
1252		case ConfigureRequest:
1253		case Expose:
1254		case MapRequest:
1255			handler[ev.type](&ev);
1256			break;
1257		case MotionNotify:
1258			nx = ocx + (ev.xmotion.x - x);
1259			ny = ocy + (ev.xmotion.y - y);
1260			if(nx >= selmon->wx && nx <= selmon->wx + selmon->ww
1261			&& ny >= selmon->wy && ny <= selmon->wy + selmon->wh) {
1262				if(abs(selmon->wx - nx) < snap)
1263					nx = selmon->wx;
1264				else if(abs((selmon->wx + selmon->ww) - (nx + WIDTH(c))) < snap)
1265					nx = selmon->wx + selmon->ww - WIDTH(c);
1266				if(abs(selmon->wy - ny) < snap)
1267					ny = selmon->wy;
1268				else if(abs((selmon->wy + selmon->wh) - (ny + HEIGHT(c))) < snap)
1269					ny = selmon->wy + selmon->wh - HEIGHT(c);
1270				if(!c->isfloating && selmon->lt[selmon->sellt]->arrange
1271				&& (abs(nx - c->x) > snap || abs(ny - c->y) > snap))
1272					togglefloating(NULL);
1273			}
1274			if(!selmon->lt[selmon->sellt]->arrange || c->isfloating)
1275				resize(c, nx, ny, c->w, c->h, True);
1276			break;
1277		}
1278	} while(ev.type != ButtonRelease);
1279	XUngrabPointer(dpy, CurrentTime);
1280	if((m = recttomon(c->x, c->y, c->w, c->h)) != selmon) {
1281		sendmon(c, m);
1282		selmon = m;
1283		focus(NULL);
1284	}
1285}
1286
1287Client *
1288nexttiled(Client *c) {
1289	for(; c && (c->isfloating || !ISVISIBLE(c)); c = c->next);
1290	return c;
1291}
1292
1293void
1294pop(Client *c) {
1295	detach(c);
1296	attach(c);
1297	focus(c);
1298	arrange(c->mon);
1299}
1300
1301void
1302propertynotify(XEvent *e) {
1303	Client *c;
1304	Window trans;
1305	XPropertyEvent *ev = &e->xproperty;
1306
1307	if((ev->window == root) && (ev->atom == XA_WM_NAME))
1308		updatestatus();
1309	else if(ev->state == PropertyDelete)
1310		return; /* ignore */
1311	else if((c = wintoclient(ev->window))) {
1312		switch(ev->atom) {
1313		default: break;
1314		case XA_WM_TRANSIENT_FOR:
1315			if(!c->isfloating && (XGetTransientForHint(dpy, c->win, &trans)) &&
1316			   (c->isfloating = (wintoclient(trans)) != NULL))
1317				arrange(c->mon);
1318			break;
1319		case XA_WM_NORMAL_HINTS:
1320			updatesizehints(c);
1321			break;
1322		case XA_WM_HINTS:
1323			updatewmhints(c);
1324			drawbars();
1325			break;
1326		}
1327		if(ev->atom == XA_WM_NAME || ev->atom == netatom[NetWMName]) {
1328			updatetitle(c);
1329			if(c == c->mon->sel)
1330				drawbar(c->mon);
1331		}
1332		if(ev->atom == netatom[NetWMWindowType])
1333			updatewindowtype(c);
1334	}
1335}
1336
1337void
1338quit(const Arg *arg) {
1339	running = False;
1340}
1341
1342Monitor *
1343recttomon(int x, int y, int w, int h) {
1344	Monitor *m, *r = selmon;
1345	int a, area = 0;
1346
1347	for(m = mons; m; m = m->next)
1348		if((a = INTERSECT(x, y, w, h, m)) > area) {
1349			area = a;
1350			r = m;
1351		}
1352	return r;
1353}
1354
1355void
1356resize(Client *c, int x, int y, int w, int h, Bool interact) {
1357	if(applysizehints(c, &x, &y, &w, &h, interact))
1358		resizeclient(c, x, y, w, h);
1359}
1360
1361void
1362resizeclient(Client *c, int x, int y, int w, int h) {
1363	XWindowChanges wc;
1364
1365	c->oldx = c->x; c->x = wc.x = x;
1366	c->oldy = c->y; c->y = wc.y = y;
1367	c->oldw = c->w; c->w = wc.width = w;
1368	c->oldh = c->h; c->h = wc.height = h;
1369	wc.border_width = c->bw;
1370	XConfigureWindow(dpy, c->win, CWX|CWY|CWWidth|CWHeight|CWBorderWidth, &wc);
1371	configure(c);
1372	XSync(dpy, False);
1373}
1374
1375void
1376resizemouse(const Arg *arg) {
1377	int ocx, ocy;
1378	int nw, nh;
1379	Client *c;
1380	Monitor *m;
1381	XEvent ev;
1382
1383	if(!(c = selmon->sel))
1384		return;
1385	if(c->isfullscreen) /* no support resizing fullscreen windows by mouse */
1386		return;
1387	restack(selmon);
1388	ocx = c->x;
1389	ocy = c->y;
1390	if(XGrabPointer(dpy, root, False, MOUSEMASK, GrabModeAsync, GrabModeAsync,
1391	                None, cursor[CurResize], CurrentTime) != GrabSuccess)
1392		return;
1393	XWarpPointer(dpy, None, c->win, 0, 0, 0, 0, c->w + c->bw - 1, c->h + c->bw - 1);
1394	do {
1395		XMaskEvent(dpy, MOUSEMASK|ExposureMask|SubstructureRedirectMask, &ev);
1396		switch(ev.type) {
1397		case ConfigureRequest:
1398		case Expose:
1399		case MapRequest:
1400			handler[ev.type](&ev);
1401			break;
1402		case MotionNotify:
1403			nw = MAX(ev.xmotion.x - ocx - 2 * c->bw + 1, 1);
1404			nh = MAX(ev.xmotion.y - ocy - 2 * c->bw + 1, 1);
1405			if(c->mon->wx + nw >= selmon->wx && c->mon->wx + nw <= selmon->wx + selmon->ww
1406			&& c->mon->wy + nh >= selmon->wy && c->mon->wy + nh <= selmon->wy + selmon->wh)
1407			{
1408				if(!c->isfloating && selmon->lt[selmon->sellt]->arrange
1409				&& (abs(nw - c->w) > snap || abs(nh - c->h) > snap))
1410					togglefloating(NULL);
1411			}
1412			if(!selmon->lt[selmon->sellt]->arrange || c->isfloating)
1413				resize(c, c->x, c->y, nw, nh, True);
1414			break;
1415		}
1416	} while(ev.type != ButtonRelease);
1417	XWarpPointer(dpy, None, c->win, 0, 0, 0, 0, c->w + c->bw - 1, c->h + c->bw - 1);
1418	XUngrabPointer(dpy, CurrentTime);
1419	while(XCheckMaskEvent(dpy, EnterWindowMask, &ev));
1420	if((m = recttomon(c->x, c->y, c->w, c->h)) != selmon) {
1421		sendmon(c, m);
1422		selmon = m;
1423		focus(NULL);
1424	}
1425}
1426
1427void
1428restack(Monitor *m) {
1429	Client *c;
1430	XEvent ev;
1431	XWindowChanges wc;
1432
1433	drawbar(m);
1434	if(!m->sel)
1435		return;
1436	if(m->sel->isfloating || !m->lt[m->sellt]->arrange)
1437		XRaiseWindow(dpy, m->sel->win);
1438	if(m->lt[m->sellt]->arrange) {
1439		wc.stack_mode = Below;
1440		wc.sibling = m->barwin;
1441		for(c = m->stack; c; c = c->snext)
1442			if(!c->isfloating && ISVISIBLE(c)) {
1443				XConfigureWindow(dpy, c->win, CWSibling|CWStackMode, &wc);
1444				wc.sibling = c->win;
1445			}
1446	}
1447	XSync(dpy, False);
1448	while(XCheckMaskEvent(dpy, EnterWindowMask, &ev));
1449}
1450
1451void
1452run(void) {
1453	XEvent ev;
1454	/* main event loop */
1455	XSync(dpy, False);
1456	while(running && !XNextEvent(dpy, &ev))
1457		if(handler[ev.type])
1458			handler[ev.type](&ev); /* call handler */
1459}
1460
1461void
1462scan(void) {
1463	unsigned int i, num;
1464	Window d1, d2, *wins = NULL;
1465	XWindowAttributes wa;
1466
1467	if(XQueryTree(dpy, root, &d1, &d2, &wins, &num)) {
1468		for(i = 0; i < num; i++) {
1469			if(!XGetWindowAttributes(dpy, wins[i], &wa)
1470			|| wa.override_redirect || XGetTransientForHint(dpy, wins[i], &d1))
1471				continue;
1472			if(wa.map_state == IsViewable || getstate(wins[i]) == IconicState)
1473				manage(wins[i], &wa);
1474		}
1475		for(i = 0; i < num; i++) { /* now the transients */
1476			if(!XGetWindowAttributes(dpy, wins[i], &wa))
1477				continue;
1478			if(XGetTransientForHint(dpy, wins[i], &d1)
1479			&& (wa.map_state == IsViewable || getstate(wins[i]) == IconicState))
1480				manage(wins[i], &wa);
1481		}
1482		if(wins)
1483			XFree(wins);
1484	}
1485}
1486
1487void
1488sendmon(Client *c, Monitor *m) {
1489	if(c->mon == m)
1490		return;
1491	unfocus(c, True);
1492	detach(c);
1493	detachstack(c);
1494	c->mon = m;
1495	c->tags = m->tagset[m->seltags]; /* assign tags of target monitor */
1496	attach(c);
1497	attachstack(c);
1498	focus(NULL);
1499	arrange(NULL);
1500}
1501
1502void
1503setclientstate(Client *c, long state) {
1504	long data[] = { state, None };
1505
1506	XChangeProperty(dpy, c->win, wmatom[WMState], wmatom[WMState], 32,
1507			PropModeReplace, (unsigned char *)data, 2);
1508}
1509
1510Bool
1511sendevent(Client *c, Atom proto) {
1512	int n;
1513	Atom *protocols;
1514	Bool exists = False;
1515	XEvent ev;
1516
1517	if(XGetWMProtocols(dpy, c->win, &protocols, &n)) {
1518		while(!exists && n--)
1519			exists = protocols[n] == proto;
1520		XFree(protocols);
1521	}
1522	if(exists) {
1523		ev.type = ClientMessage;
1524		ev.xclient.window = c->win;
1525		ev.xclient.message_type = wmatom[WMProtocols];
1526		ev.xclient.format = 32;
1527		ev.xclient.data.l[0] = proto;
1528		ev.xclient.data.l[1] = CurrentTime;
1529		XSendEvent(dpy, c->win, False, NoEventMask, &ev);
1530	}
1531	return exists;
1532}
1533
1534void
1535setfocus(Client *c) {
1536	if(!c->neverfocus) {
1537		XSetInputFocus(dpy, c->win, RevertToPointerRoot, CurrentTime);
1538		XChangeProperty(dpy, root, netatom[NetActiveWindow],
1539 		                XA_WINDOW, 32, PropModeReplace,
1540 		                (unsigned char *) &(c->win), 1);
1541	}
1542	sendevent(c, wmatom[WMTakeFocus]);
1543}
1544
1545void
1546setfullscreen(Client *c, Bool fullscreen) {
1547	if(fullscreen) {
1548		XChangeProperty(dpy, c->win, netatom[NetWMState], XA_ATOM, 32,
1549		                PropModeReplace, (unsigned char*)&netatom[NetWMFullscreen], 1);
1550		c->isfullscreen = True;
1551		c->oldstate = c->isfloating;
1552		c->oldbw = c->bw;
1553		c->bw = 0;
1554		c->isfloating = True;
1555		resizeclient(c, c->mon->mx, c->mon->my, c->mon->mw, c->mon->mh);
1556		XRaiseWindow(dpy, c->win);
1557	}
1558	else {
1559		XChangeProperty(dpy, c->win, netatom[NetWMState], XA_ATOM, 32,
1560		                PropModeReplace, (unsigned char*)0, 0);
1561		c->isfullscreen = False;
1562		c->isfloating = c->oldstate;
1563		c->bw = c->oldbw;
1564		c->x = c->oldx;
1565		c->y = c->oldy;
1566		c->w = c->oldw;
1567		c->h = c->oldh;
1568		resizeclient(c, c->x, c->y, c->w, c->h);
1569		arrange(c->mon);
1570	}
1571}
1572
1573void
1574setlayout(const Arg *arg) {
1575	if(!arg || !arg->v || arg->v != selmon->lt[selmon->sellt])
1576		selmon->sellt ^= 1;
1577	if(arg && arg->v)
1578		selmon->lt[selmon->sellt] = (Layout *)arg->v;
1579	strncpy(selmon->ltsymbol, selmon->lt[selmon->sellt]->symbol, sizeof selmon->ltsymbol);
1580	if(selmon->sel)
1581		arrange(selmon);
1582	else
1583		drawbar(selmon);
1584}
1585
1586/* arg > 1.0 will set mfact absolutly */
1587void
1588setmfact(const Arg *arg) {
1589	float f;
1590
1591	if(!arg || !selmon->lt[selmon->sellt]->arrange)
1592		return;
1593	f = arg->f < 1.0 ? arg->f + selmon->mfact : arg->f - 1.0;
1594	if(f < 0.1 || f > 0.9)
1595		return;
1596	selmon->mfact = f;
1597	arrange(selmon);
1598}
1599
1600void
1601setup(void) {
1602	XSetWindowAttributes wa;
1603
1604	/* clean up any zombies immediately */
1605	sigchld(0);
1606
1607	/* init screen */
1608	screen = DefaultScreen(dpy);
1609	root = RootWindow(dpy, screen);
1610	initfont(font);
1611	sw = DisplayWidth(dpy, screen);
1612	sh = DisplayHeight(dpy, screen);
1613	bh = dc.h = dc.font.height + 2;
1614	updategeom();
1615	/* init atoms */
1616	wmatom[WMProtocols] = XInternAtom(dpy, "WM_PROTOCOLS", False);
1617	wmatom[WMDelete] = XInternAtom(dpy, "WM_DELETE_WINDOW", False);
1618	wmatom[WMState] = XInternAtom(dpy, "WM_STATE", False);
1619	wmatom[WMTakeFocus] = XInternAtom(dpy, "WM_TAKE_FOCUS", False);
1620	netatom[NetActiveWindow] = XInternAtom(dpy, "_NET_ACTIVE_WINDOW", False);
1621	netatom[NetSupported] = XInternAtom(dpy, "_NET_SUPPORTED", False);
1622	netatom[NetWMName] = XInternAtom(dpy, "_NET_WM_NAME", False);
1623	netatom[NetWMState] = XInternAtom(dpy, "_NET_WM_STATE", False);
1624	netatom[NetWMFullscreen] = XInternAtom(dpy, "_NET_WM_STATE_FULLSCREEN", False);
1625	netatom[NetWMWindowType] = XInternAtom(dpy, "_NET_WM_WINDOW_TYPE", False);
1626	netatom[NetWMWindowTypeDialog] = XInternAtom(dpy, "_NET_WM_WINDOW_TYPE_DIALOG", False);
1627	netatom[NetClientList] = XInternAtom(dpy, "_NET_CLIENT_LIST", False);
1628	/* init cursors */
1629	cursor[CurNormal] = XCreateFontCursor(dpy, XC_left_ptr);
1630	cursor[CurResize] = XCreateFontCursor(dpy, XC_sizing);
1631	cursor[CurMove] = XCreateFontCursor(dpy, XC_fleur);
1632	/* init appearance */
1633	dc.norm[ColBorder] = getcolor(normbordercolor);
1634	dc.norm[ColBG] = getcolor(normbgcolor);
1635	dc.norm[ColFG] = getcolor(normfgcolor);
1636	dc.sel[ColBorder] = getcolor(selbordercolor);
1637	dc.sel[ColBG] = getcolor(selbgcolor);
1638	dc.sel[ColFG] = getcolor(selfgcolor);
1639	dc.drawable = XCreatePixmap(dpy, root, DisplayWidth(dpy, screen), bh, DefaultDepth(dpy, screen));
1640	dc.gc = XCreateGC(dpy, root, 0, NULL);
1641	XSetLineAttributes(dpy, dc.gc, 1, LineSolid, CapButt, JoinMiter);
1642	if(!dc.font.set)
1643		XSetFont(dpy, dc.gc, dc.font.xfont->fid);
1644	/* init bars */
1645	updatebars();
1646	updatestatus();
1647	/* EWMH support per view */
1648	XChangeProperty(dpy, root, netatom[NetSupported], XA_ATOM, 32,
1649			PropModeReplace, (unsigned char *) netatom, NetLast);
1650	XDeleteProperty(dpy, root, netatom[NetClientList]);
1651	/* select for events */
1652	wa.cursor = cursor[CurNormal];
1653	wa.event_mask = SubstructureRedirectMask|SubstructureNotifyMask|ButtonPressMask|PointerMotionMask
1654	                |EnterWindowMask|LeaveWindowMask|StructureNotifyMask|PropertyChangeMask;
1655	XChangeWindowAttributes(dpy, root, CWEventMask|CWCursor, &wa);
1656	XSelectInput(dpy, root, wa.event_mask);
1657	grabkeys();
1658}
1659
1660void
1661showhide(Client *c) {
1662	if(!c)
1663		return;
1664	if(ISVISIBLE(c)) { /* show clients top down */
1665		XMoveWindow(dpy, c->win, c->x, c->y);
1666		if((!c->mon->lt[c->mon->sellt]->arrange || c->isfloating) && !c->isfullscreen)
1667			resize(c, c->x, c->y, c->w, c->h, False);
1668		showhide(c->snext);
1669	}
1670	else { /* hide clients bottom up */
1671		showhide(c->snext);
1672		XMoveWindow(dpy, c->win, WIDTH(c) * -2, c->y);
1673	}
1674}
1675
1676void
1677sigchld(int unused) {
1678	if(signal(SIGCHLD, sigchld) == SIG_ERR)
1679		die("Can't install SIGCHLD handler");
1680	while(0 < waitpid(-1, NULL, WNOHANG));
1681}
1682
1683void
1684spawn(const Arg *arg) {
1685	if(fork() == 0) {
1686		if(dpy)
1687			close(ConnectionNumber(dpy));
1688		setsid();
1689		execvp(((char **)arg->v)[0], (char **)arg->v);
1690		fprintf(stderr, "dwm: execvp %s", ((char **)arg->v)[0]);
1691		perror(" failed");
1692		exit(EXIT_SUCCESS);
1693	}
1694}
1695
1696void
1697tag(const Arg *arg) {
1698	if(selmon->sel && arg->ui & TAGMASK) {
1699		selmon->sel->tags = arg->ui & TAGMASK;
1700		focus(NULL);
1701		arrange(selmon);
1702	}
1703}
1704
1705void
1706tagmon(const Arg *arg) {
1707	if(!selmon->sel || !mons->next)
1708		return;
1709	sendmon(selmon->sel, dirtomon(arg->i));
1710}
1711
1712int
1713textnw(const char *text, unsigned int len) {
1714	XRectangle r;
1715
1716	if(dc.font.set) {
1717		XmbTextExtents(dc.font.set, text, len, NULL, &r);
1718		return r.width;
1719	}
1720	return XTextWidth(dc.font.xfont, text, len);
1721}
1722
1723void
1724tile(Monitor *m) {
1725	unsigned int i, n, h, mw, my, ty;
1726	Client *c;
1727
1728	for(n = 0, c = nexttiled(m->clients); c; c = nexttiled(c->next), n++);
1729	if(n == 0)
1730		return;
1731
1732	if(n > m->nmaster)
1733		mw = m->nmaster ? m->ww * m->mfact : 0;
1734	else
1735		mw = m->ww;
1736	for(i = my = ty = 0, c = nexttiled(m->clients); c; c = nexttiled(c->next), i++)
1737		if(i < m->nmaster) {
1738			h = (m->wh - my) / (MIN(n, m->nmaster) - i);
1739			resize(c, m->wx, m->wy + my, mw - (2*c->bw), h - (2*c->bw), False);
1740			my += HEIGHT(c);
1741		}
1742		else {
1743			h = (m->wh - ty) / (n - i);
1744			resize(c, m->wx + mw, m->wy + ty, m->ww - mw - (2*c->bw), h - (2*c->bw), False);
1745			ty += HEIGHT(c);
1746		}
1747}
1748
1749void
1750togglebar(const Arg *arg) {
1751	selmon->showbar = !selmon->showbar;
1752	updatebarpos(selmon);
1753	XMoveResizeWindow(dpy, selmon->barwin, selmon->wx, selmon->by, selmon->ww, bh);
1754	arrange(selmon);
1755}
1756
1757void
1758togglefloating(const Arg *arg) {
1759	if(!selmon->sel)
1760		return;
1761	if(selmon->sel->isfullscreen) /* no support for fullscreen windows */
1762		return;
1763	selmon->sel->isfloating = !selmon->sel->isfloating || selmon->sel->isfixed;
1764	if(selmon->sel->isfloating)
1765		resize(selmon->sel, selmon->sel->x, selmon->sel->y,
1766		       selmon->sel->w, selmon->sel->h, False);
1767	arrange(selmon);
1768}
1769
1770void
1771toggletag(const Arg *arg) {
1772	unsigned int newtags;
1773
1774	if(!selmon->sel)
1775		return;
1776	newtags = selmon->sel->tags ^ (arg->ui & TAGMASK);
1777	if(newtags) {
1778		selmon->sel->tags = newtags;
1779		focus(NULL);
1780		arrange(selmon);
1781	}
1782}
1783
1784void
1785toggleview(const Arg *arg) {
1786	unsigned int newtagset = selmon->tagset[selmon->seltags] ^ (arg->ui & TAGMASK);
1787
1788	if(newtagset) {
1789		selmon->tagset[selmon->seltags] = newtagset;
1790		focus(NULL);
1791		arrange(selmon);
1792	}
1793}
1794
1795void
1796unfocus(Client *c, Bool setfocus) {
1797	if(!c)
1798		return;
1799	grabbuttons(c, False);
1800	XSetWindowBorder(dpy, c->win, dc.norm[ColBorder]);
1801	if(setfocus) {
1802		XSetInputFocus(dpy, root, RevertToPointerRoot, CurrentTime);
1803		XDeleteProperty(dpy, root, netatom[NetActiveWindow]);
1804	}
1805}
1806
1807void
1808unmanage(Client *c, Bool destroyed) {
1809	Monitor *m = c->mon;
1810	XWindowChanges wc;
1811
1812	/* The server grab construct avoids race conditions. */
1813	detach(c);
1814	detachstack(c);
1815	if(!destroyed) {
1816		wc.border_width = c->oldbw;
1817		XGrabServer(dpy);
1818		XSetErrorHandler(xerrordummy);
1819		XConfigureWindow(dpy, c->win, CWBorderWidth, &wc); /* restore border */
1820		XUngrabButton(dpy, AnyButton, AnyModifier, c->win);
1821		setclientstate(c, WithdrawnState);
1822		XSync(dpy, False);
1823		XSetErrorHandler(xerror);
1824		XUngrabServer(dpy);
1825	}
1826	free(c);
1827	focus(NULL);
1828	updateclientlist();
1829	arrange(m);
1830}
1831
1832void
1833unmapnotify(XEvent *e) {
1834	Client *c;
1835	XUnmapEvent *ev = &e->xunmap;
1836
1837	if((c = wintoclient(ev->window))) {
1838		if(ev->send_event)
1839			setclientstate(c, WithdrawnState);
1840		else
1841			unmanage(c, False);
1842	}
1843}
1844
1845void
1846updatebars(void) {
1847	Monitor *m;
1848	XSetWindowAttributes wa = {
1849		.override_redirect = True,
1850		.background_pixmap = ParentRelative,
1851		.event_mask = ButtonPressMask|ExposureMask
1852	};
1853	for(m = mons; m; m = m->next) {
1854		if (m->barwin)
1855			continue;
1856		m->barwin = XCreateWindow(dpy, root, m->wx, m->by, m->ww, bh, 0, DefaultDepth(dpy, screen),
1857		                          CopyFromParent, DefaultVisual(dpy, screen),
1858		                          CWOverrideRedirect|CWBackPixmap|CWEventMask, &wa);
1859		XDefineCursor(dpy, m->barwin, cursor[CurNormal]);
1860		XMapRaised(dpy, m->barwin);
1861	}
1862}
1863
1864void
1865updatebarpos(Monitor *m) {
1866	m->wy = m->my;
1867	m->wh = m->mh;
1868	if(m->showbar) {
1869		m->wh -= bh;
1870		m->by = m->topbar ? m->wy : m->wy + m->wh;
1871		m->wy = m->topbar ? m->wy + bh : m->wy;
1872	}
1873	else
1874		m->by = -bh;
1875}
1876
1877void
1878updateclientlist() {
1879	Client *c;
1880	Monitor *m;
1881
1882	XDeleteProperty(dpy, root, netatom[NetClientList]);
1883	for(m = mons; m; m = m->next)
1884		for(c = m->clients; c; c = c->next)
1885			XChangeProperty(dpy, root, netatom[NetClientList],
1886			                XA_WINDOW, 32, PropModeAppend,
1887			                (unsigned char *) &(c->win), 1);
1888}
1889
1890Bool
1891updategeom(void) {
1892	Bool dirty = False;
1893
1894#ifdef XINERAMA
1895	if(XineramaIsActive(dpy)) {
1896		int i, j, n, nn;
1897		Client *c;
1898		Monitor *m;
1899		XineramaScreenInfo *info = XineramaQueryScreens(dpy, &nn);
1900		XineramaScreenInfo *unique = NULL;
1901
1902		for(n = 0, m = mons; m; m = m->next, n++);
1903		/* only consider unique geometries as separate screens */
1904		if(!(unique = (XineramaScreenInfo *)malloc(sizeof(XineramaScreenInfo) * nn)))
1905			die("fatal: could not malloc() %u bytes\n", sizeof(XineramaScreenInfo) * nn);
1906		for(i = 0, j = 0; i < nn; i++)
1907			if(isuniquegeom(unique, j, &info[i]))
1908				memcpy(&unique[j++], &info[i], sizeof(XineramaScreenInfo));
1909		XFree(info);
1910		nn = j;
1911		if(n <= nn) {
1912			for(i = 0; i < (nn - n); i++) { /* new monitors available */
1913				for(m = mons; m && m->next; m = m->next);
1914				if(m)
1915					m->next = createmon();
1916				else
1917					mons = createmon();
1918			}
1919			for(i = 0, m = mons; i < nn && m; m = m->next, i++)
1920				if(i >= n
1921				|| (unique[i].x_org != m->mx || unique[i].y_org != m->my
1922				    || unique[i].width != m->mw || unique[i].height != m->mh))
1923				{
1924					dirty = True;
1925					m->num = i;
1926					m->mx = m->wx = unique[i].x_org;
1927					m->my = m->wy = unique[i].y_org;
1928					m->mw = m->ww = unique[i].width;
1929					m->mh = m->wh = unique[i].height;
1930					updatebarpos(m);
1931				}
1932		}
1933		else { /* less monitors available nn < n */
1934			for(i = nn; i < n; i++) {
1935				for(m = mons; m && m->next; m = m->next);
1936				while(m->clients) {
1937					dirty = True;
1938					c = m->clients;
1939					m->clients = c->next;
1940					detachstack(c);
1941					c->mon = mons;
1942					attach(c);
1943					attachstack(c);
1944				}
1945				if(m == selmon)
1946					selmon = mons;
1947				cleanupmon(m);
1948			}
1949		}
1950		free(unique);
1951	}
1952	else
1953#endif /* XINERAMA */
1954	/* default monitor setup */
1955	{
1956		if(!mons)
1957			mons = createmon();
1958		if(mons->mw != sw || mons->mh != sh) {
1959			dirty = True;
1960			mons->mw = mons->ww = sw;
1961			mons->mh = mons->wh = sh;
1962			updatebarpos(mons);
1963		}
1964	}
1965	if(dirty) {
1966		selmon = mons;
1967		selmon = wintomon(root);
1968	}
1969	return dirty;
1970}
1971
1972void
1973updatenumlockmask(void) {
1974	unsigned int i, j;
1975	XModifierKeymap *modmap;
1976
1977	numlockmask = 0;
1978	modmap = XGetModifierMapping(dpy);
1979	for(i = 0; i < 8; i++)
1980		for(j = 0; j < modmap->max_keypermod; j++)
1981			if(modmap->modifiermap[i * modmap->max_keypermod + j]
1982			   == XKeysymToKeycode(dpy, XK_Num_Lock))
1983				numlockmask = (1 << i);
1984	XFreeModifiermap(modmap);
1985}
1986
1987void
1988updatesizehints(Client *c) {
1989	long msize;
1990	XSizeHints size;
1991
1992	if(!XGetWMNormalHints(dpy, c->win, &size, &msize))
1993		/* size is uninitialized, ensure that size.flags aren't used */
1994		size.flags = PSize;
1995	if(size.flags & PBaseSize) {
1996		c->basew = size.base_width;
1997		c->baseh = size.base_height;
1998	}
1999	else if(size.flags & PMinSize) {
2000		c->basew = size.min_width;
2001		c->baseh = size.min_height;
2002	}
2003	else
2004		c->basew = c->baseh = 0;
2005	if(size.flags & PResizeInc) {
2006		c->incw = size.width_inc;
2007		c->inch = size.height_inc;
2008	}
2009	else
2010		c->incw = c->inch = 0;
2011	if(size.flags & PMaxSize) {
2012		c->maxw = size.max_width;
2013		c->maxh = size.max_height;
2014	}
2015	else
2016		c->maxw = c->maxh = 0;
2017	if(size.flags & PMinSize) {
2018		c->minw = size.min_width;
2019		c->minh = size.min_height;
2020	}
2021	else if(size.flags & PBaseSize) {
2022		c->minw = size.base_width;
2023		c->minh = size.base_height;
2024	}
2025	else
2026		c->minw = c->minh = 0;
2027	if(size.flags & PAspect) {
2028		c->mina = (float)size.min_aspect.y / size.min_aspect.x;
2029		c->maxa = (float)size.max_aspect.x / size.max_aspect.y;
2030	}
2031	else
2032		c->maxa = c->mina = 0.0;
2033	c->isfixed = (c->maxw && c->minw && c->maxh && c->minh
2034	             && c->maxw == c->minw && c->maxh == c->minh);
2035}
2036
2037void
2038updatetitle(Client *c) {
2039	if(!gettextprop(c->win, netatom[NetWMName], c->name, sizeof c->name))
2040		gettextprop(c->win, XA_WM_NAME, c->name, sizeof c->name);
2041	if(c->name[0] == '\0') /* hack to mark broken clients */
2042		strcpy(c->name, broken);
2043}
2044
2045void
2046updatestatus(void) {
2047	if(!gettextprop(root, XA_WM_NAME, stext, sizeof(stext)))
2048		strcpy(stext, "dwm-"VERSION);
2049	drawbar(selmon);
2050}
2051
2052void
2053updatewindowtype(Client *c) {
2054	Atom state = getatomprop(c, netatom[NetWMState]);
2055	Atom wtype = getatomprop(c, netatom[NetWMWindowType]);
2056
2057	if(state == netatom[NetWMFullscreen])
2058		setfullscreen(c, True);
2059	if(wtype == netatom[NetWMWindowTypeDialog])
2060		c->isfloating = True;
2061}
2062
2063void
2064updatewmhints(Client *c) {
2065	XWMHints *wmh;
2066
2067	if((wmh = XGetWMHints(dpy, c->win))) {
2068		if(c == selmon->sel && wmh->flags & XUrgencyHint) {
2069			wmh->flags &= ~XUrgencyHint;
2070			XSetWMHints(dpy, c->win, wmh);
2071		}
2072		else
2073			c->isurgent = (wmh->flags & XUrgencyHint) ? True : False;
2074		if(wmh->flags & InputHint)
2075			c->neverfocus = !wmh->input;
2076		else
2077			c->neverfocus = False;
2078		XFree(wmh);
2079	}
2080}
2081
2082void
2083view(const Arg *arg) {
2084	if((arg->ui & TAGMASK) == selmon->tagset[selmon->seltags])
2085		return;
2086	selmon->seltags ^= 1; /* toggle sel tagset */
2087	if(arg->ui & TAGMASK)
2088		selmon->tagset[selmon->seltags] = arg->ui & TAGMASK;
2089	focus(NULL);
2090	arrange(selmon);
2091}
2092
2093Client *
2094wintoclient(Window w) {
2095	Client *c;
2096	Monitor *m;
2097
2098	for(m = mons; m; m = m->next)
2099		for(c = m->clients; c; c = c->next)
2100			if(c->win == w)
2101				return c;
2102	return NULL;
2103}
2104
2105Monitor *
2106wintomon(Window w) {
2107	int x, y;
2108	Client *c;
2109	Monitor *m;
2110
2111	if(w == root && getrootptr(&x, &y))
2112		return recttomon(x, y, 1, 1);
2113	for(m = mons; m; m = m->next)
2114		if(w == m->barwin)
2115			return m;
2116	if((c = wintoclient(w)))
2117		return c->mon;
2118	return selmon;
2119}
2120
2121/* There's no way to check accesses to destroyed windows, thus those cases are
2122 * ignored (especially on UnmapNotify's).  Other types of errors call Xlibs
2123 * default error handler, which may call exit.  */
2124int
2125xerror(Display *dpy, XErrorEvent *ee) {
2126	if(ee->error_code == BadWindow
2127	|| (ee->request_code == X_SetInputFocus && ee->error_code == BadMatch)
2128	|| (ee->request_code == X_PolyText8 && ee->error_code == BadDrawable)
2129	|| (ee->request_code == X_PolyFillRectangle && ee->error_code == BadDrawable)
2130	|| (ee->request_code == X_PolySegment && ee->error_code == BadDrawable)
2131	|| (ee->request_code == X_ConfigureWindow && ee->error_code == BadMatch)
2132	|| (ee->request_code == X_GrabButton && ee->error_code == BadAccess)
2133	|| (ee->request_code == X_GrabKey && ee->error_code == BadAccess)
2134	|| (ee->request_code == X_CopyArea && ee->error_code == BadDrawable))
2135		return 0;
2136	fprintf(stderr, "dwm: fatal error: request code=%d, error code=%d\n",
2137			ee->request_code, ee->error_code);
2138	return xerrorxlib(dpy, ee); /* may call exit */
2139}
2140
2141int
2142xerrordummy(Display *dpy, XErrorEvent *ee) {
2143	return 0;
2144}
2145
2146/* Startup Error handler to check if another window manager
2147 * is already running. */
2148int
2149xerrorstart(Display *dpy, XErrorEvent *ee) {
2150	die("dwm: another window manager is already running\n");
2151	return -1;
2152}
2153
2154void
2155zoom(const Arg *arg) {
2156	Client *c = selmon->sel;
2157
2158	if(!selmon->lt[selmon->sellt]->arrange
2159	|| (selmon->sel && selmon->sel->isfloating))
2160		return;
2161	if(c == nexttiled(selmon->clients))
2162		if(!c || !(c = nexttiled(c->next)))
2163			return;
2164	pop(c);
2165}
2166
2167int
2168main(int argc, char *argv[]) {
2169	if(argc == 2 && !strcmp("-v", argv[1]))
2170		die("dwm-"VERSION", © 2006-2012 dwm engineers, see LICENSE for details\n");
2171	else if(argc != 1)
2172		die("usage: dwm [-v]\n");
2173	if(!setlocale(LC_CTYPE, "") || !XSupportsLocale())
2174		fputs("warning: no locale support\n", stderr);
2175	if(!(dpy = XOpenDisplay(NULL)))
2176		die("dwm: cannot open display\n");
2177	checkotherwm();
2178	setup();
2179	scan();
2180	run();
2181	cleanup();
2182	XCloseDisplay(dpy);
2183	return EXIT_SUCCESS;
2184}