all repos — dwm @ 2dbfda72f0c7269c3fcbb5c93173013e7dd0bea6

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 global
  15 * linked client list, the focus history is remembered through a global
  16 * stack list. 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
  42
  43/* macros */
  44#define BUTTONMASK              (ButtonPressMask|ButtonReleaseMask)
  45#define CLEANMASK(mask)         (mask & ~(numlockmask|LockMask))
  46#define INRECT(X,Y,RX,RY,RW,RH) ((X) >= (RX) && (X) < (RX) + (RW) && (Y) >= (RY) && (Y) < (RY) + (RH))
  47#define ISVISIBLE(x)            (x->tags & tagset[seltags])
  48#define LENGTH(x)               (sizeof x / sizeof x[0])
  49#define MAX(a, b)               ((a) > (b) ? (a) : (b))
  50#define MIN(a, b)               ((a) < (b) ? (a) : (b))
  51#define MOUSEMASK               (BUTTONMASK|PointerMotionMask)
  52#define WIDTH(x)                ((x)->w + 2 * (x)->bw)
  53#define HEIGHT(x)               ((x)->h + 2 * (x)->bw)
  54#define TAGMASK                 ((int)((1LL << LENGTH(tags)) - 1))
  55#define TEXTW(x)                (textnw(x, strlen(x)) + dc.font.height)
  56
  57/* enums */
  58enum { CurNormal, CurResize, CurMove, CurLast };        /* cursor */
  59enum { ColBorder, ColFG, ColBG, ColLast };              /* color */
  60enum { NetSupported, NetWMName, NetLast };              /* EWMH atoms */
  61enum { WMProtocols, WMDelete, WMState, WMLast };        /* default atoms */
  62enum { ClkTagBar, ClkLtSymbol, ClkStatusText, ClkWinTitle,
  63       ClkClientWin, ClkRootWin, ClkLast };             /* clicks */
  64
  65typedef union {
  66	int i;
  67	unsigned int ui;
  68	float f;
  69	void *v;
  70} Arg;
  71
  72typedef struct {
  73	unsigned int click;
  74	unsigned int mask;
  75	unsigned int button;
  76	void (*func)(const Arg *arg);
  77	const Arg arg;
  78} Button;
  79
  80typedef struct Client Client;
  81struct Client {
  82	char name[256];
  83	float mina, maxa;
  84	int x, y, w, h;
  85	int basew, baseh, incw, inch, maxw, maxh, minw, minh;
  86	int bw, oldbw;
  87	unsigned int tags;
  88	Bool isfixed, isfloating, isurgent;
  89	Client *next;
  90	Client *snext;
  91	Window win;
  92};
  93
  94typedef struct {
  95	int x, y, w, h;
  96	unsigned long norm[ColLast];
  97	unsigned long sel[ColLast];
  98	Drawable drawable;
  99	GC gc;
 100	struct {
 101		int ascent;
 102		int descent;
 103		int height;
 104		XFontSet set;
 105		XFontStruct *xfont;
 106	} font;
 107} DC; /* draw context */
 108
 109typedef struct {
 110	unsigned int mod;
 111	KeySym keysym;
 112	void (*func)(const Arg *);
 113	const Arg arg;
 114} Key;
 115
 116typedef struct {
 117	const char *symbol;
 118	void (*arrange)(void);
 119} Layout;
 120
 121typedef struct {
 122	const char *class;
 123	const char *instance;
 124	const char *title;
 125	unsigned int tags;
 126	Bool isfloating;
 127} Rule;
 128
 129/* function declarations */
 130static void applyrules(Client *c);
 131static Bool applysizehints(Client *c, int *x, int *y, int *w, int *h);
 132static void arrange(void);
 133static void attach(Client *c);
 134static void attachstack(Client *c);
 135static void buttonpress(XEvent *e);
 136static void checkotherwm(void);
 137static void cleanup(void);
 138static void clearurgent(Client *c);
 139static void configure(Client *c);
 140static void configurenotify(XEvent *e);
 141static void configurerequest(XEvent *e);
 142static void destroynotify(XEvent *e);
 143static void detach(Client *c);
 144static void detachstack(Client *c);
 145static void die(const char *errstr, ...);
 146static void drawbar(void);
 147static void drawsquare(Bool filled, Bool empty, Bool invert, unsigned long col[ColLast]);
 148static void drawtext(const char *text, unsigned long col[ColLast], Bool invert);
 149static void enternotify(XEvent *e);
 150static void expose(XEvent *e);
 151static void focus(Client *c);
 152static void focusin(XEvent *e);
 153static void focusstack(const Arg *arg);
 154static Client *getclient(Window w);
 155static unsigned long getcolor(const char *colstr);
 156static long getstate(Window w);
 157static Bool gettextprop(Window w, Atom atom, char *text, unsigned int size);
 158static void grabbuttons(Client *c, Bool focused);
 159static void grabkeys(void);
 160static void initfont(const char *fontstr);
 161static Bool isprotodel(Client *c);
 162static void keypress(XEvent *e);
 163static void killclient(const Arg *arg);
 164static void manage(Window w, XWindowAttributes *wa);
 165static void mappingnotify(XEvent *e);
 166static void maprequest(XEvent *e);
 167static void monocle(void);
 168static void movemouse(const Arg *arg);
 169static Client *nexttiled(Client *c);
 170static void propertynotify(XEvent *e);
 171static void quit(const Arg *arg);
 172static void resize(Client *c, int x, int y, int w, int h);
 173static void resizemouse(const Arg *arg);
 174static void restack(void);
 175static void run(void);
 176static void scan(void);
 177static void setclientstate(Client *c, long state);
 178static void setlayout(const Arg *arg);
 179static void setmfact(const Arg *arg);
 180static void setup(void);
 181static void showhide(Client *c);
 182static void sigchld(int signal);
 183static void spawn(const Arg *arg);
 184static void tag(const Arg *arg);
 185static int textnw(const char *text, unsigned int len);
 186static void tile(void);
 187static void togglebar(const Arg *arg);
 188static void togglefloating(const Arg *arg);
 189static void toggletag(const Arg *arg);
 190static void toggleview(const Arg *arg);
 191static void unmanage(Client *c);
 192static void unmapnotify(XEvent *e);
 193static void updatebar(void);
 194static void updategeom(void);
 195static void updatenumlockmask(void);
 196static void updatesizehints(Client *c);
 197static void updatestatus(void);
 198static void updatetitle(Client *c);
 199static void updatewmhints(Client *c);
 200static void view(const Arg *arg);
 201static int xerror(Display *dpy, XErrorEvent *ee);
 202static int xerrordummy(Display *dpy, XErrorEvent *ee);
 203static int xerrorstart(Display *dpy, XErrorEvent *ee);
 204static void zoom(const Arg *arg);
 205
 206/* variables */
 207static char stext[256];
 208static int screen;
 209static int sx, sy, sw, sh; /* X display screen geometry x, y, width, height */ 
 210static int by, bh, blw;    /* bar geometry y, height and layout symbol width */
 211static int wx, wy, ww, wh; /* window area geometry x, y, width, height, bar excluded */
 212static unsigned int seltags = 0, sellt = 0;
 213static int (*xerrorxlib)(Display *, XErrorEvent *);
 214static unsigned int numlockmask = 0;
 215static void (*handler[LASTEvent]) (XEvent *) = {
 216	[ButtonPress] = buttonpress,
 217	[ConfigureRequest] = configurerequest,
 218	[ConfigureNotify] = configurenotify,
 219	[DestroyNotify] = destroynotify,
 220	[EnterNotify] = enternotify,
 221	[Expose] = expose,
 222	[FocusIn] = focusin,
 223	[KeyPress] = keypress,
 224	[MappingNotify] = mappingnotify,
 225	[MapRequest] = maprequest,
 226	[PropertyNotify] = propertynotify,
 227	[UnmapNotify] = unmapnotify
 228};
 229static Atom wmatom[WMLast], netatom[NetLast];
 230static Bool otherwm;
 231static Bool running = True;
 232static Client *clients = NULL;
 233static Client *sel = NULL;
 234static Client *stack = NULL;
 235static Cursor cursor[CurLast];
 236static Display *dpy;
 237static DC dc;
 238static Layout *lt[] = { NULL, NULL };
 239static Window root, barwin;
 240/* configuration, allows nested code to access above variables */
 241#include "config.h"
 242
 243/* compile-time check if all tags fit into an unsigned int bit array. */
 244struct NumTags { char limitexceeded[sizeof(unsigned int) * 8 < LENGTH(tags) ? -1 : 1]; };
 245
 246/* function implementations */
 247void
 248applyrules(Client *c) {
 249	unsigned int i;
 250	Rule *r;
 251	XClassHint ch = { 0 };
 252
 253	/* rule matching */
 254	c->isfloating = c->tags = 0;
 255	if(XGetClassHint(dpy, c->win, &ch)) {
 256		for(i = 0; i < LENGTH(rules); i++) {
 257			r = &rules[i];
 258			if((!r->title || strstr(c->name, r->title))
 259			&& (!r->class || (ch.res_class && strstr(ch.res_class, r->class)))
 260			&& (!r->instance || (ch.res_name && strstr(ch.res_name, r->instance)))) {
 261				c->isfloating = r->isfloating;
 262				c->tags |= r->tags; 
 263			}
 264		}
 265		if(ch.res_class)
 266			XFree(ch.res_class);
 267		if(ch.res_name)
 268			XFree(ch.res_name);
 269	}
 270	c->tags = c->tags & TAGMASK ? c->tags & TAGMASK : tagset[seltags];
 271}
 272
 273Bool
 274applysizehints(Client *c, int *x, int *y, int *w, int *h) {
 275	Bool baseismin;
 276
 277	/* set minimum possible */
 278	*w = MAX(1, *w);
 279	*h = MAX(1, *h);
 280
 281	if(*x > sx + sw)
 282		*x = sw - WIDTH(c);
 283	if(*y > sy + sh)
 284		*y = sh - HEIGHT(c);
 285	if(*x + *w + 2 * c->bw < sx)
 286		*x = sx;
 287	if(*y + *h + 2 * c->bw < sy)
 288		*y = sy;
 289	if(*h < bh)
 290		*h = bh;
 291	if(*w < bh)
 292		*w = bh;
 293
 294	if(resizehints || c->isfloating) {
 295		/* see last two sentences in ICCCM 4.1.2.3 */
 296		baseismin = c->basew == c->minw && c->baseh == c->minh;
 297
 298		if(!baseismin) { /* temporarily remove base dimensions */
 299			*w -= c->basew;
 300			*h -= c->baseh;
 301		}
 302
 303		/* adjust for aspect limits */
 304		if(c->mina > 0 && c->maxa > 0) {
 305			if(c->maxa < (float)*w / *h)
 306				*w = *h * c->maxa;
 307			else if(c->mina < (float)*h / *w)
 308				*h = *w * c->mina;
 309		}
 310
 311		if(baseismin) { /* increment calculation requires this */
 312			*w -= c->basew;
 313			*h -= c->baseh;
 314		}
 315
 316		/* adjust for increment value */
 317		if(c->incw)
 318			*w -= *w % c->incw;
 319		if(c->inch)
 320			*h -= *h % c->inch;
 321
 322		/* restore base dimensions */
 323		*w += c->basew;
 324		*h += c->baseh;
 325
 326		*w = MAX(*w, c->minw);
 327		*h = MAX(*h, c->minh);
 328
 329		if(c->maxw)
 330			*w = MIN(*w, c->maxw);
 331
 332		if(c->maxh)
 333			*h = MIN(*h, c->maxh);
 334	}
 335	return *x != c->x || *y != c->y || *w != c->w || *h != c->h;
 336}
 337
 338void
 339arrange(void) {
 340	showhide(stack);
 341	focus(NULL);
 342	if(lt[sellt]->arrange)
 343		lt[sellt]->arrange();
 344	restack();
 345}
 346
 347void
 348attach(Client *c) {
 349	c->next = clients;
 350	clients = c;
 351}
 352
 353void
 354attachstack(Client *c) {
 355	c->snext = stack;
 356	stack = c;
 357}
 358
 359void
 360buttonpress(XEvent *e) {
 361	unsigned int i, x, click;
 362	Arg arg = {0};
 363	Client *c;
 364	XButtonPressedEvent *ev = &e->xbutton;
 365
 366	click = ClkRootWin;
 367	if(ev->window == barwin) {
 368		i = x = 0;
 369		do x += TEXTW(tags[i]); while(ev->x >= x && ++i < LENGTH(tags));
 370		if(i < LENGTH(tags)) {
 371			click = ClkTagBar;
 372			arg.ui = 1 << i;
 373		}
 374		else if(ev->x < x + blw)
 375			click = ClkLtSymbol;
 376		else if(ev->x > wx + ww - TEXTW(stext))
 377			click = ClkStatusText;
 378		else
 379			click = ClkWinTitle;
 380	}
 381	else if((c = getclient(ev->window))) {
 382		focus(c);
 383		click = ClkClientWin;
 384	}
 385
 386	for(i = 0; i < LENGTH(buttons); i++)
 387		if(click == buttons[i].click && buttons[i].func && buttons[i].button == ev->button
 388		   && CLEANMASK(buttons[i].mask) == CLEANMASK(ev->state))
 389			buttons[i].func(click == ClkTagBar && buttons[i].arg.i == 0 ? &arg : &buttons[i].arg);
 390}
 391
 392void
 393checkotherwm(void) {
 394	otherwm = False;
 395	xerrorxlib = XSetErrorHandler(xerrorstart);
 396
 397	/* this causes an error if some other window manager is running */
 398	XSelectInput(dpy, DefaultRootWindow(dpy), SubstructureRedirectMask);
 399	XSync(dpy, False);
 400	if(otherwm)
 401		die("dwm: another window manager is already running\n");
 402	XSetErrorHandler(xerror);
 403	XSync(dpy, False);
 404}
 405
 406void
 407cleanup(void) {
 408	Arg a = {.ui = ~0};
 409	Layout foo = { "", NULL };
 410
 411	view(&a);
 412	lt[sellt] = &foo;
 413	while(stack)
 414		unmanage(stack);
 415	if(dc.font.set)
 416		XFreeFontSet(dpy, dc.font.set);
 417	else
 418		XFreeFont(dpy, dc.font.xfont);
 419	XUngrabKey(dpy, AnyKey, AnyModifier, root);
 420	XFreePixmap(dpy, dc.drawable);
 421	XFreeGC(dpy, dc.gc);
 422	XFreeCursor(dpy, cursor[CurNormal]);
 423	XFreeCursor(dpy, cursor[CurResize]);
 424	XFreeCursor(dpy, cursor[CurMove]);
 425	XDestroyWindow(dpy, barwin);
 426	XSync(dpy, False);
 427	XSetInputFocus(dpy, PointerRoot, RevertToPointerRoot, CurrentTime);
 428}
 429
 430void
 431clearurgent(Client *c) {
 432	XWMHints *wmh;
 433
 434	c->isurgent = False;
 435	if(!(wmh = XGetWMHints(dpy, c->win)))
 436		return;
 437	wmh->flags &= ~XUrgencyHint;
 438	XSetWMHints(dpy, c->win, wmh);
 439	XFree(wmh);
 440}
 441
 442void
 443configure(Client *c) {
 444	XConfigureEvent ce;
 445
 446	ce.type = ConfigureNotify;
 447	ce.display = dpy;
 448	ce.event = c->win;
 449	ce.window = c->win;
 450	ce.x = c->x;
 451	ce.y = c->y;
 452	ce.width = c->w;
 453	ce.height = c->h;
 454	ce.border_width = c->bw;
 455	ce.above = None;
 456	ce.override_redirect = False;
 457	XSendEvent(dpy, c->win, False, StructureNotifyMask, (XEvent *)&ce);
 458}
 459
 460void
 461configurenotify(XEvent *e) {
 462	XConfigureEvent *ev = &e->xconfigure;
 463
 464	if(ev->window == root && (ev->width != sw || ev->height != sh)) {
 465		sw = ev->width;
 466		sh = ev->height;
 467		updategeom();
 468		updatebar();
 469		arrange();
 470	}
 471}
 472
 473void
 474configurerequest(XEvent *e) {
 475	Client *c;
 476	XConfigureRequestEvent *ev = &e->xconfigurerequest;
 477	XWindowChanges wc;
 478
 479	if((c = getclient(ev->window))) {
 480		if(ev->value_mask & CWBorderWidth)
 481			c->bw = ev->border_width;
 482		else if(c->isfloating || !lt[sellt]->arrange) {
 483			if(ev->value_mask & CWX)
 484				c->x = sx + ev->x;
 485			if(ev->value_mask & CWY)
 486				c->y = sy + ev->y;
 487			if(ev->value_mask & CWWidth)
 488				c->w = ev->width;
 489			if(ev->value_mask & CWHeight)
 490				c->h = ev->height;
 491			if((c->x - sx + c->w) > sw && c->isfloating)
 492				c->x = sx + (sw / 2 - c->w / 2); /* center in x direction */
 493			if((c->y - sy + c->h) > sh && c->isfloating)
 494				c->y = sy + (sh / 2 - c->h / 2); /* center in y direction */
 495			if((ev->value_mask & (CWX|CWY)) && !(ev->value_mask & (CWWidth|CWHeight)))
 496				configure(c);
 497			if(ISVISIBLE(c))
 498				XMoveResizeWindow(dpy, c->win, c->x, c->y, c->w, c->h);
 499		}
 500		else
 501			configure(c);
 502	}
 503	else {
 504		wc.x = ev->x;
 505		wc.y = ev->y;
 506		wc.width = ev->width;
 507		wc.height = ev->height;
 508		wc.border_width = ev->border_width;
 509		wc.sibling = ev->above;
 510		wc.stack_mode = ev->detail;
 511		XConfigureWindow(dpy, ev->window, ev->value_mask, &wc);
 512	}
 513	XSync(dpy, False);
 514}
 515
 516void
 517destroynotify(XEvent *e) {
 518	Client *c;
 519	XDestroyWindowEvent *ev = &e->xdestroywindow;
 520
 521	if((c = getclient(ev->window)))
 522		unmanage(c);
 523}
 524
 525void
 526detach(Client *c) {
 527	Client **tc;
 528
 529	for(tc = &clients; *tc && *tc != c; tc = &(*tc)->next);
 530	*tc = c->next;
 531}
 532
 533void
 534detachstack(Client *c) {
 535	Client **tc;
 536
 537	for(tc = &stack; *tc && *tc != c; tc = &(*tc)->snext);
 538	*tc = c->snext;
 539}
 540
 541void
 542die(const char *errstr, ...) {
 543	va_list ap;
 544
 545	va_start(ap, errstr);
 546	vfprintf(stderr, errstr, ap);
 547	va_end(ap);
 548	exit(EXIT_FAILURE);
 549}
 550
 551void
 552drawbar(void) {
 553	int x;
 554	unsigned int i, occ = 0, urg = 0;
 555	unsigned long *col;
 556	Client *c;
 557
 558	for(c = clients; c; c = c->next) {
 559		occ |= c->tags;
 560		if(c->isurgent)
 561			urg |= c->tags;
 562	}
 563
 564	dc.x = 0;
 565	for(i = 0; i < LENGTH(tags); i++) {
 566		dc.w = TEXTW(tags[i]);
 567		col = tagset[seltags] & 1 << i ? dc.sel : dc.norm;
 568		drawtext(tags[i], col, urg & 1 << i);
 569		drawsquare(sel && sel->tags & 1 << i, occ & 1 << i, urg & 1 << i, col);
 570		dc.x += dc.w;
 571	}
 572	if(blw > 0) {
 573		dc.w = blw;
 574		drawtext(lt[sellt]->symbol, dc.norm, False);
 575		x = dc.x + dc.w;
 576	}
 577	else
 578		x = dc.x;
 579	dc.w = TEXTW(stext);
 580	dc.x = ww - dc.w;
 581	if(dc.x < x) {
 582		dc.x = x;
 583		dc.w = ww - x;
 584	}
 585	drawtext(stext, dc.norm, False);
 586	if((dc.w = dc.x - x) > bh) {
 587		dc.x = x;
 588		if(sel) {
 589			drawtext(sel->name, dc.sel, False);
 590			drawsquare(sel->isfixed, sel->isfloating, False, dc.sel);
 591		}
 592		else
 593			drawtext(NULL, dc.norm, False);
 594	}
 595	XCopyArea(dpy, dc.drawable, barwin, dc.gc, 0, 0, ww, bh, 0, 0);
 596	XSync(dpy, False);
 597}
 598
 599void
 600drawsquare(Bool filled, Bool empty, Bool invert, unsigned long col[ColLast]) {
 601	int x;
 602	XGCValues gcv;
 603	XRectangle r = { dc.x, dc.y, dc.w, dc.h };
 604
 605	gcv.foreground = col[invert ? ColBG : ColFG];
 606	XChangeGC(dpy, dc.gc, GCForeground, &gcv);
 607	x = (dc.font.ascent + dc.font.descent + 2) / 4;
 608	r.x = dc.x + 1;
 609	r.y = dc.y + 1;
 610	if(filled) {
 611		r.width = r.height = x + 1;
 612		XFillRectangles(dpy, dc.drawable, dc.gc, &r, 1);
 613	}
 614	else if(empty) {
 615		r.width = r.height = x;
 616		XDrawRectangles(dpy, dc.drawable, dc.gc, &r, 1);
 617	}
 618}
 619
 620void
 621drawtext(const char *text, unsigned long col[ColLast], Bool invert) {
 622	char buf[256];
 623	int i, x, y, h, len, olen;
 624	XRectangle r = { dc.x, dc.y, dc.w, dc.h };
 625
 626	XSetForeground(dpy, dc.gc, col[invert ? ColFG : ColBG]);
 627	XFillRectangles(dpy, dc.drawable, dc.gc, &r, 1);
 628	if(!text)
 629		return;
 630	olen = strlen(text);
 631	h = dc.font.ascent + dc.font.descent;
 632	y = dc.y + (dc.h / 2) - (h / 2) + dc.font.ascent;
 633	x = dc.x + (h / 2);
 634	/* shorten text if necessary */
 635	for(len = MIN(olen, sizeof buf); len && textnw(text, len) > dc.w - h; len--);
 636	if(!len)
 637		return;
 638	memcpy(buf, text, len);
 639	if(len < olen)
 640		for(i = len; i && i > len - 3; buf[--i] = '.');
 641	XSetForeground(dpy, dc.gc, col[invert ? ColBG : ColFG]);
 642	if(dc.font.set)
 643		XmbDrawString(dpy, dc.drawable, dc.font.set, dc.gc, x, y, buf, len);
 644	else
 645		XDrawString(dpy, dc.drawable, dc.gc, x, y, buf, len);
 646}
 647
 648void
 649enternotify(XEvent *e) {
 650	Client *c;
 651	XCrossingEvent *ev = &e->xcrossing;
 652
 653	if((ev->mode != NotifyNormal || ev->detail == NotifyInferior) && ev->window != root)
 654		return;
 655	if((c = getclient(ev->window)))
 656		focus(c);
 657	else
 658		focus(NULL);
 659}
 660
 661void
 662expose(XEvent *e) {
 663	XExposeEvent *ev = &e->xexpose;
 664
 665	if(ev->count == 0 && (ev->window == barwin))
 666		drawbar();
 667}
 668
 669void
 670focus(Client *c) {
 671	if(!c || !ISVISIBLE(c))
 672		for(c = stack; c && !ISVISIBLE(c); c = c->snext);
 673	if(sel && sel != c) {
 674		grabbuttons(sel, False);
 675		XSetWindowBorder(dpy, sel->win, dc.norm[ColBorder]);
 676	}
 677	if(c) {
 678		if(c->isurgent)
 679			clearurgent(c);
 680		detachstack(c);
 681		attachstack(c);
 682		grabbuttons(c, True);
 683		XSetWindowBorder(dpy, c->win, dc.sel[ColBorder]);
 684		XSetInputFocus(dpy, c->win, RevertToPointerRoot, CurrentTime);
 685	}
 686	else
 687		XSetInputFocus(dpy, root, RevertToPointerRoot, CurrentTime);
 688	sel = c;
 689	drawbar();
 690}
 691
 692void
 693focusin(XEvent *e) { /* there are some broken focus acquiring clients */
 694	XFocusChangeEvent *ev = &e->xfocus;
 695
 696	if(sel && ev->window != sel->win)
 697		XSetInputFocus(dpy, sel->win, RevertToPointerRoot, CurrentTime);
 698}
 699
 700void
 701focusstack(const Arg *arg) {
 702	Client *c = NULL, *i;
 703
 704	if(!sel)
 705		return;
 706	if (arg->i > 0) {
 707		for(c = sel->next; c && !ISVISIBLE(c); c = c->next);
 708		if(!c)
 709			for(c = clients; c && !ISVISIBLE(c); c = c->next);
 710	}
 711	else {
 712		for(i = clients; i != sel; i = i->next)
 713			if(ISVISIBLE(i))
 714				c = i;
 715		if(!c)
 716			for(; i; i = i->next)
 717				if(ISVISIBLE(i))
 718					c = i;
 719	}
 720	if(c) {
 721		focus(c);
 722		restack();
 723	}
 724}
 725
 726Client *
 727getclient(Window w) {
 728	Client *c;
 729
 730	for(c = clients; c && c->win != w; c = c->next);
 731	return c;
 732}
 733
 734unsigned long
 735getcolor(const char *colstr) {
 736	Colormap cmap = DefaultColormap(dpy, screen);
 737	XColor color;
 738
 739	if(!XAllocNamedColor(dpy, cmap, colstr, &color, &color))
 740		die("error, cannot allocate color '%s'\n", colstr);
 741	return color.pixel;
 742}
 743
 744long
 745getstate(Window w) {
 746	int format, status;
 747	long result = -1;
 748	unsigned char *p = NULL;
 749	unsigned long n, extra;
 750	Atom real;
 751
 752	status = XGetWindowProperty(dpy, w, wmatom[WMState], 0L, 2L, False, wmatom[WMState],
 753			&real, &format, &n, &extra, (unsigned char **)&p);
 754	if(status != Success)
 755		return -1;
 756	if(n != 0)
 757		result = *p;
 758	XFree(p);
 759	return result;
 760}
 761
 762Bool
 763gettextprop(Window w, Atom atom, char *text, unsigned int size) {
 764	char **list = NULL;
 765	int n;
 766	XTextProperty name;
 767
 768	if(!text || size == 0)
 769		return False;
 770	text[0] = '\0';
 771	XGetTextProperty(dpy, w, &name, atom);
 772	if(!name.nitems)
 773		return False;
 774	if(name.encoding == XA_STRING)
 775		strncpy(text, (char *)name.value, size - 1);
 776	else {
 777		if(XmbTextPropertyToTextList(dpy, &name, &list, &n) >= Success
 778		&& n > 0 && *list) {
 779			strncpy(text, *list, size - 1);
 780			XFreeStringList(list);
 781		}
 782	}
 783	text[size - 1] = '\0';
 784	XFree(name.value);
 785	return True;
 786}
 787
 788void
 789grabbuttons(Client *c, Bool focused) {
 790	updatenumlockmask();
 791	{
 792		unsigned int i, j;
 793		unsigned int modifiers[] = { 0, LockMask, numlockmask, numlockmask|LockMask };
 794		XUngrabButton(dpy, AnyButton, AnyModifier, c->win);
 795		if(focused) {
 796			for(i = 0; i < LENGTH(buttons); i++)
 797				if(buttons[i].click == ClkClientWin)
 798					for(j = 0; j < LENGTH(modifiers); j++)
 799						XGrabButton(dpy, buttons[i].button,
 800						            buttons[i].mask | modifiers[j],
 801						            c->win, False, BUTTONMASK,
 802						            GrabModeAsync, GrabModeSync, None, None);
 803		} else
 804			XGrabButton(dpy, AnyButton, AnyModifier, c->win, False,
 805			            BUTTONMASK, GrabModeAsync, GrabModeSync, None, None);
 806	}
 807}
 808
 809void
 810grabkeys(void) {
 811	updatenumlockmask();
 812	{ /* grab keys */
 813		unsigned int i, j;
 814		unsigned int modifiers[] = { 0, LockMask, numlockmask, numlockmask|LockMask };
 815		KeyCode code;
 816
 817		XUngrabKey(dpy, AnyKey, AnyModifier, root);
 818		for(i = 0; i < LENGTH(keys); i++) {
 819			if((code = XKeysymToKeycode(dpy, keys[i].keysym)))
 820				for(j = 0; j < LENGTH(modifiers); j++)
 821					XGrabKey(dpy, code, keys[i].mod | modifiers[j], root,
 822						 True, GrabModeAsync, GrabModeAsync);
 823		}
 824	}
 825}
 826
 827void
 828initfont(const char *fontstr) {
 829	char *def, **missing;
 830	int i, n;
 831
 832	missing = NULL;
 833	dc.font.set = XCreateFontSet(dpy, fontstr, &missing, &n, &def);
 834	if(missing) {
 835		while(n--)
 836			fprintf(stderr, "dwm: missing fontset: %s\n", missing[n]);
 837		XFreeStringList(missing);
 838	}
 839	if(dc.font.set) {
 840		XFontSetExtents *font_extents;
 841		XFontStruct **xfonts;
 842		char **font_names;
 843		dc.font.ascent = dc.font.descent = 0;
 844		font_extents = XExtentsOfFontSet(dc.font.set);
 845		n = XFontsOfFontSet(dc.font.set, &xfonts, &font_names);
 846		for(i = 0, dc.font.ascent = 0, dc.font.descent = 0; i < n; i++) {
 847			dc.font.ascent = MAX(dc.font.ascent, (*xfonts)->ascent);
 848			dc.font.descent = MAX(dc.font.descent,(*xfonts)->descent);
 849			xfonts++;
 850		}
 851	}
 852	else {
 853		if(!(dc.font.xfont = XLoadQueryFont(dpy, fontstr))
 854		&& !(dc.font.xfont = XLoadQueryFont(dpy, "fixed")))
 855			die("error, cannot load font: '%s'\n", fontstr);
 856		dc.font.ascent = dc.font.xfont->ascent;
 857		dc.font.descent = dc.font.xfont->descent;
 858	}
 859	dc.font.height = dc.font.ascent + dc.font.descent;
 860}
 861
 862Bool
 863isprotodel(Client *c) {
 864	int i, n;
 865	Atom *protocols;
 866	Bool ret = False;
 867
 868	if(XGetWMProtocols(dpy, c->win, &protocols, &n)) {
 869		for(i = 0; !ret && i < n; i++)
 870			if(protocols[i] == wmatom[WMDelete])
 871				ret = True;
 872		XFree(protocols);
 873	}
 874	return ret;
 875}
 876
 877void
 878keypress(XEvent *e) {
 879	unsigned int i;
 880	KeySym keysym;
 881	XKeyEvent *ev;
 882
 883	ev = &e->xkey;
 884	keysym = XKeycodeToKeysym(dpy, (KeyCode)ev->keycode, 0);
 885	for(i = 0; i < LENGTH(keys); i++)
 886		if(keysym == keys[i].keysym
 887		   && CLEANMASK(keys[i].mod) == CLEANMASK(ev->state)
 888		   && keys[i].func)
 889			keys[i].func(&(keys[i].arg));
 890}
 891
 892void
 893killclient(const Arg *arg) {
 894	XEvent ev;
 895
 896	if(!sel)
 897		return;
 898	if(isprotodel(sel)) {
 899		ev.type = ClientMessage;
 900		ev.xclient.window = sel->win;
 901		ev.xclient.message_type = wmatom[WMProtocols];
 902		ev.xclient.format = 32;
 903		ev.xclient.data.l[0] = wmatom[WMDelete];
 904		ev.xclient.data.l[1] = CurrentTime;
 905		XSendEvent(dpy, sel->win, False, NoEventMask, &ev);
 906	}
 907	else
 908		XKillClient(dpy, sel->win);
 909}
 910
 911void
 912manage(Window w, XWindowAttributes *wa) {
 913	static Client cz;
 914	Client *c, *t = NULL;
 915	Window trans = None;
 916	XWindowChanges wc;
 917
 918	if(!(c = malloc(sizeof(Client))))
 919		die("fatal: could not malloc() %u bytes\n", sizeof(Client));
 920	*c = cz;
 921	c->win = w;
 922
 923	/* geometry */
 924	c->x = wa->x;
 925	c->y = wa->y;
 926	c->w = wa->width;
 927	c->h = wa->height;
 928	c->oldbw = wa->border_width;
 929	if(c->w == sw && c->h == sh) {
 930		c->x = sx;
 931		c->y = sy;
 932		c->bw = 0;
 933	}
 934	else {
 935		if(c->x + WIDTH(c) > sx + sw)
 936			c->x = sx + sw - WIDTH(c);
 937		if(c->y + HEIGHT(c) > sy + sh)
 938			c->y = sy + sh - HEIGHT(c);
 939		c->x = MAX(c->x, sx);
 940		/* only fix client y-offset, if the client center might cover the bar */
 941		c->y = MAX(c->y, ((by == 0) && (c->x + (c->w / 2) >= wx)
 942		                            && (c->x + (c->w / 2) < wx + ww)) ? bh : sy);
 943		c->bw = borderpx;
 944	}
 945
 946	wc.border_width = c->bw;
 947	XConfigureWindow(dpy, w, CWBorderWidth, &wc);
 948	XSetWindowBorder(dpy, w, dc.norm[ColBorder]);
 949	configure(c); /* propagates border_width, if size doesn't change */
 950	updatesizehints(c);
 951	XSelectInput(dpy, w, EnterWindowMask|FocusChangeMask|PropertyChangeMask|StructureNotifyMask);
 952	grabbuttons(c, False);
 953	updatetitle(c);
 954	if(XGetTransientForHint(dpy, w, &trans))
 955		t = getclient(trans);
 956	if(t)
 957		c->tags = t->tags;
 958	else
 959		applyrules(c);
 960	if(!c->isfloating)
 961		c->isfloating = trans != None || c->isfixed;
 962	if(c->isfloating)
 963		XRaiseWindow(dpy, c->win);
 964	attach(c);
 965	attachstack(c);
 966	XMoveResizeWindow(dpy, c->win, c->x + 2 * sw, c->y, c->w, c->h); /* some windows require this */
 967	XMapWindow(dpy, c->win);
 968	setclientstate(c, NormalState);
 969	arrange();
 970}
 971
 972void
 973mappingnotify(XEvent *e) {
 974	XMappingEvent *ev = &e->xmapping;
 975
 976	XRefreshKeyboardMapping(ev);
 977	if(ev->request == MappingKeyboard)
 978		grabkeys();
 979}
 980
 981void
 982maprequest(XEvent *e) {
 983	static XWindowAttributes wa;
 984	XMapRequestEvent *ev = &e->xmaprequest;
 985
 986	if(!XGetWindowAttributes(dpy, ev->window, &wa))
 987		return;
 988	if(wa.override_redirect)
 989		return;
 990	if(!getclient(ev->window))
 991		manage(ev->window, &wa);
 992}
 993
 994void
 995monocle(void) {
 996	Client *c;
 997
 998	for(c = nexttiled(clients); c; c = nexttiled(c->next)) {
 999		resize(c, wx, wy, ww - 2 * c->bw, wh - 2 * c->bw);
1000	}
1001}
1002
1003void
1004movemouse(const Arg *arg) {
1005	int x, y, ocx, ocy, di, nx, ny;
1006	unsigned int dui;
1007	Client *c;
1008	Window dummy;
1009	XEvent ev;
1010
1011	if(!(c = sel))
1012		return;
1013	restack();
1014	ocx = c->x;
1015	ocy = c->y;
1016	if(XGrabPointer(dpy, root, False, MOUSEMASK, GrabModeAsync, GrabModeAsync,
1017	None, cursor[CurMove], CurrentTime) != GrabSuccess)
1018		return;
1019	XQueryPointer(dpy, root, &dummy, &dummy, &x, &y, &di, &di, &dui);
1020	do {
1021		XMaskEvent(dpy, MOUSEMASK|ExposureMask|SubstructureRedirectMask, &ev);
1022		switch (ev.type) {
1023		case ConfigureRequest:
1024		case Expose:
1025		case MapRequest:
1026			handler[ev.type](&ev);
1027			break;
1028		case MotionNotify:
1029			nx = ocx + (ev.xmotion.x - x);
1030			ny = ocy + (ev.xmotion.y - y);
1031			if(snap && nx >= wx && nx <= wx + ww
1032			        && ny >= wy && ny <= wy + wh) {
1033				if(abs(wx - nx) < snap)
1034					nx = wx;
1035				else if(abs((wx + ww) - (nx + WIDTH(c))) < snap)
1036					nx = wx + ww - WIDTH(c);
1037				if(abs(wy - ny) < snap)
1038					ny = wy;
1039				else if(abs((wy + wh) - (ny + HEIGHT(c))) < snap)
1040					ny = wy + wh - HEIGHT(c);
1041				if(!c->isfloating && lt[sellt]->arrange
1042				                  && (abs(nx - c->x) > snap || abs(ny - c->y) > snap))
1043					togglefloating(NULL);
1044			}
1045			if(!lt[sellt]->arrange || c->isfloating)
1046				resize(c, nx, ny, c->w, c->h);
1047			break;
1048		}
1049	}
1050	while(ev.type != ButtonRelease);
1051	XUngrabPointer(dpy, CurrentTime);
1052}
1053
1054Client *
1055nexttiled(Client *c) {
1056	for(; c && (c->isfloating || !ISVISIBLE(c)); c = c->next);
1057	return c;
1058}
1059
1060void
1061propertynotify(XEvent *e) {
1062	Client *c;
1063	Window trans;
1064	XPropertyEvent *ev = &e->xproperty;
1065
1066	if((ev->window == root) && (ev->atom == XA_WM_NAME))
1067		updatestatus();
1068	else if(ev->state == PropertyDelete)
1069		return; /* ignore */
1070	else if((c = getclient(ev->window))) {
1071		switch (ev->atom) {
1072		default: break;
1073		case XA_WM_TRANSIENT_FOR:
1074			XGetTransientForHint(dpy, c->win, &trans);
1075			if(!c->isfloating && (c->isfloating = (getclient(trans) != NULL)))
1076				arrange();
1077			break;
1078		case XA_WM_NORMAL_HINTS:
1079			updatesizehints(c);
1080			break;
1081		case XA_WM_HINTS:
1082			updatewmhints(c);
1083			drawbar();
1084			break;
1085		}
1086		if(ev->atom == XA_WM_NAME || ev->atom == netatom[NetWMName]) {
1087			updatetitle(c);
1088			if(c == sel)
1089				drawbar();
1090		}
1091	}
1092}
1093
1094void
1095quit(const Arg *arg) {
1096	running = False;
1097}
1098
1099void
1100resize(Client *c, int x, int y, int w, int h) {
1101	XWindowChanges wc;
1102
1103	if(applysizehints(c, &x, &y, &w, &h)) {
1104		c->x = wc.x = x;
1105		c->y = wc.y = y;
1106		c->w = wc.width = w;
1107		c->h = wc.height = h;
1108		wc.border_width = c->bw;
1109		XConfigureWindow(dpy, c->win,
1110				CWX|CWY|CWWidth|CWHeight|CWBorderWidth, &wc);
1111		configure(c);
1112		XSync(dpy, False);
1113	}
1114}
1115
1116void
1117resizemouse(const Arg *arg) {
1118	int ocx, ocy;
1119	int nw, nh;
1120	Client *c;
1121	XEvent ev;
1122
1123	if(!(c = sel))
1124		return;
1125	restack();
1126	ocx = c->x;
1127	ocy = c->y;
1128	if(XGrabPointer(dpy, root, False, MOUSEMASK, GrabModeAsync, GrabModeAsync,
1129	None, cursor[CurResize], CurrentTime) != GrabSuccess)
1130		return;
1131	XWarpPointer(dpy, None, c->win, 0, 0, 0, 0, c->w + c->bw - 1, c->h + c->bw - 1);
1132	do {
1133		XMaskEvent(dpy, MOUSEMASK|ExposureMask|SubstructureRedirectMask, &ev);
1134		switch(ev.type) {
1135		case ConfigureRequest:
1136		case Expose:
1137		case MapRequest:
1138			handler[ev.type](&ev);
1139			break;
1140		case MotionNotify:
1141			nw = MAX(ev.xmotion.x - ocx - 2 * c->bw + 1, 1);
1142			nh = MAX(ev.xmotion.y - ocy - 2 * c->bw + 1, 1);
1143
1144			if(snap && nw >= wx && nw <= wx + ww
1145			        && nh >= wy && nh <= wy + wh) {
1146				if(!c->isfloating && lt[sellt]->arrange
1147				   && (abs(nw - c->w) > snap || abs(nh - c->h) > snap))
1148					togglefloating(NULL);
1149			}
1150			if(!lt[sellt]->arrange || c->isfloating)
1151				resize(c, c->x, c->y, nw, nh);
1152			break;
1153		}
1154	}
1155	while(ev.type != ButtonRelease);
1156	XWarpPointer(dpy, None, c->win, 0, 0, 0, 0, c->w + c->bw - 1, c->h + c->bw - 1);
1157	XUngrabPointer(dpy, CurrentTime);
1158	while(XCheckMaskEvent(dpy, EnterWindowMask, &ev));
1159}
1160
1161void
1162restack(void) {
1163	Client *c;
1164	XEvent ev;
1165	XWindowChanges wc;
1166
1167	drawbar();
1168	if(!sel)
1169		return;
1170	if(sel->isfloating || !lt[sellt]->arrange)
1171		XRaiseWindow(dpy, sel->win);
1172	if(lt[sellt]->arrange) {
1173		wc.stack_mode = Below;
1174		wc.sibling = barwin;
1175		for(c = stack; c; c = c->snext)
1176			if(!c->isfloating && ISVISIBLE(c)) {
1177				XConfigureWindow(dpy, c->win, CWSibling|CWStackMode, &wc);
1178				wc.sibling = c->win;
1179			}
1180	}
1181	XSync(dpy, False);
1182	while(XCheckMaskEvent(dpy, EnterWindowMask, &ev));
1183}
1184
1185void
1186run(void) {
1187	XEvent ev;
1188
1189	/* main event loop */
1190	XSync(dpy, False);
1191	while(running && !XNextEvent(dpy, &ev)) {
1192		if(handler[ev.type])
1193			(handler[ev.type])(&ev); /* call handler */
1194	}
1195}
1196
1197void
1198scan(void) {
1199	unsigned int i, num;
1200	Window d1, d2, *wins = NULL;
1201	XWindowAttributes wa;
1202
1203	if(XQueryTree(dpy, root, &d1, &d2, &wins, &num)) {
1204		for(i = 0; i < num; i++) {
1205			if(!XGetWindowAttributes(dpy, wins[i], &wa)
1206			|| wa.override_redirect || XGetTransientForHint(dpy, wins[i], &d1))
1207				continue;
1208			if(wa.map_state == IsViewable || getstate(wins[i]) == IconicState)
1209				manage(wins[i], &wa);
1210		}
1211		for(i = 0; i < num; i++) { /* now the transients */
1212			if(!XGetWindowAttributes(dpy, wins[i], &wa))
1213				continue;
1214			if(XGetTransientForHint(dpy, wins[i], &d1)
1215			&& (wa.map_state == IsViewable || getstate(wins[i]) == IconicState))
1216				manage(wins[i], &wa);
1217		}
1218		if(wins)
1219			XFree(wins);
1220	}
1221}
1222
1223void
1224setclientstate(Client *c, long state) {
1225	long data[] = {state, None};
1226
1227	XChangeProperty(dpy, c->win, wmatom[WMState], wmatom[WMState], 32,
1228			PropModeReplace, (unsigned char *)data, 2);
1229}
1230
1231void
1232setlayout(const Arg *arg) {
1233	if(!arg || !arg->v || arg->v != lt[sellt])
1234		sellt ^= 1;
1235	if(arg && arg->v)
1236		lt[sellt] = (Layout *)arg->v;
1237	if(sel)
1238		arrange();
1239	else
1240		drawbar();
1241}
1242
1243/* arg > 1.0 will set mfact absolutly */
1244void
1245setmfact(const Arg *arg) {
1246	float f;
1247
1248	if(!arg || !lt[sellt]->arrange)
1249		return;
1250	f = arg->f < 1.0 ? arg->f + mfact : arg->f - 1.0;
1251	if(f < 0.1 || f > 0.9)
1252		return;
1253	mfact = f;
1254	arrange();
1255}
1256
1257void
1258setup(void) {
1259	unsigned int i;
1260	int w;
1261	XSetWindowAttributes wa;
1262
1263	/* init screen */
1264	screen = DefaultScreen(dpy);
1265	root = RootWindow(dpy, screen);
1266	initfont(font);
1267	sx = 0;
1268	sy = 0;
1269	sw = DisplayWidth(dpy, screen);
1270	sh = DisplayHeight(dpy, screen);
1271	bh = dc.h = dc.font.height + 2;
1272	lt[0] = &layouts[0];
1273	lt[1] = &layouts[1 % LENGTH(layouts)];
1274	updategeom();
1275
1276	/* init atoms */
1277	wmatom[WMProtocols] = XInternAtom(dpy, "WM_PROTOCOLS", False);
1278	wmatom[WMDelete] = XInternAtom(dpy, "WM_DELETE_WINDOW", False);
1279	wmatom[WMState] = XInternAtom(dpy, "WM_STATE", False);
1280	netatom[NetSupported] = XInternAtom(dpy, "_NET_SUPPORTED", False);
1281	netatom[NetWMName] = XInternAtom(dpy, "_NET_WM_NAME", False);
1282
1283	/* init cursors */
1284	wa.cursor = cursor[CurNormal] = XCreateFontCursor(dpy, XC_left_ptr);
1285	cursor[CurResize] = XCreateFontCursor(dpy, XC_sizing);
1286	cursor[CurMove] = XCreateFontCursor(dpy, XC_fleur);
1287
1288	/* init appearance */
1289	dc.norm[ColBorder] = getcolor(normbordercolor);
1290	dc.norm[ColBG] = getcolor(normbgcolor);
1291	dc.norm[ColFG] = getcolor(normfgcolor);
1292	dc.sel[ColBorder] = getcolor(selbordercolor);
1293	dc.sel[ColBG] = getcolor(selbgcolor);
1294	dc.sel[ColFG] = getcolor(selfgcolor);
1295	dc.drawable = XCreatePixmap(dpy, root, DisplayWidth(dpy, screen), bh, DefaultDepth(dpy, screen));
1296	dc.gc = XCreateGC(dpy, root, 0, NULL);
1297	XSetLineAttributes(dpy, dc.gc, 1, LineSolid, CapButt, JoinMiter);
1298	if(!dc.font.set)
1299		XSetFont(dpy, dc.gc, dc.font.xfont->fid);
1300
1301	/* init bar */
1302	for(blw = i = 0; LENGTH(layouts) > 1 && i < LENGTH(layouts); i++) {
1303		w = TEXTW(layouts[i].symbol);
1304		blw = MAX(blw, w);
1305	}
1306
1307	wa.override_redirect = True;
1308	wa.background_pixmap = ParentRelative;
1309	wa.event_mask = ButtonPressMask|ExposureMask;
1310
1311	barwin = XCreateWindow(dpy, root, wx, by, ww, bh, 0, DefaultDepth(dpy, screen),
1312			CopyFromParent, DefaultVisual(dpy, screen),
1313			CWOverrideRedirect|CWBackPixmap|CWEventMask, &wa);
1314	XDefineCursor(dpy, barwin, cursor[CurNormal]);
1315	XMapRaised(dpy, barwin);
1316	updatestatus();
1317
1318	/* EWMH support per view */
1319	XChangeProperty(dpy, root, netatom[NetSupported], XA_ATOM, 32,
1320			PropModeReplace, (unsigned char *) netatom, NetLast);
1321
1322	/* select for events */
1323	wa.event_mask = SubstructureRedirectMask|SubstructureNotifyMask|ButtonPressMask
1324			|EnterWindowMask|LeaveWindowMask|StructureNotifyMask
1325			|PropertyChangeMask;
1326	XChangeWindowAttributes(dpy, root, CWEventMask|CWCursor, &wa);
1327	XSelectInput(dpy, root, wa.event_mask);
1328
1329	grabkeys();
1330}
1331
1332void
1333showhide(Client *c) {
1334	if(!c)
1335		return;
1336	if(ISVISIBLE(c)) { /* show clients top down */
1337		XMoveWindow(dpy, c->win, c->x, c->y);
1338		if(!lt[sellt]->arrange || c->isfloating)
1339			resize(c, c->x, c->y, c->w, c->h);
1340		showhide(c->snext);
1341	}
1342	else { /* hide clients bottom up */
1343		showhide(c->snext);
1344		XMoveWindow(dpy, c->win, c->x + 2 * sw, c->y);
1345	}
1346}
1347
1348
1349void
1350sigchld(int signal) {
1351	while(0 < waitpid(-1, NULL, WNOHANG));
1352}
1353
1354void
1355spawn(const Arg *arg) {
1356	signal(SIGCHLD, sigchld);
1357	if(fork() == 0) {
1358		if(dpy)
1359			close(ConnectionNumber(dpy));
1360		setsid();
1361		execvp(((char **)arg->v)[0], (char **)arg->v);
1362		fprintf(stderr, "dwm: execvp %s", ((char **)arg->v)[0]);
1363		perror(" failed");
1364		exit(0);
1365	}
1366}
1367
1368void
1369tag(const Arg *arg) {
1370	if(sel && arg->ui & TAGMASK) {
1371		sel->tags = arg->ui & TAGMASK;
1372		arrange();
1373	}
1374}
1375
1376int
1377textnw(const char *text, unsigned int len) {
1378	XRectangle r;
1379
1380	if(dc.font.set) {
1381		XmbTextExtents(dc.font.set, text, len, NULL, &r);
1382		return r.width;
1383	}
1384	return XTextWidth(dc.font.xfont, text, len);
1385}
1386
1387void
1388tile(void) {
1389	int x, y, h, w, mw;
1390	unsigned int i, n;
1391	Client *c;
1392
1393	for(n = 0, c = nexttiled(clients); c; c = nexttiled(c->next), n++);
1394	if(n == 0)
1395		return;
1396
1397	/* master */
1398	c = nexttiled(clients);
1399	mw = mfact * ww;
1400	resize(c, wx, wy, (n == 1 ? ww : mw) - 2 * c->bw, wh - 2 * c->bw);
1401
1402	if(--n == 0)
1403		return;
1404
1405	/* tile stack */
1406	x = (wx + mw > c->x + c->w) ? c->x + c->w + 2 * c->bw : wx + mw;
1407	y = wy;
1408	w = (wx + mw > c->x + c->w) ? wx + ww - x : ww - mw;
1409	h = wh / n;
1410	if(h < bh)
1411		h = wh;
1412
1413	for(i = 0, c = nexttiled(c->next); c; c = nexttiled(c->next), i++) {
1414		resize(c, x, y, w - 2 * c->bw, /* remainder */ ((i + 1 == n)
1415		       ? wy + wh - y - 2 * c->bw : h - 2 * c->bw));
1416		if(h != wh)
1417			y = c->y + HEIGHT(c);
1418	}
1419}
1420
1421void
1422togglebar(const Arg *arg) {
1423	showbar = !showbar;
1424	updategeom();
1425	updatebar();
1426	arrange();
1427}
1428
1429void
1430togglefloating(const Arg *arg) {
1431	if(!sel)
1432		return;
1433	sel->isfloating = !sel->isfloating || sel->isfixed;
1434	if(sel->isfloating)
1435		resize(sel, sel->x, sel->y, sel->w, sel->h);
1436	arrange();
1437}
1438
1439void
1440toggletag(const Arg *arg) {
1441	unsigned int mask;
1442
1443	if (!sel)
1444		return;
1445	
1446	mask = sel->tags ^ (arg->ui & TAGMASK);
1447	if(mask) {
1448		sel->tags = mask;
1449		arrange();
1450	}
1451}
1452
1453void
1454toggleview(const Arg *arg) {
1455	unsigned int mask = tagset[seltags] ^ (arg->ui & TAGMASK);
1456
1457	if(mask) {
1458		tagset[seltags] = mask;
1459		arrange();
1460	}
1461}
1462
1463void
1464unmanage(Client *c) {
1465	XWindowChanges wc;
1466
1467	wc.border_width = c->oldbw;
1468	/* The server grab construct avoids race conditions. */
1469	XGrabServer(dpy);
1470	XSetErrorHandler(xerrordummy);
1471	XConfigureWindow(dpy, c->win, CWBorderWidth, &wc); /* restore border */
1472	detach(c);
1473	detachstack(c);
1474	if(sel == c)
1475		focus(NULL);
1476	XUngrabButton(dpy, AnyButton, AnyModifier, c->win);
1477	setclientstate(c, WithdrawnState);
1478	free(c);
1479	XSync(dpy, False);
1480	XSetErrorHandler(xerror);
1481	XUngrabServer(dpy);
1482	arrange();
1483}
1484
1485void
1486unmapnotify(XEvent *e) {
1487	Client *c;
1488	XUnmapEvent *ev = &e->xunmap;
1489
1490	if((c = getclient(ev->window)))
1491		unmanage(c);
1492}
1493
1494void
1495updatebar(void) {
1496	if(dc.drawable != 0)
1497		XFreePixmap(dpy, dc.drawable);
1498	dc.drawable = XCreatePixmap(dpy, root, ww, bh, DefaultDepth(dpy, screen));
1499	XMoveResizeWindow(dpy, barwin, wx, by, ww, bh);
1500}
1501
1502void
1503updategeom(void) {
1504#ifdef XINERAMA
1505	int n, i = 0;
1506	XineramaScreenInfo *info = NULL;
1507
1508	/* window area geometry */
1509	if(XineramaIsActive(dpy) && (info = XineramaQueryScreens(dpy, &n))) { 
1510		if(n > 1) {
1511			int di, x, y;
1512			unsigned int dui;
1513			Window dummy;
1514			if(XQueryPointer(dpy, root, &dummy, &dummy, &x, &y, &di, &di, &dui))
1515				for(i = 0; i < n; i++)
1516					if(INRECT(x, y, info[i].x_org, info[i].y_org, info[i].width, info[i].height))
1517						break;
1518		}
1519		wx = info[i].x_org;
1520		wy = showbar && topbar ?  info[i].y_org + bh : info[i].y_org;
1521		ww = info[i].width;
1522		wh = showbar ? info[i].height - bh : info[i].height;
1523		XFree(info);
1524	}
1525	else
1526#endif
1527	{
1528		wx = sx;
1529		wy = showbar && topbar ? sy + bh : sy;
1530		ww = sw;
1531		wh = showbar ? sh - bh : sh;
1532	}
1533
1534	/* bar position */
1535	by = showbar ? (topbar ? wy - bh : wy + wh) : -bh;
1536}
1537
1538void
1539updatenumlockmask(void) {
1540	unsigned int i, j;
1541	XModifierKeymap *modmap;
1542
1543	numlockmask = 0;
1544	modmap = XGetModifierMapping(dpy);
1545	for(i = 0; i < 8; i++)
1546		for(j = 0; j < modmap->max_keypermod; j++)
1547			if(modmap->modifiermap[i * modmap->max_keypermod + j]
1548			   == XKeysymToKeycode(dpy, XK_Num_Lock))
1549				numlockmask = (1 << i);
1550	XFreeModifiermap(modmap);
1551}
1552
1553void
1554updatesizehints(Client *c) {
1555	long msize;
1556	XSizeHints size;
1557
1558	if(!XGetWMNormalHints(dpy, c->win, &size, &msize))
1559		/* size is uninitialized, ensure that size.flags aren't used */
1560		size.flags = PSize; 
1561	if(size.flags & PBaseSize) {
1562		c->basew = size.base_width;
1563		c->baseh = size.base_height;
1564	}
1565	else if(size.flags & PMinSize) {
1566		c->basew = size.min_width;
1567		c->baseh = size.min_height;
1568	}
1569	else
1570		c->basew = c->baseh = 0;
1571	if(size.flags & PResizeInc) {
1572		c->incw = size.width_inc;
1573		c->inch = size.height_inc;
1574	}
1575	else
1576		c->incw = c->inch = 0;
1577	if(size.flags & PMaxSize) {
1578		c->maxw = size.max_width;
1579		c->maxh = size.max_height;
1580	}
1581	else
1582		c->maxw = c->maxh = 0;
1583	if(size.flags & PMinSize) {
1584		c->minw = size.min_width;
1585		c->minh = size.min_height;
1586	}
1587	else if(size.flags & PBaseSize) {
1588		c->minw = size.base_width;
1589		c->minh = size.base_height;
1590	}
1591	else
1592		c->minw = c->minh = 0;
1593	if(size.flags & PAspect) {
1594		c->mina = (float)size.min_aspect.y / (float)size.min_aspect.x;
1595		c->maxa = (float)size.max_aspect.x / (float)size.max_aspect.y;
1596	}
1597	else
1598		c->maxa = c->mina = 0.0;
1599	c->isfixed = (c->maxw && c->minw && c->maxh && c->minh
1600	             && c->maxw == c->minw && c->maxh == c->minh);
1601}
1602
1603void
1604updatetitle(Client *c) {
1605	if(!gettextprop(c->win, netatom[NetWMName], c->name, sizeof c->name))
1606		gettextprop(c->win, XA_WM_NAME, c->name, sizeof c->name);
1607}
1608
1609void
1610updatestatus() {
1611	if(!gettextprop(root, XA_WM_NAME, stext, sizeof(stext)))
1612		strcpy(stext, "dwm-"VERSION);
1613	drawbar();
1614}
1615
1616void
1617updatewmhints(Client *c) {
1618	XWMHints *wmh;
1619
1620	if((wmh = XGetWMHints(dpy, c->win))) {
1621		if(c == sel && wmh->flags & XUrgencyHint) {
1622			wmh->flags &= ~XUrgencyHint;
1623			XSetWMHints(dpy, c->win, wmh);
1624		}
1625		else
1626			c->isurgent = (wmh->flags & XUrgencyHint) ? True : False;
1627
1628		XFree(wmh);
1629	}
1630}
1631
1632void
1633view(const Arg *arg) {
1634	if((arg->ui & TAGMASK) == tagset[seltags])
1635		return;
1636	seltags ^= 1; /* toggle sel tagset */
1637	if(arg->ui & TAGMASK)
1638		tagset[seltags] = arg->ui & TAGMASK;
1639	arrange();
1640}
1641
1642/* There's no way to check accesses to destroyed windows, thus those cases are
1643 * ignored (especially on UnmapNotify's).  Other types of errors call Xlibs
1644 * default error handler, which may call exit.  */
1645int
1646xerror(Display *dpy, XErrorEvent *ee) {
1647	if(ee->error_code == BadWindow
1648	|| (ee->request_code == X_SetInputFocus && ee->error_code == BadMatch)
1649	|| (ee->request_code == X_PolyText8 && ee->error_code == BadDrawable)
1650	|| (ee->request_code == X_PolyFillRectangle && ee->error_code == BadDrawable)
1651	|| (ee->request_code == X_PolySegment && ee->error_code == BadDrawable)
1652	|| (ee->request_code == X_ConfigureWindow && ee->error_code == BadMatch)
1653	|| (ee->request_code == X_GrabButton && ee->error_code == BadAccess)
1654	|| (ee->request_code == X_GrabKey && ee->error_code == BadAccess)
1655	|| (ee->request_code == X_CopyArea && ee->error_code == BadDrawable))
1656		return 0;
1657	fprintf(stderr, "dwm: fatal error: request code=%d, error code=%d\n",
1658			ee->request_code, ee->error_code);
1659	return xerrorxlib(dpy, ee); /* may call exit */
1660}
1661
1662int
1663xerrordummy(Display *dpy, XErrorEvent *ee) {
1664	return 0;
1665}
1666
1667/* Startup Error handler to check if another window manager
1668 * is already running. */
1669int
1670xerrorstart(Display *dpy, XErrorEvent *ee) {
1671	otherwm = True;
1672	return -1;
1673}
1674
1675void
1676zoom(const Arg *arg) {
1677	Client *c = sel;
1678
1679	if(!lt[sellt]->arrange || lt[sellt]->arrange == monocle || (sel && sel->isfloating))
1680		return;
1681	if(c == nexttiled(clients))
1682		if(!c || !(c = nexttiled(c->next)))
1683			return;
1684	detach(c);
1685	attach(c);
1686	focus(c);
1687	arrange();
1688}
1689
1690int
1691main(int argc, char *argv[]) {
1692	if(argc == 2 && !strcmp("-v", argv[1]))
1693		die("dwm-"VERSION", © 2006-2009 dwm engineers, see LICENSE for details\n");
1694	else if(argc != 1)
1695		die("usage: dwm [-v]\n");
1696
1697	if(!setlocale(LC_CTYPE, "") || !XSupportsLocale())
1698		fputs("warning: no locale support\n", stderr);
1699
1700	if(!(dpy = XOpenDisplay(NULL)))
1701		die("dwm: cannot open display\n");
1702
1703	checkotherwm();
1704	setup();
1705	scan();
1706	run();
1707	cleanup();
1708
1709	XCloseDisplay(dpy);
1710	return 0;
1711}