all repos — dwm @ 3632d7132fc212a50e62327858a3d15c0e81e030

fork of suckless dynamic window manager

dwm.c (view raw)

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