all repos — dwm @ cd96232f7e97726413baeb0d411cc5f537575f0e

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