all repos — dwm @ 8dc9fcf1b95db927ce50a63c7e571fdb074529e8

fork of suckless dynamic window manager

dwm.c (view raw)

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