all repos — dwm @ 52bd69c2a4998294a259efbedafca961dc2781eb

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