all repos — dwm @ 1d729384d12d289951504b130b8804ab85c0b12b

fork of suckless dynamic window manager

dwm.c (view raw)

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