all repos — dwm @ 758b100d12ba1c52b5d7479e3ed334ba89e701f8

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