all repos — dwm @ 18b1312449531c7b77403aafb71611e9e48500ec

fork of suckless dynamic window manager

dwm.c (view raw)

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